]> git.proxmox.com Git - pve-eslint.git/blame - src/eslint.js
factor out path expansion
[pve-eslint.git] / src / eslint.js
CommitLineData
eb39fafa
DC
1var eslint =
2/******/ (function(modules) { // webpackBootstrap
3/******/ // The module cache
4/******/ var installedModules = {};
5/******/
6/******/ // The require function
7/******/ function __webpack_require__(moduleId) {
8/******/
9/******/ // Check if module is in cache
10/******/ if(installedModules[moduleId]) {
11/******/ return installedModules[moduleId].exports;
12/******/ }
13/******/ // Create a new module (and put it into the cache)
14/******/ var module = installedModules[moduleId] = {
15/******/ i: moduleId,
16/******/ l: false,
17/******/ exports: {}
18/******/ };
19/******/
20/******/ // Execute the module function
21/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22/******/
23/******/ // Flag the module as loaded
24/******/ module.l = true;
25/******/
26/******/ // Return the exports of the module
27/******/ return module.exports;
28/******/ }
29/******/
30/******/
31/******/ // expose the modules object (__webpack_modules__)
32/******/ __webpack_require__.m = modules;
33/******/
34/******/ // expose the module cache
35/******/ __webpack_require__.c = installedModules;
36/******/
37/******/ // define getter function for harmony exports
38/******/ __webpack_require__.d = function(exports, name, getter) {
39/******/ if(!__webpack_require__.o(exports, name)) {
40/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
41/******/ }
42/******/ };
43/******/
44/******/ // define __esModule on exports
45/******/ __webpack_require__.r = function(exports) {
46/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
47/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
48/******/ }
49/******/ Object.defineProperty(exports, '__esModule', { value: true });
50/******/ };
51/******/
52/******/ // create a fake namespace object
53/******/ // mode & 1: value is a module id, require it
54/******/ // mode & 2: merge all properties of value into the ns
55/******/ // mode & 4: return value when already ns object
56/******/ // mode & 8|1: behave like require
57/******/ __webpack_require__.t = function(value, mode) {
58/******/ if(mode & 1) value = __webpack_require__(value);
59/******/ if(mode & 8) return value;
60/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
61/******/ var ns = Object.create(null);
62/******/ __webpack_require__.r(ns);
63/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
64/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
65/******/ return ns;
66/******/ };
67/******/
68/******/ // getDefaultExport function for compatibility with non-harmony modules
69/******/ __webpack_require__.n = function(module) {
70/******/ var getter = module && module.__esModule ?
71/******/ function getDefault() { return module['default']; } :
72/******/ function getModuleExports() { return module; };
73/******/ __webpack_require__.d(getter, 'a', getter);
74/******/ return getter;
75/******/ };
76/******/
77/******/ // Object.prototype.hasOwnProperty.call
78/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
79/******/
80/******/ // __webpack_public_path__
81/******/ __webpack_require__.p = "";
82/******/
83/******/
84/******/ // Load entry module and return exports
85/******/ return __webpack_require__(__webpack_require__.s = 0);
86/******/ })
87/************************************************************************/
88/******/ ([
89/* 0 */
90/***/ (function(module, exports, __webpack_require__) {
91
92__webpack_require__(1);
93__webpack_require__(375);
94__webpack_require__(376);
6a5a0f88 95module.exports = __webpack_require__(823);
eb39fafa
DC
96
97
98/***/ }),
99/* 1 */
100/***/ (function(module, exports, __webpack_require__) {
101
102__webpack_require__(2);
103
104__webpack_require__(362);
105
106var path = __webpack_require__(37);
107
108module.exports = path;
109
110/***/ }),
111/* 2 */
112/***/ (function(module, exports, __webpack_require__) {
113
114__webpack_require__(3);
115
116__webpack_require__(64);
117
118__webpack_require__(65);
119
120__webpack_require__(66);
121
122__webpack_require__(67);
123
124__webpack_require__(68);
125
126__webpack_require__(69);
127
128__webpack_require__(70);
129
130__webpack_require__(71);
131
132__webpack_require__(72);
133
134__webpack_require__(73);
135
136__webpack_require__(74);
137
138__webpack_require__(75);
139
140__webpack_require__(76);
141
142__webpack_require__(77);
143
144__webpack_require__(78);
145
146__webpack_require__(80);
147
148__webpack_require__(81);
149
150__webpack_require__(82);
151
152__webpack_require__(83);
153
154__webpack_require__(85);
155
156__webpack_require__(88);
157
158__webpack_require__(97);
159
160__webpack_require__(98);
161
162__webpack_require__(99);
163
164__webpack_require__(100);
165
166__webpack_require__(103);
167
168__webpack_require__(105);
169
170__webpack_require__(106);
171
172__webpack_require__(107);
173
174__webpack_require__(108);
175
176__webpack_require__(109);
177
178__webpack_require__(110);
179
180__webpack_require__(111);
181
182__webpack_require__(114);
183
184__webpack_require__(115);
185
186__webpack_require__(117);
187
188__webpack_require__(119);
189
190__webpack_require__(120);
191
192__webpack_require__(121);
193
194__webpack_require__(122);
195
196__webpack_require__(124);
197
198__webpack_require__(125);
199
200__webpack_require__(126);
201
202__webpack_require__(127);
203
204__webpack_require__(130);
205
206__webpack_require__(131);
207
208__webpack_require__(132);
209
210__webpack_require__(136);
211
212__webpack_require__(139);
213
214__webpack_require__(142);
215
216__webpack_require__(144);
217
218__webpack_require__(145);
219
220__webpack_require__(146);
221
222__webpack_require__(147);
223
224__webpack_require__(149);
225
226__webpack_require__(150);
227
228__webpack_require__(152);
229
230__webpack_require__(153);
231
232__webpack_require__(154);
233
234__webpack_require__(155);
235
236__webpack_require__(157);
237
238__webpack_require__(158);
239
240__webpack_require__(160);
241
242__webpack_require__(161);
243
244__webpack_require__(162);
245
246__webpack_require__(163);
247
248__webpack_require__(164);
249
250__webpack_require__(165);
251
252__webpack_require__(166);
253
254__webpack_require__(168);
255
256__webpack_require__(169);
257
258__webpack_require__(170);
259
260__webpack_require__(174);
261
262__webpack_require__(175);
263
264__webpack_require__(176);
265
266__webpack_require__(178);
267
268__webpack_require__(182);
269
270__webpack_require__(183);
271
272__webpack_require__(191);
273
274__webpack_require__(193);
275
276__webpack_require__(197);
277
278__webpack_require__(198);
279
280__webpack_require__(199);
281
282__webpack_require__(200);
283
284__webpack_require__(201);
285
286__webpack_require__(202);
287
288__webpack_require__(203);
289
290__webpack_require__(207);
291
292__webpack_require__(208);
293
294__webpack_require__(209);
295
296__webpack_require__(210);
297
298__webpack_require__(213);
299
300__webpack_require__(214);
301
302__webpack_require__(215);
303
304__webpack_require__(216);
305
306__webpack_require__(217);
307
308__webpack_require__(218);
309
310__webpack_require__(219);
311
312__webpack_require__(220);
313
314__webpack_require__(221);
315
316__webpack_require__(222);
317
318__webpack_require__(223);
319
320__webpack_require__(224);
321
322__webpack_require__(225);
323
324__webpack_require__(185);
325
326__webpack_require__(227);
327
328__webpack_require__(228);
329
330__webpack_require__(229);
331
332__webpack_require__(230);
333
334__webpack_require__(231);
335
336__webpack_require__(233);
337
338__webpack_require__(235);
339
340__webpack_require__(236);
341
342__webpack_require__(237);
343
344__webpack_require__(239);
345
346__webpack_require__(241);
347
348__webpack_require__(242);
349
350__webpack_require__(243);
351
352__webpack_require__(244);
353
354__webpack_require__(245);
355
356__webpack_require__(246);
357
358__webpack_require__(247);
359
360__webpack_require__(249);
361
362__webpack_require__(250);
363
364__webpack_require__(252);
365
366__webpack_require__(253);
367
368__webpack_require__(254);
369
370__webpack_require__(256);
371
372__webpack_require__(257);
373
374__webpack_require__(259);
375
376__webpack_require__(260);
377
378__webpack_require__(262);
379
380__webpack_require__(263);
381
382__webpack_require__(264);
383
384__webpack_require__(265);
385
386__webpack_require__(266);
387
388__webpack_require__(267);
389
390__webpack_require__(268);
391
392__webpack_require__(269);
393
394__webpack_require__(270);
395
396__webpack_require__(271);
397
398__webpack_require__(272);
399
400__webpack_require__(273);
401
402__webpack_require__(274);
403
404__webpack_require__(276);
405
406__webpack_require__(277);
407
408__webpack_require__(279);
409
410__webpack_require__(280);
411
412__webpack_require__(281);
413
414__webpack_require__(292);
415
416__webpack_require__(293);
417
418__webpack_require__(294);
419
420__webpack_require__(297);
421
422__webpack_require__(298);
423
424__webpack_require__(300);
425
426__webpack_require__(301);
427
428__webpack_require__(306);
429
430__webpack_require__(308);
431
432__webpack_require__(309);
433
434__webpack_require__(310);
435
436__webpack_require__(316);
437
438__webpack_require__(317);
439
440__webpack_require__(318);
441
442__webpack_require__(319);
443
444__webpack_require__(320);
445
446__webpack_require__(321);
447
448__webpack_require__(322);
449
450__webpack_require__(323);
451
452__webpack_require__(324);
453
454__webpack_require__(325);
455
456__webpack_require__(326);
457
458__webpack_require__(327);
459
460__webpack_require__(328);
461
462__webpack_require__(329);
463
464__webpack_require__(330);
465
466__webpack_require__(331);
467
468__webpack_require__(332);
469
470__webpack_require__(333);
471
472__webpack_require__(334);
473
474__webpack_require__(335);
475
476__webpack_require__(336);
477
478__webpack_require__(337);
479
480__webpack_require__(338);
481
482__webpack_require__(339);
483
484__webpack_require__(340);
485
486__webpack_require__(341);
487
488__webpack_require__(342);
489
490__webpack_require__(343);
491
492__webpack_require__(344);
493
494__webpack_require__(345);
495
496__webpack_require__(346);
497
498__webpack_require__(347);
499
500__webpack_require__(348);
501
502__webpack_require__(349);
503
504__webpack_require__(350);
505
506__webpack_require__(351);
507
508__webpack_require__(352);
509
510__webpack_require__(353);
511
512__webpack_require__(354);
513
514__webpack_require__(355);
515
516__webpack_require__(356);
517
518__webpack_require__(357);
519
520__webpack_require__(358);
521
522__webpack_require__(359);
523
524__webpack_require__(360);
525
526__webpack_require__(361);
527
528var path = __webpack_require__(37);
529
530module.exports = path;
531
532/***/ }),
533/* 3 */
534/***/ (function(module, exports, __webpack_require__) {
535
536"use strict";
537
538
539var $ = __webpack_require__(4);
540
541var global = __webpack_require__(5);
542
543var getBuiltIn = __webpack_require__(36);
544
545var IS_PURE = __webpack_require__(31);
546
547var DESCRIPTORS = __webpack_require__(7);
548
549var NATIVE_SYMBOL = __webpack_require__(47);
550
551var USE_SYMBOL_AS_UID = __webpack_require__(48);
552
553var fails = __webpack_require__(8);
554
555var has = __webpack_require__(17);
556
557var isArray = __webpack_require__(49);
558
559var isObject = __webpack_require__(16);
560
561var anObject = __webpack_require__(22);
562
563var toObject = __webpack_require__(50);
564
565var toIndexedObject = __webpack_require__(11);
566
567var toPrimitive = __webpack_require__(15);
568
569var createPropertyDescriptor = __webpack_require__(10);
570
571var nativeObjectCreate = __webpack_require__(51);
572
573var objectKeys = __webpack_require__(53);
574
575var getOwnPropertyNamesModule = __webpack_require__(38);
576
577var getOwnPropertyNamesExternal = __webpack_require__(55);
578
579var getOwnPropertySymbolsModule = __webpack_require__(45);
580
581var getOwnPropertyDescriptorModule = __webpack_require__(6);
582
583var definePropertyModule = __webpack_require__(21);
584
585var propertyIsEnumerableModule = __webpack_require__(9);
586
587var createNonEnumerableProperty = __webpack_require__(20);
588
589var redefine = __webpack_require__(23);
590
591var shared = __webpack_require__(30);
592
593var sharedKey = __webpack_require__(29);
594
595var hiddenKeys = __webpack_require__(33);
596
597var uid = __webpack_require__(32);
598
599var wellKnownSymbol = __webpack_require__(56);
600
601var wrappedWellKnownSymbolModule = __webpack_require__(57);
602
603var defineWellKnownSymbol = __webpack_require__(58);
604
605var setToStringTag = __webpack_require__(59);
606
607var InternalStateModule = __webpack_require__(27);
608
609var $forEach = __webpack_require__(60).forEach;
610
611var HIDDEN = sharedKey('hidden');
612var SYMBOL = 'Symbol';
613var PROTOTYPE = 'prototype';
614var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
615var setInternalState = InternalStateModule.set;
616var getInternalState = InternalStateModule.getterFor(SYMBOL);
617var ObjectPrototype = Object[PROTOTYPE];
618var $Symbol = global.Symbol;
619var $stringify = getBuiltIn('JSON', 'stringify');
620var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
621var nativeDefineProperty = definePropertyModule.f;
622var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;
623var nativePropertyIsEnumerable = propertyIsEnumerableModule.f;
624var AllSymbols = shared('symbols');
625var ObjectPrototypeSymbols = shared('op-symbols');
626var StringToSymbolRegistry = shared('string-to-symbol-registry');
627var SymbolToStringRegistry = shared('symbol-to-string-registry');
628var WellKnownSymbolsStore = shared('wks');
629var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
630
631var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
632
633var setSymbolDescriptor = DESCRIPTORS && fails(function () {
634 return nativeObjectCreate(nativeDefineProperty({}, 'a', {
635 get: function get() {
636 return nativeDefineProperty(this, 'a', {
637 value: 7
638 }).a;
639 }
640 })).a != 7;
641}) ? function (O, P, Attributes) {
642 var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);
643 if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
644 nativeDefineProperty(O, P, Attributes);
645
646 if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
647 nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);
648 }
649} : nativeDefineProperty;
650
651var wrap = function wrap(tag, description) {
652 var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]);
653 setInternalState(symbol, {
654 type: SYMBOL,
655 tag: tag,
656 description: description
657 });
658 if (!DESCRIPTORS) symbol.description = description;
659 return symbol;
660};
661
662var isSymbol = USE_SYMBOL_AS_UID ? function (it) {
663 return typeof it == 'symbol';
664} : function (it) {
665 return Object(it) instanceof $Symbol;
666};
667
668var $defineProperty = function defineProperty(O, P, Attributes) {
669 if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
670 anObject(O);
671 var key = toPrimitive(P, true);
672 anObject(Attributes);
673
674 if (has(AllSymbols, key)) {
675 if (!Attributes.enumerable) {
676 if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));
677 O[HIDDEN][key] = true;
678 } else {
679 if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
680 Attributes = nativeObjectCreate(Attributes, {
681 enumerable: createPropertyDescriptor(0, false)
682 });
683 }
684
685 return setSymbolDescriptor(O, key, Attributes);
686 }
687
688 return nativeDefineProperty(O, key, Attributes);
689};
690
691var $defineProperties = function defineProperties(O, Properties) {
692 anObject(O);
693 var properties = toIndexedObject(Properties);
694 var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
695 $forEach(keys, function (key) {
696 if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
697 });
698 return O;
699};
700
701var $create = function create(O, Properties) {
702 return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);
703};
704
705var $propertyIsEnumerable = function propertyIsEnumerable(V) {
706 var P = toPrimitive(V, true);
707 var enumerable = nativePropertyIsEnumerable.call(this, P);
708 if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
709 return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
710};
711
712var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
713 var it = toIndexedObject(O);
714 var key = toPrimitive(P, true);
715 if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
716 var descriptor = nativeGetOwnPropertyDescriptor(it, key);
717
718 if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
719 descriptor.enumerable = true;
720 }
721
722 return descriptor;
723};
724
725var $getOwnPropertyNames = function getOwnPropertyNames(O) {
726 var names = nativeGetOwnPropertyNames(toIndexedObject(O));
727 var result = [];
728 $forEach(names, function (key) {
729 if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
730 });
731 return result;
732};
733
734var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
735 var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
736 var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
737 var result = [];
738 $forEach(names, function (key) {
739 if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
740 result.push(AllSymbols[key]);
741 }
742 });
743 return result;
744}; // `Symbol` constructor
745// https://tc39.github.io/ecma262/#sec-symbol-constructor
746
747
748if (!NATIVE_SYMBOL) {
749 $Symbol = function Symbol() {
750 if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
751 var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
752 var tag = uid(description);
753
754 var setter = function setter(value) {
755 if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
756 if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
757 setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
758 };
759
760 if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, {
761 configurable: true,
762 set: setter
763 });
764 return wrap(tag, description);
765 };
766
767 redefine($Symbol[PROTOTYPE], 'toString', function toString() {
768 return getInternalState(this).tag;
769 });
770 redefine($Symbol, 'withoutSetter', function (description) {
771 return wrap(uid(description), description);
772 });
773 propertyIsEnumerableModule.f = $propertyIsEnumerable;
774 definePropertyModule.f = $defineProperty;
775 getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;
776 getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;
777 getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;
778
779 wrappedWellKnownSymbolModule.f = function (name) {
780 return wrap(wellKnownSymbol(name), name);
781 };
782
783 if (DESCRIPTORS) {
784 // https://github.com/tc39/proposal-Symbol-description
785 nativeDefineProperty($Symbol[PROTOTYPE], 'description', {
786 configurable: true,
787 get: function description() {
788 return getInternalState(this).description;
789 }
790 });
791
792 if (!IS_PURE) {
793 redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, {
794 unsafe: true
795 });
796 }
797 }
798}
799
800$({
801 global: true,
802 wrap: true,
803 forced: !NATIVE_SYMBOL,
804 sham: !NATIVE_SYMBOL
805}, {
806 Symbol: $Symbol
807});
808$forEach(objectKeys(WellKnownSymbolsStore), function (name) {
809 defineWellKnownSymbol(name);
810});
811$({
812 target: SYMBOL,
813 stat: true,
814 forced: !NATIVE_SYMBOL
815}, {
816 // `Symbol.for` method
817 // https://tc39.github.io/ecma262/#sec-symbol.for
818 'for': function _for(key) {
819 var string = String(key);
820 if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
821 var symbol = $Symbol(string);
822 StringToSymbolRegistry[string] = symbol;
823 SymbolToStringRegistry[symbol] = string;
824 return symbol;
825 },
826 // `Symbol.keyFor` method
827 // https://tc39.github.io/ecma262/#sec-symbol.keyfor
828 keyFor: function keyFor(sym) {
829 if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
830 if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
831 },
832 useSetter: function useSetter() {
833 USE_SETTER = true;
834 },
835 useSimple: function useSimple() {
836 USE_SETTER = false;
837 }
838});
839$({
840 target: 'Object',
841 stat: true,
842 forced: !NATIVE_SYMBOL,
843 sham: !DESCRIPTORS
844}, {
845 // `Object.create` method
846 // https://tc39.github.io/ecma262/#sec-object.create
847 create: $create,
848 // `Object.defineProperty` method
849 // https://tc39.github.io/ecma262/#sec-object.defineproperty
850 defineProperty: $defineProperty,
851 // `Object.defineProperties` method
852 // https://tc39.github.io/ecma262/#sec-object.defineproperties
853 defineProperties: $defineProperties,
854 // `Object.getOwnPropertyDescriptor` method
855 // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
856 getOwnPropertyDescriptor: $getOwnPropertyDescriptor
857});
858$({
859 target: 'Object',
860 stat: true,
861 forced: !NATIVE_SYMBOL
862}, {
863 // `Object.getOwnPropertyNames` method
864 // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
865 getOwnPropertyNames: $getOwnPropertyNames,
866 // `Object.getOwnPropertySymbols` method
867 // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
868 getOwnPropertySymbols: $getOwnPropertySymbols
869}); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
870// https://bugs.chromium.org/p/v8/issues/detail?id=3443
871
872$({
873 target: 'Object',
874 stat: true,
875 forced: fails(function () {
876 getOwnPropertySymbolsModule.f(1);
877 })
878}, {
879 getOwnPropertySymbols: function getOwnPropertySymbols(it) {
880 return getOwnPropertySymbolsModule.f(toObject(it));
881 }
882}); // `JSON.stringify` method behavior with symbols
883// https://tc39.github.io/ecma262/#sec-json.stringify
884
885if ($stringify) {
886 var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () {
887 var symbol = $Symbol(); // MS Edge converts symbol values to JSON as {}
888
889 return $stringify([symbol]) != '[null]' // WebKit converts symbol values to JSON as null
890 || $stringify({
891 a: symbol
892 }) != '{}' // V8 throws on boxed symbols
893 || $stringify(Object(symbol)) != '{}';
894 });
895 $({
896 target: 'JSON',
897 stat: true,
898 forced: FORCED_JSON_STRINGIFY
899 }, {
900 // eslint-disable-next-line no-unused-vars
901 stringify: function stringify(it, replacer, space) {
902 var args = [it];
903 var index = 1;
904 var $replacer;
905
906 while (arguments.length > index) args.push(arguments[index++]);
907
908 $replacer = replacer;
909 if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
910
911 if (!isArray(replacer)) replacer = function replacer(key, value) {
912 if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
913 if (!isSymbol(value)) return value;
914 };
915 args[1] = replacer;
916 return $stringify.apply(null, args);
917 }
918 });
919} // `Symbol.prototype[@@toPrimitive]` method
920// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
921
922
923if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {
924 createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
925} // `Symbol.prototype[@@toStringTag]` property
926// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
927
928
929setToStringTag($Symbol, SYMBOL);
930hiddenKeys[HIDDEN] = true;
931
932/***/ }),
933/* 4 */
934/***/ (function(module, exports, __webpack_require__) {
935
936var global = __webpack_require__(5);
937
938var getOwnPropertyDescriptor = __webpack_require__(6).f;
939
940var createNonEnumerableProperty = __webpack_require__(20);
941
942var redefine = __webpack_require__(23);
943
944var setGlobal = __webpack_require__(24);
945
946var copyConstructorProperties = __webpack_require__(34);
947
948var isForced = __webpack_require__(46);
949/*
950 options.target - name of the target object
951 options.global - target is the global object
952 options.stat - export as static methods of target
953 options.proto - export as prototype methods of target
954 options.real - real prototype method for the `pure` version
955 options.forced - export even if the native feature is available
956 options.bind - bind methods to the target, required for the `pure` version
957 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
958 options.unsafe - use the simple assignment of property instead of delete + defineProperty
959 options.sham - add a flag to not completely full polyfills
960 options.enumerable - export as enumerable property
961 options.noTargetGet - prevent calling a getter on target
962*/
963
964
965module.exports = function (options, source) {
966 var TARGET = options.target;
967 var GLOBAL = options.global;
968 var STATIC = options.stat;
969 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
970
971 if (GLOBAL) {
972 target = global;
973 } else if (STATIC) {
974 target = global[TARGET] || setGlobal(TARGET, {});
975 } else {
976 target = (global[TARGET] || {}).prototype;
977 }
978
979 if (target) for (key in source) {
980 sourceProperty = source[key];
981
982 if (options.noTargetGet) {
983 descriptor = getOwnPropertyDescriptor(target, key);
984 targetProperty = descriptor && descriptor.value;
985 } else targetProperty = target[key];
986
987 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target
988
989 if (!FORCED && targetProperty !== undefined) {
990 if (typeof sourceProperty === typeof targetProperty) continue;
991 copyConstructorProperties(sourceProperty, targetProperty);
992 } // add a flag to not completely full polyfills
993
994
995 if (options.sham || targetProperty && targetProperty.sham) {
996 createNonEnumerableProperty(sourceProperty, 'sham', true);
997 } // extend global
998
999
1000 redefine(target, key, sourceProperty, options);
1001 }
1002};
1003
1004/***/ }),
1005/* 5 */
1006/***/ (function(module, exports) {
1007
1008var check = function check(it) {
1009 return it && it.Math == Math && it;
1010}; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
1011
1012
1013module.exports = // eslint-disable-next-line no-undef
1014check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || // eslint-disable-next-line no-new-func
1015Function('return this')();
1016
1017/***/ }),
1018/* 6 */
1019/***/ (function(module, exports, __webpack_require__) {
1020
1021var DESCRIPTORS = __webpack_require__(7);
1022
1023var propertyIsEnumerableModule = __webpack_require__(9);
1024
1025var createPropertyDescriptor = __webpack_require__(10);
1026
1027var toIndexedObject = __webpack_require__(11);
1028
1029var toPrimitive = __webpack_require__(15);
1030
1031var has = __webpack_require__(17);
1032
1033var IE8_DOM_DEFINE = __webpack_require__(18);
1034
1035var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method
1036// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
1037
1038exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
1039 O = toIndexedObject(O);
1040 P = toPrimitive(P, true);
1041 if (IE8_DOM_DEFINE) try {
1042 return nativeGetOwnPropertyDescriptor(O, P);
1043 } catch (error) {
1044 /* empty */
1045 }
1046 if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
1047};
1048
1049/***/ }),
1050/* 7 */
1051/***/ (function(module, exports, __webpack_require__) {
1052
1053var fails = __webpack_require__(8); // Thank's IE8 for his funny defineProperty
1054
1055
1056module.exports = !fails(function () {
1057 return Object.defineProperty({}, 1, {
1058 get: function get() {
1059 return 7;
1060 }
1061 })[1] != 7;
1062});
1063
1064/***/ }),
1065/* 8 */
1066/***/ (function(module, exports) {
1067
1068module.exports = function (exec) {
1069 try {
1070 return !!exec();
1071 } catch (error) {
1072 return true;
1073 }
1074};
1075
1076/***/ }),
1077/* 9 */
1078/***/ (function(module, exports, __webpack_require__) {
1079
1080"use strict";
1081
1082
1083var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
1084var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug
1085
1086var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({
1087 1: 2
1088}, 1); // `Object.prototype.propertyIsEnumerable` method implementation
1089// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
1090
1091exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
1092 var descriptor = getOwnPropertyDescriptor(this, V);
1093 return !!descriptor && descriptor.enumerable;
1094} : nativePropertyIsEnumerable;
1095
1096/***/ }),
1097/* 10 */
1098/***/ (function(module, exports) {
1099
1100module.exports = function (bitmap, value) {
1101 return {
1102 enumerable: !(bitmap & 1),
1103 configurable: !(bitmap & 2),
1104 writable: !(bitmap & 4),
1105 value: value
1106 };
1107};
1108
1109/***/ }),
1110/* 11 */
1111/***/ (function(module, exports, __webpack_require__) {
1112
1113// toObject with fallback for non-array-like ES3 strings
1114var IndexedObject = __webpack_require__(12);
1115
1116var requireObjectCoercible = __webpack_require__(14);
1117
1118module.exports = function (it) {
1119 return IndexedObject(requireObjectCoercible(it));
1120};
1121
1122/***/ }),
1123/* 12 */
1124/***/ (function(module, exports, __webpack_require__) {
1125
1126var fails = __webpack_require__(8);
1127
1128var classof = __webpack_require__(13);
1129
1130var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings
1131
1132module.exports = fails(function () {
1133 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
1134 // eslint-disable-next-line no-prototype-builtins
1135 return !Object('z').propertyIsEnumerable(0);
1136}) ? function (it) {
1137 return classof(it) == 'String' ? split.call(it, '') : Object(it);
1138} : Object;
1139
1140/***/ }),
1141/* 13 */
1142/***/ (function(module, exports) {
1143
1144var toString = {}.toString;
1145
1146module.exports = function (it) {
1147 return toString.call(it).slice(8, -1);
1148};
1149
1150/***/ }),
1151/* 14 */
1152/***/ (function(module, exports) {
1153
1154// `RequireObjectCoercible` abstract operation
1155// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
1156module.exports = function (it) {
1157 if (it == undefined) throw TypeError("Can't call method on " + it);
1158 return it;
1159};
1160
1161/***/ }),
1162/* 15 */
1163/***/ (function(module, exports, __webpack_require__) {
1164
1165var isObject = __webpack_require__(16); // `ToPrimitive` abstract operation
1166// https://tc39.github.io/ecma262/#sec-toprimitive
1167// instead of the ES6 spec version, we didn't implement @@toPrimitive case
1168// and the second argument - flag - preferred type is a string
1169
1170
1171module.exports = function (input, PREFERRED_STRING) {
1172 if (!isObject(input)) return input;
1173 var fn, val;
1174 if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
1175 if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
1176 if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
1177 throw TypeError("Can't convert object to primitive value");
1178};
1179
1180/***/ }),
1181/* 16 */
1182/***/ (function(module, exports) {
1183
1184module.exports = function (it) {
1185 return typeof it === 'object' ? it !== null : typeof it === 'function';
1186};
1187
1188/***/ }),
1189/* 17 */
1190/***/ (function(module, exports) {
1191
1192var hasOwnProperty = {}.hasOwnProperty;
1193
1194module.exports = function (it, key) {
1195 return hasOwnProperty.call(it, key);
1196};
1197
1198/***/ }),
1199/* 18 */
1200/***/ (function(module, exports, __webpack_require__) {
1201
1202var DESCRIPTORS = __webpack_require__(7);
1203
1204var fails = __webpack_require__(8);
1205
1206var createElement = __webpack_require__(19); // Thank's IE8 for his funny defineProperty
1207
1208
1209module.exports = !DESCRIPTORS && !fails(function () {
1210 return Object.defineProperty(createElement('div'), 'a', {
1211 get: function get() {
1212 return 7;
1213 }
1214 }).a != 7;
1215});
1216
1217/***/ }),
1218/* 19 */
1219/***/ (function(module, exports, __webpack_require__) {
1220
1221var global = __webpack_require__(5);
1222
1223var isObject = __webpack_require__(16);
1224
1225var document = global.document; // typeof document.createElement is 'object' in old IE
1226
1227var EXISTS = isObject(document) && isObject(document.createElement);
1228
1229module.exports = function (it) {
1230 return EXISTS ? document.createElement(it) : {};
1231};
1232
1233/***/ }),
1234/* 20 */
1235/***/ (function(module, exports, __webpack_require__) {
1236
1237var DESCRIPTORS = __webpack_require__(7);
1238
1239var definePropertyModule = __webpack_require__(21);
1240
1241var createPropertyDescriptor = __webpack_require__(10);
1242
1243module.exports = DESCRIPTORS ? function (object, key, value) {
1244 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
1245} : function (object, key, value) {
1246 object[key] = value;
1247 return object;
1248};
1249
1250/***/ }),
1251/* 21 */
1252/***/ (function(module, exports, __webpack_require__) {
1253
1254var DESCRIPTORS = __webpack_require__(7);
1255
1256var IE8_DOM_DEFINE = __webpack_require__(18);
1257
1258var anObject = __webpack_require__(22);
1259
1260var toPrimitive = __webpack_require__(15);
1261
1262var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method
1263// https://tc39.github.io/ecma262/#sec-object.defineproperty
1264
1265exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
1266 anObject(O);
1267 P = toPrimitive(P, true);
1268 anObject(Attributes);
1269 if (IE8_DOM_DEFINE) try {
1270 return nativeDefineProperty(O, P, Attributes);
1271 } catch (error) {
1272 /* empty */
1273 }
1274 if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
1275 if ('value' in Attributes) O[P] = Attributes.value;
1276 return O;
1277};
1278
1279/***/ }),
1280/* 22 */
1281/***/ (function(module, exports, __webpack_require__) {
1282
1283var isObject = __webpack_require__(16);
1284
1285module.exports = function (it) {
1286 if (!isObject(it)) {
1287 throw TypeError(String(it) + ' is not an object');
1288 }
1289
1290 return it;
1291};
1292
1293/***/ }),
1294/* 23 */
1295/***/ (function(module, exports, __webpack_require__) {
1296
1297var global = __webpack_require__(5);
1298
1299var createNonEnumerableProperty = __webpack_require__(20);
1300
1301var has = __webpack_require__(17);
1302
1303var setGlobal = __webpack_require__(24);
1304
1305var inspectSource = __webpack_require__(25);
1306
1307var InternalStateModule = __webpack_require__(27);
1308
1309var getInternalState = InternalStateModule.get;
1310var enforceInternalState = InternalStateModule.enforce;
1311var TEMPLATE = String(String).split('String');
1312(module.exports = function (O, key, value, options) {
1313 var unsafe = options ? !!options.unsafe : false;
1314 var simple = options ? !!options.enumerable : false;
1315 var noTargetGet = options ? !!options.noTargetGet : false;
1316
1317 if (typeof value == 'function') {
1318 if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
1319 enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
1320 }
1321
1322 if (O === global) {
1323 if (simple) O[key] = value;else setGlobal(key, value);
1324 return;
1325 } else if (!unsafe) {
1326 delete O[key];
1327 } else if (!noTargetGet && O[key]) {
1328 simple = true;
1329 }
1330
1331 if (simple) O[key] = value;else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
1332})(Function.prototype, 'toString', function toString() {
1333 return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
1334});
1335
1336/***/ }),
1337/* 24 */
1338/***/ (function(module, exports, __webpack_require__) {
1339
1340var global = __webpack_require__(5);
1341
1342var createNonEnumerableProperty = __webpack_require__(20);
1343
1344module.exports = function (key, value) {
1345 try {
1346 createNonEnumerableProperty(global, key, value);
1347 } catch (error) {
1348 global[key] = value;
1349 }
1350
1351 return value;
1352};
1353
1354/***/ }),
1355/* 25 */
1356/***/ (function(module, exports, __webpack_require__) {
1357
1358var store = __webpack_require__(26);
1359
1360var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
1361
1362if (typeof store.inspectSource != 'function') {
1363 store.inspectSource = function (it) {
1364 return functionToString.call(it);
1365 };
1366}
1367
1368module.exports = store.inspectSource;
1369
1370/***/ }),
1371/* 26 */
1372/***/ (function(module, exports, __webpack_require__) {
1373
1374var global = __webpack_require__(5);
1375
1376var setGlobal = __webpack_require__(24);
1377
1378var SHARED = '__core-js_shared__';
1379var store = global[SHARED] || setGlobal(SHARED, {});
1380module.exports = store;
1381
1382/***/ }),
1383/* 27 */
1384/***/ (function(module, exports, __webpack_require__) {
1385
1386var NATIVE_WEAK_MAP = __webpack_require__(28);
1387
1388var global = __webpack_require__(5);
1389
1390var isObject = __webpack_require__(16);
1391
1392var createNonEnumerableProperty = __webpack_require__(20);
1393
1394var objectHas = __webpack_require__(17);
1395
1396var sharedKey = __webpack_require__(29);
1397
1398var hiddenKeys = __webpack_require__(33);
1399
1400var WeakMap = global.WeakMap;
1401var set, get, has;
1402
1403var enforce = function enforce(it) {
1404 return has(it) ? get(it) : set(it, {});
1405};
1406
1407var getterFor = function getterFor(TYPE) {
1408 return function (it) {
1409 var state;
1410
1411 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1412 throw TypeError('Incompatible receiver, ' + TYPE + ' required');
1413 }
1414
1415 return state;
1416 };
1417};
1418
1419if (NATIVE_WEAK_MAP) {
1420 var store = new WeakMap();
1421 var wmget = store.get;
1422 var wmhas = store.has;
1423 var wmset = store.set;
1424
1425 set = function set(it, metadata) {
1426 wmset.call(store, it, metadata);
1427 return metadata;
1428 };
1429
1430 get = function get(it) {
1431 return wmget.call(store, it) || {};
1432 };
1433
1434 has = function has(it) {
1435 return wmhas.call(store, it);
1436 };
1437} else {
1438 var STATE = sharedKey('state');
1439 hiddenKeys[STATE] = true;
1440
1441 set = function set(it, metadata) {
1442 createNonEnumerableProperty(it, STATE, metadata);
1443 return metadata;
1444 };
1445
1446 get = function get(it) {
1447 return objectHas(it, STATE) ? it[STATE] : {};
1448 };
1449
1450 has = function has(it) {
1451 return objectHas(it, STATE);
1452 };
1453}
1454
1455module.exports = {
1456 set: set,
1457 get: get,
1458 has: has,
1459 enforce: enforce,
1460 getterFor: getterFor
1461};
1462
1463/***/ }),
1464/* 28 */
1465/***/ (function(module, exports, __webpack_require__) {
1466
1467var global = __webpack_require__(5);
1468
1469var inspectSource = __webpack_require__(25);
1470
1471var WeakMap = global.WeakMap;
1472module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
1473
1474/***/ }),
1475/* 29 */
1476/***/ (function(module, exports, __webpack_require__) {
1477
1478var shared = __webpack_require__(30);
1479
1480var uid = __webpack_require__(32);
1481
1482var keys = shared('keys');
1483
1484module.exports = function (key) {
1485 return keys[key] || (keys[key] = uid(key));
1486};
1487
1488/***/ }),
1489/* 30 */
1490/***/ (function(module, exports, __webpack_require__) {
1491
1492var IS_PURE = __webpack_require__(31);
1493
1494var store = __webpack_require__(26);
1495
1496(module.exports = function (key, value) {
1497 return store[key] || (store[key] = value !== undefined ? value : {});
1498})('versions', []).push({
56c4a2cb 1499 version: '3.6.5',
eb39fafa
DC
1500 mode: IS_PURE ? 'pure' : 'global',
1501 copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
1502});
1503
1504/***/ }),
1505/* 31 */
1506/***/ (function(module, exports) {
1507
1508module.exports = false;
1509
1510/***/ }),
1511/* 32 */
1512/***/ (function(module, exports) {
1513
1514var id = 0;
1515var postfix = Math.random();
1516
1517module.exports = function (key) {
1518 return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
1519};
1520
1521/***/ }),
1522/* 33 */
1523/***/ (function(module, exports) {
1524
1525module.exports = {};
1526
1527/***/ }),
1528/* 34 */
1529/***/ (function(module, exports, __webpack_require__) {
1530
1531var has = __webpack_require__(17);
1532
1533var ownKeys = __webpack_require__(35);
1534
1535var getOwnPropertyDescriptorModule = __webpack_require__(6);
1536
1537var definePropertyModule = __webpack_require__(21);
1538
1539module.exports = function (target, source) {
1540 var keys = ownKeys(source);
1541 var defineProperty = definePropertyModule.f;
1542 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
1543
1544 for (var i = 0; i < keys.length; i++) {
1545 var key = keys[i];
1546 if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
1547 }
1548};
1549
1550/***/ }),
1551/* 35 */
1552/***/ (function(module, exports, __webpack_require__) {
1553
1554var getBuiltIn = __webpack_require__(36);
1555
1556var getOwnPropertyNamesModule = __webpack_require__(38);
1557
1558var getOwnPropertySymbolsModule = __webpack_require__(45);
1559
1560var anObject = __webpack_require__(22); // all object keys, includes non-enumerable and symbols
1561
1562
1563module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
1564 var keys = getOwnPropertyNamesModule.f(anObject(it));
1565 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
1566 return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
1567};
1568
1569/***/ }),
1570/* 36 */
1571/***/ (function(module, exports, __webpack_require__) {
1572
1573var path = __webpack_require__(37);
1574
1575var global = __webpack_require__(5);
1576
1577var aFunction = function aFunction(variable) {
1578 return typeof variable == 'function' ? variable : undefined;
1579};
1580
1581module.exports = function (namespace, method) {
1582 return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace]) : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
1583};
1584
1585/***/ }),
1586/* 37 */
1587/***/ (function(module, exports, __webpack_require__) {
1588
1589var global = __webpack_require__(5);
1590
1591module.exports = global;
1592
1593/***/ }),
1594/* 38 */
1595/***/ (function(module, exports, __webpack_require__) {
1596
1597var internalObjectKeys = __webpack_require__(39);
1598
1599var enumBugKeys = __webpack_require__(44);
1600
1601var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method
1602// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
1603
1604exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
1605 return internalObjectKeys(O, hiddenKeys);
1606};
1607
1608/***/ }),
1609/* 39 */
1610/***/ (function(module, exports, __webpack_require__) {
1611
1612var has = __webpack_require__(17);
1613
1614var toIndexedObject = __webpack_require__(11);
1615
1616var indexOf = __webpack_require__(40).indexOf;
1617
1618var hiddenKeys = __webpack_require__(33);
1619
1620module.exports = function (object, names) {
1621 var O = toIndexedObject(object);
1622 var i = 0;
1623 var result = [];
1624 var key;
1625
1626 for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys
1627
1628
1629 while (names.length > i) if (has(O, key = names[i++])) {
1630 ~indexOf(result, key) || result.push(key);
1631 }
1632
1633 return result;
1634};
1635
1636/***/ }),
1637/* 40 */
1638/***/ (function(module, exports, __webpack_require__) {
1639
1640var toIndexedObject = __webpack_require__(11);
1641
1642var toLength = __webpack_require__(41);
1643
1644var toAbsoluteIndex = __webpack_require__(43); // `Array.prototype.{ indexOf, includes }` methods implementation
1645
1646
1647var createMethod = function createMethod(IS_INCLUDES) {
1648 return function ($this, el, fromIndex) {
1649 var O = toIndexedObject($this);
1650 var length = toLength(O.length);
1651 var index = toAbsoluteIndex(fromIndex, length);
1652 var value; // Array#includes uses SameValueZero equality algorithm
1653 // eslint-disable-next-line no-self-compare
1654
1655 if (IS_INCLUDES && el != el) while (length > index) {
1656 value = O[index++]; // eslint-disable-next-line no-self-compare
1657
1658 if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not
1659 } else for (; length > index; index++) {
1660 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
1661 }
1662 return !IS_INCLUDES && -1;
1663 };
1664};
1665
1666module.exports = {
1667 // `Array.prototype.includes` method
1668 // https://tc39.github.io/ecma262/#sec-array.prototype.includes
1669 includes: createMethod(true),
1670 // `Array.prototype.indexOf` method
1671 // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
1672 indexOf: createMethod(false)
1673};
1674
1675/***/ }),
1676/* 41 */
1677/***/ (function(module, exports, __webpack_require__) {
1678
1679var toInteger = __webpack_require__(42);
1680
1681var min = Math.min; // `ToLength` abstract operation
1682// https://tc39.github.io/ecma262/#sec-tolength
1683
1684module.exports = function (argument) {
1685 return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
1686};
1687
1688/***/ }),
1689/* 42 */
1690/***/ (function(module, exports) {
1691
1692var ceil = Math.ceil;
1693var floor = Math.floor; // `ToInteger` abstract operation
1694// https://tc39.github.io/ecma262/#sec-tointeger
1695
1696module.exports = function (argument) {
1697 return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
1698};
1699
1700/***/ }),
1701/* 43 */
1702/***/ (function(module, exports, __webpack_require__) {
1703
1704var toInteger = __webpack_require__(42);
1705
1706var max = Math.max;
1707var min = Math.min; // Helper for a popular repeating case of the spec:
1708// Let integer be ? ToInteger(index).
1709// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
1710
1711module.exports = function (index, length) {
1712 var integer = toInteger(index);
1713 return integer < 0 ? max(integer + length, 0) : min(integer, length);
1714};
1715
1716/***/ }),
1717/* 44 */
1718/***/ (function(module, exports) {
1719
1720// IE8- don't enum bug keys
1721module.exports = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
1722
1723/***/ }),
1724/* 45 */
1725/***/ (function(module, exports) {
1726
1727exports.f = Object.getOwnPropertySymbols;
1728
1729/***/ }),
1730/* 46 */
1731/***/ (function(module, exports, __webpack_require__) {
1732
1733var fails = __webpack_require__(8);
1734
1735var replacement = /#|\.prototype\./;
1736
1737var isForced = function isForced(feature, detection) {
1738 var value = data[normalize(feature)];
1739 return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection;
1740};
1741
1742var normalize = isForced.normalize = function (string) {
1743 return String(string).replace(replacement, '.').toLowerCase();
1744};
1745
1746var data = isForced.data = {};
1747var NATIVE = isForced.NATIVE = 'N';
1748var POLYFILL = isForced.POLYFILL = 'P';
1749module.exports = isForced;
1750
1751/***/ }),
1752/* 47 */
1753/***/ (function(module, exports, __webpack_require__) {
1754
1755var fails = __webpack_require__(8);
1756
1757module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
1758 // Chrome 38 Symbol has incorrect toString conversion
1759 // eslint-disable-next-line no-undef
1760 return !String(Symbol());
1761});
1762
1763/***/ }),
1764/* 48 */
1765/***/ (function(module, exports, __webpack_require__) {
1766
1767var NATIVE_SYMBOL = __webpack_require__(47);
1768
1769module.exports = NATIVE_SYMBOL // eslint-disable-next-line no-undef
1770&& !Symbol.sham // eslint-disable-next-line no-undef
1771&& typeof Symbol.iterator == 'symbol';
1772
1773/***/ }),
1774/* 49 */
1775/***/ (function(module, exports, __webpack_require__) {
1776
1777var classof = __webpack_require__(13); // `IsArray` abstract operation
1778// https://tc39.github.io/ecma262/#sec-isarray
1779
1780
1781module.exports = Array.isArray || function isArray(arg) {
1782 return classof(arg) == 'Array';
1783};
1784
1785/***/ }),
1786/* 50 */
1787/***/ (function(module, exports, __webpack_require__) {
1788
1789var requireObjectCoercible = __webpack_require__(14); // `ToObject` abstract operation
1790// https://tc39.github.io/ecma262/#sec-toobject
1791
1792
1793module.exports = function (argument) {
1794 return Object(requireObjectCoercible(argument));
1795};
1796
1797/***/ }),
1798/* 51 */
1799/***/ (function(module, exports, __webpack_require__) {
1800
1801var anObject = __webpack_require__(22);
1802
1803var defineProperties = __webpack_require__(52);
1804
1805var enumBugKeys = __webpack_require__(44);
1806
1807var hiddenKeys = __webpack_require__(33);
1808
1809var html = __webpack_require__(54);
1810
1811var documentCreateElement = __webpack_require__(19);
1812
1813var sharedKey = __webpack_require__(29);
1814
1815var GT = '>';
1816var LT = '<';
1817var PROTOTYPE = 'prototype';
1818var SCRIPT = 'script';
1819var IE_PROTO = sharedKey('IE_PROTO');
1820
1821var EmptyConstructor = function EmptyConstructor() {
1822 /* empty */
1823};
1824
1825var scriptTag = function scriptTag(content) {
1826 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
1827}; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
1828
1829
1830var NullProtoObjectViaActiveX = function NullProtoObjectViaActiveX(activeXDocument) {
1831 activeXDocument.write(scriptTag(''));
1832 activeXDocument.close();
1833 var temp = activeXDocument.parentWindow.Object;
1834 activeXDocument = null; // avoid memory leak
1835
1836 return temp;
1837}; // Create object with fake `null` prototype: use iframe Object with cleared prototype
1838
1839
1840var NullProtoObjectViaIFrame = function NullProtoObjectViaIFrame() {
1841 // Thrash, waste and sodomy: IE GC bug
1842 var iframe = documentCreateElement('iframe');
1843 var JS = 'java' + SCRIPT + ':';
1844 var iframeDocument;
1845 iframe.style.display = 'none';
1846 html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475
1847
1848 iframe.src = String(JS);
1849 iframeDocument = iframe.contentWindow.document;
1850 iframeDocument.open();
1851 iframeDocument.write(scriptTag('document.F=Object'));
1852 iframeDocument.close();
1853 return iframeDocument.F;
1854}; // Check for document.domain and active x support
1855// No need to use active x approach when document.domain is not set
1856// see https://github.com/es-shims/es5-shim/issues/150
1857// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
1858// avoid IE GC bug
1859
1860
1861var activeXDocument;
1862
1863var _NullProtoObject = function NullProtoObject() {
1864 try {
1865 /* global ActiveXObject */
1866 activeXDocument = document.domain && new ActiveXObject('htmlfile');
1867 } catch (error) {
1868 /* ignore */
1869 }
1870
1871 _NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();
1872 var length = enumBugKeys.length;
1873
1874 while (length--) delete _NullProtoObject[PROTOTYPE][enumBugKeys[length]];
1875
1876 return _NullProtoObject();
1877};
1878
1879hiddenKeys[IE_PROTO] = true; // `Object.create` method
1880// https://tc39.github.io/ecma262/#sec-object.create
1881
1882module.exports = Object.create || function create(O, Properties) {
1883 var result;
1884
1885 if (O !== null) {
1886 EmptyConstructor[PROTOTYPE] = anObject(O);
1887 result = new EmptyConstructor();
1888 EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill
1889
1890 result[IE_PROTO] = O;
1891 } else result = _NullProtoObject();
1892
1893 return Properties === undefined ? result : defineProperties(result, Properties);
1894};
1895
1896/***/ }),
1897/* 52 */
1898/***/ (function(module, exports, __webpack_require__) {
1899
1900var DESCRIPTORS = __webpack_require__(7);
1901
1902var definePropertyModule = __webpack_require__(21);
1903
1904var anObject = __webpack_require__(22);
1905
1906var objectKeys = __webpack_require__(53); // `Object.defineProperties` method
1907// https://tc39.github.io/ecma262/#sec-object.defineproperties
1908
1909
1910module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
1911 anObject(O);
1912 var keys = objectKeys(Properties);
1913 var length = keys.length;
1914 var index = 0;
1915 var key;
1916
1917 while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);
1918
1919 return O;
1920};
1921
1922/***/ }),
1923/* 53 */
1924/***/ (function(module, exports, __webpack_require__) {
1925
1926var internalObjectKeys = __webpack_require__(39);
1927
1928var enumBugKeys = __webpack_require__(44); // `Object.keys` method
1929// https://tc39.github.io/ecma262/#sec-object.keys
1930
1931
1932module.exports = Object.keys || function keys(O) {
1933 return internalObjectKeys(O, enumBugKeys);
1934};
1935
1936/***/ }),
1937/* 54 */
1938/***/ (function(module, exports, __webpack_require__) {
1939
1940var getBuiltIn = __webpack_require__(36);
1941
1942module.exports = getBuiltIn('document', 'documentElement');
1943
1944/***/ }),
1945/* 55 */
1946/***/ (function(module, exports, __webpack_require__) {
1947
1948var toIndexedObject = __webpack_require__(11);
1949
1950var nativeGetOwnPropertyNames = __webpack_require__(38).f;
1951
1952var toString = {}.toString;
1953var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [];
1954
1955var getWindowNames = function getWindowNames(it) {
1956 try {
1957 return nativeGetOwnPropertyNames(it);
1958 } catch (error) {
1959 return windowNames.slice();
1960 }
1961}; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
1962
1963
1964module.exports.f = function getOwnPropertyNames(it) {
1965 return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : nativeGetOwnPropertyNames(toIndexedObject(it));
1966};
1967
1968/***/ }),
1969/* 56 */
1970/***/ (function(module, exports, __webpack_require__) {
1971
1972var global = __webpack_require__(5);
1973
1974var shared = __webpack_require__(30);
1975
1976var has = __webpack_require__(17);
1977
1978var uid = __webpack_require__(32);
1979
1980var NATIVE_SYMBOL = __webpack_require__(47);
1981
1982var USE_SYMBOL_AS_UID = __webpack_require__(48);
1983
1984var WellKnownSymbolsStore = shared('wks');
1985var Symbol = global.Symbol;
1986var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;
1987
1988module.exports = function (name) {
1989 if (!has(WellKnownSymbolsStore, name)) {
1990 if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name];else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);
1991 }
1992
1993 return WellKnownSymbolsStore[name];
1994};
1995
1996/***/ }),
1997/* 57 */
1998/***/ (function(module, exports, __webpack_require__) {
1999
2000var wellKnownSymbol = __webpack_require__(56);
2001
2002exports.f = wellKnownSymbol;
2003
2004/***/ }),
2005/* 58 */
2006/***/ (function(module, exports, __webpack_require__) {
2007
2008var path = __webpack_require__(37);
2009
2010var has = __webpack_require__(17);
2011
2012var wrappedWellKnownSymbolModule = __webpack_require__(57);
2013
2014var defineProperty = __webpack_require__(21).f;
2015
2016module.exports = function (NAME) {
2017 var Symbol = path.Symbol || (path.Symbol = {});
2018 if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {
2019 value: wrappedWellKnownSymbolModule.f(NAME)
2020 });
2021};
2022
2023/***/ }),
2024/* 59 */
2025/***/ (function(module, exports, __webpack_require__) {
2026
2027var defineProperty = __webpack_require__(21).f;
2028
2029var has = __webpack_require__(17);
2030
2031var wellKnownSymbol = __webpack_require__(56);
2032
2033var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2034
2035module.exports = function (it, TAG, STATIC) {
2036 if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
2037 defineProperty(it, TO_STRING_TAG, {
2038 configurable: true,
2039 value: TAG
2040 });
2041 }
2042};
2043
2044/***/ }),
2045/* 60 */
2046/***/ (function(module, exports, __webpack_require__) {
2047
2048var bind = __webpack_require__(61);
2049
2050var IndexedObject = __webpack_require__(12);
2051
2052var toObject = __webpack_require__(50);
2053
2054var toLength = __webpack_require__(41);
2055
2056var arraySpeciesCreate = __webpack_require__(63);
2057
2058var push = [].push; // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
2059
2060var createMethod = function createMethod(TYPE) {
2061 var IS_MAP = TYPE == 1;
2062 var IS_FILTER = TYPE == 2;
2063 var IS_SOME = TYPE == 3;
2064 var IS_EVERY = TYPE == 4;
2065 var IS_FIND_INDEX = TYPE == 6;
2066 var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
2067 return function ($this, callbackfn, that, specificCreate) {
2068 var O = toObject($this);
2069 var self = IndexedObject(O);
2070 var boundFunction = bind(callbackfn, that, 3);
2071 var length = toLength(self.length);
2072 var index = 0;
2073 var create = specificCreate || arraySpeciesCreate;
2074 var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
2075 var value, result;
2076
2077 for (; length > index; index++) if (NO_HOLES || index in self) {
2078 value = self[index];
2079 result = boundFunction(value, index, O);
2080
2081 if (TYPE) {
2082 if (IS_MAP) target[index] = result; // map
2083 else if (result) switch (TYPE) {
2084 case 3:
2085 return true;
2086 // some
2087
2088 case 5:
2089 return value;
2090 // find
2091
2092 case 6:
2093 return index;
2094 // findIndex
2095
2096 case 2:
2097 push.call(target, value);
2098 // filter
2099 } else if (IS_EVERY) return false; // every
2100 }
2101 }
2102
2103 return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
2104 };
2105};
2106
2107module.exports = {
2108 // `Array.prototype.forEach` method
2109 // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
2110 forEach: createMethod(0),
2111 // `Array.prototype.map` method
2112 // https://tc39.github.io/ecma262/#sec-array.prototype.map
2113 map: createMethod(1),
2114 // `Array.prototype.filter` method
2115 // https://tc39.github.io/ecma262/#sec-array.prototype.filter
2116 filter: createMethod(2),
2117 // `Array.prototype.some` method
2118 // https://tc39.github.io/ecma262/#sec-array.prototype.some
2119 some: createMethod(3),
2120 // `Array.prototype.every` method
2121 // https://tc39.github.io/ecma262/#sec-array.prototype.every
2122 every: createMethod(4),
2123 // `Array.prototype.find` method
2124 // https://tc39.github.io/ecma262/#sec-array.prototype.find
2125 find: createMethod(5),
2126 // `Array.prototype.findIndex` method
2127 // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
2128 findIndex: createMethod(6)
2129};
2130
2131/***/ }),
2132/* 61 */
2133/***/ (function(module, exports, __webpack_require__) {
2134
2135var aFunction = __webpack_require__(62); // optional / simple context binding
2136
2137
2138module.exports = function (fn, that, length) {
2139 aFunction(fn);
2140 if (that === undefined) return fn;
2141
2142 switch (length) {
2143 case 0:
2144 return function () {
2145 return fn.call(that);
2146 };
2147
2148 case 1:
2149 return function (a) {
2150 return fn.call(that, a);
2151 };
2152
2153 case 2:
2154 return function (a, b) {
2155 return fn.call(that, a, b);
2156 };
2157
2158 case 3:
2159 return function (a, b, c) {
2160 return fn.call(that, a, b, c);
2161 };
2162 }
2163
2164 return function ()
2165 /* ...args */
2166 {
2167 return fn.apply(that, arguments);
2168 };
2169};
2170
2171/***/ }),
2172/* 62 */
2173/***/ (function(module, exports) {
2174
2175module.exports = function (it) {
2176 if (typeof it != 'function') {
2177 throw TypeError(String(it) + ' is not a function');
2178 }
2179
2180 return it;
2181};
2182
2183/***/ }),
2184/* 63 */
2185/***/ (function(module, exports, __webpack_require__) {
2186
2187var isObject = __webpack_require__(16);
2188
2189var isArray = __webpack_require__(49);
2190
2191var wellKnownSymbol = __webpack_require__(56);
2192
2193var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation
2194// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
2195
2196module.exports = function (originalArray, length) {
2197 var C;
2198
2199 if (isArray(originalArray)) {
2200 C = originalArray.constructor; // cross-realm fallback
2201
2202 if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;else if (isObject(C)) {
2203 C = C[SPECIES];
2204 if (C === null) C = undefined;
2205 }
2206 }
2207
2208 return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
2209};
2210
2211/***/ }),
2212/* 64 */
2213/***/ (function(module, exports, __webpack_require__) {
2214
2215var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.asyncIterator` well-known symbol
2216// https://tc39.github.io/ecma262/#sec-symbol.asynciterator
2217
2218
2219defineWellKnownSymbol('asyncIterator');
2220
2221/***/ }),
2222/* 65 */
2223/***/ (function(module, exports, __webpack_require__) {
2224
2225"use strict";
2226// `Symbol.prototype.description` getter
2227// https://tc39.github.io/ecma262/#sec-symbol.prototype.description
2228
2229
2230var $ = __webpack_require__(4);
2231
2232var DESCRIPTORS = __webpack_require__(7);
2233
2234var global = __webpack_require__(5);
2235
2236var has = __webpack_require__(17);
2237
2238var isObject = __webpack_require__(16);
2239
2240var defineProperty = __webpack_require__(21).f;
2241
2242var copyConstructorProperties = __webpack_require__(34);
2243
2244var NativeSymbol = global.Symbol;
2245
2246if (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || // Safari 12 bug
2247NativeSymbol().description !== undefined)) {
2248 var EmptyStringDescriptionStore = {}; // wrap Symbol constructor for correct work with undefined description
2249
2250 var SymbolWrapper = function Symbol() {
2251 var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
2252 var result = this instanceof SymbolWrapper ? new NativeSymbol(description) // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
2253 : description === undefined ? NativeSymbol() : NativeSymbol(description);
2254 if (description === '') EmptyStringDescriptionStore[result] = true;
2255 return result;
2256 };
2257
2258 copyConstructorProperties(SymbolWrapper, NativeSymbol);
2259 var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
2260 symbolPrototype.constructor = SymbolWrapper;
2261 var symbolToString = symbolPrototype.toString;
2262 var native = String(NativeSymbol('test')) == 'Symbol(test)';
2263 var regexp = /^Symbol\((.*)\)[^)]+$/;
2264 defineProperty(symbolPrototype, 'description', {
2265 configurable: true,
2266 get: function description() {
2267 var symbol = isObject(this) ? this.valueOf() : this;
2268 var string = symbolToString.call(symbol);
2269 if (has(EmptyStringDescriptionStore, symbol)) return '';
2270 var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');
2271 return desc === '' ? undefined : desc;
2272 }
2273 });
2274 $({
2275 global: true,
2276 forced: true
2277 }, {
2278 Symbol: SymbolWrapper
2279 });
2280}
2281
2282/***/ }),
2283/* 66 */
2284/***/ (function(module, exports, __webpack_require__) {
2285
2286var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.hasInstance` well-known symbol
2287// https://tc39.github.io/ecma262/#sec-symbol.hasinstance
2288
2289
2290defineWellKnownSymbol('hasInstance');
2291
2292/***/ }),
2293/* 67 */
2294/***/ (function(module, exports, __webpack_require__) {
2295
2296var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.isConcatSpreadable` well-known symbol
2297// https://tc39.github.io/ecma262/#sec-symbol.isconcatspreadable
2298
2299
2300defineWellKnownSymbol('isConcatSpreadable');
2301
2302/***/ }),
2303/* 68 */
2304/***/ (function(module, exports, __webpack_require__) {
2305
2306var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.iterator` well-known symbol
2307// https://tc39.github.io/ecma262/#sec-symbol.iterator
2308
2309
2310defineWellKnownSymbol('iterator');
2311
2312/***/ }),
2313/* 69 */
2314/***/ (function(module, exports, __webpack_require__) {
2315
2316var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.match` well-known symbol
2317// https://tc39.github.io/ecma262/#sec-symbol.match
2318
2319
2320defineWellKnownSymbol('match');
2321
2322/***/ }),
2323/* 70 */
2324/***/ (function(module, exports, __webpack_require__) {
2325
2326var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.matchAll` well-known symbol
2327
2328
2329defineWellKnownSymbol('matchAll');
2330
2331/***/ }),
2332/* 71 */
2333/***/ (function(module, exports, __webpack_require__) {
2334
2335var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.replace` well-known symbol
2336// https://tc39.github.io/ecma262/#sec-symbol.replace
2337
2338
2339defineWellKnownSymbol('replace');
2340
2341/***/ }),
2342/* 72 */
2343/***/ (function(module, exports, __webpack_require__) {
2344
2345var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.search` well-known symbol
2346// https://tc39.github.io/ecma262/#sec-symbol.search
2347
2348
2349defineWellKnownSymbol('search');
2350
2351/***/ }),
2352/* 73 */
2353/***/ (function(module, exports, __webpack_require__) {
2354
2355var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.species` well-known symbol
2356// https://tc39.github.io/ecma262/#sec-symbol.species
2357
2358
2359defineWellKnownSymbol('species');
2360
2361/***/ }),
2362/* 74 */
2363/***/ (function(module, exports, __webpack_require__) {
2364
2365var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.split` well-known symbol
2366// https://tc39.github.io/ecma262/#sec-symbol.split
2367
2368
2369defineWellKnownSymbol('split');
2370
2371/***/ }),
2372/* 75 */
2373/***/ (function(module, exports, __webpack_require__) {
2374
2375var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.toPrimitive` well-known symbol
2376// https://tc39.github.io/ecma262/#sec-symbol.toprimitive
2377
2378
2379defineWellKnownSymbol('toPrimitive');
2380
2381/***/ }),
2382/* 76 */
2383/***/ (function(module, exports, __webpack_require__) {
2384
2385var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.toStringTag` well-known symbol
2386// https://tc39.github.io/ecma262/#sec-symbol.tostringtag
2387
2388
2389defineWellKnownSymbol('toStringTag');
2390
2391/***/ }),
2392/* 77 */
2393/***/ (function(module, exports, __webpack_require__) {
2394
2395var defineWellKnownSymbol = __webpack_require__(58); // `Symbol.unscopables` well-known symbol
2396// https://tc39.github.io/ecma262/#sec-symbol.unscopables
2397
2398
2399defineWellKnownSymbol('unscopables');
2400
2401/***/ }),
2402/* 78 */
2403/***/ (function(module, exports, __webpack_require__) {
2404
2405var $ = __webpack_require__(4);
2406
2407var assign = __webpack_require__(79); // `Object.assign` method
2408// https://tc39.github.io/ecma262/#sec-object.assign
2409
2410
2411$({
2412 target: 'Object',
2413 stat: true,
2414 forced: Object.assign !== assign
2415}, {
2416 assign: assign
2417});
2418
2419/***/ }),
2420/* 79 */
2421/***/ (function(module, exports, __webpack_require__) {
2422
2423"use strict";
2424
2425
2426var DESCRIPTORS = __webpack_require__(7);
2427
2428var fails = __webpack_require__(8);
2429
2430var objectKeys = __webpack_require__(53);
2431
2432var getOwnPropertySymbolsModule = __webpack_require__(45);
2433
2434var propertyIsEnumerableModule = __webpack_require__(9);
2435
2436var toObject = __webpack_require__(50);
2437
2438var IndexedObject = __webpack_require__(12);
2439
2440var nativeAssign = Object.assign;
2441var defineProperty = Object.defineProperty; // `Object.assign` method
2442// https://tc39.github.io/ecma262/#sec-object.assign
2443
2444module.exports = !nativeAssign || fails(function () {
2445 // should have correct order of operations (Edge bug)
2446 if (DESCRIPTORS && nativeAssign({
2447 b: 1
2448 }, nativeAssign(defineProperty({}, 'a', {
2449 enumerable: true,
2450 get: function get() {
2451 defineProperty(this, 'b', {
2452 value: 3,
2453 enumerable: false
2454 });
2455 }
2456 }), {
2457 b: 2
2458 })).b !== 1) return true; // should work with symbols and should have deterministic property order (V8 bug)
2459
2460 var A = {};
2461 var B = {}; // eslint-disable-next-line no-undef
2462
2463 var symbol = Symbol();
2464 var alphabet = 'abcdefghijklmnopqrst';
2465 A[symbol] = 7;
2466 alphabet.split('').forEach(function (chr) {
2467 B[chr] = chr;
2468 });
2469 return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
2470}) ? function assign(target, source) {
2471 // eslint-disable-line no-unused-vars
2472 var T = toObject(target);
2473 var argumentsLength = arguments.length;
2474 var index = 1;
2475 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
2476 var propertyIsEnumerable = propertyIsEnumerableModule.f;
2477
2478 while (argumentsLength > index) {
2479 var S = IndexedObject(arguments[index++]);
2480 var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
2481 var length = keys.length;
2482 var j = 0;
2483 var key;
2484
2485 while (length > j) {
2486 key = keys[j++];
2487 if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
2488 }
2489 }
2490
2491 return T;
2492} : nativeAssign;
2493
2494/***/ }),
2495/* 80 */
2496/***/ (function(module, exports, __webpack_require__) {
2497
2498var $ = __webpack_require__(4);
2499
2500var DESCRIPTORS = __webpack_require__(7);
2501
2502var create = __webpack_require__(51); // `Object.create` method
2503// https://tc39.github.io/ecma262/#sec-object.create
2504
2505
2506$({
2507 target: 'Object',
2508 stat: true,
2509 sham: !DESCRIPTORS
2510}, {
2511 create: create
2512});
2513
2514/***/ }),
2515/* 81 */
2516/***/ (function(module, exports, __webpack_require__) {
2517
2518var $ = __webpack_require__(4);
2519
2520var DESCRIPTORS = __webpack_require__(7);
2521
2522var objectDefinePropertyModile = __webpack_require__(21); // `Object.defineProperty` method
2523// https://tc39.github.io/ecma262/#sec-object.defineproperty
2524
2525
2526$({
2527 target: 'Object',
2528 stat: true,
2529 forced: !DESCRIPTORS,
2530 sham: !DESCRIPTORS
2531}, {
2532 defineProperty: objectDefinePropertyModile.f
2533});
2534
2535/***/ }),
2536/* 82 */
2537/***/ (function(module, exports, __webpack_require__) {
2538
2539var $ = __webpack_require__(4);
2540
2541var DESCRIPTORS = __webpack_require__(7);
2542
2543var defineProperties = __webpack_require__(52); // `Object.defineProperties` method
2544// https://tc39.github.io/ecma262/#sec-object.defineproperties
2545
2546
2547$({
2548 target: 'Object',
2549 stat: true,
2550 forced: !DESCRIPTORS,
2551 sham: !DESCRIPTORS
2552}, {
2553 defineProperties: defineProperties
2554});
2555
2556/***/ }),
2557/* 83 */
2558/***/ (function(module, exports, __webpack_require__) {
2559
2560var $ = __webpack_require__(4);
2561
2562var $entries = __webpack_require__(84).entries; // `Object.entries` method
2563// https://tc39.github.io/ecma262/#sec-object.entries
2564
2565
2566$({
2567 target: 'Object',
2568 stat: true
2569}, {
2570 entries: function entries(O) {
2571 return $entries(O);
2572 }
2573});
2574
2575/***/ }),
2576/* 84 */
2577/***/ (function(module, exports, __webpack_require__) {
2578
2579var DESCRIPTORS = __webpack_require__(7);
2580
2581var objectKeys = __webpack_require__(53);
2582
2583var toIndexedObject = __webpack_require__(11);
2584
2585var propertyIsEnumerable = __webpack_require__(9).f; // `Object.{ entries, values }` methods implementation
2586
2587
2588var createMethod = function createMethod(TO_ENTRIES) {
2589 return function (it) {
2590 var O = toIndexedObject(it);
2591 var keys = objectKeys(O);
2592 var length = keys.length;
2593 var i = 0;
2594 var result = [];
2595 var key;
2596
2597 while (length > i) {
2598 key = keys[i++];
2599
2600 if (!DESCRIPTORS || propertyIsEnumerable.call(O, key)) {
2601 result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
2602 }
2603 }
2604
2605 return result;
2606 };
2607};
2608
2609module.exports = {
2610 // `Object.entries` method
2611 // https://tc39.github.io/ecma262/#sec-object.entries
2612 entries: createMethod(true),
2613 // `Object.values` method
2614 // https://tc39.github.io/ecma262/#sec-object.values
2615 values: createMethod(false)
2616};
2617
2618/***/ }),
2619/* 85 */
2620/***/ (function(module, exports, __webpack_require__) {
2621
2622var $ = __webpack_require__(4);
2623
2624var FREEZING = __webpack_require__(86);
2625
2626var fails = __webpack_require__(8);
2627
2628var isObject = __webpack_require__(16);
2629
2630var onFreeze = __webpack_require__(87).onFreeze;
2631
2632var nativeFreeze = Object.freeze;
2633var FAILS_ON_PRIMITIVES = fails(function () {
2634 nativeFreeze(1);
2635}); // `Object.freeze` method
2636// https://tc39.github.io/ecma262/#sec-object.freeze
2637
2638$({
2639 target: 'Object',
2640 stat: true,
2641 forced: FAILS_ON_PRIMITIVES,
2642 sham: !FREEZING
2643}, {
2644 freeze: function freeze(it) {
2645 return nativeFreeze && isObject(it) ? nativeFreeze(onFreeze(it)) : it;
2646 }
2647});
2648
2649/***/ }),
2650/* 86 */
2651/***/ (function(module, exports, __webpack_require__) {
2652
2653var fails = __webpack_require__(8);
2654
2655module.exports = !fails(function () {
2656 return Object.isExtensible(Object.preventExtensions({}));
2657});
2658
2659/***/ }),
2660/* 87 */
2661/***/ (function(module, exports, __webpack_require__) {
2662
2663var hiddenKeys = __webpack_require__(33);
2664
2665var isObject = __webpack_require__(16);
2666
2667var has = __webpack_require__(17);
2668
2669var defineProperty = __webpack_require__(21).f;
2670
2671var uid = __webpack_require__(32);
2672
2673var FREEZING = __webpack_require__(86);
2674
2675var METADATA = uid('meta');
2676var id = 0;
2677
2678var isExtensible = Object.isExtensible || function () {
2679 return true;
2680};
2681
2682var setMetadata = function setMetadata(it) {
2683 defineProperty(it, METADATA, {
2684 value: {
2685 objectID: 'O' + ++id,
2686 // object ID
2687 weakData: {} // weak collections IDs
2688
2689 }
2690 });
2691};
2692
2693var fastKey = function fastKey(it, create) {
2694 // return a primitive with prefix
2695 if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
2696
2697 if (!has(it, METADATA)) {
2698 // can't set metadata to uncaught frozen object
2699 if (!isExtensible(it)) return 'F'; // not necessary to add metadata
2700
2701 if (!create) return 'E'; // add missing metadata
2702
2703 setMetadata(it); // return object ID
2704 }
2705
2706 return it[METADATA].objectID;
2707};
2708
2709var getWeakData = function getWeakData(it, create) {
2710 if (!has(it, METADATA)) {
2711 // can't set metadata to uncaught frozen object
2712 if (!isExtensible(it)) return true; // not necessary to add metadata
2713
2714 if (!create) return false; // add missing metadata
2715
2716 setMetadata(it); // return the store of weak collections IDs
2717 }
2718
2719 return it[METADATA].weakData;
2720}; // add metadata on freeze-family methods calling
2721
2722
2723var onFreeze = function onFreeze(it) {
2724 if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it);
2725 return it;
2726};
2727
2728var meta = module.exports = {
2729 REQUIRED: false,
2730 fastKey: fastKey,
2731 getWeakData: getWeakData,
2732 onFreeze: onFreeze
2733};
2734hiddenKeys[METADATA] = true;
2735
2736/***/ }),
2737/* 88 */
2738/***/ (function(module, exports, __webpack_require__) {
2739
2740var $ = __webpack_require__(4);
2741
2742var iterate = __webpack_require__(89);
2743
2744var createProperty = __webpack_require__(96); // `Object.fromEntries` method
2745// https://github.com/tc39/proposal-object-from-entries
2746
2747
2748$({
2749 target: 'Object',
2750 stat: true
2751}, {
2752 fromEntries: function fromEntries(iterable) {
2753 var obj = {};
2754 iterate(iterable, function (k, v) {
2755 createProperty(obj, k, v);
2756 }, undefined, true);
2757 return obj;
2758 }
2759});
2760
2761/***/ }),
2762/* 89 */
2763/***/ (function(module, exports, __webpack_require__) {
2764
2765var anObject = __webpack_require__(22);
2766
2767var isArrayIteratorMethod = __webpack_require__(90);
2768
2769var toLength = __webpack_require__(41);
2770
2771var bind = __webpack_require__(61);
2772
2773var getIteratorMethod = __webpack_require__(92);
2774
2775var callWithSafeIterationClosing = __webpack_require__(95);
2776
2777var Result = function Result(stopped, result) {
2778 this.stopped = stopped;
2779 this.result = result;
2780};
2781
2782var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) {
2783 var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1);
2784 var iterator, iterFn, index, length, result, next, step;
2785
2786 if (IS_ITERATOR) {
2787 iterator = iterable;
2788 } else {
2789 iterFn = getIteratorMethod(iterable);
2790 if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); // optimisation for array iterators
2791
2792 if (isArrayIteratorMethod(iterFn)) {
2793 for (index = 0, length = toLength(iterable.length); length > index; index++) {
2794 result = AS_ENTRIES ? boundFunction(anObject(step = iterable[index])[0], step[1]) : boundFunction(iterable[index]);
2795 if (result && result instanceof Result) return result;
2796 }
2797
2798 return new Result(false);
2799 }
2800
2801 iterator = iterFn.call(iterable);
2802 }
2803
2804 next = iterator.next;
2805
2806 while (!(step = next.call(iterator)).done) {
2807 result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES);
2808 if (typeof result == 'object' && result && result instanceof Result) return result;
2809 }
2810
2811 return new Result(false);
2812};
2813
2814iterate.stop = function (result) {
2815 return new Result(true, result);
2816};
2817
2818/***/ }),
2819/* 90 */
2820/***/ (function(module, exports, __webpack_require__) {
2821
2822var wellKnownSymbol = __webpack_require__(56);
2823
2824var Iterators = __webpack_require__(91);
2825
2826var ITERATOR = wellKnownSymbol('iterator');
2827var ArrayPrototype = Array.prototype; // check on default Array iterator
2828
2829module.exports = function (it) {
2830 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
2831};
2832
2833/***/ }),
2834/* 91 */
2835/***/ (function(module, exports) {
2836
2837module.exports = {};
2838
2839/***/ }),
2840/* 92 */
2841/***/ (function(module, exports, __webpack_require__) {
2842
2843var classof = __webpack_require__(93);
2844
2845var Iterators = __webpack_require__(91);
2846
2847var wellKnownSymbol = __webpack_require__(56);
2848
2849var ITERATOR = wellKnownSymbol('iterator');
2850
2851module.exports = function (it) {
2852 if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)];
2853};
2854
2855/***/ }),
2856/* 93 */
2857/***/ (function(module, exports, __webpack_require__) {
2858
2859var TO_STRING_TAG_SUPPORT = __webpack_require__(94);
2860
2861var classofRaw = __webpack_require__(13);
2862
2863var wellKnownSymbol = __webpack_require__(56);
2864
2865var TO_STRING_TAG = wellKnownSymbol('toStringTag'); // ES3 wrong here
2866
2867var CORRECT_ARGUMENTS = classofRaw(function () {
2868 return arguments;
2869}()) == 'Arguments'; // fallback for IE11 Script Access Denied error
2870
2871var tryGet = function tryGet(it, key) {
2872 try {
2873 return it[key];
2874 } catch (error) {
2875 /* empty */
2876 }
2877}; // getting tag from ES6+ `Object.prototype.toString`
2878
2879
2880module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
2881 var O, tag, result;
2882 return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case
2883 : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case
2884 : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback
2885 : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
2886};
2887
2888/***/ }),
2889/* 94 */
2890/***/ (function(module, exports, __webpack_require__) {
2891
2892var wellKnownSymbol = __webpack_require__(56);
2893
2894var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2895var test = {};
2896test[TO_STRING_TAG] = 'z';
2897module.exports = String(test) === '[object z]';
2898
2899/***/ }),
2900/* 95 */
2901/***/ (function(module, exports, __webpack_require__) {
2902
2903var anObject = __webpack_require__(22); // call something on iterator step with safe closing on error
2904
2905
2906module.exports = function (iterator, fn, value, ENTRIES) {
2907 try {
2908 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion)
2909 } catch (error) {
2910 var returnMethod = iterator['return'];
2911 if (returnMethod !== undefined) anObject(returnMethod.call(iterator));
2912 throw error;
2913 }
2914};
2915
2916/***/ }),
2917/* 96 */
2918/***/ (function(module, exports, __webpack_require__) {
2919
2920"use strict";
2921
2922
2923var toPrimitive = __webpack_require__(15);
2924
2925var definePropertyModule = __webpack_require__(21);
2926
2927var createPropertyDescriptor = __webpack_require__(10);
2928
2929module.exports = function (object, key, value) {
2930 var propertyKey = toPrimitive(key);
2931 if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));else object[propertyKey] = value;
2932};
2933
2934/***/ }),
2935/* 97 */
2936/***/ (function(module, exports, __webpack_require__) {
2937
2938var $ = __webpack_require__(4);
2939
2940var fails = __webpack_require__(8);
2941
2942var toIndexedObject = __webpack_require__(11);
2943
2944var nativeGetOwnPropertyDescriptor = __webpack_require__(6).f;
2945
2946var DESCRIPTORS = __webpack_require__(7);
2947
2948var FAILS_ON_PRIMITIVES = fails(function () {
2949 nativeGetOwnPropertyDescriptor(1);
2950});
2951var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES; // `Object.getOwnPropertyDescriptor` method
2952// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
2953
2954$({
2955 target: 'Object',
2956 stat: true,
2957 forced: FORCED,
2958 sham: !DESCRIPTORS
2959}, {
2960 getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
2961 return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key);
2962 }
2963});
2964
2965/***/ }),
2966/* 98 */
2967/***/ (function(module, exports, __webpack_require__) {
2968
2969var $ = __webpack_require__(4);
2970
2971var DESCRIPTORS = __webpack_require__(7);
2972
2973var ownKeys = __webpack_require__(35);
2974
2975var toIndexedObject = __webpack_require__(11);
2976
2977var getOwnPropertyDescriptorModule = __webpack_require__(6);
2978
2979var createProperty = __webpack_require__(96); // `Object.getOwnPropertyDescriptors` method
2980// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
2981
2982
2983$({
2984 target: 'Object',
2985 stat: true,
2986 sham: !DESCRIPTORS
2987}, {
2988 getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
2989 var O = toIndexedObject(object);
2990 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
2991 var keys = ownKeys(O);
2992 var result = {};
2993 var index = 0;
2994 var key, descriptor;
2995
2996 while (keys.length > index) {
2997 descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
2998 if (descriptor !== undefined) createProperty(result, key, descriptor);
2999 }
3000
3001 return result;
3002 }
3003});
3004
3005/***/ }),
3006/* 99 */
3007/***/ (function(module, exports, __webpack_require__) {
3008
3009var $ = __webpack_require__(4);
3010
3011var fails = __webpack_require__(8);
3012
3013var nativeGetOwnPropertyNames = __webpack_require__(55).f;
3014
3015var FAILS_ON_PRIMITIVES = fails(function () {
3016 return !Object.getOwnPropertyNames(1);
3017}); // `Object.getOwnPropertyNames` method
3018// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
3019
3020$({
3021 target: 'Object',
3022 stat: true,
3023 forced: FAILS_ON_PRIMITIVES
3024}, {
3025 getOwnPropertyNames: nativeGetOwnPropertyNames
3026});
3027
3028/***/ }),
3029/* 100 */
3030/***/ (function(module, exports, __webpack_require__) {
3031
3032var $ = __webpack_require__(4);
3033
3034var fails = __webpack_require__(8);
3035
3036var toObject = __webpack_require__(50);
3037
3038var nativeGetPrototypeOf = __webpack_require__(101);
3039
3040var CORRECT_PROTOTYPE_GETTER = __webpack_require__(102);
3041
3042var FAILS_ON_PRIMITIVES = fails(function () {
3043 nativeGetPrototypeOf(1);
3044}); // `Object.getPrototypeOf` method
3045// https://tc39.github.io/ecma262/#sec-object.getprototypeof
3046
3047$({
3048 target: 'Object',
3049 stat: true,
3050 forced: FAILS_ON_PRIMITIVES,
3051 sham: !CORRECT_PROTOTYPE_GETTER
3052}, {
3053 getPrototypeOf: function getPrototypeOf(it) {
3054 return nativeGetPrototypeOf(toObject(it));
3055 }
3056});
3057
3058/***/ }),
3059/* 101 */
3060/***/ (function(module, exports, __webpack_require__) {
3061
3062var has = __webpack_require__(17);
3063
3064var toObject = __webpack_require__(50);
3065
3066var sharedKey = __webpack_require__(29);
3067
3068var CORRECT_PROTOTYPE_GETTER = __webpack_require__(102);
3069
3070var IE_PROTO = sharedKey('IE_PROTO');
3071var ObjectPrototype = Object.prototype; // `Object.getPrototypeOf` method
3072// https://tc39.github.io/ecma262/#sec-object.getprototypeof
3073
3074module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
3075 O = toObject(O);
3076 if (has(O, IE_PROTO)) return O[IE_PROTO];
3077
3078 if (typeof O.constructor == 'function' && O instanceof O.constructor) {
3079 return O.constructor.prototype;
3080 }
3081
3082 return O instanceof Object ? ObjectPrototype : null;
3083};
3084
3085/***/ }),
3086/* 102 */
3087/***/ (function(module, exports, __webpack_require__) {
3088
3089var fails = __webpack_require__(8);
3090
3091module.exports = !fails(function () {
3092 function F() {
3093 /* empty */
3094 }
3095
3096 F.prototype.constructor = null;
3097 return Object.getPrototypeOf(new F()) !== F.prototype;
3098});
3099
3100/***/ }),
3101/* 103 */
3102/***/ (function(module, exports, __webpack_require__) {
3103
3104var $ = __webpack_require__(4);
3105
3106var is = __webpack_require__(104); // `Object.is` method
3107// https://tc39.github.io/ecma262/#sec-object.is
3108
3109
3110$({
3111 target: 'Object',
3112 stat: true
3113}, {
3114 is: is
3115});
3116
3117/***/ }),
3118/* 104 */
3119/***/ (function(module, exports) {
3120
3121// `SameValue` abstract operation
3122// https://tc39.github.io/ecma262/#sec-samevalue
3123module.exports = Object.is || function is(x, y) {
3124 // eslint-disable-next-line no-self-compare
3125 return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
3126};
3127
3128/***/ }),
3129/* 105 */
3130/***/ (function(module, exports, __webpack_require__) {
3131
3132var $ = __webpack_require__(4);
3133
3134var fails = __webpack_require__(8);
3135
3136var isObject = __webpack_require__(16);
3137
3138var nativeIsExtensible = Object.isExtensible;
3139var FAILS_ON_PRIMITIVES = fails(function () {
3140 nativeIsExtensible(1);
3141}); // `Object.isExtensible` method
3142// https://tc39.github.io/ecma262/#sec-object.isextensible
3143
3144$({
3145 target: 'Object',
3146 stat: true,
3147 forced: FAILS_ON_PRIMITIVES
3148}, {
3149 isExtensible: function isExtensible(it) {
3150 return isObject(it) ? nativeIsExtensible ? nativeIsExtensible(it) : true : false;
3151 }
3152});
3153
3154/***/ }),
3155/* 106 */
3156/***/ (function(module, exports, __webpack_require__) {
3157
3158var $ = __webpack_require__(4);
3159
3160var fails = __webpack_require__(8);
3161
3162var isObject = __webpack_require__(16);
3163
3164var nativeIsFrozen = Object.isFrozen;
3165var FAILS_ON_PRIMITIVES = fails(function () {
3166 nativeIsFrozen(1);
3167}); // `Object.isFrozen` method
3168// https://tc39.github.io/ecma262/#sec-object.isfrozen
3169
3170$({
3171 target: 'Object',
3172 stat: true,
3173 forced: FAILS_ON_PRIMITIVES
3174}, {
3175 isFrozen: function isFrozen(it) {
3176 return isObject(it) ? nativeIsFrozen ? nativeIsFrozen(it) : false : true;
3177 }
3178});
3179
3180/***/ }),
3181/* 107 */
3182/***/ (function(module, exports, __webpack_require__) {
3183
3184var $ = __webpack_require__(4);
3185
3186var fails = __webpack_require__(8);
3187
3188var isObject = __webpack_require__(16);
3189
3190var nativeIsSealed = Object.isSealed;
3191var FAILS_ON_PRIMITIVES = fails(function () {
3192 nativeIsSealed(1);
3193}); // `Object.isSealed` method
3194// https://tc39.github.io/ecma262/#sec-object.issealed
3195
3196$({
3197 target: 'Object',
3198 stat: true,
3199 forced: FAILS_ON_PRIMITIVES
3200}, {
3201 isSealed: function isSealed(it) {
3202 return isObject(it) ? nativeIsSealed ? nativeIsSealed(it) : false : true;
3203 }
3204});
3205
3206/***/ }),
3207/* 108 */
3208/***/ (function(module, exports, __webpack_require__) {
3209
3210var $ = __webpack_require__(4);
3211
3212var toObject = __webpack_require__(50);
3213
3214var nativeKeys = __webpack_require__(53);
3215
3216var fails = __webpack_require__(8);
3217
3218var FAILS_ON_PRIMITIVES = fails(function () {
3219 nativeKeys(1);
3220}); // `Object.keys` method
3221// https://tc39.github.io/ecma262/#sec-object.keys
3222
3223$({
3224 target: 'Object',
3225 stat: true,
3226 forced: FAILS_ON_PRIMITIVES
3227}, {
3228 keys: function keys(it) {
3229 return nativeKeys(toObject(it));
3230 }
3231});
3232
3233/***/ }),
3234/* 109 */
3235/***/ (function(module, exports, __webpack_require__) {
3236
3237var $ = __webpack_require__(4);
3238
3239var isObject = __webpack_require__(16);
3240
3241var onFreeze = __webpack_require__(87).onFreeze;
3242
3243var FREEZING = __webpack_require__(86);
3244
3245var fails = __webpack_require__(8);
3246
3247var nativePreventExtensions = Object.preventExtensions;
3248var FAILS_ON_PRIMITIVES = fails(function () {
3249 nativePreventExtensions(1);
3250}); // `Object.preventExtensions` method
3251// https://tc39.github.io/ecma262/#sec-object.preventextensions
3252
3253$({
3254 target: 'Object',
3255 stat: true,
3256 forced: FAILS_ON_PRIMITIVES,
3257 sham: !FREEZING
3258}, {
3259 preventExtensions: function preventExtensions(it) {
3260 return nativePreventExtensions && isObject(it) ? nativePreventExtensions(onFreeze(it)) : it;
3261 }
3262});
3263
3264/***/ }),
3265/* 110 */
3266/***/ (function(module, exports, __webpack_require__) {
3267
3268var $ = __webpack_require__(4);
3269
3270var isObject = __webpack_require__(16);
3271
3272var onFreeze = __webpack_require__(87).onFreeze;
3273
3274var FREEZING = __webpack_require__(86);
3275
3276var fails = __webpack_require__(8);
3277
3278var nativeSeal = Object.seal;
3279var FAILS_ON_PRIMITIVES = fails(function () {
3280 nativeSeal(1);
3281}); // `Object.seal` method
3282// https://tc39.github.io/ecma262/#sec-object.seal
3283
3284$({
3285 target: 'Object',
3286 stat: true,
3287 forced: FAILS_ON_PRIMITIVES,
3288 sham: !FREEZING
3289}, {
3290 seal: function seal(it) {
3291 return nativeSeal && isObject(it) ? nativeSeal(onFreeze(it)) : it;
3292 }
3293});
3294
3295/***/ }),
3296/* 111 */
3297/***/ (function(module, exports, __webpack_require__) {
3298
3299var $ = __webpack_require__(4);
3300
3301var setPrototypeOf = __webpack_require__(112); // `Object.setPrototypeOf` method
3302// https://tc39.github.io/ecma262/#sec-object.setprototypeof
3303
3304
3305$({
3306 target: 'Object',
3307 stat: true
3308}, {
3309 setPrototypeOf: setPrototypeOf
3310});
3311
3312/***/ }),
3313/* 112 */
3314/***/ (function(module, exports, __webpack_require__) {
3315
3316var anObject = __webpack_require__(22);
3317
3318var aPossiblePrototype = __webpack_require__(113); // `Object.setPrototypeOf` method
3319// https://tc39.github.io/ecma262/#sec-object.setprototypeof
3320// Works with __proto__ only. Old v8 can't work with null proto objects.
3321
3322/* eslint-disable no-proto */
3323
3324
3325module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
3326 var CORRECT_SETTER = false;
3327 var test = {};
3328 var setter;
3329
3330 try {
3331 setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
3332 setter.call(test, []);
3333 CORRECT_SETTER = test instanceof Array;
3334 } catch (error) {
3335 /* empty */
3336 }
3337
3338 return function setPrototypeOf(O, proto) {
3339 anObject(O);
3340 aPossiblePrototype(proto);
3341 if (CORRECT_SETTER) setter.call(O, proto);else O.__proto__ = proto;
3342 return O;
3343 };
3344}() : undefined);
3345
3346/***/ }),
3347/* 113 */
3348/***/ (function(module, exports, __webpack_require__) {
3349
3350var isObject = __webpack_require__(16);
3351
3352module.exports = function (it) {
3353 if (!isObject(it) && it !== null) {
3354 throw TypeError("Can't set " + String(it) + ' as a prototype');
3355 }
3356
3357 return it;
3358};
3359
3360/***/ }),
3361/* 114 */
3362/***/ (function(module, exports, __webpack_require__) {
3363
3364var $ = __webpack_require__(4);
3365
3366var $values = __webpack_require__(84).values; // `Object.values` method
3367// https://tc39.github.io/ecma262/#sec-object.values
3368
3369
3370$({
3371 target: 'Object',
3372 stat: true
3373}, {
3374 values: function values(O) {
3375 return $values(O);
3376 }
3377});
3378
3379/***/ }),
3380/* 115 */
3381/***/ (function(module, exports, __webpack_require__) {
3382
3383var TO_STRING_TAG_SUPPORT = __webpack_require__(94);
3384
3385var redefine = __webpack_require__(23);
3386
3387var toString = __webpack_require__(116); // `Object.prototype.toString` method
3388// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
3389
3390
3391if (!TO_STRING_TAG_SUPPORT) {
3392 redefine(Object.prototype, 'toString', toString, {
3393 unsafe: true
3394 });
3395}
3396
3397/***/ }),
3398/* 116 */
3399/***/ (function(module, exports, __webpack_require__) {
3400
3401"use strict";
3402
3403
3404var TO_STRING_TAG_SUPPORT = __webpack_require__(94);
3405
3406var classof = __webpack_require__(93); // `Object.prototype.toString` method implementation
3407// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
3408
3409
3410module.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() {
3411 return '[object ' + classof(this) + ']';
3412};
3413
3414/***/ }),
3415/* 117 */
3416/***/ (function(module, exports, __webpack_require__) {
3417
3418"use strict";
3419
3420
3421var $ = __webpack_require__(4);
3422
3423var DESCRIPTORS = __webpack_require__(7);
3424
3425var FORCED = __webpack_require__(118);
3426
3427var toObject = __webpack_require__(50);
3428
3429var aFunction = __webpack_require__(62);
3430
3431var definePropertyModule = __webpack_require__(21); // `Object.prototype.__defineGetter__` method
3432// https://tc39.github.io/ecma262/#sec-object.prototype.__defineGetter__
3433
3434
3435if (DESCRIPTORS) {
3436 $({
3437 target: 'Object',
3438 proto: true,
3439 forced: FORCED
3440 }, {
3441 __defineGetter__: function __defineGetter__(P, getter) {
3442 definePropertyModule.f(toObject(this), P, {
3443 get: aFunction(getter),
3444 enumerable: true,
3445 configurable: true
3446 });
3447 }
3448 });
3449}
3450
3451/***/ }),
3452/* 118 */
3453/***/ (function(module, exports, __webpack_require__) {
3454
3455"use strict";
3456
3457
3458var IS_PURE = __webpack_require__(31);
3459
3460var global = __webpack_require__(5);
3461
3462var fails = __webpack_require__(8); // Forced replacement object prototype accessors methods
3463
3464
3465module.exports = IS_PURE || !fails(function () {
3466 var key = Math.random(); // In FF throws only define methods
3467 // eslint-disable-next-line no-undef, no-useless-call
3468
3469 __defineSetter__.call(null, key, function () {
3470 /* empty */
3471 });
3472
3473 delete global[key];
3474});
3475
3476/***/ }),
3477/* 119 */
3478/***/ (function(module, exports, __webpack_require__) {
3479
3480"use strict";
3481
3482
3483var $ = __webpack_require__(4);
3484
3485var DESCRIPTORS = __webpack_require__(7);
3486
3487var FORCED = __webpack_require__(118);
3488
3489var toObject = __webpack_require__(50);
3490
3491var aFunction = __webpack_require__(62);
3492
3493var definePropertyModule = __webpack_require__(21); // `Object.prototype.__defineSetter__` method
3494// https://tc39.github.io/ecma262/#sec-object.prototype.__defineSetter__
3495
3496
3497if (DESCRIPTORS) {
3498 $({
3499 target: 'Object',
3500 proto: true,
3501 forced: FORCED
3502 }, {
3503 __defineSetter__: function __defineSetter__(P, setter) {
3504 definePropertyModule.f(toObject(this), P, {
3505 set: aFunction(setter),
3506 enumerable: true,
3507 configurable: true
3508 });
3509 }
3510 });
3511}
3512
3513/***/ }),
3514/* 120 */
3515/***/ (function(module, exports, __webpack_require__) {
3516
3517"use strict";
3518
3519
3520var $ = __webpack_require__(4);
3521
3522var DESCRIPTORS = __webpack_require__(7);
3523
3524var FORCED = __webpack_require__(118);
3525
3526var toObject = __webpack_require__(50);
3527
3528var toPrimitive = __webpack_require__(15);
3529
3530var getPrototypeOf = __webpack_require__(101);
3531
3532var getOwnPropertyDescriptor = __webpack_require__(6).f; // `Object.prototype.__lookupGetter__` method
3533// https://tc39.github.io/ecma262/#sec-object.prototype.__lookupGetter__
3534
3535
3536if (DESCRIPTORS) {
3537 $({
3538 target: 'Object',
3539 proto: true,
3540 forced: FORCED
3541 }, {
3542 __lookupGetter__: function __lookupGetter__(P) {
3543 var O = toObject(this);
3544 var key = toPrimitive(P, true);
3545 var desc;
3546
3547 do {
3548 if (desc = getOwnPropertyDescriptor(O, key)) return desc.get;
3549 } while (O = getPrototypeOf(O));
3550 }
3551 });
3552}
3553
3554/***/ }),
3555/* 121 */
3556/***/ (function(module, exports, __webpack_require__) {
3557
3558"use strict";
3559
3560
3561var $ = __webpack_require__(4);
3562
3563var DESCRIPTORS = __webpack_require__(7);
3564
3565var FORCED = __webpack_require__(118);
3566
3567var toObject = __webpack_require__(50);
3568
3569var toPrimitive = __webpack_require__(15);
3570
3571var getPrototypeOf = __webpack_require__(101);
3572
3573var getOwnPropertyDescriptor = __webpack_require__(6).f; // `Object.prototype.__lookupSetter__` method
3574// https://tc39.github.io/ecma262/#sec-object.prototype.__lookupSetter__
3575
3576
3577if (DESCRIPTORS) {
3578 $({
3579 target: 'Object',
3580 proto: true,
3581 forced: FORCED
3582 }, {
3583 __lookupSetter__: function __lookupSetter__(P) {
3584 var O = toObject(this);
3585 var key = toPrimitive(P, true);
3586 var desc;
3587
3588 do {
3589 if (desc = getOwnPropertyDescriptor(O, key)) return desc.set;
3590 } while (O = getPrototypeOf(O));
3591 }
3592 });
3593}
3594
3595/***/ }),
3596/* 122 */
3597/***/ (function(module, exports, __webpack_require__) {
3598
3599var $ = __webpack_require__(4);
3600
3601var bind = __webpack_require__(123); // `Function.prototype.bind` method
3602// https://tc39.github.io/ecma262/#sec-function.prototype.bind
3603
3604
3605$({
3606 target: 'Function',
3607 proto: true
3608}, {
3609 bind: bind
3610});
3611
3612/***/ }),
3613/* 123 */
3614/***/ (function(module, exports, __webpack_require__) {
3615
3616"use strict";
3617
3618
3619var aFunction = __webpack_require__(62);
3620
3621var isObject = __webpack_require__(16);
3622
3623var slice = [].slice;
3624var factories = {};
3625
3626var construct = function construct(C, argsLength, args) {
3627 if (!(argsLength in factories)) {
3628 for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; // eslint-disable-next-line no-new-func
3629
3630
3631 factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')');
3632 }
3633
3634 return factories[argsLength](C, args);
3635}; // `Function.prototype.bind` method implementation
3636// https://tc39.github.io/ecma262/#sec-function.prototype.bind
3637
3638
3639module.exports = Function.bind || function bind(that
3640/* , ...args */
3641) {
3642 var fn = aFunction(this);
3643 var partArgs = slice.call(arguments, 1);
3644
3645 var boundFunction = function bound()
3646 /* args... */
3647 {
3648 var args = partArgs.concat(slice.call(arguments));
3649 return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args);
3650 };
3651
3652 if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype;
3653 return boundFunction;
3654};
3655
3656/***/ }),
3657/* 124 */
3658/***/ (function(module, exports, __webpack_require__) {
3659
3660var DESCRIPTORS = __webpack_require__(7);
3661
3662var defineProperty = __webpack_require__(21).f;
3663
3664var FunctionPrototype = Function.prototype;
3665var FunctionPrototypeToString = FunctionPrototype.toString;
3666var nameRE = /^\s*function ([^ (]*)/;
3667var NAME = 'name'; // Function instances `.name` property
3668// https://tc39.github.io/ecma262/#sec-function-instances-name
3669
3670if (DESCRIPTORS && !(NAME in FunctionPrototype)) {
3671 defineProperty(FunctionPrototype, NAME, {
3672 configurable: true,
3673 get: function get() {
3674 try {
3675 return FunctionPrototypeToString.call(this).match(nameRE)[1];
3676 } catch (error) {
3677 return '';
3678 }
3679 }
3680 });
3681}
3682
3683/***/ }),
3684/* 125 */
3685/***/ (function(module, exports, __webpack_require__) {
3686
3687"use strict";
3688
3689
3690var isObject = __webpack_require__(16);
3691
3692var definePropertyModule = __webpack_require__(21);
3693
3694var getPrototypeOf = __webpack_require__(101);
3695
3696var wellKnownSymbol = __webpack_require__(56);
3697
3698var HAS_INSTANCE = wellKnownSymbol('hasInstance');
3699var FunctionPrototype = Function.prototype; // `Function.prototype[@@hasInstance]` method
3700// https://tc39.github.io/ecma262/#sec-function.prototype-@@hasinstance
3701
3702if (!(HAS_INSTANCE in FunctionPrototype)) {
3703 definePropertyModule.f(FunctionPrototype, HAS_INSTANCE, {
3704 value: function value(O) {
3705 if (typeof this != 'function' || !isObject(O)) return false;
3706 if (!isObject(this.prototype)) return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
3707
3708 while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
3709
3710 return false;
3711 }
3712 });
3713}
3714
3715/***/ }),
3716/* 126 */
3717/***/ (function(module, exports, __webpack_require__) {
3718
3719var $ = __webpack_require__(4);
3720
3721var global = __webpack_require__(5); // `globalThis` object
3722// https://github.com/tc39/proposal-global
3723
3724
3725$({
3726 global: true
3727}, {
3728 globalThis: global
3729});
3730
3731/***/ }),
3732/* 127 */
3733/***/ (function(module, exports, __webpack_require__) {
3734
3735var $ = __webpack_require__(4);
3736
3737var from = __webpack_require__(128);
3738
3739var checkCorrectnessOfIteration = __webpack_require__(129);
3740
3741var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
3742 Array.from(iterable);
3743}); // `Array.from` method
3744// https://tc39.github.io/ecma262/#sec-array.from
3745
3746$({
3747 target: 'Array',
3748 stat: true,
3749 forced: INCORRECT_ITERATION
3750}, {
3751 from: from
3752});
3753
3754/***/ }),
3755/* 128 */
3756/***/ (function(module, exports, __webpack_require__) {
3757
3758"use strict";
3759
3760
3761var bind = __webpack_require__(61);
3762
3763var toObject = __webpack_require__(50);
3764
3765var callWithSafeIterationClosing = __webpack_require__(95);
3766
3767var isArrayIteratorMethod = __webpack_require__(90);
3768
3769var toLength = __webpack_require__(41);
3770
3771var createProperty = __webpack_require__(96);
3772
3773var getIteratorMethod = __webpack_require__(92); // `Array.from` method implementation
3774// https://tc39.github.io/ecma262/#sec-array.from
3775
3776
3777module.exports = function from(arrayLike
3778/* , mapfn = undefined, thisArg = undefined */
3779) {
3780 var O = toObject(arrayLike);
3781 var C = typeof this == 'function' ? this : Array;
3782 var argumentsLength = arguments.length;
3783 var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
3784 var mapping = mapfn !== undefined;
3785 var iteratorMethod = getIteratorMethod(O);
3786 var index = 0;
3787 var length, result, step, iterator, next, value;
3788 if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case
3789
3790 if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {
3791 iterator = iteratorMethod.call(O);
3792 next = iterator.next;
3793 result = new C();
3794
3795 for (; !(step = next.call(iterator)).done; index++) {
3796 value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
3797 createProperty(result, index, value);
3798 }
3799 } else {
3800 length = toLength(O.length);
3801 result = new C(length);
3802
3803 for (; length > index; index++) {
3804 value = mapping ? mapfn(O[index], index) : O[index];
3805 createProperty(result, index, value);
3806 }
3807 }
3808
3809 result.length = index;
3810 return result;
3811};
3812
3813/***/ }),
3814/* 129 */
3815/***/ (function(module, exports, __webpack_require__) {
3816
3817var wellKnownSymbol = __webpack_require__(56);
3818
3819var ITERATOR = wellKnownSymbol('iterator');
3820var SAFE_CLOSING = false;
3821
3822try {
3823 var called = 0;
3824 var iteratorWithReturn = {
3825 next: function next() {
3826 return {
3827 done: !!called++
3828 };
3829 },
3830 'return': function _return() {
3831 SAFE_CLOSING = true;
3832 }
3833 };
3834
3835 iteratorWithReturn[ITERATOR] = function () {
3836 return this;
3837 }; // eslint-disable-next-line no-throw-literal
3838
3839
3840 Array.from(iteratorWithReturn, function () {
3841 throw 2;
3842 });
3843} catch (error) {
3844 /* empty */
3845}
3846
3847module.exports = function (exec, SKIP_CLOSING) {
3848 if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
3849 var ITERATION_SUPPORT = false;
3850
3851 try {
3852 var object = {};
3853
3854 object[ITERATOR] = function () {
3855 return {
3856 next: function next() {
3857 return {
3858 done: ITERATION_SUPPORT = true
3859 };
3860 }
3861 };
3862 };
3863
3864 exec(object);
3865 } catch (error) {
3866 /* empty */
3867 }
3868
3869 return ITERATION_SUPPORT;
3870};
3871
3872/***/ }),
3873/* 130 */
3874/***/ (function(module, exports, __webpack_require__) {
3875
3876var $ = __webpack_require__(4);
3877
3878var isArray = __webpack_require__(49); // `Array.isArray` method
3879// https://tc39.github.io/ecma262/#sec-array.isarray
3880
3881
3882$({
3883 target: 'Array',
3884 stat: true
3885}, {
3886 isArray: isArray
3887});
3888
3889/***/ }),
3890/* 131 */
3891/***/ (function(module, exports, __webpack_require__) {
3892
3893"use strict";
3894
3895
3896var $ = __webpack_require__(4);
3897
3898var fails = __webpack_require__(8);
3899
3900var createProperty = __webpack_require__(96);
3901
3902var ISNT_GENERIC = fails(function () {
3903 function F() {
3904 /* empty */
3905 }
3906
3907 return !(Array.of.call(F) instanceof F);
3908}); // `Array.of` method
3909// https://tc39.github.io/ecma262/#sec-array.of
3910// WebKit Array.of isn't generic
3911
3912$({
3913 target: 'Array',
3914 stat: true,
3915 forced: ISNT_GENERIC
3916}, {
3917 of: function of()
3918 /* ...args */
3919 {
3920 var index = 0;
3921 var argumentsLength = arguments.length;
3922 var result = new (typeof this == 'function' ? this : Array)(argumentsLength);
3923
3924 while (argumentsLength > index) createProperty(result, index, arguments[index++]);
3925
3926 result.length = argumentsLength;
3927 return result;
3928 }
3929});
3930
3931/***/ }),
3932/* 132 */
3933/***/ (function(module, exports, __webpack_require__) {
3934
3935"use strict";
3936
3937
3938var $ = __webpack_require__(4);
3939
3940var fails = __webpack_require__(8);
3941
3942var isArray = __webpack_require__(49);
3943
3944var isObject = __webpack_require__(16);
3945
3946var toObject = __webpack_require__(50);
3947
3948var toLength = __webpack_require__(41);
3949
3950var createProperty = __webpack_require__(96);
3951
3952var arraySpeciesCreate = __webpack_require__(63);
3953
3954var arrayMethodHasSpeciesSupport = __webpack_require__(133);
3955
3956var wellKnownSymbol = __webpack_require__(56);
3957
3958var V8_VERSION = __webpack_require__(134);
3959
3960var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
3961var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
3962var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes
3963// deoptimization and serious performance degradation
3964// https://github.com/zloirock/core-js/issues/679
3965
3966var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {
3967 var array = [];
3968 array[IS_CONCAT_SPREADABLE] = false;
3969 return array.concat()[0] !== array;
3970});
3971var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
3972
3973var isConcatSpreadable = function isConcatSpreadable(O) {
3974 if (!isObject(O)) return false;
3975 var spreadable = O[IS_CONCAT_SPREADABLE];
3976 return spreadable !== undefined ? !!spreadable : isArray(O);
3977};
3978
3979var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method
3980// https://tc39.github.io/ecma262/#sec-array.prototype.concat
3981// with adding support of @@isConcatSpreadable and @@species
3982
3983$({
3984 target: 'Array',
3985 proto: true,
3986 forced: FORCED
3987}, {
3988 concat: function concat(arg) {
3989 // eslint-disable-line no-unused-vars
3990 var O = toObject(this);
3991 var A = arraySpeciesCreate(O, 0);
3992 var n = 0;
3993 var i, k, length, len, E;
3994
3995 for (i = -1, length = arguments.length; i < length; i++) {
3996 E = i === -1 ? O : arguments[i];
3997
3998 if (isConcatSpreadable(E)) {
3999 len = toLength(E.length);
4000 if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
4001
4002 for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
4003 } else {
4004 if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
4005 createProperty(A, n++, E);
4006 }
4007 }
4008
4009 A.length = n;
4010 return A;
4011 }
4012});
4013
4014/***/ }),
4015/* 133 */
4016/***/ (function(module, exports, __webpack_require__) {
4017
4018var fails = __webpack_require__(8);
4019
4020var wellKnownSymbol = __webpack_require__(56);
4021
4022var V8_VERSION = __webpack_require__(134);
4023
4024var SPECIES = wellKnownSymbol('species');
4025
4026module.exports = function (METHOD_NAME) {
4027 // We can't use this feature detection in V8 since it causes
4028 // deoptimization and serious performance degradation
4029 // https://github.com/zloirock/core-js/issues/677
4030 return V8_VERSION >= 51 || !fails(function () {
4031 var array = [];
4032 var constructor = array.constructor = {};
4033
4034 constructor[SPECIES] = function () {
4035 return {
4036 foo: 1
4037 };
4038 };
4039
4040 return array[METHOD_NAME](Boolean).foo !== 1;
4041 });
4042};
4043
4044/***/ }),
4045/* 134 */
4046/***/ (function(module, exports, __webpack_require__) {
4047
4048var global = __webpack_require__(5);
4049
4050var userAgent = __webpack_require__(135);
4051
4052var process = global.process;
4053var versions = process && process.versions;
4054var v8 = versions && versions.v8;
4055var match, version;
4056
4057if (v8) {
4058 match = v8.split('.');
4059 version = match[0] + match[1];
4060} else if (userAgent) {
4061 match = userAgent.match(/Edge\/(\d+)/);
4062
4063 if (!match || match[1] >= 74) {
4064 match = userAgent.match(/Chrome\/(\d+)/);
4065 if (match) version = match[1];
4066 }
4067}
4068
4069module.exports = version && +version;
4070
4071/***/ }),
4072/* 135 */
4073/***/ (function(module, exports, __webpack_require__) {
4074
4075var getBuiltIn = __webpack_require__(36);
4076
4077module.exports = getBuiltIn('navigator', 'userAgent') || '';
4078
4079/***/ }),
4080/* 136 */
4081/***/ (function(module, exports, __webpack_require__) {
4082
4083var $ = __webpack_require__(4);
4084
4085var copyWithin = __webpack_require__(137);
4086
4087var addToUnscopables = __webpack_require__(138); // `Array.prototype.copyWithin` method
4088// https://tc39.github.io/ecma262/#sec-array.prototype.copywithin
4089
4090
4091$({
4092 target: 'Array',
4093 proto: true
4094}, {
4095 copyWithin: copyWithin
4096}); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
4097
4098addToUnscopables('copyWithin');
4099
4100/***/ }),
4101/* 137 */
4102/***/ (function(module, exports, __webpack_require__) {
4103
4104"use strict";
4105
4106
4107var toObject = __webpack_require__(50);
4108
4109var toAbsoluteIndex = __webpack_require__(43);
4110
4111var toLength = __webpack_require__(41);
4112
4113var min = Math.min; // `Array.prototype.copyWithin` method implementation
4114// https://tc39.github.io/ecma262/#sec-array.prototype.copywithin
4115
4116module.exports = [].copyWithin || function copyWithin(target
4117/* = 0 */
4118, start
4119/* = 0, end = @length */
4120) {
4121 var O = toObject(this);
4122 var len = toLength(O.length);
4123 var to = toAbsoluteIndex(target, len);
4124 var from = toAbsoluteIndex(start, len);
4125 var end = arguments.length > 2 ? arguments[2] : undefined;
4126 var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
4127 var inc = 1;
4128
4129 if (from < to && to < from + count) {
4130 inc = -1;
4131 from += count - 1;
4132 to += count - 1;
4133 }
4134
4135 while (count-- > 0) {
4136 if (from in O) O[to] = O[from];else delete O[to];
4137 to += inc;
4138 from += inc;
4139 }
4140
4141 return O;
4142};
4143
4144/***/ }),
4145/* 138 */
4146/***/ (function(module, exports, __webpack_require__) {
4147
4148var wellKnownSymbol = __webpack_require__(56);
4149
4150var create = __webpack_require__(51);
4151
4152var definePropertyModule = __webpack_require__(21);
4153
4154var UNSCOPABLES = wellKnownSymbol('unscopables');
4155var ArrayPrototype = Array.prototype; // Array.prototype[@@unscopables]
4156// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
4157
4158if (ArrayPrototype[UNSCOPABLES] == undefined) {
4159 definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {
4160 configurable: true,
4161 value: create(null)
4162 });
4163} // add a key to Array.prototype[@@unscopables]
4164
4165
4166module.exports = function (key) {
4167 ArrayPrototype[UNSCOPABLES][key] = true;
4168};
4169
4170/***/ }),
4171/* 139 */
4172/***/ (function(module, exports, __webpack_require__) {
4173
4174"use strict";
4175
4176
4177var $ = __webpack_require__(4);
4178
4179var $every = __webpack_require__(60).every;
4180
4181var arrayMethodIsStrict = __webpack_require__(140);
4182
4183var arrayMethodUsesToLength = __webpack_require__(141);
4184
4185var STRICT_METHOD = arrayMethodIsStrict('every');
4186var USES_TO_LENGTH = arrayMethodUsesToLength('every'); // `Array.prototype.every` method
4187// https://tc39.github.io/ecma262/#sec-array.prototype.every
4188
4189$({
4190 target: 'Array',
4191 proto: true,
4192 forced: !STRICT_METHOD || !USES_TO_LENGTH
4193}, {
4194 every: function every(callbackfn
4195 /* , thisArg */
4196 ) {
4197 return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4198 }
4199});
4200
4201/***/ }),
4202/* 140 */
4203/***/ (function(module, exports, __webpack_require__) {
4204
4205"use strict";
4206
4207
4208var fails = __webpack_require__(8);
4209
4210module.exports = function (METHOD_NAME, argument) {
4211 var method = [][METHOD_NAME];
4212 return !!method && fails(function () {
4213 // eslint-disable-next-line no-useless-call,no-throw-literal
4214 method.call(null, argument || function () {
4215 throw 1;
4216 }, 1);
4217 });
4218};
4219
4220/***/ }),
4221/* 141 */
4222/***/ (function(module, exports, __webpack_require__) {
4223
4224var DESCRIPTORS = __webpack_require__(7);
4225
4226var fails = __webpack_require__(8);
4227
4228var has = __webpack_require__(17);
4229
4230var defineProperty = Object.defineProperty;
4231var cache = {};
4232
4233var thrower = function thrower(it) {
4234 throw it;
4235};
4236
4237module.exports = function (METHOD_NAME, options) {
4238 if (has(cache, METHOD_NAME)) return cache[METHOD_NAME];
4239 if (!options) options = {};
4240 var method = [][METHOD_NAME];
4241 var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;
4242 var argument0 = has(options, 0) ? options[0] : thrower;
4243 var argument1 = has(options, 1) ? options[1] : undefined;
4244 return cache[METHOD_NAME] = !!method && !fails(function () {
4245 if (ACCESSORS && !DESCRIPTORS) return true;
4246 var O = {
4247 length: -1
4248 };
4249 if (ACCESSORS) defineProperty(O, 1, {
4250 enumerable: true,
4251 get: thrower
4252 });else O[1] = 1;
4253 method.call(O, argument0, argument1);
4254 });
4255};
4256
4257/***/ }),
4258/* 142 */
4259/***/ (function(module, exports, __webpack_require__) {
4260
4261var $ = __webpack_require__(4);
4262
4263var fill = __webpack_require__(143);
4264
4265var addToUnscopables = __webpack_require__(138); // `Array.prototype.fill` method
4266// https://tc39.github.io/ecma262/#sec-array.prototype.fill
4267
4268
4269$({
4270 target: 'Array',
4271 proto: true
4272}, {
4273 fill: fill
4274}); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
4275
4276addToUnscopables('fill');
4277
4278/***/ }),
4279/* 143 */
4280/***/ (function(module, exports, __webpack_require__) {
4281
4282"use strict";
4283
4284
4285var toObject = __webpack_require__(50);
4286
4287var toAbsoluteIndex = __webpack_require__(43);
4288
4289var toLength = __webpack_require__(41); // `Array.prototype.fill` method implementation
4290// https://tc39.github.io/ecma262/#sec-array.prototype.fill
4291
4292
4293module.exports = function fill(value
4294/* , start = 0, end = @length */
4295) {
4296 var O = toObject(this);
4297 var length = toLength(O.length);
4298 var argumentsLength = arguments.length;
4299 var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);
4300 var end = argumentsLength > 2 ? arguments[2] : undefined;
4301 var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
4302
4303 while (endPos > index) O[index++] = value;
4304
4305 return O;
4306};
4307
4308/***/ }),
4309/* 144 */
4310/***/ (function(module, exports, __webpack_require__) {
4311
4312"use strict";
4313
4314
4315var $ = __webpack_require__(4);
4316
4317var $filter = __webpack_require__(60).filter;
4318
4319var arrayMethodHasSpeciesSupport = __webpack_require__(133);
4320
4321var arrayMethodUsesToLength = __webpack_require__(141);
4322
4323var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); // Edge 14- issue
4324
4325var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); // `Array.prototype.filter` method
4326// https://tc39.github.io/ecma262/#sec-array.prototype.filter
4327// with adding support of @@species
4328
4329$({
4330 target: 'Array',
4331 proto: true,
4332 forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH
4333}, {
4334 filter: function filter(callbackfn
4335 /* , thisArg */
4336 ) {
4337 return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4338 }
4339});
4340
4341/***/ }),
4342/* 145 */
4343/***/ (function(module, exports, __webpack_require__) {
4344
4345"use strict";
4346
4347
4348var $ = __webpack_require__(4);
4349
4350var $find = __webpack_require__(60).find;
4351
4352var addToUnscopables = __webpack_require__(138);
4353
4354var arrayMethodUsesToLength = __webpack_require__(141);
4355
4356var FIND = 'find';
4357var SKIPS_HOLES = true;
4358var USES_TO_LENGTH = arrayMethodUsesToLength(FIND); // Shouldn't skip holes
4359
4360if (FIND in []) Array(1)[FIND](function () {
4361 SKIPS_HOLES = false;
4362}); // `Array.prototype.find` method
4363// https://tc39.github.io/ecma262/#sec-array.prototype.find
4364
4365$({
4366 target: 'Array',
4367 proto: true,
4368 forced: SKIPS_HOLES || !USES_TO_LENGTH
4369}, {
4370 find: function find(callbackfn
4371 /* , that = undefined */
4372 ) {
4373 return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4374 }
4375}); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
4376
4377addToUnscopables(FIND);
4378
4379/***/ }),
4380/* 146 */
4381/***/ (function(module, exports, __webpack_require__) {
4382
4383"use strict";
4384
4385
4386var $ = __webpack_require__(4);
4387
4388var $findIndex = __webpack_require__(60).findIndex;
4389
4390var addToUnscopables = __webpack_require__(138);
4391
4392var arrayMethodUsesToLength = __webpack_require__(141);
4393
4394var FIND_INDEX = 'findIndex';
4395var SKIPS_HOLES = true;
4396var USES_TO_LENGTH = arrayMethodUsesToLength(FIND_INDEX); // Shouldn't skip holes
4397
4398if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () {
4399 SKIPS_HOLES = false;
4400}); // `Array.prototype.findIndex` method
4401// https://tc39.github.io/ecma262/#sec-array.prototype.findindex
4402
4403$({
4404 target: 'Array',
4405 proto: true,
4406 forced: SKIPS_HOLES || !USES_TO_LENGTH
4407}, {
4408 findIndex: function findIndex(callbackfn
4409 /* , that = undefined */
4410 ) {
4411 return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4412 }
4413}); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
4414
4415addToUnscopables(FIND_INDEX);
4416
4417/***/ }),
4418/* 147 */
4419/***/ (function(module, exports, __webpack_require__) {
4420
4421"use strict";
4422
4423
4424var $ = __webpack_require__(4);
4425
4426var flattenIntoArray = __webpack_require__(148);
4427
4428var toObject = __webpack_require__(50);
4429
4430var toLength = __webpack_require__(41);
4431
4432var toInteger = __webpack_require__(42);
4433
4434var arraySpeciesCreate = __webpack_require__(63); // `Array.prototype.flat` method
4435// https://github.com/tc39/proposal-flatMap
4436
4437
4438$({
4439 target: 'Array',
4440 proto: true
4441}, {
4442 flat: function flat()
4443 /* depthArg = 1 */
4444 {
4445 var depthArg = arguments.length ? arguments[0] : undefined;
4446 var O = toObject(this);
4447 var sourceLen = toLength(O.length);
4448 var A = arraySpeciesCreate(O, 0);
4449 A.length = flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
4450 return A;
4451 }
4452});
4453
4454/***/ }),
4455/* 148 */
4456/***/ (function(module, exports, __webpack_require__) {
4457
4458"use strict";
4459
4460
4461var isArray = __webpack_require__(49);
4462
4463var toLength = __webpack_require__(41);
4464
4465var bind = __webpack_require__(61); // `FlattenIntoArray` abstract operation
4466// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
4467
4468
4469var flattenIntoArray = function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) {
4470 var targetIndex = start;
4471 var sourceIndex = 0;
4472 var mapFn = mapper ? bind(mapper, thisArg, 3) : false;
4473 var element;
4474
4475 while (sourceIndex < sourceLen) {
4476 if (sourceIndex in source) {
4477 element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
4478
4479 if (depth > 0 && isArray(element)) {
4480 targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
4481 } else {
4482 if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError('Exceed the acceptable array length');
4483 target[targetIndex] = element;
4484 }
4485
4486 targetIndex++;
4487 }
4488
4489 sourceIndex++;
4490 }
4491
4492 return targetIndex;
4493};
4494
4495module.exports = flattenIntoArray;
4496
4497/***/ }),
4498/* 149 */
4499/***/ (function(module, exports, __webpack_require__) {
4500
4501"use strict";
4502
4503
4504var $ = __webpack_require__(4);
4505
4506var flattenIntoArray = __webpack_require__(148);
4507
4508var toObject = __webpack_require__(50);
4509
4510var toLength = __webpack_require__(41);
4511
4512var aFunction = __webpack_require__(62);
4513
4514var arraySpeciesCreate = __webpack_require__(63); // `Array.prototype.flatMap` method
4515// https://github.com/tc39/proposal-flatMap
4516
4517
4518$({
4519 target: 'Array',
4520 proto: true
4521}, {
4522 flatMap: function flatMap(callbackfn
4523 /* , thisArg */
4524 ) {
4525 var O = toObject(this);
4526 var sourceLen = toLength(O.length);
4527 var A;
4528 aFunction(callbackfn);
4529 A = arraySpeciesCreate(O, 0);
4530 A.length = flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4531 return A;
4532 }
4533});
4534
4535/***/ }),
4536/* 150 */
4537/***/ (function(module, exports, __webpack_require__) {
4538
4539"use strict";
4540
4541
4542var $ = __webpack_require__(4);
4543
4544var forEach = __webpack_require__(151); // `Array.prototype.forEach` method
4545// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
4546
4547
4548$({
4549 target: 'Array',
4550 proto: true,
4551 forced: [].forEach != forEach
4552}, {
4553 forEach: forEach
4554});
4555
4556/***/ }),
4557/* 151 */
4558/***/ (function(module, exports, __webpack_require__) {
4559
4560"use strict";
4561
4562
4563var $forEach = __webpack_require__(60).forEach;
4564
4565var arrayMethodIsStrict = __webpack_require__(140);
4566
4567var arrayMethodUsesToLength = __webpack_require__(141);
4568
4569var STRICT_METHOD = arrayMethodIsStrict('forEach');
4570var USES_TO_LENGTH = arrayMethodUsesToLength('forEach'); // `Array.prototype.forEach` method implementation
4571// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
4572
4573module.exports = !STRICT_METHOD || !USES_TO_LENGTH ? function forEach(callbackfn
4574/* , thisArg */
4575) {
4576 return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4577} : [].forEach;
4578
4579/***/ }),
4580/* 152 */
4581/***/ (function(module, exports, __webpack_require__) {
4582
4583"use strict";
4584
4585
4586var $ = __webpack_require__(4);
4587
4588var $includes = __webpack_require__(40).includes;
4589
4590var addToUnscopables = __webpack_require__(138);
4591
4592var arrayMethodUsesToLength = __webpack_require__(141);
4593
4594var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', {
4595 ACCESSORS: true,
4596 1: 0
4597}); // `Array.prototype.includes` method
4598// https://tc39.github.io/ecma262/#sec-array.prototype.includes
4599
4600$({
4601 target: 'Array',
4602 proto: true,
4603 forced: !USES_TO_LENGTH
4604}, {
4605 includes: function includes(el
4606 /* , fromIndex = 0 */
4607 ) {
4608 return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
4609 }
4610}); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
4611
4612addToUnscopables('includes');
4613
4614/***/ }),
4615/* 153 */
4616/***/ (function(module, exports, __webpack_require__) {
4617
4618"use strict";
4619
4620
4621var $ = __webpack_require__(4);
4622
4623var $indexOf = __webpack_require__(40).indexOf;
4624
4625var arrayMethodIsStrict = __webpack_require__(140);
4626
4627var arrayMethodUsesToLength = __webpack_require__(141);
4628
4629var nativeIndexOf = [].indexOf;
4630var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
4631var STRICT_METHOD = arrayMethodIsStrict('indexOf');
4632var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', {
4633 ACCESSORS: true,
4634 1: 0
4635}); // `Array.prototype.indexOf` method
4636// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
4637
4638$({
4639 target: 'Array',
4640 proto: true,
4641 forced: NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH
4642}, {
4643 indexOf: function indexOf(searchElement
4644 /* , fromIndex = 0 */
4645 ) {
4646 return NEGATIVE_ZERO // convert -0 to +0
4647 ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
4648 }
4649});
4650
4651/***/ }),
4652/* 154 */
4653/***/ (function(module, exports, __webpack_require__) {
4654
4655"use strict";
4656
4657
4658var $ = __webpack_require__(4);
4659
4660var IndexedObject = __webpack_require__(12);
4661
4662var toIndexedObject = __webpack_require__(11);
4663
4664var arrayMethodIsStrict = __webpack_require__(140);
4665
4666var nativeJoin = [].join;
4667var ES3_STRINGS = IndexedObject != Object;
4668var STRICT_METHOD = arrayMethodIsStrict('join', ','); // `Array.prototype.join` method
4669// https://tc39.github.io/ecma262/#sec-array.prototype.join
4670
4671$({
4672 target: 'Array',
4673 proto: true,
4674 forced: ES3_STRINGS || !STRICT_METHOD
4675}, {
4676 join: function join(separator) {
4677 return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
4678 }
4679});
4680
4681/***/ }),
4682/* 155 */
4683/***/ (function(module, exports, __webpack_require__) {
4684
4685var $ = __webpack_require__(4);
4686
4687var lastIndexOf = __webpack_require__(156); // `Array.prototype.lastIndexOf` method
4688// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
4689
4690
4691$({
4692 target: 'Array',
4693 proto: true,
4694 forced: lastIndexOf !== [].lastIndexOf
4695}, {
4696 lastIndexOf: lastIndexOf
4697});
4698
4699/***/ }),
4700/* 156 */
4701/***/ (function(module, exports, __webpack_require__) {
4702
4703"use strict";
4704
4705
4706var toIndexedObject = __webpack_require__(11);
4707
4708var toInteger = __webpack_require__(42);
4709
4710var toLength = __webpack_require__(41);
4711
4712var arrayMethodIsStrict = __webpack_require__(140);
4713
4714var arrayMethodUsesToLength = __webpack_require__(141);
4715
4716var min = Math.min;
4717var nativeLastIndexOf = [].lastIndexOf;
4718var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
4719var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf'); // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method
4720
4721var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', {
4722 ACCESSORS: true,
4723 1: 0
4724});
4725var FORCED = NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH; // `Array.prototype.lastIndexOf` method implementation
4726// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
4727
4728module.exports = FORCED ? function lastIndexOf(searchElement
4729/* , fromIndex = @[*-1] */
4730) {
4731 // convert -0 to +0
4732 if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0;
4733 var O = toIndexedObject(this);
4734 var length = toLength(O.length);
4735 var index = length - 1;
4736 if (arguments.length > 1) index = min(index, toInteger(arguments[1]));
4737 if (index < 0) index = length + index;
4738
4739 for (; index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
4740
4741 return -1;
4742} : nativeLastIndexOf;
4743
4744/***/ }),
4745/* 157 */
4746/***/ (function(module, exports, __webpack_require__) {
4747
4748"use strict";
4749
4750
4751var $ = __webpack_require__(4);
4752
4753var $map = __webpack_require__(60).map;
4754
4755var arrayMethodHasSpeciesSupport = __webpack_require__(133);
4756
4757var arrayMethodUsesToLength = __webpack_require__(141);
4758
4759var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map'); // FF49- issue
4760
4761var USES_TO_LENGTH = arrayMethodUsesToLength('map'); // `Array.prototype.map` method
4762// https://tc39.github.io/ecma262/#sec-array.prototype.map
4763// with adding support of @@species
4764
4765$({
4766 target: 'Array',
4767 proto: true,
4768 forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH
4769}, {
4770 map: function map(callbackfn
4771 /* , thisArg */
4772 ) {
4773 return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
4774 }
4775});
4776
4777/***/ }),
4778/* 158 */
4779/***/ (function(module, exports, __webpack_require__) {
4780
4781"use strict";
4782
4783
4784var $ = __webpack_require__(4);
4785
4786var $reduce = __webpack_require__(159).left;
4787
4788var arrayMethodIsStrict = __webpack_require__(140);
4789
4790var arrayMethodUsesToLength = __webpack_require__(141);
4791
4792var STRICT_METHOD = arrayMethodIsStrict('reduce');
4793var USES_TO_LENGTH = arrayMethodUsesToLength('reduce', {
4794 1: 0
4795}); // `Array.prototype.reduce` method
4796// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
4797
4798$({
4799 target: 'Array',
4800 proto: true,
4801 forced: !STRICT_METHOD || !USES_TO_LENGTH
4802}, {
4803 reduce: function reduce(callbackfn
4804 /* , initialValue */
4805 ) {
4806 return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
4807 }
4808});
4809
4810/***/ }),
4811/* 159 */
4812/***/ (function(module, exports, __webpack_require__) {
4813
4814var aFunction = __webpack_require__(62);
4815
4816var toObject = __webpack_require__(50);
4817
4818var IndexedObject = __webpack_require__(12);
4819
4820var toLength = __webpack_require__(41); // `Array.prototype.{ reduce, reduceRight }` methods implementation
4821
4822
4823var createMethod = function createMethod(IS_RIGHT) {
4824 return function (that, callbackfn, argumentsLength, memo) {
4825 aFunction(callbackfn);
4826 var O = toObject(that);
4827 var self = IndexedObject(O);
4828 var length = toLength(O.length);
4829 var index = IS_RIGHT ? length - 1 : 0;
4830 var i = IS_RIGHT ? -1 : 1;
4831 if (argumentsLength < 2) while (true) {
4832 if (index in self) {
4833 memo = self[index];
4834 index += i;
4835 break;
4836 }
4837
4838 index += i;
4839
4840 if (IS_RIGHT ? index < 0 : length <= index) {
4841 throw TypeError('Reduce of empty array with no initial value');
4842 }
4843 }
4844
4845 for (; IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
4846 memo = callbackfn(memo, self[index], index, O);
4847 }
4848
4849 return memo;
4850 };
4851};
4852
4853module.exports = {
4854 // `Array.prototype.reduce` method
4855 // https://tc39.github.io/ecma262/#sec-array.prototype.reduce
4856 left: createMethod(false),
4857 // `Array.prototype.reduceRight` method
4858 // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
4859 right: createMethod(true)
4860};
4861
4862/***/ }),
4863/* 160 */
4864/***/ (function(module, exports, __webpack_require__) {
4865
4866"use strict";
4867
4868
4869var $ = __webpack_require__(4);
4870
4871var $reduceRight = __webpack_require__(159).right;
4872
4873var arrayMethodIsStrict = __webpack_require__(140);
4874
4875var arrayMethodUsesToLength = __webpack_require__(141);
4876
4877var STRICT_METHOD = arrayMethodIsStrict('reduceRight'); // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method
4878
4879var USES_TO_LENGTH = arrayMethodUsesToLength('reduce', {
4880 1: 0
4881}); // `Array.prototype.reduceRight` method
4882// https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
4883
4884$({
4885 target: 'Array',
4886 proto: true,
4887 forced: !STRICT_METHOD || !USES_TO_LENGTH
4888}, {
4889 reduceRight: function reduceRight(callbackfn
4890 /* , initialValue */
4891 ) {
4892 return $reduceRight(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
4893 }
4894});
4895
4896/***/ }),
4897/* 161 */
4898/***/ (function(module, exports, __webpack_require__) {
4899
4900"use strict";
4901
4902
4903var $ = __webpack_require__(4);
4904
4905var isArray = __webpack_require__(49);
4906
4907var nativeReverse = [].reverse;
4908var test = [1, 2]; // `Array.prototype.reverse` method
4909// https://tc39.github.io/ecma262/#sec-array.prototype.reverse
4910// fix for Safari 12.0 bug
4911// https://bugs.webkit.org/show_bug.cgi?id=188794
4912
4913$({
4914 target: 'Array',
4915 proto: true,
4916 forced: String(test) === String(test.reverse())
4917}, {
4918 reverse: function reverse() {
4919 // eslint-disable-next-line no-self-assign
4920 if (isArray(this)) this.length = this.length;
4921 return nativeReverse.call(this);
4922 }
4923});
4924
4925/***/ }),
4926/* 162 */
4927/***/ (function(module, exports, __webpack_require__) {
4928
4929"use strict";
4930
4931
4932var $ = __webpack_require__(4);
4933
4934var isObject = __webpack_require__(16);
4935
4936var isArray = __webpack_require__(49);
4937
4938var toAbsoluteIndex = __webpack_require__(43);
4939
4940var toLength = __webpack_require__(41);
4941
4942var toIndexedObject = __webpack_require__(11);
4943
4944var createProperty = __webpack_require__(96);
4945
4946var wellKnownSymbol = __webpack_require__(56);
4947
4948var arrayMethodHasSpeciesSupport = __webpack_require__(133);
4949
4950var arrayMethodUsesToLength = __webpack_require__(141);
4951
4952var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');
4953var USES_TO_LENGTH = arrayMethodUsesToLength('slice', {
4954 ACCESSORS: true,
4955 0: 0,
4956 1: 2
4957});
4958var SPECIES = wellKnownSymbol('species');
4959var nativeSlice = [].slice;
4960var max = Math.max; // `Array.prototype.slice` method
4961// https://tc39.github.io/ecma262/#sec-array.prototype.slice
4962// fallback for not array-like ES3 strings and DOM objects
4963
4964$({
4965 target: 'Array',
4966 proto: true,
4967 forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH
4968}, {
4969 slice: function slice(start, end) {
4970 var O = toIndexedObject(this);
4971 var length = toLength(O.length);
4972 var k = toAbsoluteIndex(start, length);
4973 var fin = toAbsoluteIndex(end === undefined ? length : end, length); // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
4974
4975 var Constructor, result, n;
4976
4977 if (isArray(O)) {
4978 Constructor = O.constructor; // cross-realm fallback
4979
4980 if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
4981 Constructor = undefined;
4982 } else if (isObject(Constructor)) {
4983 Constructor = Constructor[SPECIES];
4984 if (Constructor === null) Constructor = undefined;
4985 }
4986
4987 if (Constructor === Array || Constructor === undefined) {
4988 return nativeSlice.call(O, k, fin);
4989 }
4990 }
4991
4992 result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
4993
4994 for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
4995
4996 result.length = n;
4997 return result;
4998 }
4999});
5000
5001/***/ }),
5002/* 163 */
5003/***/ (function(module, exports, __webpack_require__) {
5004
5005"use strict";
5006
5007
5008var $ = __webpack_require__(4);
5009
5010var $some = __webpack_require__(60).some;
5011
5012var arrayMethodIsStrict = __webpack_require__(140);
5013
5014var arrayMethodUsesToLength = __webpack_require__(141);
5015
5016var STRICT_METHOD = arrayMethodIsStrict('some');
5017var USES_TO_LENGTH = arrayMethodUsesToLength('some'); // `Array.prototype.some` method
5018// https://tc39.github.io/ecma262/#sec-array.prototype.some
5019
5020$({
5021 target: 'Array',
5022 proto: true,
5023 forced: !STRICT_METHOD || !USES_TO_LENGTH
5024}, {
5025 some: function some(callbackfn
5026 /* , thisArg */
5027 ) {
5028 return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
5029 }
5030});
5031
5032/***/ }),
5033/* 164 */
5034/***/ (function(module, exports, __webpack_require__) {
5035
5036"use strict";
5037
5038
5039var $ = __webpack_require__(4);
5040
5041var aFunction = __webpack_require__(62);
5042
5043var toObject = __webpack_require__(50);
5044
5045var fails = __webpack_require__(8);
5046
5047var arrayMethodIsStrict = __webpack_require__(140);
5048
5049var test = [];
5050var nativeSort = test.sort; // IE8-
5051
5052var FAILS_ON_UNDEFINED = fails(function () {
5053 test.sort(undefined);
5054}); // V8 bug
5055
5056var FAILS_ON_NULL = fails(function () {
5057 test.sort(null);
5058}); // Old WebKit
5059
5060var STRICT_METHOD = arrayMethodIsStrict('sort');
5061var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD; // `Array.prototype.sort` method
5062// https://tc39.github.io/ecma262/#sec-array.prototype.sort
5063
5064$({
5065 target: 'Array',
5066 proto: true,
5067 forced: FORCED
5068}, {
5069 sort: function sort(comparefn) {
5070 return comparefn === undefined ? nativeSort.call(toObject(this)) : nativeSort.call(toObject(this), aFunction(comparefn));
5071 }
5072});
5073
5074/***/ }),
5075/* 165 */
5076/***/ (function(module, exports, __webpack_require__) {
5077
5078"use strict";
5079
5080
5081var $ = __webpack_require__(4);
5082
5083var toAbsoluteIndex = __webpack_require__(43);
5084
5085var toInteger = __webpack_require__(42);
5086
5087var toLength = __webpack_require__(41);
5088
5089var toObject = __webpack_require__(50);
5090
5091var arraySpeciesCreate = __webpack_require__(63);
5092
5093var createProperty = __webpack_require__(96);
5094
5095var arrayMethodHasSpeciesSupport = __webpack_require__(133);
5096
5097var arrayMethodUsesToLength = __webpack_require__(141);
5098
5099var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice');
5100var USES_TO_LENGTH = arrayMethodUsesToLength('splice', {
5101 ACCESSORS: true,
5102 0: 0,
5103 1: 2
5104});
5105var max = Math.max;
5106var min = Math.min;
5107var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
5108var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; // `Array.prototype.splice` method
5109// https://tc39.github.io/ecma262/#sec-array.prototype.splice
5110// with adding support of @@species
5111
5112$({
5113 target: 'Array',
5114 proto: true,
5115 forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH
5116}, {
5117 splice: function splice(start, deleteCount
5118 /* , ...items */
5119 ) {
5120 var O = toObject(this);
5121 var len = toLength(O.length);
5122 var actualStart = toAbsoluteIndex(start, len);
5123 var argumentsLength = arguments.length;
5124 var insertCount, actualDeleteCount, A, k, from, to;
5125
5126 if (argumentsLength === 0) {
5127 insertCount = actualDeleteCount = 0;
5128 } else if (argumentsLength === 1) {
5129 insertCount = 0;
5130 actualDeleteCount = len - actualStart;
5131 } else {
5132 insertCount = argumentsLength - 2;
5133 actualDeleteCount = min(max(toInteger(deleteCount), 0), len - actualStart);
5134 }
5135
5136 if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) {
5137 throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);
5138 }
5139
5140 A = arraySpeciesCreate(O, actualDeleteCount);
5141
5142 for (k = 0; k < actualDeleteCount; k++) {
5143 from = actualStart + k;
5144 if (from in O) createProperty(A, k, O[from]);
5145 }
5146
5147 A.length = actualDeleteCount;
5148
5149 if (insertCount < actualDeleteCount) {
5150 for (k = actualStart; k < len - actualDeleteCount; k++) {
5151 from = k + actualDeleteCount;
5152 to = k + insertCount;
5153 if (from in O) O[to] = O[from];else delete O[to];
5154 }
5155
5156 for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];
5157 } else if (insertCount > actualDeleteCount) {
5158 for (k = len - actualDeleteCount; k > actualStart; k--) {
5159 from = k + actualDeleteCount - 1;
5160 to = k + insertCount - 1;
5161 if (from in O) O[to] = O[from];else delete O[to];
5162 }
5163 }
5164
5165 for (k = 0; k < insertCount; k++) {
5166 O[k + actualStart] = arguments[k + 2];
5167 }
5168
5169 O.length = len - actualDeleteCount + insertCount;
5170 return A;
5171 }
5172});
5173
5174/***/ }),
5175/* 166 */
5176/***/ (function(module, exports, __webpack_require__) {
5177
5178var setSpecies = __webpack_require__(167); // `Array[@@species]` getter
5179// https://tc39.github.io/ecma262/#sec-get-array-@@species
5180
5181
5182setSpecies('Array');
5183
5184/***/ }),
5185/* 167 */
5186/***/ (function(module, exports, __webpack_require__) {
5187
5188"use strict";
5189
5190
5191var getBuiltIn = __webpack_require__(36);
5192
5193var definePropertyModule = __webpack_require__(21);
5194
5195var wellKnownSymbol = __webpack_require__(56);
5196
5197var DESCRIPTORS = __webpack_require__(7);
5198
5199var SPECIES = wellKnownSymbol('species');
5200
5201module.exports = function (CONSTRUCTOR_NAME) {
5202 var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
5203 var defineProperty = definePropertyModule.f;
5204
5205 if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {
5206 defineProperty(Constructor, SPECIES, {
5207 configurable: true,
5208 get: function get() {
5209 return this;
5210 }
5211 });
5212 }
5213};
5214
5215/***/ }),
5216/* 168 */
5217/***/ (function(module, exports, __webpack_require__) {
5218
5219// this method was added to unscopables after implementation
5220// in popular engines, so it's moved to a separate module
5221var addToUnscopables = __webpack_require__(138);
5222
5223addToUnscopables('flat');
5224
5225/***/ }),
5226/* 169 */
5227/***/ (function(module, exports, __webpack_require__) {
5228
5229// this method was added to unscopables after implementation
5230// in popular engines, so it's moved to a separate module
5231var addToUnscopables = __webpack_require__(138);
5232
5233addToUnscopables('flatMap');
5234
5235/***/ }),
5236/* 170 */
5237/***/ (function(module, exports, __webpack_require__) {
5238
5239"use strict";
5240
5241
5242var toIndexedObject = __webpack_require__(11);
5243
5244var addToUnscopables = __webpack_require__(138);
5245
5246var Iterators = __webpack_require__(91);
5247
5248var InternalStateModule = __webpack_require__(27);
5249
5250var defineIterator = __webpack_require__(171);
5251
5252var ARRAY_ITERATOR = 'Array Iterator';
5253var setInternalState = InternalStateModule.set;
5254var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method
5255// https://tc39.github.io/ecma262/#sec-array.prototype.entries
5256// `Array.prototype.keys` method
5257// https://tc39.github.io/ecma262/#sec-array.prototype.keys
5258// `Array.prototype.values` method
5259// https://tc39.github.io/ecma262/#sec-array.prototype.values
5260// `Array.prototype[@@iterator]` method
5261// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
5262// `CreateArrayIterator` internal method
5263// https://tc39.github.io/ecma262/#sec-createarrayiterator
5264
5265module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
5266 setInternalState(this, {
5267 type: ARRAY_ITERATOR,
5268 target: toIndexedObject(iterated),
5269 // target
5270 index: 0,
5271 // next index
5272 kind: kind // kind
5273
5274 }); // `%ArrayIteratorPrototype%.next` method
5275 // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
5276}, function () {
5277 var state = getInternalState(this);
5278 var target = state.target;
5279 var kind = state.kind;
5280 var index = state.index++;
5281
5282 if (!target || index >= target.length) {
5283 state.target = undefined;
5284 return {
5285 value: undefined,
5286 done: true
5287 };
5288 }
5289
5290 if (kind == 'keys') return {
5291 value: index,
5292 done: false
5293 };
5294 if (kind == 'values') return {
5295 value: target[index],
5296 done: false
5297 };
5298 return {
5299 value: [index, target[index]],
5300 done: false
5301 };
5302}, 'values'); // argumentsList[@@iterator] is %ArrayProto_values%
5303// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
5304// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
5305
5306Iterators.Arguments = Iterators.Array; // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
5307
5308addToUnscopables('keys');
5309addToUnscopables('values');
5310addToUnscopables('entries');
5311
5312/***/ }),
5313/* 171 */
5314/***/ (function(module, exports, __webpack_require__) {
5315
5316"use strict";
5317
5318
5319var $ = __webpack_require__(4);
5320
5321var createIteratorConstructor = __webpack_require__(172);
5322
5323var getPrototypeOf = __webpack_require__(101);
5324
5325var setPrototypeOf = __webpack_require__(112);
5326
5327var setToStringTag = __webpack_require__(59);
5328
5329var createNonEnumerableProperty = __webpack_require__(20);
5330
5331var redefine = __webpack_require__(23);
5332
5333var wellKnownSymbol = __webpack_require__(56);
5334
5335var IS_PURE = __webpack_require__(31);
5336
5337var Iterators = __webpack_require__(91);
5338
5339var IteratorsCore = __webpack_require__(173);
5340
5341var IteratorPrototype = IteratorsCore.IteratorPrototype;
5342var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
5343var ITERATOR = wellKnownSymbol('iterator');
5344var KEYS = 'keys';
5345var VALUES = 'values';
5346var ENTRIES = 'entries';
5347
5348var returnThis = function returnThis() {
5349 return this;
5350};
5351
5352module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
5353 createIteratorConstructor(IteratorConstructor, NAME, next);
5354
5355 var getIterationMethod = function getIterationMethod(KIND) {
5356 if (KIND === DEFAULT && defaultIterator) return defaultIterator;
5357 if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
5358
5359 switch (KIND) {
5360 case KEYS:
5361 return function keys() {
5362 return new IteratorConstructor(this, KIND);
5363 };
5364
5365 case VALUES:
5366 return function values() {
5367 return new IteratorConstructor(this, KIND);
5368 };
5369
5370 case ENTRIES:
5371 return function entries() {
5372 return new IteratorConstructor(this, KIND);
5373 };
5374 }
5375
5376 return function () {
5377 return new IteratorConstructor(this);
5378 };
5379 };
5380
5381 var TO_STRING_TAG = NAME + ' Iterator';
5382 var INCORRECT_VALUES_NAME = false;
5383 var IterablePrototype = Iterable.prototype;
5384 var nativeIterator = IterablePrototype[ITERATOR] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT];
5385 var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
5386 var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
5387 var CurrentIteratorPrototype, methods, KEY; // fix native
5388
5389 if (anyNativeIterator) {
5390 CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
5391
5392 if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
5393 if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
5394 if (setPrototypeOf) {
5395 setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
5396 } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {
5397 createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);
5398 }
5399 } // Set @@toStringTag to native iterators
5400
5401
5402 setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
5403 if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
5404 }
5405 } // fix Array#{values, @@iterator}.name in V8 / FF
5406
5407
5408 if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
5409 INCORRECT_VALUES_NAME = true;
5410
5411 defaultIterator = function values() {
5412 return nativeIterator.call(this);
5413 };
5414 } // define iterator
5415
5416
5417 if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
5418 createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);
5419 }
5420
5421 Iterators[NAME] = defaultIterator; // export additional methods
5422
5423 if (DEFAULT) {
5424 methods = {
5425 values: getIterationMethod(VALUES),
5426 keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
5427 entries: getIterationMethod(ENTRIES)
5428 };
5429 if (FORCED) for (KEY in methods) {
5430 if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
5431 redefine(IterablePrototype, KEY, methods[KEY]);
5432 }
5433 } else $({
5434 target: NAME,
5435 proto: true,
5436 forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME
5437 }, methods);
5438 }
5439
5440 return methods;
5441};
5442
5443/***/ }),
5444/* 172 */
5445/***/ (function(module, exports, __webpack_require__) {
5446
5447"use strict";
5448
5449
5450var IteratorPrototype = __webpack_require__(173).IteratorPrototype;
5451
5452var create = __webpack_require__(51);
5453
5454var createPropertyDescriptor = __webpack_require__(10);
5455
5456var setToStringTag = __webpack_require__(59);
5457
5458var Iterators = __webpack_require__(91);
5459
5460var returnThis = function returnThis() {
5461 return this;
5462};
5463
5464module.exports = function (IteratorConstructor, NAME, next) {
5465 var TO_STRING_TAG = NAME + ' Iterator';
5466 IteratorConstructor.prototype = create(IteratorPrototype, {
5467 next: createPropertyDescriptor(1, next)
5468 });
5469 setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
5470 Iterators[TO_STRING_TAG] = returnThis;
5471 return IteratorConstructor;
5472};
5473
5474/***/ }),
5475/* 173 */
5476/***/ (function(module, exports, __webpack_require__) {
5477
5478"use strict";
5479
5480
5481var getPrototypeOf = __webpack_require__(101);
5482
5483var createNonEnumerableProperty = __webpack_require__(20);
5484
5485var has = __webpack_require__(17);
5486
5487var wellKnownSymbol = __webpack_require__(56);
5488
5489var IS_PURE = __webpack_require__(31);
5490
5491var ITERATOR = wellKnownSymbol('iterator');
5492var BUGGY_SAFARI_ITERATORS = false;
5493
5494var returnThis = function returnThis() {
5495 return this;
5496}; // `%IteratorPrototype%` object
5497// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
5498
5499
5500var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
5501
5502if ([].keys) {
5503 arrayIterator = [].keys(); // Safari 8 has buggy iterators w/o `next`
5504
5505 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;else {
5506 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
5507 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
5508 }
5509}
5510
5511if (IteratorPrototype == undefined) IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
5512
5513if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {
5514 createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
5515}
5516
5517module.exports = {
5518 IteratorPrototype: IteratorPrototype,
5519 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
5520};
5521
5522/***/ }),
5523/* 174 */
5524/***/ (function(module, exports, __webpack_require__) {
5525
5526var $ = __webpack_require__(4);
5527
5528var toAbsoluteIndex = __webpack_require__(43);
5529
5530var fromCharCode = String.fromCharCode;
5531var nativeFromCodePoint = String.fromCodePoint; // length should be 1, old FF problem
5532
5533var INCORRECT_LENGTH = !!nativeFromCodePoint && nativeFromCodePoint.length != 1; // `String.fromCodePoint` method
5534// https://tc39.github.io/ecma262/#sec-string.fromcodepoint
5535
5536$({
5537 target: 'String',
5538 stat: true,
5539 forced: INCORRECT_LENGTH
5540}, {
5541 fromCodePoint: function fromCodePoint(x) {
5542 // eslint-disable-line no-unused-vars
5543 var elements = [];
5544 var length = arguments.length;
5545 var i = 0;
5546 var code;
5547
5548 while (length > i) {
5549 code = +arguments[i++];
5550 if (toAbsoluteIndex(code, 0x10FFFF) !== code) throw RangeError(code + ' is not a valid code point');
5551 elements.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xD800, code % 0x400 + 0xDC00));
5552 }
5553
5554 return elements.join('');
5555 }
5556});
5557
5558/***/ }),
5559/* 175 */
5560/***/ (function(module, exports, __webpack_require__) {
5561
5562var $ = __webpack_require__(4);
5563
5564var toIndexedObject = __webpack_require__(11);
5565
5566var toLength = __webpack_require__(41); // `String.raw` method
5567// https://tc39.github.io/ecma262/#sec-string.raw
5568
5569
5570$({
5571 target: 'String',
5572 stat: true
5573}, {
5574 raw: function raw(template) {
5575 var rawTemplate = toIndexedObject(template.raw);
5576 var literalSegments = toLength(rawTemplate.length);
5577 var argumentsLength = arguments.length;
5578 var elements = [];
5579 var i = 0;
5580
5581 while (literalSegments > i) {
5582 elements.push(String(rawTemplate[i++]));
5583 if (i < argumentsLength) elements.push(String(arguments[i]));
5584 }
5585
5586 return elements.join('');
5587 }
5588});
5589
5590/***/ }),
5591/* 176 */
5592/***/ (function(module, exports, __webpack_require__) {
5593
5594"use strict";
5595
5596
5597var $ = __webpack_require__(4);
5598
5599var codeAt = __webpack_require__(177).codeAt; // `String.prototype.codePointAt` method
5600// https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
5601
5602
5603$({
5604 target: 'String',
5605 proto: true
5606}, {
5607 codePointAt: function codePointAt(pos) {
5608 return codeAt(this, pos);
5609 }
5610});
5611
5612/***/ }),
5613/* 177 */
5614/***/ (function(module, exports, __webpack_require__) {
5615
5616var toInteger = __webpack_require__(42);
5617
5618var requireObjectCoercible = __webpack_require__(14); // `String.prototype.{ codePointAt, at }` methods implementation
5619
5620
5621var createMethod = function createMethod(CONVERT_TO_STRING) {
5622 return function ($this, pos) {
5623 var S = String(requireObjectCoercible($this));
5624 var position = toInteger(pos);
5625 var size = S.length;
5626 var first, second;
5627 if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
5628 first = S.charCodeAt(position);
5629 return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
5630 };
5631};
5632
5633module.exports = {
5634 // `String.prototype.codePointAt` method
5635 // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
5636 codeAt: createMethod(false),
5637 // `String.prototype.at` method
5638 // https://github.com/mathiasbynens/String.prototype.at
5639 charAt: createMethod(true)
5640};
5641
5642/***/ }),
5643/* 178 */
5644/***/ (function(module, exports, __webpack_require__) {
5645
5646"use strict";
5647
5648
5649var $ = __webpack_require__(4);
5650
5651var getOwnPropertyDescriptor = __webpack_require__(6).f;
5652
5653var toLength = __webpack_require__(41);
5654
5655var notARegExp = __webpack_require__(179);
5656
5657var requireObjectCoercible = __webpack_require__(14);
5658
5659var correctIsRegExpLogic = __webpack_require__(181);
5660
5661var IS_PURE = __webpack_require__(31);
5662
5663var nativeEndsWith = ''.endsWith;
5664var min = Math.min;
5665var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('endsWith'); // https://github.com/zloirock/core-js/pull/702
5666
5667var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () {
5668 var descriptor = getOwnPropertyDescriptor(String.prototype, 'endsWith');
5669 return descriptor && !descriptor.writable;
5670}(); // `String.prototype.endsWith` method
5671// https://tc39.github.io/ecma262/#sec-string.prototype.endswith
5672
5673$({
5674 target: 'String',
5675 proto: true,
5676 forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC
5677}, {
5678 endsWith: function endsWith(searchString
5679 /* , endPosition = @length */
5680 ) {
5681 var that = String(requireObjectCoercible(this));
5682 notARegExp(searchString);
5683 var endPosition = arguments.length > 1 ? arguments[1] : undefined;
5684 var len = toLength(that.length);
5685 var end = endPosition === undefined ? len : min(toLength(endPosition), len);
5686 var search = String(searchString);
5687 return nativeEndsWith ? nativeEndsWith.call(that, search, end) : that.slice(end - search.length, end) === search;
5688 }
5689});
5690
5691/***/ }),
5692/* 179 */
5693/***/ (function(module, exports, __webpack_require__) {
5694
5695var isRegExp = __webpack_require__(180);
5696
5697module.exports = function (it) {
5698 if (isRegExp(it)) {
5699 throw TypeError("The method doesn't accept regular expressions");
5700 }
5701
5702 return it;
5703};
5704
5705/***/ }),
5706/* 180 */
5707/***/ (function(module, exports, __webpack_require__) {
5708
5709var isObject = __webpack_require__(16);
5710
5711var classof = __webpack_require__(13);
5712
5713var wellKnownSymbol = __webpack_require__(56);
5714
5715var MATCH = wellKnownSymbol('match'); // `IsRegExp` abstract operation
5716// https://tc39.github.io/ecma262/#sec-isregexp
5717
5718module.exports = function (it) {
5719 var isRegExp;
5720 return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp');
5721};
5722
5723/***/ }),
5724/* 181 */
5725/***/ (function(module, exports, __webpack_require__) {
5726
5727var wellKnownSymbol = __webpack_require__(56);
5728
5729var MATCH = wellKnownSymbol('match');
5730
5731module.exports = function (METHOD_NAME) {
5732 var regexp = /./;
5733
5734 try {
5735 '/./'[METHOD_NAME](regexp);
5736 } catch (e) {
5737 try {
5738 regexp[MATCH] = false;
5739 return '/./'[METHOD_NAME](regexp);
5740 } catch (f) {
5741 /* empty */
5742 }
5743 }
5744
5745 return false;
5746};
5747
5748/***/ }),
5749/* 182 */
5750/***/ (function(module, exports, __webpack_require__) {
5751
5752"use strict";
5753
5754
5755var $ = __webpack_require__(4);
5756
5757var notARegExp = __webpack_require__(179);
5758
5759var requireObjectCoercible = __webpack_require__(14);
5760
5761var correctIsRegExpLogic = __webpack_require__(181); // `String.prototype.includes` method
5762// https://tc39.github.io/ecma262/#sec-string.prototype.includes
5763
5764
5765$({
5766 target: 'String',
5767 proto: true,
5768 forced: !correctIsRegExpLogic('includes')
5769}, {
5770 includes: function includes(searchString
5771 /* , position = 0 */
5772 ) {
5773 return !!~String(requireObjectCoercible(this)).indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined);
5774 }
5775});
5776
5777/***/ }),
5778/* 183 */
5779/***/ (function(module, exports, __webpack_require__) {
5780
5781"use strict";
5782
5783
5784var fixRegExpWellKnownSymbolLogic = __webpack_require__(184);
5785
5786var anObject = __webpack_require__(22);
5787
5788var toLength = __webpack_require__(41);
5789
5790var requireObjectCoercible = __webpack_require__(14);
5791
5792var advanceStringIndex = __webpack_require__(189);
5793
5794var regExpExec = __webpack_require__(190); // @@match logic
5795
5796
5797fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) {
5798 return [// `String.prototype.match` method
5799 // https://tc39.github.io/ecma262/#sec-string.prototype.match
5800 function match(regexp) {
5801 var O = requireObjectCoercible(this);
5802 var matcher = regexp == undefined ? undefined : regexp[MATCH];
5803 return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
5804 }, // `RegExp.prototype[@@match]` method
5805 // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
5806 function (regexp) {
5807 var res = maybeCallNative(nativeMatch, regexp, this);
5808 if (res.done) return res.value;
5809 var rx = anObject(regexp);
5810 var S = String(this);
5811 if (!rx.global) return regExpExec(rx, S);
5812 var fullUnicode = rx.unicode;
5813 rx.lastIndex = 0;
5814 var A = [];
5815 var n = 0;
5816 var result;
5817
5818 while ((result = regExpExec(rx, S)) !== null) {
5819 var matchStr = String(result[0]);
5820 A[n] = matchStr;
5821 if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
5822 n++;
5823 }
5824
5825 return n === 0 ? null : A;
5826 }];
5827});
5828
5829/***/ }),
5830/* 184 */
5831/***/ (function(module, exports, __webpack_require__) {
5832
5833"use strict";
5834 // TODO: Remove from `core-js@4` since it's moved to entry points
5835
5836__webpack_require__(185);
5837
5838var redefine = __webpack_require__(23);
5839
5840var fails = __webpack_require__(8);
5841
5842var wellKnownSymbol = __webpack_require__(56);
5843
5844var regexpExec = __webpack_require__(186);
5845
5846var createNonEnumerableProperty = __webpack_require__(20);
5847
5848var SPECIES = wellKnownSymbol('species');
5849var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
5850 // #replace needs built-in support for named groups.
5851 // #match works fine because it just return the exec results, even if it has
5852 // a "grops" property.
5853 var re = /./;
5854
5855 re.exec = function () {
5856 var result = [];
5857 result.groups = {
5858 a: '7'
5859 };
5860 return result;
5861 };
5862
5863 return ''.replace(re, '$<a>') !== '7';
5864}); // IE <= 11 replaces $0 with the whole match, as if it was $&
5865// https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0
5866
5867var REPLACE_KEEPS_$0 = function () {
5868 return 'a'.replace(/./, '$0') === '$0';
5869}();
5870
5871var REPLACE = wellKnownSymbol('replace'); // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string
5872
5873var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = function () {
5874 if (/./[REPLACE]) {
5875 return /./[REPLACE]('a', '$0') === '';
5876 }
5877
5878 return false;
5879}(); // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
5880// Weex JS has frozen built-in prototypes, so use try / catch wrapper
5881
5882
5883var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
5884 var re = /(?:)/;
5885 var originalExec = re.exec;
5886
5887 re.exec = function () {
5888 return originalExec.apply(this, arguments);
5889 };
5890
5891 var result = 'ab'.split(re);
5892 return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
5893});
5894
5895module.exports = function (KEY, length, exec, sham) {
5896 var SYMBOL = wellKnownSymbol(KEY);
5897 var DELEGATES_TO_SYMBOL = !fails(function () {
5898 // String methods call symbol-named RegEp methods
5899 var O = {};
5900
5901 O[SYMBOL] = function () {
5902 return 7;
5903 };
5904
5905 return ''[KEY](O) != 7;
5906 });
5907 var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
5908 // Symbol-named RegExp methods call .exec
5909 var execCalled = false;
5910 var re = /a/;
5911
5912 if (KEY === 'split') {
5913 // We can't use real regex here since it causes deoptimization
5914 // and serious performance degradation in V8
5915 // https://github.com/zloirock/core-js/issues/306
5916 re = {}; // RegExp[@@split] doesn't call the regex's exec method, but first creates
5917 // a new one. We need to return the patched regex when creating the new one.
5918
5919 re.constructor = {};
5920
5921 re.constructor[SPECIES] = function () {
5922 return re;
5923 };
5924
5925 re.flags = '';
5926 re[SYMBOL] = /./[SYMBOL];
5927 }
5928
5929 re.exec = function () {
5930 execCalled = true;
5931 return null;
5932 };
5933
5934 re[SYMBOL]('');
5935 return !execCalled;
5936 });
5937
5938 if (!DELEGATES_TO_SYMBOL || !DELEGATES_TO_EXEC || KEY === 'replace' && !(REPLACE_SUPPORTS_NAMED_GROUPS && REPLACE_KEEPS_$0 && !REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE) || KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) {
5939 var nativeRegExpMethod = /./[SYMBOL];
5940 var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
5941 if (regexp.exec === regexpExec) {
5942 if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
5943 // The native String method already delegates to @@method (this
5944 // polyfilled function), leasing to infinite recursion.
5945 // We avoid it by directly calling the native @@method method.
5946 return {
5947 done: true,
5948 value: nativeRegExpMethod.call(regexp, str, arg2)
5949 };
5950 }
5951
5952 return {
5953 done: true,
5954 value: nativeMethod.call(str, regexp, arg2)
5955 };
5956 }
5957
5958 return {
5959 done: false
5960 };
5961 }, {
5962 REPLACE_KEEPS_$0: REPLACE_KEEPS_$0,
5963 REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE
5964 });
5965 var stringMethod = methods[0];
5966 var regexMethod = methods[1];
5967 redefine(String.prototype, KEY, stringMethod);
5968 redefine(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
5969 // 21.2.5.11 RegExp.prototype[@@split](string, limit)
5970 ? function (string, arg) {
5971 return regexMethod.call(string, this, arg);
5972 } // 21.2.5.6 RegExp.prototype[@@match](string)
5973 // 21.2.5.9 RegExp.prototype[@@search](string)
5974 : function (string) {
5975 return regexMethod.call(string, this);
5976 });
5977 }
5978
5979 if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true);
5980};
5981
5982/***/ }),
5983/* 185 */
5984/***/ (function(module, exports, __webpack_require__) {
5985
5986"use strict";
5987
5988
5989var $ = __webpack_require__(4);
5990
5991var exec = __webpack_require__(186);
5992
5993$({
5994 target: 'RegExp',
5995 proto: true,
5996 forced: /./.exec !== exec
5997}, {
5998 exec: exec
5999});
6000
6001/***/ }),
6002/* 186 */
6003/***/ (function(module, exports, __webpack_require__) {
6004
6005"use strict";
6006
6007
6008var regexpFlags = __webpack_require__(187);
6009
6010var stickyHelpers = __webpack_require__(188);
6011
6012var nativeExec = RegExp.prototype.exec; // This always refers to the native implementation, because the
6013// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
6014// which loads this file before patching the method.
6015
6016var nativeReplace = String.prototype.replace;
6017var patchedExec = nativeExec;
6018
6019var UPDATES_LAST_INDEX_WRONG = function () {
6020 var re1 = /a/;
6021 var re2 = /b*/g;
6022 nativeExec.call(re1, 'a');
6023 nativeExec.call(re2, 'a');
6024 return re1.lastIndex !== 0 || re2.lastIndex !== 0;
6025}();
6026
6027var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y || stickyHelpers.BROKEN_CARET; // nonparticipating capturing group, copied from es5-shim's String#split patch.
6028
6029var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
6030var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y;
6031
6032if (PATCH) {
6033 patchedExec = function exec(str) {
6034 var re = this;
6035 var lastIndex, reCopy, match, i;
6036 var sticky = UNSUPPORTED_Y && re.sticky;
6037 var flags = regexpFlags.call(re);
6038 var source = re.source;
6039 var charsAdded = 0;
6040 var strCopy = str;
6041
6042 if (sticky) {
6043 flags = flags.replace('y', '');
6044
6045 if (flags.indexOf('g') === -1) {
6046 flags += 'g';
6047 }
6048
6049 strCopy = String(str).slice(re.lastIndex); // Support anchored sticky behavior.
6050
6051 if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) {
6052 source = '(?: ' + source + ')';
6053 strCopy = ' ' + strCopy;
6054 charsAdded++;
6055 } // ^(? + rx + ) is needed, in combination with some str slicing, to
6056 // simulate the 'y' flag.
6057
6058
6059 reCopy = new RegExp('^(?:' + source + ')', flags);
6060 }
6061
6062 if (NPCG_INCLUDED) {
6063 reCopy = new RegExp('^' + source + '$(?!\\s)', flags);
6064 }
6065
6066 if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
6067 match = nativeExec.call(sticky ? reCopy : re, strCopy);
6068
6069 if (sticky) {
6070 if (match) {
6071 match.input = match.input.slice(charsAdded);
6072 match[0] = match[0].slice(charsAdded);
6073 match.index = re.lastIndex;
6074 re.lastIndex += match[0].length;
6075 } else re.lastIndex = 0;
6076 } else if (UPDATES_LAST_INDEX_WRONG && match) {
6077 re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
6078 }
6079
6080 if (NPCG_INCLUDED && match && match.length > 1) {
6081 // Fix browsers whose `exec` methods don't consistently return `undefined`
6082 // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
6083 nativeReplace.call(match[0], reCopy, function () {
6084 for (i = 1; i < arguments.length - 2; i++) {
6085 if (arguments[i] === undefined) match[i] = undefined;
6086 }
6087 });
6088 }
6089
6090 return match;
6091 };
6092}
6093
6094module.exports = patchedExec;
6095
6096/***/ }),
6097/* 187 */
6098/***/ (function(module, exports, __webpack_require__) {
6099
6100"use strict";
6101
6102
6103var anObject = __webpack_require__(22); // `RegExp.prototype.flags` getter implementation
6104// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
6105
6106
6107module.exports = function () {
6108 var that = anObject(this);
6109 var result = '';
6110 if (that.global) result += 'g';
6111 if (that.ignoreCase) result += 'i';
6112 if (that.multiline) result += 'm';
6113 if (that.dotAll) result += 's';
6114 if (that.unicode) result += 'u';
6115 if (that.sticky) result += 'y';
6116 return result;
6117};
6118
6119/***/ }),
6120/* 188 */
6121/***/ (function(module, exports, __webpack_require__) {
6122
6123"use strict";
6124
6125
6126var fails = __webpack_require__(8); // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError,
6127// so we use an intermediate function.
6128
6129
6130function RE(s, f) {
6131 return RegExp(s, f);
6132}
6133
6134exports.UNSUPPORTED_Y = fails(function () {
6135 // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError
6136 var re = RE('a', 'y');
6137 re.lastIndex = 2;
6138 return re.exec('abcd') != null;
6139});
6140exports.BROKEN_CARET = fails(function () {
6141 // https://bugzilla.mozilla.org/show_bug.cgi?id=773687
6142 var re = RE('^r', 'gy');
6143 re.lastIndex = 2;
6144 return re.exec('str') != null;
6145});
6146
6147/***/ }),
6148/* 189 */
6149/***/ (function(module, exports, __webpack_require__) {
6150
6151"use strict";
6152
6153
6154var charAt = __webpack_require__(177).charAt; // `AdvanceStringIndex` abstract operation
6155// https://tc39.github.io/ecma262/#sec-advancestringindex
6156
6157
6158module.exports = function (S, index, unicode) {
6159 return index + (unicode ? charAt(S, index).length : 1);
6160};
6161
6162/***/ }),
6163/* 190 */
6164/***/ (function(module, exports, __webpack_require__) {
6165
6166var classof = __webpack_require__(13);
6167
6168var regexpExec = __webpack_require__(186); // `RegExpExec` abstract operation
6169// https://tc39.github.io/ecma262/#sec-regexpexec
6170
6171
6172module.exports = function (R, S) {
6173 var exec = R.exec;
6174
6175 if (typeof exec === 'function') {
6176 var result = exec.call(R, S);
6177
6178 if (typeof result !== 'object') {
6179 throw TypeError('RegExp exec method returned something other than an Object or null');
6180 }
6181
6182 return result;
6183 }
6184
6185 if (classof(R) !== 'RegExp') {
6186 throw TypeError('RegExp#exec called on incompatible receiver');
6187 }
6188
6189 return regexpExec.call(R, S);
6190};
6191
6192/***/ }),
6193/* 191 */
6194/***/ (function(module, exports, __webpack_require__) {
6195
6196"use strict";
6197
6198
6199var $ = __webpack_require__(4);
6200
6201var createIteratorConstructor = __webpack_require__(172);
6202
6203var requireObjectCoercible = __webpack_require__(14);
6204
6205var toLength = __webpack_require__(41);
6206
6207var aFunction = __webpack_require__(62);
6208
6209var anObject = __webpack_require__(22);
6210
6211var classof = __webpack_require__(13);
6212
6213var isRegExp = __webpack_require__(180);
6214
6215var getRegExpFlags = __webpack_require__(187);
6216
6217var createNonEnumerableProperty = __webpack_require__(20);
6218
6219var fails = __webpack_require__(8);
6220
6221var wellKnownSymbol = __webpack_require__(56);
6222
6223var speciesConstructor = __webpack_require__(192);
6224
6225var advanceStringIndex = __webpack_require__(189);
6226
6227var InternalStateModule = __webpack_require__(27);
6228
6229var IS_PURE = __webpack_require__(31);
6230
6231var MATCH_ALL = wellKnownSymbol('matchAll');
6232var REGEXP_STRING = 'RegExp String';
6233var REGEXP_STRING_ITERATOR = REGEXP_STRING + ' Iterator';
6234var setInternalState = InternalStateModule.set;
6235var getInternalState = InternalStateModule.getterFor(REGEXP_STRING_ITERATOR);
6236var RegExpPrototype = RegExp.prototype;
6237var regExpBuiltinExec = RegExpPrototype.exec;
6238var nativeMatchAll = ''.matchAll;
6239var WORKS_WITH_NON_GLOBAL_REGEX = !!nativeMatchAll && !fails(function () {
6240 'a'.matchAll(/./);
6241});
6242
6243var regExpExec = function regExpExec(R, S) {
6244 var exec = R.exec;
6245 var result;
6246
6247 if (typeof exec == 'function') {
6248 result = exec.call(R, S);
6249 if (typeof result != 'object') throw TypeError('Incorrect exec result');
6250 return result;
6251 }
6252
6253 return regExpBuiltinExec.call(R, S);
6254}; // eslint-disable-next-line max-len
6255
6256
6257var $RegExpStringIterator = createIteratorConstructor(function RegExpStringIterator(regexp, string, global, fullUnicode) {
6258 setInternalState(this, {
6259 type: REGEXP_STRING_ITERATOR,
6260 regexp: regexp,
6261 string: string,
6262 global: global,
6263 unicode: fullUnicode,
6264 done: false
6265 });
6266}, REGEXP_STRING, function next() {
6267 var state = getInternalState(this);
6268 if (state.done) return {
6269 value: undefined,
6270 done: true
6271 };
6272 var R = state.regexp;
6273 var S = state.string;
6274 var match = regExpExec(R, S);
6275 if (match === null) return {
6276 value: undefined,
6277 done: state.done = true
6278 };
6279
6280 if (state.global) {
6281 if (String(match[0]) == '') R.lastIndex = advanceStringIndex(S, toLength(R.lastIndex), state.unicode);
6282 return {
6283 value: match,
6284 done: false
6285 };
6286 }
6287
6288 state.done = true;
6289 return {
6290 value: match,
6291 done: false
6292 };
6293});
6294
6295var $matchAll = function $matchAll(string) {
6296 var R = anObject(this);
6297 var S = String(string);
6298 var C, flagsValue, flags, matcher, global, fullUnicode;
6299 C = speciesConstructor(R, RegExp);
6300 flagsValue = R.flags;
6301
6302 if (flagsValue === undefined && R instanceof RegExp && !('flags' in RegExpPrototype)) {
6303 flagsValue = getRegExpFlags.call(R);
6304 }
6305
6306 flags = flagsValue === undefined ? '' : String(flagsValue);
6307 matcher = new C(C === RegExp ? R.source : R, flags);
6308 global = !!~flags.indexOf('g');
6309 fullUnicode = !!~flags.indexOf('u');
6310 matcher.lastIndex = toLength(R.lastIndex);
6311 return new $RegExpStringIterator(matcher, S, global, fullUnicode);
6312}; // `String.prototype.matchAll` method
6313// https://github.com/tc39/proposal-string-matchall
6314
6315
6316$({
6317 target: 'String',
6318 proto: true,
6319 forced: WORKS_WITH_NON_GLOBAL_REGEX
6320}, {
6321 matchAll: function matchAll(regexp) {
6322 var O = requireObjectCoercible(this);
6323 var flags, S, matcher, rx;
6324
6325 if (regexp != null) {
6326 if (isRegExp(regexp)) {
6327 flags = String(requireObjectCoercible('flags' in RegExpPrototype ? regexp.flags : getRegExpFlags.call(regexp)));
6328 if (!~flags.indexOf('g')) throw TypeError('`.matchAll` does not allow non-global regexes');
6329 }
6330
6331 if (WORKS_WITH_NON_GLOBAL_REGEX) return nativeMatchAll.apply(O, arguments);
6332 matcher = regexp[MATCH_ALL];
6333 if (matcher === undefined && IS_PURE && classof(regexp) == 'RegExp') matcher = $matchAll;
6334 if (matcher != null) return aFunction(matcher).call(regexp, O);
6335 } else if (WORKS_WITH_NON_GLOBAL_REGEX) return nativeMatchAll.apply(O, arguments);
6336
6337 S = String(O);
6338 rx = new RegExp(regexp, 'g');
6339 return IS_PURE ? $matchAll.call(rx, S) : rx[MATCH_ALL](S);
6340 }
6341});
6342IS_PURE || MATCH_ALL in RegExpPrototype || createNonEnumerableProperty(RegExpPrototype, MATCH_ALL, $matchAll);
6343
6344/***/ }),
6345/* 192 */
6346/***/ (function(module, exports, __webpack_require__) {
6347
6348var anObject = __webpack_require__(22);
6349
6350var aFunction = __webpack_require__(62);
6351
6352var wellKnownSymbol = __webpack_require__(56);
6353
6354var SPECIES = wellKnownSymbol('species'); // `SpeciesConstructor` abstract operation
6355// https://tc39.github.io/ecma262/#sec-speciesconstructor
6356
6357module.exports = function (O, defaultConstructor) {
6358 var C = anObject(O).constructor;
6359 var S;
6360 return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S);
6361};
6362
6363/***/ }),
6364/* 193 */
6365/***/ (function(module, exports, __webpack_require__) {
6366
6367"use strict";
6368
6369
6370var $ = __webpack_require__(4);
6371
6372var $padEnd = __webpack_require__(194).end;
6373
6374var WEBKIT_BUG = __webpack_require__(196); // `String.prototype.padEnd` method
6375// https://tc39.github.io/ecma262/#sec-string.prototype.padend
6376
6377
6378$({
6379 target: 'String',
6380 proto: true,
6381 forced: WEBKIT_BUG
6382}, {
6383 padEnd: function padEnd(maxLength
6384 /* , fillString = ' ' */
6385 ) {
6386 return $padEnd(this, maxLength, arguments.length > 1 ? arguments[1] : undefined);
6387 }
6388});
6389
6390/***/ }),
6391/* 194 */
6392/***/ (function(module, exports, __webpack_require__) {
6393
6394// https://github.com/tc39/proposal-string-pad-start-end
6395var toLength = __webpack_require__(41);
6396
6397var repeat = __webpack_require__(195);
6398
6399var requireObjectCoercible = __webpack_require__(14);
6400
6401var ceil = Math.ceil; // `String.prototype.{ padStart, padEnd }` methods implementation
6402
6403var createMethod = function createMethod(IS_END) {
6404 return function ($this, maxLength, fillString) {
6405 var S = String(requireObjectCoercible($this));
6406 var stringLength = S.length;
6407 var fillStr = fillString === undefined ? ' ' : String(fillString);
6408 var intMaxLength = toLength(maxLength);
6409 var fillLen, stringFiller;
6410 if (intMaxLength <= stringLength || fillStr == '') return S;
6411 fillLen = intMaxLength - stringLength;
6412 stringFiller = repeat.call(fillStr, ceil(fillLen / fillStr.length));
6413 if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
6414 return IS_END ? S + stringFiller : stringFiller + S;
6415 };
6416};
6417
6418module.exports = {
6419 // `String.prototype.padStart` method
6420 // https://tc39.github.io/ecma262/#sec-string.prototype.padstart
6421 start: createMethod(false),
6422 // `String.prototype.padEnd` method
6423 // https://tc39.github.io/ecma262/#sec-string.prototype.padend
6424 end: createMethod(true)
6425};
6426
6427/***/ }),
6428/* 195 */
6429/***/ (function(module, exports, __webpack_require__) {
6430
6431"use strict";
6432
6433
6434var toInteger = __webpack_require__(42);
6435
6436var requireObjectCoercible = __webpack_require__(14); // `String.prototype.repeat` method implementation
6437// https://tc39.github.io/ecma262/#sec-string.prototype.repeat
6438
6439
6440module.exports = ''.repeat || function repeat(count) {
6441 var str = String(requireObjectCoercible(this));
6442 var result = '';
6443 var n = toInteger(count);
6444 if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions');
6445
6446 for (; n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;
6447
6448 return result;
6449};
6450
6451/***/ }),
6452/* 196 */
6453/***/ (function(module, exports, __webpack_require__) {
6454
6455// https://github.com/zloirock/core-js/issues/280
6456var userAgent = __webpack_require__(135); // eslint-disable-next-line unicorn/no-unsafe-regex
6457
6458
6459module.exports = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent);
6460
6461/***/ }),
6462/* 197 */
6463/***/ (function(module, exports, __webpack_require__) {
6464
6465"use strict";
6466
6467
6468var $ = __webpack_require__(4);
6469
6470var $padStart = __webpack_require__(194).start;
6471
6472var WEBKIT_BUG = __webpack_require__(196); // `String.prototype.padStart` method
6473// https://tc39.github.io/ecma262/#sec-string.prototype.padstart
6474
6475
6476$({
6477 target: 'String',
6478 proto: true,
6479 forced: WEBKIT_BUG
6480}, {
6481 padStart: function padStart(maxLength
6482 /* , fillString = ' ' */
6483 ) {
6484 return $padStart(this, maxLength, arguments.length > 1 ? arguments[1] : undefined);
6485 }
6486});
6487
6488/***/ }),
6489/* 198 */
6490/***/ (function(module, exports, __webpack_require__) {
6491
6492var $ = __webpack_require__(4);
6493
6494var repeat = __webpack_require__(195); // `String.prototype.repeat` method
6495// https://tc39.github.io/ecma262/#sec-string.prototype.repeat
6496
6497
6498$({
6499 target: 'String',
6500 proto: true
6501}, {
6502 repeat: repeat
6503});
6504
6505/***/ }),
6506/* 199 */
6507/***/ (function(module, exports, __webpack_require__) {
6508
6509"use strict";
6510
6511
6512var fixRegExpWellKnownSymbolLogic = __webpack_require__(184);
6513
6514var anObject = __webpack_require__(22);
6515
6516var toObject = __webpack_require__(50);
6517
6518var toLength = __webpack_require__(41);
6519
6520var toInteger = __webpack_require__(42);
6521
6522var requireObjectCoercible = __webpack_require__(14);
6523
6524var advanceStringIndex = __webpack_require__(189);
6525
6526var regExpExec = __webpack_require__(190);
6527
6528var max = Math.max;
6529var min = Math.min;
6530var floor = Math.floor;
6531var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g;
6532var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g;
6533
6534var maybeToString = function maybeToString(it) {
6535 return it === undefined ? it : String(it);
6536}; // @@replace logic
6537
6538
6539fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) {
6540 var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE;
6541 var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0;
6542 var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0';
6543 return [// `String.prototype.replace` method
6544 // https://tc39.github.io/ecma262/#sec-string.prototype.replace
6545 function replace(searchValue, replaceValue) {
6546 var O = requireObjectCoercible(this);
6547 var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
6548 return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue);
6549 }, // `RegExp.prototype[@@replace]` method
6550 // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
6551 function (regexp, replaceValue) {
6552 if (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0 || typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1) {
6553 var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);
6554 if (res.done) return res.value;
6555 }
6556
6557 var rx = anObject(regexp);
6558 var S = String(this);
6559 var functionalReplace = typeof replaceValue === 'function';
6560 if (!functionalReplace) replaceValue = String(replaceValue);
6561 var global = rx.global;
6562
6563 if (global) {
6564 var fullUnicode = rx.unicode;
6565 rx.lastIndex = 0;
6566 }
6567
6568 var results = [];
6569
6570 while (true) {
6571 var result = regExpExec(rx, S);
6572 if (result === null) break;
6573 results.push(result);
6574 if (!global) break;
6575 var matchStr = String(result[0]);
6576 if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
6577 }
6578
6579 var accumulatedResult = '';
6580 var nextSourcePosition = 0;
6581
6582 for (var i = 0; i < results.length; i++) {
6583 result = results[i];
6584 var matched = String(result[0]);
6585 var position = max(min(toInteger(result.index), S.length), 0);
6586 var captures = []; // NOTE: This is equivalent to
6587 // captures = result.slice(1).map(maybeToString)
6588 // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
6589 // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
6590 // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
6591
6592 for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
6593
6594 var namedCaptures = result.groups;
6595
6596 if (functionalReplace) {
6597 var replacerArgs = [matched].concat(captures, position, S);
6598 if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
6599 var replacement = String(replaceValue.apply(undefined, replacerArgs));
6600 } else {
6601 replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
6602 }
6603
6604 if (position >= nextSourcePosition) {
6605 accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
6606 nextSourcePosition = position + matched.length;
6607 }
6608 }
6609
6610 return accumulatedResult + S.slice(nextSourcePosition);
6611 }]; // https://tc39.github.io/ecma262/#sec-getsubstitution
6612
6613 function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
6614 var tailPos = position + matched.length;
6615 var m = captures.length;
6616 var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
6617
6618 if (namedCaptures !== undefined) {
6619 namedCaptures = toObject(namedCaptures);
6620 symbols = SUBSTITUTION_SYMBOLS;
6621 }
6622
6623 return nativeReplace.call(replacement, symbols, function (match, ch) {
6624 var capture;
6625
6626 switch (ch.charAt(0)) {
6627 case '$':
6628 return '$';
6629
6630 case '&':
6631 return matched;
6632
6633 case '`':
6634 return str.slice(0, position);
6635
6636 case "'":
6637 return str.slice(tailPos);
6638
6639 case '<':
6640 capture = namedCaptures[ch.slice(1, -1)];
6641 break;
6642
6643 default:
6644 // \d\d?
6645 var n = +ch;
6646 if (n === 0) return match;
6647
6648 if (n > m) {
6649 var f = floor(n / 10);
6650 if (f === 0) return match;
6651 if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
6652 return match;
6653 }
6654
6655 capture = captures[n - 1];
6656 }
6657
6658 return capture === undefined ? '' : capture;
6659 });
6660 }
6661});
6662
6663/***/ }),
6664/* 200 */
6665/***/ (function(module, exports, __webpack_require__) {
6666
6667"use strict";
6668
6669
6670var fixRegExpWellKnownSymbolLogic = __webpack_require__(184);
6671
6672var anObject = __webpack_require__(22);
6673
6674var requireObjectCoercible = __webpack_require__(14);
6675
6676var sameValue = __webpack_require__(104);
6677
6678var regExpExec = __webpack_require__(190); // @@search logic
6679
6680
6681fixRegExpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) {
6682 return [// `String.prototype.search` method
6683 // https://tc39.github.io/ecma262/#sec-string.prototype.search
6684 function search(regexp) {
6685 var O = requireObjectCoercible(this);
6686 var searcher = regexp == undefined ? undefined : regexp[SEARCH];
6687 return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
6688 }, // `RegExp.prototype[@@search]` method
6689 // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
6690 function (regexp) {
6691 var res = maybeCallNative(nativeSearch, regexp, this);
6692 if (res.done) return res.value;
6693 var rx = anObject(regexp);
6694 var S = String(this);
6695 var previousLastIndex = rx.lastIndex;
6696 if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
6697 var result = regExpExec(rx, S);
6698 if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
6699 return result === null ? -1 : result.index;
6700 }];
6701});
6702
6703/***/ }),
6704/* 201 */
6705/***/ (function(module, exports, __webpack_require__) {
6706
6707"use strict";
6708
6709
6710var fixRegExpWellKnownSymbolLogic = __webpack_require__(184);
6711
6712var isRegExp = __webpack_require__(180);
6713
6714var anObject = __webpack_require__(22);
6715
6716var requireObjectCoercible = __webpack_require__(14);
6717
6718var speciesConstructor = __webpack_require__(192);
6719
6720var advanceStringIndex = __webpack_require__(189);
6721
6722var toLength = __webpack_require__(41);
6723
6724var callRegExpExec = __webpack_require__(190);
6725
6726var regexpExec = __webpack_require__(186);
6727
6728var fails = __webpack_require__(8);
6729
6730var arrayPush = [].push;
6731var min = Math.min;
6732var MAX_UINT32 = 0xFFFFFFFF; // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
6733
6734var SUPPORTS_Y = !fails(function () {
6735 return !RegExp(MAX_UINT32, 'y');
6736}); // @@split logic
6737
6738fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {
6739 var internalSplit;
6740
6741 if ('abbc'.split(/(b)*/)[1] == 'c' || 'test'.split(/(?:)/, -1).length != 4 || 'ab'.split(/(?:ab)*/).length != 2 || '.'.split(/(.?)(.?)/).length != 4 || '.'.split(/()()/).length > 1 || ''.split(/.?/).length) {
6742 // based on es5-shim implementation, need to rework it
6743 internalSplit = function internalSplit(separator, limit) {
6744 var string = String(requireObjectCoercible(this));
6745 var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
6746 if (lim === 0) return [];
6747 if (separator === undefined) return [string]; // If `separator` is not a regex, use native split
6748
6749 if (!isRegExp(separator)) {
6750 return nativeSplit.call(string, separator, lim);
6751 }
6752
6753 var output = [];
6754 var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : '');
6755 var lastLastIndex = 0; // Make `global` and avoid `lastIndex` issues by working with a copy
6756
6757 var separatorCopy = new RegExp(separator.source, flags + 'g');
6758 var match, lastIndex, lastLength;
6759
6760 while (match = regexpExec.call(separatorCopy, string)) {
6761 lastIndex = separatorCopy.lastIndex;
6762
6763 if (lastIndex > lastLastIndex) {
6764 output.push(string.slice(lastLastIndex, match.index));
6765 if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
6766 lastLength = match[0].length;
6767 lastLastIndex = lastIndex;
6768 if (output.length >= lim) break;
6769 }
6770
6771 if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
6772 }
6773
6774 if (lastLastIndex === string.length) {
6775 if (lastLength || !separatorCopy.test('')) output.push('');
6776 } else output.push(string.slice(lastLastIndex));
6777
6778 return output.length > lim ? output.slice(0, lim) : output;
6779 }; // Chakra, V8
6780
6781 } else if ('0'.split(undefined, 0).length) {
6782 internalSplit = function internalSplit(separator, limit) {
6783 return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
6784 };
6785 } else internalSplit = nativeSplit;
6786
6787 return [// `String.prototype.split` method
6788 // https://tc39.github.io/ecma262/#sec-string.prototype.split
6789 function split(separator, limit) {
6790 var O = requireObjectCoercible(this);
6791 var splitter = separator == undefined ? undefined : separator[SPLIT];
6792 return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(String(O), separator, limit);
6793 }, // `RegExp.prototype[@@split]` method
6794 // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
6795 //
6796 // NOTE: This cannot be properly polyfilled in engines that don't support
6797 // the 'y' flag.
6798 function (regexp, limit) {
6799 var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);
6800 if (res.done) return res.value;
6801 var rx = anObject(regexp);
6802 var S = String(this);
6803 var C = speciesConstructor(rx, RegExp);
6804 var unicodeMatching = rx.unicode;
6805 var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (SUPPORTS_Y ? 'y' : 'g'); // ^(? + rx + ) is needed, in combination with some S slicing, to
6806 // simulate the 'y' flag.
6807
6808 var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
6809 var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
6810 if (lim === 0) return [];
6811 if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : [];
6812 var p = 0;
6813 var q = 0;
6814 var A = [];
6815
6816 while (q < S.length) {
6817 splitter.lastIndex = SUPPORTS_Y ? q : 0;
6818 var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q));
6819 var e;
6820
6821 if (z === null || (e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p) {
6822 q = advanceStringIndex(S, q, unicodeMatching);
6823 } else {
6824 A.push(S.slice(p, q));
6825 if (A.length === lim) return A;
6826
6827 for (var i = 1; i <= z.length - 1; i++) {
6828 A.push(z[i]);
6829 if (A.length === lim) return A;
6830 }
6831
6832 q = p = e;
6833 }
6834 }
6835
6836 A.push(S.slice(p));
6837 return A;
6838 }];
6839}, !SUPPORTS_Y);
6840
6841/***/ }),
6842/* 202 */
6843/***/ (function(module, exports, __webpack_require__) {
6844
6845"use strict";
6846
6847
6848var $ = __webpack_require__(4);
6849
6850var getOwnPropertyDescriptor = __webpack_require__(6).f;
6851
6852var toLength = __webpack_require__(41);
6853
6854var notARegExp = __webpack_require__(179);
6855
6856var requireObjectCoercible = __webpack_require__(14);
6857
6858var correctIsRegExpLogic = __webpack_require__(181);
6859
6860var IS_PURE = __webpack_require__(31);
6861
6862var nativeStartsWith = ''.startsWith;
6863var min = Math.min;
6864var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith'); // https://github.com/zloirock/core-js/pull/702
6865
6866var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () {
6867 var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith');
6868 return descriptor && !descriptor.writable;
6869}(); // `String.prototype.startsWith` method
6870// https://tc39.github.io/ecma262/#sec-string.prototype.startswith
6871
6872$({
6873 target: 'String',
6874 proto: true,
6875 forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC
6876}, {
6877 startsWith: function startsWith(searchString
6878 /* , position = 0 */
6879 ) {
6880 var that = String(requireObjectCoercible(this));
6881 notARegExp(searchString);
6882 var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length));
6883 var search = String(searchString);
6884 return nativeStartsWith ? nativeStartsWith.call(that, search, index) : that.slice(index, index + search.length) === search;
6885 }
6886});
6887
6888/***/ }),
6889/* 203 */
6890/***/ (function(module, exports, __webpack_require__) {
6891
6892"use strict";
6893
6894
6895var $ = __webpack_require__(4);
6896
6897var $trim = __webpack_require__(204).trim;
6898
6899var forcedStringTrimMethod = __webpack_require__(206); // `String.prototype.trim` method
6900// https://tc39.github.io/ecma262/#sec-string.prototype.trim
6901
6902
6903$({
6904 target: 'String',
6905 proto: true,
6906 forced: forcedStringTrimMethod('trim')
6907}, {
6908 trim: function trim() {
6909 return $trim(this);
6910 }
6911});
6912
6913/***/ }),
6914/* 204 */
6915/***/ (function(module, exports, __webpack_require__) {
6916
6917var requireObjectCoercible = __webpack_require__(14);
6918
6919var whitespaces = __webpack_require__(205);
6920
6921var whitespace = '[' + whitespaces + ']';
6922var ltrim = RegExp('^' + whitespace + whitespace + '*');
6923var rtrim = RegExp(whitespace + whitespace + '*$'); // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
6924
6925var createMethod = function createMethod(TYPE) {
6926 return function ($this) {
6927 var string = String(requireObjectCoercible($this));
6928 if (TYPE & 1) string = string.replace(ltrim, '');
6929 if (TYPE & 2) string = string.replace(rtrim, '');
6930 return string;
6931 };
6932};
6933
6934module.exports = {
6935 // `String.prototype.{ trimLeft, trimStart }` methods
6936 // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
6937 start: createMethod(1),
6938 // `String.prototype.{ trimRight, trimEnd }` methods
6939 // https://tc39.github.io/ecma262/#sec-string.prototype.trimend
6940 end: createMethod(2),
6941 // `String.prototype.trim` method
6942 // https://tc39.github.io/ecma262/#sec-string.prototype.trim
6943 trim: createMethod(3)
6944};
6945
6946/***/ }),
6947/* 205 */
6948/***/ (function(module, exports) {
6949
6950// a string of all valid unicode whitespaces
6951// eslint-disable-next-line max-len
6952module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
6953
6954/***/ }),
6955/* 206 */
6956/***/ (function(module, exports, __webpack_require__) {
6957
6958var fails = __webpack_require__(8);
6959
6960var whitespaces = __webpack_require__(205);
6961
6962var non = '\u200B\u0085\u180E'; // check that a method works with the correct list
6963// of whitespaces and has a correct name
6964
6965module.exports = function (METHOD_NAME) {
6966 return fails(function () {
6967 return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;
6968 });
6969};
6970
6971/***/ }),
6972/* 207 */
6973/***/ (function(module, exports, __webpack_require__) {
6974
6975"use strict";
6976
6977
6978var $ = __webpack_require__(4);
6979
6980var $trimStart = __webpack_require__(204).start;
6981
6982var forcedStringTrimMethod = __webpack_require__(206);
6983
6984var FORCED = forcedStringTrimMethod('trimStart');
6985var trimStart = FORCED ? function trimStart() {
6986 return $trimStart(this);
6987} : ''.trimStart; // `String.prototype.{ trimStart, trimLeft }` methods
6988// https://github.com/tc39/ecmascript-string-left-right-trim
6989
6990$({
6991 target: 'String',
6992 proto: true,
6993 forced: FORCED
6994}, {
6995 trimStart: trimStart,
6996 trimLeft: trimStart
6997});
6998
6999/***/ }),
7000/* 208 */
7001/***/ (function(module, exports, __webpack_require__) {
7002
7003"use strict";
7004
7005
7006var $ = __webpack_require__(4);
7007
7008var $trimEnd = __webpack_require__(204).end;
7009
7010var forcedStringTrimMethod = __webpack_require__(206);
7011
7012var FORCED = forcedStringTrimMethod('trimEnd');
7013var trimEnd = FORCED ? function trimEnd() {
7014 return $trimEnd(this);
7015} : ''.trimEnd; // `String.prototype.{ trimEnd, trimRight }` methods
7016// https://github.com/tc39/ecmascript-string-left-right-trim
7017
7018$({
7019 target: 'String',
7020 proto: true,
7021 forced: FORCED
7022}, {
7023 trimEnd: trimEnd,
7024 trimRight: trimEnd
7025});
7026
7027/***/ }),
7028/* 209 */
7029/***/ (function(module, exports, __webpack_require__) {
7030
7031"use strict";
7032
7033
7034var charAt = __webpack_require__(177).charAt;
7035
7036var InternalStateModule = __webpack_require__(27);
7037
7038var defineIterator = __webpack_require__(171);
7039
7040var STRING_ITERATOR = 'String Iterator';
7041var setInternalState = InternalStateModule.set;
7042var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method
7043// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
7044
7045defineIterator(String, 'String', function (iterated) {
7046 setInternalState(this, {
7047 type: STRING_ITERATOR,
7048 string: String(iterated),
7049 index: 0
7050 }); // `%StringIteratorPrototype%.next` method
7051 // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
7052}, function next() {
7053 var state = getInternalState(this);
7054 var string = state.string;
7055 var index = state.index;
7056 var point;
7057 if (index >= string.length) return {
7058 value: undefined,
7059 done: true
7060 };
7061 point = charAt(string, index);
7062 state.index += point.length;
7063 return {
7064 value: point,
7065 done: false
7066 };
7067});
7068
7069/***/ }),
7070/* 210 */
7071/***/ (function(module, exports, __webpack_require__) {
7072
7073"use strict";
7074
7075
7076var $ = __webpack_require__(4);
7077
7078var createHTML = __webpack_require__(211);
7079
7080var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.anchor` method
7081// https://tc39.github.io/ecma262/#sec-string.prototype.anchor
7082
7083
7084$({
7085 target: 'String',
7086 proto: true,
7087 forced: forcedStringHTMLMethod('anchor')
7088}, {
7089 anchor: function anchor(name) {
7090 return createHTML(this, 'a', 'name', name);
7091 }
7092});
7093
7094/***/ }),
7095/* 211 */
7096/***/ (function(module, exports, __webpack_require__) {
7097
7098var requireObjectCoercible = __webpack_require__(14);
7099
7100var quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value)
7101// https://tc39.github.io/ecma262/#sec-createhtml
7102
7103module.exports = function (string, tag, attribute, value) {
7104 var S = String(requireObjectCoercible(string));
7105 var p1 = '<' + tag;
7106 if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"';
7107 return p1 + '>' + S + '</' + tag + '>';
7108};
7109
7110/***/ }),
7111/* 212 */
7112/***/ (function(module, exports, __webpack_require__) {
7113
7114var fails = __webpack_require__(8); // check the existence of a method, lowercase
7115// of a tag and escaping quotes in arguments
7116
7117
7118module.exports = function (METHOD_NAME) {
7119 return fails(function () {
7120 var test = ''[METHOD_NAME]('"');
7121 return test !== test.toLowerCase() || test.split('"').length > 3;
7122 });
7123};
7124
7125/***/ }),
7126/* 213 */
7127/***/ (function(module, exports, __webpack_require__) {
7128
7129"use strict";
7130
7131
7132var $ = __webpack_require__(4);
7133
7134var createHTML = __webpack_require__(211);
7135
7136var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.big` method
7137// https://tc39.github.io/ecma262/#sec-string.prototype.big
7138
7139
7140$({
7141 target: 'String',
7142 proto: true,
7143 forced: forcedStringHTMLMethod('big')
7144}, {
7145 big: function big() {
7146 return createHTML(this, 'big', '', '');
7147 }
7148});
7149
7150/***/ }),
7151/* 214 */
7152/***/ (function(module, exports, __webpack_require__) {
7153
7154"use strict";
7155
7156
7157var $ = __webpack_require__(4);
7158
7159var createHTML = __webpack_require__(211);
7160
7161var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.blink` method
7162// https://tc39.github.io/ecma262/#sec-string.prototype.blink
7163
7164
7165$({
7166 target: 'String',
7167 proto: true,
7168 forced: forcedStringHTMLMethod('blink')
7169}, {
7170 blink: function blink() {
7171 return createHTML(this, 'blink', '', '');
7172 }
7173});
7174
7175/***/ }),
7176/* 215 */
7177/***/ (function(module, exports, __webpack_require__) {
7178
7179"use strict";
7180
7181
7182var $ = __webpack_require__(4);
7183
7184var createHTML = __webpack_require__(211);
7185
7186var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.bold` method
7187// https://tc39.github.io/ecma262/#sec-string.prototype.bold
7188
7189
7190$({
7191 target: 'String',
7192 proto: true,
7193 forced: forcedStringHTMLMethod('bold')
7194}, {
7195 bold: function bold() {
7196 return createHTML(this, 'b', '', '');
7197 }
7198});
7199
7200/***/ }),
7201/* 216 */
7202/***/ (function(module, exports, __webpack_require__) {
7203
7204"use strict";
7205
7206
7207var $ = __webpack_require__(4);
7208
7209var createHTML = __webpack_require__(211);
7210
7211var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.fixed` method
7212// https://tc39.github.io/ecma262/#sec-string.prototype.fixed
7213
7214
7215$({
7216 target: 'String',
7217 proto: true,
7218 forced: forcedStringHTMLMethod('fixed')
7219}, {
7220 fixed: function fixed() {
7221 return createHTML(this, 'tt', '', '');
7222 }
7223});
7224
7225/***/ }),
7226/* 217 */
7227/***/ (function(module, exports, __webpack_require__) {
7228
7229"use strict";
7230
7231
7232var $ = __webpack_require__(4);
7233
7234var createHTML = __webpack_require__(211);
7235
7236var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.fontcolor` method
7237// https://tc39.github.io/ecma262/#sec-string.prototype.fontcolor
7238
7239
7240$({
7241 target: 'String',
7242 proto: true,
7243 forced: forcedStringHTMLMethod('fontcolor')
7244}, {
7245 fontcolor: function fontcolor(color) {
7246 return createHTML(this, 'font', 'color', color);
7247 }
7248});
7249
7250/***/ }),
7251/* 218 */
7252/***/ (function(module, exports, __webpack_require__) {
7253
7254"use strict";
7255
7256
7257var $ = __webpack_require__(4);
7258
7259var createHTML = __webpack_require__(211);
7260
7261var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.fontsize` method
7262// https://tc39.github.io/ecma262/#sec-string.prototype.fontsize
7263
7264
7265$({
7266 target: 'String',
7267 proto: true,
7268 forced: forcedStringHTMLMethod('fontsize')
7269}, {
7270 fontsize: function fontsize(size) {
7271 return createHTML(this, 'font', 'size', size);
7272 }
7273});
7274
7275/***/ }),
7276/* 219 */
7277/***/ (function(module, exports, __webpack_require__) {
7278
7279"use strict";
7280
7281
7282var $ = __webpack_require__(4);
7283
7284var createHTML = __webpack_require__(211);
7285
7286var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.italics` method
7287// https://tc39.github.io/ecma262/#sec-string.prototype.italics
7288
7289
7290$({
7291 target: 'String',
7292 proto: true,
7293 forced: forcedStringHTMLMethod('italics')
7294}, {
7295 italics: function italics() {
7296 return createHTML(this, 'i', '', '');
7297 }
7298});
7299
7300/***/ }),
7301/* 220 */
7302/***/ (function(module, exports, __webpack_require__) {
7303
7304"use strict";
7305
7306
7307var $ = __webpack_require__(4);
7308
7309var createHTML = __webpack_require__(211);
7310
7311var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.link` method
7312// https://tc39.github.io/ecma262/#sec-string.prototype.link
7313
7314
7315$({
7316 target: 'String',
7317 proto: true,
7318 forced: forcedStringHTMLMethod('link')
7319}, {
7320 link: function link(url) {
7321 return createHTML(this, 'a', 'href', url);
7322 }
7323});
7324
7325/***/ }),
7326/* 221 */
7327/***/ (function(module, exports, __webpack_require__) {
7328
7329"use strict";
7330
7331
7332var $ = __webpack_require__(4);
7333
7334var createHTML = __webpack_require__(211);
7335
7336var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.small` method
7337// https://tc39.github.io/ecma262/#sec-string.prototype.small
7338
7339
7340$({
7341 target: 'String',
7342 proto: true,
7343 forced: forcedStringHTMLMethod('small')
7344}, {
7345 small: function small() {
7346 return createHTML(this, 'small', '', '');
7347 }
7348});
7349
7350/***/ }),
7351/* 222 */
7352/***/ (function(module, exports, __webpack_require__) {
7353
7354"use strict";
7355
7356
7357var $ = __webpack_require__(4);
7358
7359var createHTML = __webpack_require__(211);
7360
7361var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.strike` method
7362// https://tc39.github.io/ecma262/#sec-string.prototype.strike
7363
7364
7365$({
7366 target: 'String',
7367 proto: true,
7368 forced: forcedStringHTMLMethod('strike')
7369}, {
7370 strike: function strike() {
7371 return createHTML(this, 'strike', '', '');
7372 }
7373});
7374
7375/***/ }),
7376/* 223 */
7377/***/ (function(module, exports, __webpack_require__) {
7378
7379"use strict";
7380
7381
7382var $ = __webpack_require__(4);
7383
7384var createHTML = __webpack_require__(211);
7385
7386var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.sub` method
7387// https://tc39.github.io/ecma262/#sec-string.prototype.sub
7388
7389
7390$({
7391 target: 'String',
7392 proto: true,
7393 forced: forcedStringHTMLMethod('sub')
7394}, {
7395 sub: function sub() {
7396 return createHTML(this, 'sub', '', '');
7397 }
7398});
7399
7400/***/ }),
7401/* 224 */
7402/***/ (function(module, exports, __webpack_require__) {
7403
7404"use strict";
7405
7406
7407var $ = __webpack_require__(4);
7408
7409var createHTML = __webpack_require__(211);
7410
7411var forcedStringHTMLMethod = __webpack_require__(212); // `String.prototype.sup` method
7412// https://tc39.github.io/ecma262/#sec-string.prototype.sup
7413
7414
7415$({
7416 target: 'String',
7417 proto: true,
7418 forced: forcedStringHTMLMethod('sup')
7419}, {
7420 sup: function sup() {
7421 return createHTML(this, 'sup', '', '');
7422 }
7423});
7424
7425/***/ }),
7426/* 225 */
7427/***/ (function(module, exports, __webpack_require__) {
7428
7429var DESCRIPTORS = __webpack_require__(7);
7430
7431var global = __webpack_require__(5);
7432
7433var isForced = __webpack_require__(46);
7434
7435var inheritIfRequired = __webpack_require__(226);
7436
7437var defineProperty = __webpack_require__(21).f;
7438
7439var getOwnPropertyNames = __webpack_require__(38).f;
7440
7441var isRegExp = __webpack_require__(180);
7442
7443var getFlags = __webpack_require__(187);
7444
7445var stickyHelpers = __webpack_require__(188);
7446
7447var redefine = __webpack_require__(23);
7448
7449var fails = __webpack_require__(8);
7450
7451var setInternalState = __webpack_require__(27).set;
7452
7453var setSpecies = __webpack_require__(167);
7454
7455var wellKnownSymbol = __webpack_require__(56);
7456
7457var MATCH = wellKnownSymbol('match');
7458var NativeRegExp = global.RegExp;
7459var RegExpPrototype = NativeRegExp.prototype;
7460var re1 = /a/g;
7461var re2 = /a/g; // "new" should create a new object, old webkit bug
7462
7463var CORRECT_NEW = new NativeRegExp(re1) !== re1;
7464var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y;
7465var FORCED = DESCRIPTORS && isForced('RegExp', !CORRECT_NEW || UNSUPPORTED_Y || fails(function () {
7466 re2[MATCH] = false; // RegExp constructor can alter flags and IsRegExp works correct with @@match
7467
7468 return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i';
7469})); // `RegExp` constructor
7470// https://tc39.github.io/ecma262/#sec-regexp-constructor
7471
7472if (FORCED) {
7473 var RegExpWrapper = function RegExp(pattern, flags) {
7474 var thisIsRegExp = this instanceof RegExpWrapper;
7475 var patternIsRegExp = isRegExp(pattern);
7476 var flagsAreUndefined = flags === undefined;
7477 var sticky;
7478
7479 if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) {
7480 return pattern;
7481 }
7482
7483 if (CORRECT_NEW) {
7484 if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source;
7485 } else if (pattern instanceof RegExpWrapper) {
7486 if (flagsAreUndefined) flags = getFlags.call(pattern);
7487 pattern = pattern.source;
7488 }
7489
7490 if (UNSUPPORTED_Y) {
7491 sticky = !!flags && flags.indexOf('y') > -1;
7492 if (sticky) flags = flags.replace(/y/g, '');
7493 }
7494
7495 var result = inheritIfRequired(CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags), thisIsRegExp ? this : RegExpPrototype, RegExpWrapper);
7496 if (UNSUPPORTED_Y && sticky) setInternalState(result, {
7497 sticky: sticky
7498 });
7499 return result;
7500 };
7501
7502 var proxy = function proxy(key) {
7503 key in RegExpWrapper || defineProperty(RegExpWrapper, key, {
7504 configurable: true,
7505 get: function get() {
7506 return NativeRegExp[key];
7507 },
7508 set: function set(it) {
7509 NativeRegExp[key] = it;
7510 }
7511 });
7512 };
7513
7514 var keys = getOwnPropertyNames(NativeRegExp);
7515 var index = 0;
7516
7517 while (keys.length > index) proxy(keys[index++]);
7518
7519 RegExpPrototype.constructor = RegExpWrapper;
7520 RegExpWrapper.prototype = RegExpPrototype;
7521 redefine(global, 'RegExp', RegExpWrapper);
7522} // https://tc39.github.io/ecma262/#sec-get-regexp-@@species
7523
7524
7525setSpecies('RegExp');
7526
7527/***/ }),
7528/* 226 */
7529/***/ (function(module, exports, __webpack_require__) {
7530
7531var isObject = __webpack_require__(16);
7532
7533var setPrototypeOf = __webpack_require__(112); // makes subclassing work correct for wrapped built-ins
7534
7535
7536module.exports = function ($this, dummy, Wrapper) {
7537 var NewTarget, NewTargetPrototype;
7538 if ( // it can work only with native `setPrototypeOf`
7539 setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
7540 typeof (NewTarget = dummy.constructor) == 'function' && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype) setPrototypeOf($this, NewTargetPrototype);
7541 return $this;
7542};
7543
7544/***/ }),
7545/* 227 */
7546/***/ (function(module, exports, __webpack_require__) {
7547
7548var DESCRIPTORS = __webpack_require__(7);
7549
7550var objectDefinePropertyModule = __webpack_require__(21);
7551
7552var regExpFlags = __webpack_require__(187);
7553
7554var UNSUPPORTED_Y = __webpack_require__(188).UNSUPPORTED_Y; // `RegExp.prototype.flags` getter
7555// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
7556
7557
7558if (DESCRIPTORS && (/./g.flags != 'g' || UNSUPPORTED_Y)) {
7559 objectDefinePropertyModule.f(RegExp.prototype, 'flags', {
7560 configurable: true,
7561 get: regExpFlags
7562 });
7563}
7564
7565/***/ }),
7566/* 228 */
7567/***/ (function(module, exports, __webpack_require__) {
7568
7569var DESCRIPTORS = __webpack_require__(7);
7570
7571var UNSUPPORTED_Y = __webpack_require__(188).UNSUPPORTED_Y;
7572
7573var defineProperty = __webpack_require__(21).f;
7574
7575var getInternalState = __webpack_require__(27).get;
7576
7577var RegExpPrototype = RegExp.prototype; // `RegExp.prototype.sticky` getter
7578
7579if (DESCRIPTORS && UNSUPPORTED_Y) {
7580 defineProperty(RegExp.prototype, 'sticky', {
7581 configurable: true,
7582 get: function get() {
7583 if (this === RegExpPrototype) return undefined; // We can't use InternalStateModule.getterFor because
7584 // we don't add metadata for regexps created by a literal.
7585
7586 if (this instanceof RegExp) {
7587 return !!getInternalState(this).sticky;
7588 }
7589
7590 throw TypeError('Incompatible receiver, RegExp required');
7591 }
7592 });
7593}
7594
7595/***/ }),
7596/* 229 */
7597/***/ (function(module, exports, __webpack_require__) {
7598
7599"use strict";
7600 // TODO: Remove from `core-js@4` since it's moved to entry points
7601
7602__webpack_require__(185);
7603
7604var $ = __webpack_require__(4);
7605
7606var isObject = __webpack_require__(16);
7607
7608var DELEGATES_TO_EXEC = function () {
7609 var execCalled = false;
7610 var re = /[ac]/;
7611
7612 re.exec = function () {
7613 execCalled = true;
7614 return /./.exec.apply(this, arguments);
7615 };
7616
7617 return re.test('abc') === true && execCalled;
7618}();
7619
7620var nativeTest = /./.test;
7621$({
7622 target: 'RegExp',
7623 proto: true,
7624 forced: !DELEGATES_TO_EXEC
7625}, {
7626 test: function test(str) {
7627 if (typeof this.exec !== 'function') {
7628 return nativeTest.call(this, str);
7629 }
7630
7631 var result = this.exec(str);
7632
7633 if (result !== null && !isObject(result)) {
7634 throw new Error('RegExp exec method returned something other than an Object or null');
7635 }
7636
7637 return !!result;
7638 }
7639});
7640
7641/***/ }),
7642/* 230 */
7643/***/ (function(module, exports, __webpack_require__) {
7644
7645"use strict";
7646
7647
7648var redefine = __webpack_require__(23);
7649
7650var anObject = __webpack_require__(22);
7651
7652var fails = __webpack_require__(8);
7653
7654var flags = __webpack_require__(187);
7655
7656var TO_STRING = 'toString';
7657var RegExpPrototype = RegExp.prototype;
7658var nativeToString = RegExpPrototype[TO_STRING];
7659var NOT_GENERIC = fails(function () {
7660 return nativeToString.call({
7661 source: 'a',
7662 flags: 'b'
7663 }) != '/a/b';
7664}); // FF44- RegExp#toString has a wrong name
7665
7666var INCORRECT_NAME = nativeToString.name != TO_STRING; // `RegExp.prototype.toString` method
7667// https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring
7668
7669if (NOT_GENERIC || INCORRECT_NAME) {
7670 redefine(RegExp.prototype, TO_STRING, function toString() {
7671 var R = anObject(this);
7672 var p = String(R.source);
7673 var rf = R.flags;
7674 var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf);
7675 return '/' + p + '/' + f;
7676 }, {
7677 unsafe: true
7678 });
7679}
7680
7681/***/ }),
7682/* 231 */
7683/***/ (function(module, exports, __webpack_require__) {
7684
7685var $ = __webpack_require__(4);
7686
7687var parseIntImplementation = __webpack_require__(232); // `parseInt` method
7688// https://tc39.github.io/ecma262/#sec-parseint-string-radix
7689
7690
7691$({
7692 global: true,
7693 forced: parseInt != parseIntImplementation
7694}, {
7695 parseInt: parseIntImplementation
7696});
7697
7698/***/ }),
7699/* 232 */
7700/***/ (function(module, exports, __webpack_require__) {
7701
7702var global = __webpack_require__(5);
7703
7704var trim = __webpack_require__(204).trim;
7705
7706var whitespaces = __webpack_require__(205);
7707
7708var $parseInt = global.parseInt;
7709var hex = /^[+-]?0[Xx]/;
7710var FORCED = $parseInt(whitespaces + '08') !== 8 || $parseInt(whitespaces + '0x16') !== 22; // `parseInt` method
7711// https://tc39.github.io/ecma262/#sec-parseint-string-radix
7712
7713module.exports = FORCED ? function parseInt(string, radix) {
7714 var S = trim(String(string));
7715 return $parseInt(S, radix >>> 0 || (hex.test(S) ? 16 : 10));
7716} : $parseInt;
7717
7718/***/ }),
7719/* 233 */
7720/***/ (function(module, exports, __webpack_require__) {
7721
7722var $ = __webpack_require__(4);
7723
7724var parseFloatImplementation = __webpack_require__(234); // `parseFloat` method
7725// https://tc39.github.io/ecma262/#sec-parsefloat-string
7726
7727
7728$({
7729 global: true,
7730 forced: parseFloat != parseFloatImplementation
7731}, {
7732 parseFloat: parseFloatImplementation
7733});
7734
7735/***/ }),
7736/* 234 */
7737/***/ (function(module, exports, __webpack_require__) {
7738
7739var global = __webpack_require__(5);
7740
7741var trim = __webpack_require__(204).trim;
7742
7743var whitespaces = __webpack_require__(205);
7744
7745var $parseFloat = global.parseFloat;
7746var FORCED = 1 / $parseFloat(whitespaces + '-0') !== -Infinity; // `parseFloat` method
7747// https://tc39.github.io/ecma262/#sec-parsefloat-string
7748
7749module.exports = FORCED ? function parseFloat(string) {
7750 var trimmedString = trim(String(string));
7751 var result = $parseFloat(trimmedString);
7752 return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result;
7753} : $parseFloat;
7754
7755/***/ }),
7756/* 235 */
7757/***/ (function(module, exports, __webpack_require__) {
7758
7759"use strict";
7760
7761
7762var DESCRIPTORS = __webpack_require__(7);
7763
7764var global = __webpack_require__(5);
7765
7766var isForced = __webpack_require__(46);
7767
7768var redefine = __webpack_require__(23);
7769
7770var has = __webpack_require__(17);
7771
7772var classof = __webpack_require__(13);
7773
7774var inheritIfRequired = __webpack_require__(226);
7775
7776var toPrimitive = __webpack_require__(15);
7777
7778var fails = __webpack_require__(8);
7779
7780var create = __webpack_require__(51);
7781
7782var getOwnPropertyNames = __webpack_require__(38).f;
7783
7784var getOwnPropertyDescriptor = __webpack_require__(6).f;
7785
7786var defineProperty = __webpack_require__(21).f;
7787
7788var trim = __webpack_require__(204).trim;
7789
7790var NUMBER = 'Number';
7791var NativeNumber = global[NUMBER];
7792var NumberPrototype = NativeNumber.prototype; // Opera ~12 has broken Object#toString
7793
7794var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER; // `ToNumber` abstract operation
7795// https://tc39.github.io/ecma262/#sec-tonumber
7796
7797var toNumber = function toNumber(argument) {
7798 var it = toPrimitive(argument, false);
7799 var first, third, radix, maxCode, digits, length, index, code;
7800
7801 if (typeof it == 'string' && it.length > 2) {
7802 it = trim(it);
7803 first = it.charCodeAt(0);
7804
7805 if (first === 43 || first === 45) {
7806 third = it.charCodeAt(2);
7807 if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
7808 } else if (first === 48) {
7809 switch (it.charCodeAt(1)) {
7810 case 66:
7811 case 98:
7812 radix = 2;
7813 maxCode = 49;
7814 break;
7815 // fast equal of /^0b[01]+$/i
7816
7817 case 79:
7818 case 111:
7819 radix = 8;
7820 maxCode = 55;
7821 break;
7822 // fast equal of /^0o[0-7]+$/i
7823
7824 default:
7825 return +it;
7826 }
7827
7828 digits = it.slice(2);
7829 length = digits.length;
7830
7831 for (index = 0; index < length; index++) {
7832 code = digits.charCodeAt(index); // parseInt parses a string to a first unavailable symbol
7833 // but ToNumber should return NaN if a string contains unavailable symbols
7834
7835 if (code < 48 || code > maxCode) return NaN;
7836 }
7837
7838 return parseInt(digits, radix);
7839 }
7840 }
7841
7842 return +it;
7843}; // `Number` constructor
7844// https://tc39.github.io/ecma262/#sec-number-constructor
7845
7846
7847if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
7848 var NumberWrapper = function Number(value) {
7849 var it = arguments.length < 1 ? 0 : value;
7850 var dummy = this;
7851 return dummy instanceof NumberWrapper // check on 1..constructor(foo) case
7852 && (BROKEN_CLASSOF ? fails(function () {
7853 NumberPrototype.valueOf.call(dummy);
7854 }) : classof(dummy) != NUMBER) ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
7855 };
7856
7857 for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : ( // ES3:
7858 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before):
7859 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger').split(','), j = 0, key; keys.length > j; j++) {
7860 if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) {
7861 defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key));
7862 }
7863 }
7864
7865 NumberWrapper.prototype = NumberPrototype;
7866 NumberPrototype.constructor = NumberWrapper;
7867 redefine(global, NUMBER, NumberWrapper);
7868}
7869
7870/***/ }),
7871/* 236 */
7872/***/ (function(module, exports, __webpack_require__) {
7873
7874var $ = __webpack_require__(4); // `Number.EPSILON` constant
7875// https://tc39.github.io/ecma262/#sec-number.epsilon
7876
7877
7878$({
7879 target: 'Number',
7880 stat: true
7881}, {
7882 EPSILON: Math.pow(2, -52)
7883});
7884
7885/***/ }),
7886/* 237 */
7887/***/ (function(module, exports, __webpack_require__) {
7888
7889var $ = __webpack_require__(4);
7890
7891var numberIsFinite = __webpack_require__(238); // `Number.isFinite` method
7892// https://tc39.github.io/ecma262/#sec-number.isfinite
7893
7894
7895$({
7896 target: 'Number',
7897 stat: true
7898}, {
7899 isFinite: numberIsFinite
7900});
7901
7902/***/ }),
7903/* 238 */
7904/***/ (function(module, exports, __webpack_require__) {
7905
7906var global = __webpack_require__(5);
7907
7908var globalIsFinite = global.isFinite; // `Number.isFinite` method
7909// https://tc39.github.io/ecma262/#sec-number.isfinite
7910
7911module.exports = Number.isFinite || function isFinite(it) {
7912 return typeof it == 'number' && globalIsFinite(it);
7913};
7914
7915/***/ }),
7916/* 239 */
7917/***/ (function(module, exports, __webpack_require__) {
7918
7919var $ = __webpack_require__(4);
7920
7921var isInteger = __webpack_require__(240); // `Number.isInteger` method
7922// https://tc39.github.io/ecma262/#sec-number.isinteger
7923
7924
7925$({
7926 target: 'Number',
7927 stat: true
7928}, {
7929 isInteger: isInteger
7930});
7931
7932/***/ }),
7933/* 240 */
7934/***/ (function(module, exports, __webpack_require__) {
7935
7936var isObject = __webpack_require__(16);
7937
7938var floor = Math.floor; // `Number.isInteger` method implementation
7939// https://tc39.github.io/ecma262/#sec-number.isinteger
7940
7941module.exports = function isInteger(it) {
7942 return !isObject(it) && isFinite(it) && floor(it) === it;
7943};
7944
7945/***/ }),
7946/* 241 */
7947/***/ (function(module, exports, __webpack_require__) {
7948
7949var $ = __webpack_require__(4); // `Number.isNaN` method
7950// https://tc39.github.io/ecma262/#sec-number.isnan
7951
7952
7953$({
7954 target: 'Number',
7955 stat: true
7956}, {
7957 isNaN: function isNaN(number) {
7958 // eslint-disable-next-line no-self-compare
7959 return number != number;
7960 }
7961});
7962
7963/***/ }),
7964/* 242 */
7965/***/ (function(module, exports, __webpack_require__) {
7966
7967var $ = __webpack_require__(4);
7968
7969var isInteger = __webpack_require__(240);
7970
7971var abs = Math.abs; // `Number.isSafeInteger` method
7972// https://tc39.github.io/ecma262/#sec-number.issafeinteger
7973
7974$({
7975 target: 'Number',
7976 stat: true
7977}, {
7978 isSafeInteger: function isSafeInteger(number) {
7979 return isInteger(number) && abs(number) <= 0x1FFFFFFFFFFFFF;
7980 }
7981});
7982
7983/***/ }),
7984/* 243 */
7985/***/ (function(module, exports, __webpack_require__) {
7986
7987var $ = __webpack_require__(4); // `Number.MAX_SAFE_INTEGER` constant
7988// https://tc39.github.io/ecma262/#sec-number.max_safe_integer
7989
7990
7991$({
7992 target: 'Number',
7993 stat: true
7994}, {
7995 MAX_SAFE_INTEGER: 0x1FFFFFFFFFFFFF
7996});
7997
7998/***/ }),
7999/* 244 */
8000/***/ (function(module, exports, __webpack_require__) {
8001
8002var $ = __webpack_require__(4); // `Number.MIN_SAFE_INTEGER` constant
8003// https://tc39.github.io/ecma262/#sec-number.min_safe_integer
8004
8005
8006$({
8007 target: 'Number',
8008 stat: true
8009}, {
8010 MIN_SAFE_INTEGER: -0x1FFFFFFFFFFFFF
8011});
8012
8013/***/ }),
8014/* 245 */
8015/***/ (function(module, exports, __webpack_require__) {
8016
8017var $ = __webpack_require__(4);
8018
8019var parseFloat = __webpack_require__(234); // `Number.parseFloat` method
8020// https://tc39.github.io/ecma262/#sec-number.parseFloat
8021
8022
8023$({
8024 target: 'Number',
8025 stat: true,
8026 forced: Number.parseFloat != parseFloat
8027}, {
8028 parseFloat: parseFloat
8029});
8030
8031/***/ }),
8032/* 246 */
8033/***/ (function(module, exports, __webpack_require__) {
8034
8035var $ = __webpack_require__(4);
8036
8037var parseInt = __webpack_require__(232); // `Number.parseInt` method
8038// https://tc39.github.io/ecma262/#sec-number.parseint
8039
8040
8041$({
8042 target: 'Number',
8043 stat: true,
8044 forced: Number.parseInt != parseInt
8045}, {
8046 parseInt: parseInt
8047});
8048
8049/***/ }),
8050/* 247 */
8051/***/ (function(module, exports, __webpack_require__) {
8052
8053"use strict";
8054
8055
8056var $ = __webpack_require__(4);
8057
8058var toInteger = __webpack_require__(42);
8059
8060var thisNumberValue = __webpack_require__(248);
8061
8062var repeat = __webpack_require__(195);
8063
8064var fails = __webpack_require__(8);
8065
8066var nativeToFixed = 1.0.toFixed;
8067var floor = Math.floor;
8068
8069var pow = function pow(x, n, acc) {
8070 return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
8071};
8072
8073var log = function log(x) {
8074 var n = 0;
8075 var x2 = x;
8076
8077 while (x2 >= 4096) {
8078 n += 12;
8079 x2 /= 4096;
8080 }
8081
8082 while (x2 >= 2) {
8083 n += 1;
8084 x2 /= 2;
8085 }
8086
8087 return n;
8088};
8089
8090var FORCED = nativeToFixed && (0.00008.toFixed(3) !== '0.000' || 0.9.toFixed(0) !== '1' || 1.255.toFixed(2) !== '1.25' || 1000000000000000128.0.toFixed(0) !== '1000000000000000128') || !fails(function () {
8091 // V8 ~ Android 4.3-
8092 nativeToFixed.call({});
8093}); // `Number.prototype.toFixed` method
8094// https://tc39.github.io/ecma262/#sec-number.prototype.tofixed
8095
8096$({
8097 target: 'Number',
8098 proto: true,
8099 forced: FORCED
8100}, {
8101 // eslint-disable-next-line max-statements
8102 toFixed: function toFixed(fractionDigits) {
8103 var number = thisNumberValue(this);
8104 var fractDigits = toInteger(fractionDigits);
8105 var data = [0, 0, 0, 0, 0, 0];
8106 var sign = '';
8107 var result = '0';
8108 var e, z, j, k;
8109
8110 var multiply = function multiply(n, c) {
8111 var index = -1;
8112 var c2 = c;
8113
8114 while (++index < 6) {
8115 c2 += n * data[index];
8116 data[index] = c2 % 1e7;
8117 c2 = floor(c2 / 1e7);
8118 }
8119 };
8120
8121 var divide = function divide(n) {
8122 var index = 6;
8123 var c = 0;
8124
8125 while (--index >= 0) {
8126 c += data[index];
8127 data[index] = floor(c / n);
8128 c = c % n * 1e7;
8129 }
8130 };
8131
8132 var dataToString = function dataToString() {
8133 var index = 6;
8134 var s = '';
8135
8136 while (--index >= 0) {
8137 if (s !== '' || index === 0 || data[index] !== 0) {
8138 var t = String(data[index]);
8139 s = s === '' ? t : s + repeat.call('0', 7 - t.length) + t;
8140 }
8141 }
8142
8143 return s;
8144 };
8145
8146 if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); // eslint-disable-next-line no-self-compare
8147
8148 if (number != number) return 'NaN';
8149 if (number <= -1e21 || number >= 1e21) return String(number);
8150
8151 if (number < 0) {
8152 sign = '-';
8153 number = -number;
8154 }
8155
8156 if (number > 1e-21) {
8157 e = log(number * pow(2, 69, 1)) - 69;
8158 z = e < 0 ? number * pow(2, -e, 1) : number / pow(2, e, 1);
8159 z *= 0x10000000000000;
8160 e = 52 - e;
8161
8162 if (e > 0) {
8163 multiply(0, z);
8164 j = fractDigits;
8165
8166 while (j >= 7) {
8167 multiply(1e7, 0);
8168 j -= 7;
8169 }
8170
8171 multiply(pow(10, j, 1), 0);
8172 j = e - 1;
8173
8174 while (j >= 23) {
8175 divide(1 << 23);
8176 j -= 23;
8177 }
8178
8179 divide(1 << j);
8180 multiply(1, 1);
8181 divide(2);
8182 result = dataToString();
8183 } else {
8184 multiply(0, z);
8185 multiply(1 << -e, 0);
8186 result = dataToString() + repeat.call('0', fractDigits);
8187 }
8188 }
8189
8190 if (fractDigits > 0) {
8191 k = result.length;
8192 result = sign + (k <= fractDigits ? '0.' + repeat.call('0', fractDigits - k) + result : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits));
8193 } else {
8194 result = sign + result;
8195 }
8196
8197 return result;
8198 }
8199});
8200
8201/***/ }),
8202/* 248 */
8203/***/ (function(module, exports, __webpack_require__) {
8204
8205var classof = __webpack_require__(13); // `thisNumberValue` abstract operation
8206// https://tc39.github.io/ecma262/#sec-thisnumbervalue
8207
8208
8209module.exports = function (value) {
8210 if (typeof value != 'number' && classof(value) != 'Number') {
8211 throw TypeError('Incorrect invocation');
8212 }
8213
8214 return +value;
8215};
8216
8217/***/ }),
8218/* 249 */
8219/***/ (function(module, exports, __webpack_require__) {
8220
8221"use strict";
8222
8223
8224var $ = __webpack_require__(4);
8225
8226var fails = __webpack_require__(8);
8227
8228var thisNumberValue = __webpack_require__(248);
8229
8230var nativeToPrecision = 1.0.toPrecision;
8231var FORCED = fails(function () {
8232 // IE7-
8233 return nativeToPrecision.call(1, undefined) !== '1';
8234}) || !fails(function () {
8235 // V8 ~ Android 4.3-
8236 nativeToPrecision.call({});
8237}); // `Number.prototype.toPrecision` method
8238// https://tc39.github.io/ecma262/#sec-number.prototype.toprecision
8239
8240$({
8241 target: 'Number',
8242 proto: true,
8243 forced: FORCED
8244}, {
8245 toPrecision: function toPrecision(precision) {
8246 return precision === undefined ? nativeToPrecision.call(thisNumberValue(this)) : nativeToPrecision.call(thisNumberValue(this), precision);
8247 }
8248});
8249
8250/***/ }),
8251/* 250 */
8252/***/ (function(module, exports, __webpack_require__) {
8253
8254var $ = __webpack_require__(4);
8255
8256var log1p = __webpack_require__(251);
8257
8258var nativeAcosh = Math.acosh;
8259var log = Math.log;
8260var sqrt = Math.sqrt;
8261var LN2 = Math.LN2;
8262var FORCED = !nativeAcosh // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
8263|| Math.floor(nativeAcosh(Number.MAX_VALUE)) != 710 // Tor Browser bug: Math.acosh(Infinity) -> NaN
8264|| nativeAcosh(Infinity) != Infinity; // `Math.acosh` method
8265// https://tc39.github.io/ecma262/#sec-math.acosh
8266
8267$({
8268 target: 'Math',
8269 stat: true,
8270 forced: FORCED
8271}, {
8272 acosh: function acosh(x) {
8273 return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? log(x) + LN2 : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
8274 }
8275});
8276
8277/***/ }),
8278/* 251 */
8279/***/ (function(module, exports) {
8280
8281var log = Math.log; // `Math.log1p` method implementation
8282// https://tc39.github.io/ecma262/#sec-math.log1p
8283
8284module.exports = Math.log1p || function log1p(x) {
8285 return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x);
8286};
8287
8288/***/ }),
8289/* 252 */
8290/***/ (function(module, exports, __webpack_require__) {
8291
8292var $ = __webpack_require__(4);
8293
8294var nativeAsinh = Math.asinh;
8295var log = Math.log;
8296var sqrt = Math.sqrt;
8297
8298function asinh(x) {
8299 return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1));
8300} // `Math.asinh` method
8301// https://tc39.github.io/ecma262/#sec-math.asinh
8302// Tor Browser bug: Math.asinh(0) -> -0
8303
8304
8305$({
8306 target: 'Math',
8307 stat: true,
8308 forced: !(nativeAsinh && 1 / nativeAsinh(0) > 0)
8309}, {
8310 asinh: asinh
8311});
8312
8313/***/ }),
8314/* 253 */
8315/***/ (function(module, exports, __webpack_require__) {
8316
8317var $ = __webpack_require__(4);
8318
8319var nativeAtanh = Math.atanh;
8320var log = Math.log; // `Math.atanh` method
8321// https://tc39.github.io/ecma262/#sec-math.atanh
8322// Tor Browser bug: Math.atanh(-0) -> 0
8323
8324$({
8325 target: 'Math',
8326 stat: true,
8327 forced: !(nativeAtanh && 1 / nativeAtanh(-0) < 0)
8328}, {
8329 atanh: function atanh(x) {
8330 return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2;
8331 }
8332});
8333
8334/***/ }),
8335/* 254 */
8336/***/ (function(module, exports, __webpack_require__) {
8337
8338var $ = __webpack_require__(4);
8339
8340var sign = __webpack_require__(255);
8341
8342var abs = Math.abs;
8343var pow = Math.pow; // `Math.cbrt` method
8344// https://tc39.github.io/ecma262/#sec-math.cbrt
8345
8346$({
8347 target: 'Math',
8348 stat: true
8349}, {
8350 cbrt: function cbrt(x) {
8351 return sign(x = +x) * pow(abs(x), 1 / 3);
8352 }
8353});
8354
8355/***/ }),
8356/* 255 */
8357/***/ (function(module, exports) {
8358
8359// `Math.sign` method implementation
8360// https://tc39.github.io/ecma262/#sec-math.sign
8361module.exports = Math.sign || function sign(x) {
8362 // eslint-disable-next-line no-self-compare
8363 return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
8364};
8365
8366/***/ }),
8367/* 256 */
8368/***/ (function(module, exports, __webpack_require__) {
8369
8370var $ = __webpack_require__(4);
8371
8372var floor = Math.floor;
8373var log = Math.log;
8374var LOG2E = Math.LOG2E; // `Math.clz32` method
8375// https://tc39.github.io/ecma262/#sec-math.clz32
8376
8377$({
8378 target: 'Math',
8379 stat: true
8380}, {
8381 clz32: function clz32(x) {
8382 return (x >>>= 0) ? 31 - floor(log(x + 0.5) * LOG2E) : 32;
8383 }
8384});
8385
8386/***/ }),
8387/* 257 */
8388/***/ (function(module, exports, __webpack_require__) {
8389
8390var $ = __webpack_require__(4);
8391
8392var expm1 = __webpack_require__(258);
8393
8394var nativeCosh = Math.cosh;
8395var abs = Math.abs;
8396var E = Math.E; // `Math.cosh` method
8397// https://tc39.github.io/ecma262/#sec-math.cosh
8398
8399$({
8400 target: 'Math',
8401 stat: true,
8402 forced: !nativeCosh || nativeCosh(710) === Infinity
8403}, {
8404 cosh: function cosh(x) {
8405 var t = expm1(abs(x) - 1) + 1;
8406 return (t + 1 / (t * E * E)) * (E / 2);
8407 }
8408});
8409
8410/***/ }),
8411/* 258 */
8412/***/ (function(module, exports) {
8413
8414var nativeExpm1 = Math.expm1;
8415var exp = Math.exp; // `Math.expm1` method implementation
8416// https://tc39.github.io/ecma262/#sec-math.expm1
8417
8418module.exports = !nativeExpm1 // Old FF bug
8419|| nativeExpm1(10) > 22025.465794806719 || nativeExpm1(10) < 22025.4657948067165168 // Tor Browser bug
8420|| nativeExpm1(-2e-17) != -2e-17 ? function expm1(x) {
8421 return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1;
8422} : nativeExpm1;
8423
8424/***/ }),
8425/* 259 */
8426/***/ (function(module, exports, __webpack_require__) {
8427
8428var $ = __webpack_require__(4);
8429
8430var expm1 = __webpack_require__(258); // `Math.expm1` method
8431// https://tc39.github.io/ecma262/#sec-math.expm1
8432
8433
8434$({
8435 target: 'Math',
8436 stat: true,
8437 forced: expm1 != Math.expm1
8438}, {
8439 expm1: expm1
8440});
8441
8442/***/ }),
8443/* 260 */
8444/***/ (function(module, exports, __webpack_require__) {
8445
8446var $ = __webpack_require__(4);
8447
8448var fround = __webpack_require__(261); // `Math.fround` method
8449// https://tc39.github.io/ecma262/#sec-math.fround
8450
8451
8452$({
8453 target: 'Math',
8454 stat: true
8455}, {
8456 fround: fround
8457});
8458
8459/***/ }),
8460/* 261 */
8461/***/ (function(module, exports, __webpack_require__) {
8462
8463var sign = __webpack_require__(255);
8464
8465var abs = Math.abs;
8466var pow = Math.pow;
8467var EPSILON = pow(2, -52);
8468var EPSILON32 = pow(2, -23);
8469var MAX32 = pow(2, 127) * (2 - EPSILON32);
8470var MIN32 = pow(2, -126);
8471
8472var roundTiesToEven = function roundTiesToEven(n) {
8473 return n + 1 / EPSILON - 1 / EPSILON;
8474}; // `Math.fround` method implementation
8475// https://tc39.github.io/ecma262/#sec-math.fround
8476
8477
8478module.exports = Math.fround || function fround(x) {
8479 var $abs = abs(x);
8480 var $sign = sign(x);
8481 var a, result;
8482 if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
8483 a = (1 + EPSILON32 / EPSILON) * $abs;
8484 result = a - (a - $abs); // eslint-disable-next-line no-self-compare
8485
8486 if (result > MAX32 || result != result) return $sign * Infinity;
8487 return $sign * result;
8488};
8489
8490/***/ }),
8491/* 262 */
8492/***/ (function(module, exports, __webpack_require__) {
8493
8494var $ = __webpack_require__(4);
8495
8496var $hypot = Math.hypot;
8497var abs = Math.abs;
8498var sqrt = Math.sqrt; // Chrome 77 bug
8499// https://bugs.chromium.org/p/v8/issues/detail?id=9546
8500
8501var BUGGY = !!$hypot && $hypot(Infinity, NaN) !== Infinity; // `Math.hypot` method
8502// https://tc39.github.io/ecma262/#sec-math.hypot
8503
8504$({
8505 target: 'Math',
8506 stat: true,
8507 forced: BUGGY
8508}, {
8509 hypot: function hypot(value1, value2) {
8510 // eslint-disable-line no-unused-vars
8511 var sum = 0;
8512 var i = 0;
8513 var aLen = arguments.length;
8514 var larg = 0;
8515 var arg, div;
8516
8517 while (i < aLen) {
8518 arg = abs(arguments[i++]);
8519
8520 if (larg < arg) {
8521 div = larg / arg;
8522 sum = sum * div * div + 1;
8523 larg = arg;
8524 } else if (arg > 0) {
8525 div = arg / larg;
8526 sum += div * div;
8527 } else sum += arg;
8528 }
8529
8530 return larg === Infinity ? Infinity : larg * sqrt(sum);
8531 }
8532});
8533
8534/***/ }),
8535/* 263 */
8536/***/ (function(module, exports, __webpack_require__) {
8537
8538var $ = __webpack_require__(4);
8539
8540var fails = __webpack_require__(8);
8541
8542var nativeImul = Math.imul;
8543var FORCED = fails(function () {
8544 return nativeImul(0xFFFFFFFF, 5) != -5 || nativeImul.length != 2;
8545}); // `Math.imul` method
8546// https://tc39.github.io/ecma262/#sec-math.imul
8547// some WebKit versions fails with big numbers, some has wrong arity
8548
8549$({
8550 target: 'Math',
8551 stat: true,
8552 forced: FORCED
8553}, {
8554 imul: function imul(x, y) {
8555 var UINT16 = 0xFFFF;
8556 var xn = +x;
8557 var yn = +y;
8558 var xl = UINT16 & xn;
8559 var yl = UINT16 & yn;
8560 return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
8561 }
8562});
8563
8564/***/ }),
8565/* 264 */
8566/***/ (function(module, exports, __webpack_require__) {
8567
8568var $ = __webpack_require__(4);
8569
8570var log = Math.log;
8571var LOG10E = Math.LOG10E; // `Math.log10` method
8572// https://tc39.github.io/ecma262/#sec-math.log10
8573
8574$({
8575 target: 'Math',
8576 stat: true
8577}, {
8578 log10: function log10(x) {
8579 return log(x) * LOG10E;
8580 }
8581});
8582
8583/***/ }),
8584/* 265 */
8585/***/ (function(module, exports, __webpack_require__) {
8586
8587var $ = __webpack_require__(4);
8588
8589var log1p = __webpack_require__(251); // `Math.log1p` method
8590// https://tc39.github.io/ecma262/#sec-math.log1p
8591
8592
8593$({
8594 target: 'Math',
8595 stat: true
8596}, {
8597 log1p: log1p
8598});
8599
8600/***/ }),
8601/* 266 */
8602/***/ (function(module, exports, __webpack_require__) {
8603
8604var $ = __webpack_require__(4);
8605
8606var log = Math.log;
8607var LN2 = Math.LN2; // `Math.log2` method
8608// https://tc39.github.io/ecma262/#sec-math.log2
8609
8610$({
8611 target: 'Math',
8612 stat: true
8613}, {
8614 log2: function log2(x) {
8615 return log(x) / LN2;
8616 }
8617});
8618
8619/***/ }),
8620/* 267 */
8621/***/ (function(module, exports, __webpack_require__) {
8622
8623var $ = __webpack_require__(4);
8624
8625var sign = __webpack_require__(255); // `Math.sign` method
8626// https://tc39.github.io/ecma262/#sec-math.sign
8627
8628
8629$({
8630 target: 'Math',
8631 stat: true
8632}, {
8633 sign: sign
8634});
8635
8636/***/ }),
8637/* 268 */
8638/***/ (function(module, exports, __webpack_require__) {
8639
8640var $ = __webpack_require__(4);
8641
8642var fails = __webpack_require__(8);
8643
8644var expm1 = __webpack_require__(258);
8645
8646var abs = Math.abs;
8647var exp = Math.exp;
8648var E = Math.E;
8649var FORCED = fails(function () {
8650 return Math.sinh(-2e-17) != -2e-17;
8651}); // `Math.sinh` method
8652// https://tc39.github.io/ecma262/#sec-math.sinh
8653// V8 near Chromium 38 has a problem with very small numbers
8654
8655$({
8656 target: 'Math',
8657 stat: true,
8658 forced: FORCED
8659}, {
8660 sinh: function sinh(x) {
8661 return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2);
8662 }
8663});
8664
8665/***/ }),
8666/* 269 */
8667/***/ (function(module, exports, __webpack_require__) {
8668
8669var $ = __webpack_require__(4);
8670
8671var expm1 = __webpack_require__(258);
8672
8673var exp = Math.exp; // `Math.tanh` method
8674// https://tc39.github.io/ecma262/#sec-math.tanh
8675
8676$({
8677 target: 'Math',
8678 stat: true
8679}, {
8680 tanh: function tanh(x) {
8681 var a = expm1(x = +x);
8682 var b = expm1(-x);
8683 return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
8684 }
8685});
8686
8687/***/ }),
8688/* 270 */
8689/***/ (function(module, exports, __webpack_require__) {
8690
8691var setToStringTag = __webpack_require__(59); // Math[@@toStringTag] property
8692// https://tc39.github.io/ecma262/#sec-math-@@tostringtag
8693
8694
8695setToStringTag(Math, 'Math', true);
8696
8697/***/ }),
8698/* 271 */
8699/***/ (function(module, exports, __webpack_require__) {
8700
8701var $ = __webpack_require__(4);
8702
8703var ceil = Math.ceil;
8704var floor = Math.floor; // `Math.trunc` method
8705// https://tc39.github.io/ecma262/#sec-math.trunc
8706
8707$({
8708 target: 'Math',
8709 stat: true
8710}, {
8711 trunc: function trunc(it) {
8712 return (it > 0 ? floor : ceil)(it);
8713 }
8714});
8715
8716/***/ }),
8717/* 272 */
8718/***/ (function(module, exports, __webpack_require__) {
8719
8720var $ = __webpack_require__(4); // `Date.now` method
8721// https://tc39.github.io/ecma262/#sec-date.now
8722
8723
8724$({
8725 target: 'Date',
8726 stat: true
8727}, {
8728 now: function now() {
8729 return new Date().getTime();
8730 }
8731});
8732
8733/***/ }),
8734/* 273 */
8735/***/ (function(module, exports, __webpack_require__) {
8736
8737"use strict";
8738
8739
8740var $ = __webpack_require__(4);
8741
8742var fails = __webpack_require__(8);
8743
8744var toObject = __webpack_require__(50);
8745
8746var toPrimitive = __webpack_require__(15);
8747
8748var FORCED = fails(function () {
8749 return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({
8750 toISOString: function toISOString() {
8751 return 1;
8752 }
8753 }) !== 1;
8754}); // `Date.prototype.toJSON` method
8755// https://tc39.github.io/ecma262/#sec-date.prototype.tojson
8756
8757$({
8758 target: 'Date',
8759 proto: true,
8760 forced: FORCED
8761}, {
8762 // eslint-disable-next-line no-unused-vars
8763 toJSON: function toJSON(key) {
8764 var O = toObject(this);
8765 var pv = toPrimitive(O);
8766 return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
8767 }
8768});
8769
8770/***/ }),
8771/* 274 */
8772/***/ (function(module, exports, __webpack_require__) {
8773
8774var $ = __webpack_require__(4);
8775
8776var toISOString = __webpack_require__(275); // `Date.prototype.toISOString` method
8777// https://tc39.github.io/ecma262/#sec-date.prototype.toisostring
8778// PhantomJS / old WebKit has a broken implementations
8779
8780
8781$({
8782 target: 'Date',
8783 proto: true,
8784 forced: Date.prototype.toISOString !== toISOString
8785}, {
8786 toISOString: toISOString
8787});
8788
8789/***/ }),
8790/* 275 */
8791/***/ (function(module, exports, __webpack_require__) {
8792
8793"use strict";
8794
8795
8796var fails = __webpack_require__(8);
8797
8798var padStart = __webpack_require__(194).start;
8799
8800var abs = Math.abs;
8801var DatePrototype = Date.prototype;
8802var getTime = DatePrototype.getTime;
8803var nativeDateToISOString = DatePrototype.toISOString; // `Date.prototype.toISOString` method implementation
8804// https://tc39.github.io/ecma262/#sec-date.prototype.toisostring
8805// PhantomJS / old WebKit fails here:
8806
8807module.exports = fails(function () {
8808 return nativeDateToISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
8809}) || !fails(function () {
8810 nativeDateToISOString.call(new Date(NaN));
8811}) ? function toISOString() {
8812 if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value');
8813 var date = this;
8814 var year = date.getUTCFullYear();
8815 var milliseconds = date.getUTCMilliseconds();
8816 var sign = year < 0 ? '-' : year > 9999 ? '+' : '';
8817 return sign + padStart(abs(year), sign ? 6 : 4, 0) + '-' + padStart(date.getUTCMonth() + 1, 2, 0) + '-' + padStart(date.getUTCDate(), 2, 0) + 'T' + padStart(date.getUTCHours(), 2, 0) + ':' + padStart(date.getUTCMinutes(), 2, 0) + ':' + padStart(date.getUTCSeconds(), 2, 0) + '.' + padStart(milliseconds, 3, 0) + 'Z';
8818} : nativeDateToISOString;
8819
8820/***/ }),
8821/* 276 */
8822/***/ (function(module, exports, __webpack_require__) {
8823
8824var redefine = __webpack_require__(23);
8825
8826var DatePrototype = Date.prototype;
8827var INVALID_DATE = 'Invalid Date';
8828var TO_STRING = 'toString';
8829var nativeDateToString = DatePrototype[TO_STRING];
8830var getTime = DatePrototype.getTime; // `Date.prototype.toString` method
8831// https://tc39.github.io/ecma262/#sec-date.prototype.tostring
8832
8833if (new Date(NaN) + '' != INVALID_DATE) {
8834 redefine(DatePrototype, TO_STRING, function toString() {
8835 var value = getTime.call(this); // eslint-disable-next-line no-self-compare
8836
8837 return value === value ? nativeDateToString.call(this) : INVALID_DATE;
8838 });
8839}
8840
8841/***/ }),
8842/* 277 */
8843/***/ (function(module, exports, __webpack_require__) {
8844
8845var createNonEnumerableProperty = __webpack_require__(20);
8846
8847var dateToPrimitive = __webpack_require__(278);
8848
8849var wellKnownSymbol = __webpack_require__(56);
8850
8851var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
8852var DatePrototype = Date.prototype; // `Date.prototype[@@toPrimitive]` method
8853// https://tc39.github.io/ecma262/#sec-date.prototype-@@toprimitive
8854
8855if (!(TO_PRIMITIVE in DatePrototype)) {
8856 createNonEnumerableProperty(DatePrototype, TO_PRIMITIVE, dateToPrimitive);
8857}
8858
8859/***/ }),
8860/* 278 */
8861/***/ (function(module, exports, __webpack_require__) {
8862
8863"use strict";
8864
8865
8866var anObject = __webpack_require__(22);
8867
8868var toPrimitive = __webpack_require__(15);
8869
8870module.exports = function (hint) {
8871 if (hint !== 'string' && hint !== 'number' && hint !== 'default') {
8872 throw TypeError('Incorrect hint');
8873 }
8874
8875 return toPrimitive(anObject(this), hint !== 'number');
8876};
8877
8878/***/ }),
8879/* 279 */
8880/***/ (function(module, exports, __webpack_require__) {
8881
8882var $ = __webpack_require__(4);
8883
8884var getBuiltIn = __webpack_require__(36);
8885
8886var fails = __webpack_require__(8);
8887
8888var $stringify = getBuiltIn('JSON', 'stringify');
8889var re = /[\uD800-\uDFFF]/g;
8890var low = /^[\uD800-\uDBFF]$/;
8891var hi = /^[\uDC00-\uDFFF]$/;
8892
8893var fix = function fix(match, offset, string) {
8894 var prev = string.charAt(offset - 1);
8895 var next = string.charAt(offset + 1);
8896
8897 if (low.test(match) && !hi.test(next) || hi.test(match) && !low.test(prev)) {
8898 return '\\u' + match.charCodeAt(0).toString(16);
8899 }
8900
8901 return match;
8902};
8903
8904var FORCED = fails(function () {
8905 return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"' || $stringify('\uDEAD') !== '"\\udead"';
8906});
8907
8908if ($stringify) {
8909 // https://github.com/tc39/proposal-well-formed-stringify
8910 $({
8911 target: 'JSON',
8912 stat: true,
8913 forced: FORCED
8914 }, {
8915 // eslint-disable-next-line no-unused-vars
8916 stringify: function stringify(it, replacer, space) {
8917 var result = $stringify.apply(null, arguments);
8918 return typeof result == 'string' ? result.replace(re, fix) : result;
8919 }
8920 });
8921}
8922
8923/***/ }),
8924/* 280 */
8925/***/ (function(module, exports, __webpack_require__) {
8926
8927var global = __webpack_require__(5);
8928
8929var setToStringTag = __webpack_require__(59); // JSON[@@toStringTag] property
8930// https://tc39.github.io/ecma262/#sec-json-@@tostringtag
8931
8932
8933setToStringTag(global.JSON, 'JSON', true);
8934
8935/***/ }),
8936/* 281 */
8937/***/ (function(module, exports, __webpack_require__) {
8938
8939"use strict";
8940
8941
8942var $ = __webpack_require__(4);
8943
8944var IS_PURE = __webpack_require__(31);
8945
8946var global = __webpack_require__(5);
8947
8948var getBuiltIn = __webpack_require__(36);
8949
8950var NativePromise = __webpack_require__(282);
8951
8952var redefine = __webpack_require__(23);
8953
8954var redefineAll = __webpack_require__(283);
8955
8956var setToStringTag = __webpack_require__(59);
8957
8958var setSpecies = __webpack_require__(167);
8959
8960var isObject = __webpack_require__(16);
8961
8962var aFunction = __webpack_require__(62);
8963
8964var anInstance = __webpack_require__(284);
8965
8966var classof = __webpack_require__(13);
8967
8968var inspectSource = __webpack_require__(25);
8969
8970var iterate = __webpack_require__(89);
8971
8972var checkCorrectnessOfIteration = __webpack_require__(129);
8973
8974var speciesConstructor = __webpack_require__(192);
8975
8976var task = __webpack_require__(285).set;
8977
8978var microtask = __webpack_require__(287);
8979
8980var promiseResolve = __webpack_require__(288);
8981
8982var hostReportErrors = __webpack_require__(290);
8983
8984var newPromiseCapabilityModule = __webpack_require__(289);
8985
8986var perform = __webpack_require__(291);
8987
8988var InternalStateModule = __webpack_require__(27);
8989
8990var isForced = __webpack_require__(46);
8991
8992var wellKnownSymbol = __webpack_require__(56);
8993
8994var V8_VERSION = __webpack_require__(134);
8995
8996var SPECIES = wellKnownSymbol('species');
8997var PROMISE = 'Promise';
8998var getInternalState = InternalStateModule.get;
8999var setInternalState = InternalStateModule.set;
9000var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
9001var PromiseConstructor = NativePromise;
9002var TypeError = global.TypeError;
9003var document = global.document;
9004var process = global.process;
9005var $fetch = getBuiltIn('fetch');
9006var newPromiseCapability = newPromiseCapabilityModule.f;
9007var newGenericPromiseCapability = newPromiseCapability;
9008var IS_NODE = classof(process) == 'process';
9009var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);
9010var UNHANDLED_REJECTION = 'unhandledrejection';
9011var REJECTION_HANDLED = 'rejectionhandled';
9012var PENDING = 0;
9013var FULFILLED = 1;
9014var REJECTED = 2;
9015var HANDLED = 1;
9016var UNHANDLED = 2;
9017var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
9018var FORCED = isForced(PROMISE, function () {
9019 var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);
9020
9021 if (!GLOBAL_CORE_JS_PROMISE) {
9022 // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
9023 // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
9024 // We can't detect it synchronously, so just check versions
9025 if (V8_VERSION === 66) return true; // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
9026
9027 if (!IS_NODE && typeof PromiseRejectionEvent != 'function') return true;
9028 } // We need Promise#finally in the pure version for preventing prototype pollution
9029
9030
9031 if (IS_PURE && !PromiseConstructor.prototype['finally']) return true; // We can't use @@species feature detection in V8 since it causes
9032 // deoptimization and performance degradation
9033 // https://github.com/zloirock/core-js/issues/679
9034
9035 if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false; // Detect correctness of subclassing with @@species support
9036
9037 var promise = PromiseConstructor.resolve(1);
9038
9039 var FakePromise = function FakePromise(exec) {
9040 exec(function () {
9041 /* empty */
9042 }, function () {
9043 /* empty */
9044 });
9045 };
9046
9047 var constructor = promise.constructor = {};
9048 constructor[SPECIES] = FakePromise;
9049 return !(promise.then(function () {
9050 /* empty */
9051 }) instanceof FakePromise);
9052});
9053var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {
9054 PromiseConstructor.all(iterable)['catch'](function () {
9055 /* empty */
9056 });
9057}); // helpers
9058
9059var isThenable = function isThenable(it) {
9060 var then;
9061 return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
9062};
9063
9064var notify = function notify(promise, state, isReject) {
9065 if (state.notified) return;
9066 state.notified = true;
9067 var chain = state.reactions;
9068 microtask(function () {
9069 var value = state.value;
9070 var ok = state.state == FULFILLED;
9071 var index = 0; // variable length - can't use forEach
9072
9073 while (chain.length > index) {
9074 var reaction = chain[index++];
9075 var handler = ok ? reaction.ok : reaction.fail;
9076 var resolve = reaction.resolve;
9077 var reject = reaction.reject;
9078 var domain = reaction.domain;
9079 var result, then, exited;
9080
9081 try {
9082 if (handler) {
9083 if (!ok) {
9084 if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state);
9085 state.rejection = HANDLED;
9086 }
9087
9088 if (handler === true) result = value;else {
9089 if (domain) domain.enter();
9090 result = handler(value); // can throw
9091
9092 if (domain) {
9093 domain.exit();
9094 exited = true;
9095 }
9096 }
9097
9098 if (result === reaction.promise) {
9099 reject(TypeError('Promise-chain cycle'));
9100 } else if (then = isThenable(result)) {
9101 then.call(result, resolve, reject);
9102 } else resolve(result);
9103 } else reject(value);
9104 } catch (error) {
9105 if (domain && !exited) domain.exit();
9106 reject(error);
9107 }
9108 }
9109
9110 state.reactions = [];
9111 state.notified = false;
9112 if (isReject && !state.rejection) onUnhandled(promise, state);
9113 });
9114};
9115
9116var dispatchEvent = function dispatchEvent(name, promise, reason) {
9117 var event, handler;
9118
9119 if (DISPATCH_EVENT) {
9120 event = document.createEvent('Event');
9121 event.promise = promise;
9122 event.reason = reason;
9123 event.initEvent(name, false, true);
9124 global.dispatchEvent(event);
9125 } else event = {
9126 promise: promise,
9127 reason: reason
9128 };
9129
9130 if (handler = global['on' + name]) handler(event);else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
9131};
9132
9133var onUnhandled = function onUnhandled(promise, state) {
9134 task.call(global, function () {
9135 var value = state.value;
9136 var IS_UNHANDLED = isUnhandled(state);
9137 var result;
9138
9139 if (IS_UNHANDLED) {
9140 result = perform(function () {
9141 if (IS_NODE) {
9142 process.emit('unhandledRejection', value, promise);
9143 } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
9144 }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
9145
9146 state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
9147 if (result.error) throw result.value;
9148 }
9149 });
9150};
9151
9152var isUnhandled = function isUnhandled(state) {
9153 return state.rejection !== HANDLED && !state.parent;
9154};
9155
9156var onHandleUnhandled = function onHandleUnhandled(promise, state) {
9157 task.call(global, function () {
9158 if (IS_NODE) {
9159 process.emit('rejectionHandled', promise);
9160 } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
9161 });
9162};
9163
9164var bind = function bind(fn, promise, state, unwrap) {
9165 return function (value) {
9166 fn(promise, state, value, unwrap);
9167 };
9168};
9169
9170var internalReject = function internalReject(promise, state, value, unwrap) {
9171 if (state.done) return;
9172 state.done = true;
9173 if (unwrap) state = unwrap;
9174 state.value = value;
9175 state.state = REJECTED;
9176 notify(promise, state, true);
9177};
9178
9179var internalResolve = function internalResolve(promise, state, value, unwrap) {
9180 if (state.done) return;
9181 state.done = true;
9182 if (unwrap) state = unwrap;
9183
9184 try {
9185 if (promise === value) throw TypeError("Promise can't be resolved itself");
9186 var then = isThenable(value);
9187
9188 if (then) {
9189 microtask(function () {
9190 var wrapper = {
9191 done: false
9192 };
9193
9194 try {
9195 then.call(value, bind(internalResolve, promise, wrapper, state), bind(internalReject, promise, wrapper, state));
9196 } catch (error) {
9197 internalReject(promise, wrapper, error, state);
9198 }
9199 });
9200 } else {
9201 state.value = value;
9202 state.state = FULFILLED;
9203 notify(promise, state, false);
9204 }
9205 } catch (error) {
9206 internalReject(promise, {
9207 done: false
9208 }, error, state);
9209 }
9210}; // constructor polyfill
9211
9212
9213if (FORCED) {
9214 // 25.4.3.1 Promise(executor)
9215 PromiseConstructor = function Promise(executor) {
9216 anInstance(this, PromiseConstructor, PROMISE);
9217 aFunction(executor);
9218 Internal.call(this);
9219 var state = getInternalState(this);
9220
9221 try {
9222 executor(bind(internalResolve, this, state), bind(internalReject, this, state));
9223 } catch (error) {
9224 internalReject(this, state, error);
9225 }
9226 }; // eslint-disable-next-line no-unused-vars
9227
9228
9229 Internal = function Promise(executor) {
9230 setInternalState(this, {
9231 type: PROMISE,
9232 done: false,
9233 notified: false,
9234 parent: false,
9235 reactions: [],
9236 rejection: false,
9237 state: PENDING,
9238 value: undefined
9239 });
9240 };
9241
9242 Internal.prototype = redefineAll(PromiseConstructor.prototype, {
9243 // `Promise.prototype.then` method
9244 // https://tc39.github.io/ecma262/#sec-promise.prototype.then
9245 then: function then(onFulfilled, onRejected) {
9246 var state = getInternalPromiseState(this);
9247 var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));
9248 reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
9249 reaction.fail = typeof onRejected == 'function' && onRejected;
9250 reaction.domain = IS_NODE ? process.domain : undefined;
9251 state.parent = true;
9252 state.reactions.push(reaction);
9253 if (state.state != PENDING) notify(this, state, false);
9254 return reaction.promise;
9255 },
9256 // `Promise.prototype.catch` method
9257 // https://tc39.github.io/ecma262/#sec-promise.prototype.catch
9258 'catch': function _catch(onRejected) {
9259 return this.then(undefined, onRejected);
9260 }
9261 });
9262
9263 OwnPromiseCapability = function OwnPromiseCapability() {
9264 var promise = new Internal();
9265 var state = getInternalState(promise);
9266 this.promise = promise;
9267 this.resolve = bind(internalResolve, promise, state);
9268 this.reject = bind(internalReject, promise, state);
9269 };
9270
9271 newPromiseCapabilityModule.f = newPromiseCapability = function newPromiseCapability(C) {
9272 return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C);
9273 };
9274
9275 if (!IS_PURE && typeof NativePromise == 'function') {
9276 nativeThen = NativePromise.prototype.then; // wrap native Promise#then for native async functions
9277
9278 redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) {
9279 var that = this;
9280 return new PromiseConstructor(function (resolve, reject) {
9281 nativeThen.call(that, resolve, reject);
9282 }).then(onFulfilled, onRejected); // https://github.com/zloirock/core-js/issues/640
9283 }, {
9284 unsafe: true
9285 }); // wrap fetch result
9286
9287 if (typeof $fetch == 'function') $({
9288 global: true,
9289 enumerable: true,
9290 forced: true
9291 }, {
9292 // eslint-disable-next-line no-unused-vars
9293 fetch: function fetch(input
9294 /* , init */
9295 ) {
9296 return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments));
9297 }
9298 });
9299 }
9300}
9301
9302$({
9303 global: true,
9304 wrap: true,
9305 forced: FORCED
9306}, {
9307 Promise: PromiseConstructor
9308});
9309setToStringTag(PromiseConstructor, PROMISE, false, true);
9310setSpecies(PROMISE);
9311PromiseWrapper = getBuiltIn(PROMISE); // statics
9312
9313$({
9314 target: PROMISE,
9315 stat: true,
9316 forced: FORCED
9317}, {
9318 // `Promise.reject` method
9319 // https://tc39.github.io/ecma262/#sec-promise.reject
9320 reject: function reject(r) {
9321 var capability = newPromiseCapability(this);
9322 capability.reject.call(undefined, r);
9323 return capability.promise;
9324 }
9325});
9326$({
9327 target: PROMISE,
9328 stat: true,
9329 forced: IS_PURE || FORCED
9330}, {
9331 // `Promise.resolve` method
9332 // https://tc39.github.io/ecma262/#sec-promise.resolve
9333 resolve: function resolve(x) {
9334 return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);
9335 }
9336});
9337$({
9338 target: PROMISE,
9339 stat: true,
9340 forced: INCORRECT_ITERATION
9341}, {
9342 // `Promise.all` method
9343 // https://tc39.github.io/ecma262/#sec-promise.all
9344 all: function all(iterable) {
9345 var C = this;
9346 var capability = newPromiseCapability(C);
9347 var resolve = capability.resolve;
9348 var reject = capability.reject;
9349 var result = perform(function () {
9350 var $promiseResolve = aFunction(C.resolve);
9351 var values = [];
9352 var counter = 0;
9353 var remaining = 1;
9354 iterate(iterable, function (promise) {
9355 var index = counter++;
9356 var alreadyCalled = false;
9357 values.push(undefined);
9358 remaining++;
9359 $promiseResolve.call(C, promise).then(function (value) {
9360 if (alreadyCalled) return;
9361 alreadyCalled = true;
9362 values[index] = value;
9363 --remaining || resolve(values);
9364 }, reject);
9365 });
9366 --remaining || resolve(values);
9367 });
9368 if (result.error) reject(result.value);
9369 return capability.promise;
9370 },
9371 // `Promise.race` method
9372 // https://tc39.github.io/ecma262/#sec-promise.race
9373 race: function race(iterable) {
9374 var C = this;
9375 var capability = newPromiseCapability(C);
9376 var reject = capability.reject;
9377 var result = perform(function () {
9378 var $promiseResolve = aFunction(C.resolve);
9379 iterate(iterable, function (promise) {
9380 $promiseResolve.call(C, promise).then(capability.resolve, reject);
9381 });
9382 });
9383 if (result.error) reject(result.value);
9384 return capability.promise;
9385 }
9386});
9387
9388/***/ }),
9389/* 282 */
9390/***/ (function(module, exports, __webpack_require__) {
9391
9392var global = __webpack_require__(5);
9393
9394module.exports = global.Promise;
9395
9396/***/ }),
9397/* 283 */
9398/***/ (function(module, exports, __webpack_require__) {
9399
9400var redefine = __webpack_require__(23);
9401
9402module.exports = function (target, src, options) {
9403 for (var key in src) redefine(target, key, src[key], options);
9404
9405 return target;
9406};
9407
9408/***/ }),
9409/* 284 */
9410/***/ (function(module, exports) {
9411
9412module.exports = function (it, Constructor, name) {
9413 if (!(it instanceof Constructor)) {
9414 throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
9415 }
9416
9417 return it;
9418};
9419
9420/***/ }),
9421/* 285 */
9422/***/ (function(module, exports, __webpack_require__) {
9423
9424var global = __webpack_require__(5);
9425
9426var fails = __webpack_require__(8);
9427
9428var classof = __webpack_require__(13);
9429
9430var bind = __webpack_require__(61);
9431
9432var html = __webpack_require__(54);
9433
9434var createElement = __webpack_require__(19);
9435
9436var IS_IOS = __webpack_require__(286);
9437
9438var location = global.location;
9439var set = global.setImmediate;
9440var clear = global.clearImmediate;
9441var process = global.process;
9442var MessageChannel = global.MessageChannel;
9443var Dispatch = global.Dispatch;
9444var counter = 0;
9445var queue = {};
9446var ONREADYSTATECHANGE = 'onreadystatechange';
9447var defer, channel, port;
9448
9449var run = function run(id) {
9450 // eslint-disable-next-line no-prototype-builtins
9451 if (queue.hasOwnProperty(id)) {
9452 var fn = queue[id];
9453 delete queue[id];
9454 fn();
9455 }
9456};
9457
9458var runner = function runner(id) {
9459 return function () {
9460 run(id);
9461 };
9462};
9463
9464var listener = function listener(event) {
9465 run(event.data);
9466};
9467
9468var post = function post(id) {
9469 // old engines have not location.origin
9470 global.postMessage(id + '', location.protocol + '//' + location.host);
9471}; // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
9472
9473
9474if (!set || !clear) {
9475 set = function setImmediate(fn) {
9476 var args = [];
9477 var i = 1;
9478
9479 while (arguments.length > i) args.push(arguments[i++]);
9480
9481 queue[++counter] = function () {
9482 // eslint-disable-next-line no-new-func
9483 (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);
9484 };
9485
9486 defer(counter);
9487 return counter;
9488 };
9489
9490 clear = function clearImmediate(id) {
9491 delete queue[id];
9492 }; // Node.js 0.8-
9493
9494
9495 if (classof(process) == 'process') {
9496 defer = function defer(id) {
9497 process.nextTick(runner(id));
9498 }; // Sphere (JS game engine) Dispatch API
9499
9500 } else if (Dispatch && Dispatch.now) {
9501 defer = function defer(id) {
9502 Dispatch.now(runner(id));
9503 }; // Browsers with MessageChannel, includes WebWorkers
9504 // except iOS - https://github.com/zloirock/core-js/issues/624
9505
9506 } else if (MessageChannel && !IS_IOS) {
9507 channel = new MessageChannel();
9508 port = channel.port2;
9509 channel.port1.onmessage = listener;
9510 defer = bind(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers
9511 // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
56c4a2cb 9512 } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post) && location.protocol !== 'file:') {
eb39fafa
DC
9513 defer = post;
9514 global.addEventListener('message', listener, false); // IE8-
9515 } else if (ONREADYSTATECHANGE in createElement('script')) {
9516 defer = function defer(id) {
9517 html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
9518 html.removeChild(this);
9519 run(id);
9520 };
9521 }; // Rest old browsers
9522
9523 } else {
9524 defer = function defer(id) {
9525 setTimeout(runner(id), 0);
9526 };
9527 }
9528}
9529
9530module.exports = {
9531 set: set,
9532 clear: clear
9533};
9534
9535/***/ }),
9536/* 286 */
9537/***/ (function(module, exports, __webpack_require__) {
9538
9539var userAgent = __webpack_require__(135);
9540
9541module.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent);
9542
9543/***/ }),
9544/* 287 */
9545/***/ (function(module, exports, __webpack_require__) {
9546
9547var global = __webpack_require__(5);
9548
9549var getOwnPropertyDescriptor = __webpack_require__(6).f;
9550
9551var classof = __webpack_require__(13);
9552
9553var macrotask = __webpack_require__(285).set;
9554
9555var IS_IOS = __webpack_require__(286);
9556
9557var MutationObserver = global.MutationObserver || global.WebKitMutationObserver;
9558var process = global.process;
9559var Promise = global.Promise;
9560var IS_NODE = classof(process) == 'process'; // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
9561
9562var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');
9563var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
9564var flush, head, last, notify, toggle, node, promise, then; // modern engines have queueMicrotask method
9565
9566if (!queueMicrotask) {
9567 flush = function flush() {
9568 var parent, fn;
9569 if (IS_NODE && (parent = process.domain)) parent.exit();
9570
9571 while (head) {
9572 fn = head.fn;
9573 head = head.next;
9574
9575 try {
9576 fn();
9577 } catch (error) {
9578 if (head) notify();else last = undefined;
9579 throw error;
9580 }
9581 }
9582
9583 last = undefined;
9584 if (parent) parent.enter();
9585 }; // Node.js
9586
9587
9588 if (IS_NODE) {
9589 notify = function notify() {
9590 process.nextTick(flush);
9591 }; // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
9592
9593 } else if (MutationObserver && !IS_IOS) {
9594 toggle = true;
9595 node = document.createTextNode('');
9596 new MutationObserver(flush).observe(node, {
9597 characterData: true
9598 });
9599
9600 notify = function notify() {
9601 node.data = toggle = !toggle;
9602 }; // environments with maybe non-completely correct, but existent Promise
9603
9604 } else if (Promise && Promise.resolve) {
9605 // Promise.resolve without an argument throws an error in LG WebOS 2
9606 promise = Promise.resolve(undefined);
9607 then = promise.then;
9608
9609 notify = function notify() {
9610 then.call(promise, flush);
9611 }; // for other environments - macrotask based on:
9612 // - setImmediate
9613 // - MessageChannel
9614 // - window.postMessag
9615 // - onreadystatechange
9616 // - setTimeout
9617
9618 } else {
9619 notify = function notify() {
9620 // strange IE + webpack dev server bug - use .call(global)
9621 macrotask.call(global, flush);
9622 };
9623 }
9624}
9625
9626module.exports = queueMicrotask || function (fn) {
9627 var task = {
9628 fn: fn,
9629 next: undefined
9630 };
9631 if (last) last.next = task;
9632
9633 if (!head) {
9634 head = task;
9635 notify();
9636 }
9637
9638 last = task;
9639};
9640
9641/***/ }),
9642/* 288 */
9643/***/ (function(module, exports, __webpack_require__) {
9644
9645var anObject = __webpack_require__(22);
9646
9647var isObject = __webpack_require__(16);
9648
9649var newPromiseCapability = __webpack_require__(289);
9650
9651module.exports = function (C, x) {
9652 anObject(C);
9653 if (isObject(x) && x.constructor === C) return x;
9654 var promiseCapability = newPromiseCapability.f(C);
9655 var resolve = promiseCapability.resolve;
9656 resolve(x);
9657 return promiseCapability.promise;
9658};
9659
9660/***/ }),
9661/* 289 */
9662/***/ (function(module, exports, __webpack_require__) {
9663
9664"use strict";
9665
9666
9667var aFunction = __webpack_require__(62);
9668
9669var PromiseCapability = function PromiseCapability(C) {
9670 var resolve, reject;
9671 this.promise = new C(function ($$resolve, $$reject) {
9672 if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
9673 resolve = $$resolve;
9674 reject = $$reject;
9675 });
9676 this.resolve = aFunction(resolve);
9677 this.reject = aFunction(reject);
9678}; // 25.4.1.5 NewPromiseCapability(C)
9679
9680
9681module.exports.f = function (C) {
9682 return new PromiseCapability(C);
9683};
9684
9685/***/ }),
9686/* 290 */
9687/***/ (function(module, exports, __webpack_require__) {
9688
9689var global = __webpack_require__(5);
9690
9691module.exports = function (a, b) {
9692 var console = global.console;
9693
9694 if (console && console.error) {
9695 arguments.length === 1 ? console.error(a) : console.error(a, b);
9696 }
9697};
9698
9699/***/ }),
9700/* 291 */
9701/***/ (function(module, exports) {
9702
9703module.exports = function (exec) {
9704 try {
9705 return {
9706 error: false,
9707 value: exec()
9708 };
9709 } catch (error) {
9710 return {
9711 error: true,
9712 value: error
9713 };
9714 }
9715};
9716
9717/***/ }),
9718/* 292 */
9719/***/ (function(module, exports, __webpack_require__) {
9720
9721"use strict";
9722
9723
9724var $ = __webpack_require__(4);
9725
9726var aFunction = __webpack_require__(62);
9727
9728var newPromiseCapabilityModule = __webpack_require__(289);
9729
9730var perform = __webpack_require__(291);
9731
9732var iterate = __webpack_require__(89); // `Promise.allSettled` method
9733// https://github.com/tc39/proposal-promise-allSettled
9734
9735
9736$({
9737 target: 'Promise',
9738 stat: true
9739}, {
9740 allSettled: function allSettled(iterable) {
9741 var C = this;
9742 var capability = newPromiseCapabilityModule.f(C);
9743 var resolve = capability.resolve;
9744 var reject = capability.reject;
9745 var result = perform(function () {
9746 var promiseResolve = aFunction(C.resolve);
9747 var values = [];
9748 var counter = 0;
9749 var remaining = 1;
9750 iterate(iterable, function (promise) {
9751 var index = counter++;
9752 var alreadyCalled = false;
9753 values.push(undefined);
9754 remaining++;
9755 promiseResolve.call(C, promise).then(function (value) {
9756 if (alreadyCalled) return;
9757 alreadyCalled = true;
9758 values[index] = {
9759 status: 'fulfilled',
9760 value: value
9761 };
9762 --remaining || resolve(values);
9763 }, function (e) {
9764 if (alreadyCalled) return;
9765 alreadyCalled = true;
9766 values[index] = {
9767 status: 'rejected',
9768 reason: e
9769 };
9770 --remaining || resolve(values);
9771 });
9772 });
9773 --remaining || resolve(values);
9774 });
9775 if (result.error) reject(result.value);
9776 return capability.promise;
9777 }
9778});
9779
9780/***/ }),
9781/* 293 */
9782/***/ (function(module, exports, __webpack_require__) {
9783
9784"use strict";
9785
9786
9787var $ = __webpack_require__(4);
9788
9789var IS_PURE = __webpack_require__(31);
9790
9791var NativePromise = __webpack_require__(282);
9792
9793var fails = __webpack_require__(8);
9794
9795var getBuiltIn = __webpack_require__(36);
9796
9797var speciesConstructor = __webpack_require__(192);
9798
9799var promiseResolve = __webpack_require__(288);
9800
9801var redefine = __webpack_require__(23); // Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829
9802
9803
9804var NON_GENERIC = !!NativePromise && fails(function () {
9805 NativePromise.prototype['finally'].call({
9806 then: function then() {
9807 /* empty */
9808 }
9809 }, function () {
9810 /* empty */
9811 });
9812}); // `Promise.prototype.finally` method
9813// https://tc39.github.io/ecma262/#sec-promise.prototype.finally
9814
9815$({
9816 target: 'Promise',
9817 proto: true,
9818 real: true,
9819 forced: NON_GENERIC
9820}, {
9821 'finally': function _finally(onFinally) {
9822 var C = speciesConstructor(this, getBuiltIn('Promise'));
9823 var isFunction = typeof onFinally == 'function';
9824 return this.then(isFunction ? function (x) {
9825 return promiseResolve(C, onFinally()).then(function () {
9826 return x;
9827 });
9828 } : onFinally, isFunction ? function (e) {
9829 return promiseResolve(C, onFinally()).then(function () {
9830 throw e;
9831 });
9832 } : onFinally);
9833 }
9834}); // patch native Promise.prototype for native async functions
9835
9836if (!IS_PURE && typeof NativePromise == 'function' && !NativePromise.prototype['finally']) {
9837 redefine(NativePromise.prototype, 'finally', getBuiltIn('Promise').prototype['finally']);
9838}
9839
9840/***/ }),
9841/* 294 */
9842/***/ (function(module, exports, __webpack_require__) {
9843
9844"use strict";
9845
9846
9847var collection = __webpack_require__(295);
9848
9849var collectionStrong = __webpack_require__(296); // `Map` constructor
9850// https://tc39.github.io/ecma262/#sec-map-objects
9851
9852
9853module.exports = collection('Map', function (init) {
9854 return function Map() {
9855 return init(this, arguments.length ? arguments[0] : undefined);
9856 };
9857}, collectionStrong);
9858
9859/***/ }),
9860/* 295 */
9861/***/ (function(module, exports, __webpack_require__) {
9862
9863"use strict";
9864
9865
9866var $ = __webpack_require__(4);
9867
9868var global = __webpack_require__(5);
9869
9870var isForced = __webpack_require__(46);
9871
9872var redefine = __webpack_require__(23);
9873
9874var InternalMetadataModule = __webpack_require__(87);
9875
9876var iterate = __webpack_require__(89);
9877
9878var anInstance = __webpack_require__(284);
9879
9880var isObject = __webpack_require__(16);
9881
9882var fails = __webpack_require__(8);
9883
9884var checkCorrectnessOfIteration = __webpack_require__(129);
9885
9886var setToStringTag = __webpack_require__(59);
9887
9888var inheritIfRequired = __webpack_require__(226);
9889
9890module.exports = function (CONSTRUCTOR_NAME, wrapper, common) {
9891 var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;
9892 var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;
9893 var ADDER = IS_MAP ? 'set' : 'add';
9894 var NativeConstructor = global[CONSTRUCTOR_NAME];
9895 var NativePrototype = NativeConstructor && NativeConstructor.prototype;
9896 var Constructor = NativeConstructor;
9897 var exported = {};
9898
9899 var fixMethod = function fixMethod(KEY) {
9900 var nativeMethod = NativePrototype[KEY];
9901 redefine(NativePrototype, KEY, KEY == 'add' ? function add(value) {
9902 nativeMethod.call(this, value === 0 ? 0 : value);
9903 return this;
9904 } : KEY == 'delete' ? function (key) {
9905 return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
9906 } : KEY == 'get' ? function get(key) {
9907 return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key);
9908 } : KEY == 'has' ? function has(key) {
9909 return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
9910 } : function set(key, value) {
9911 nativeMethod.call(this, key === 0 ? 0 : key, value);
9912 return this;
9913 });
9914 }; // eslint-disable-next-line max-len
9915
9916
9917 if (isForced(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () {
9918 new NativeConstructor().entries().next();
9919 })))) {
9920 // create collection constructor
9921 Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
9922 InternalMetadataModule.REQUIRED = true;
9923 } else if (isForced(CONSTRUCTOR_NAME, true)) {
9924 var instance = new Constructor(); // early implementations not supports chaining
9925
9926 var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
9927
9928 var THROWS_ON_PRIMITIVES = fails(function () {
9929 instance.has(1);
9930 }); // most early implementations doesn't supports iterables, most modern - not close it correctly
9931 // eslint-disable-next-line no-new
9932
9933 var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) {
9934 new NativeConstructor(iterable);
9935 }); // for early implementations -0 and +0 not the same
9936
9937 var BUGGY_ZERO = !IS_WEAK && fails(function () {
9938 // V8 ~ Chromium 42- fails only with 5+ elements
9939 var $instance = new NativeConstructor();
9940 var index = 5;
9941
9942 while (index--) $instance[ADDER](index, index);
9943
9944 return !$instance.has(-0);
9945 });
9946
9947 if (!ACCEPT_ITERABLES) {
9948 Constructor = wrapper(function (dummy, iterable) {
9949 anInstance(dummy, Constructor, CONSTRUCTOR_NAME);
9950 var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor);
9951 if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP);
9952 return that;
9953 });
9954 Constructor.prototype = NativePrototype;
9955 NativePrototype.constructor = Constructor;
9956 }
9957
9958 if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
9959 fixMethod('delete');
9960 fixMethod('has');
9961 IS_MAP && fixMethod('get');
9962 }
9963
9964 if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); // weak collections should not contains .clear method
9965
9966 if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;
9967 }
9968
9969 exported[CONSTRUCTOR_NAME] = Constructor;
9970 $({
9971 global: true,
9972 forced: Constructor != NativeConstructor
9973 }, exported);
9974 setToStringTag(Constructor, CONSTRUCTOR_NAME);
9975 if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
9976 return Constructor;
9977};
9978
9979/***/ }),
9980/* 296 */
9981/***/ (function(module, exports, __webpack_require__) {
9982
9983"use strict";
9984
9985
9986var defineProperty = __webpack_require__(21).f;
9987
9988var create = __webpack_require__(51);
9989
9990var redefineAll = __webpack_require__(283);
9991
9992var bind = __webpack_require__(61);
9993
9994var anInstance = __webpack_require__(284);
9995
9996var iterate = __webpack_require__(89);
9997
9998var defineIterator = __webpack_require__(171);
9999
10000var setSpecies = __webpack_require__(167);
10001
10002var DESCRIPTORS = __webpack_require__(7);
10003
10004var fastKey = __webpack_require__(87).fastKey;
10005
10006var InternalStateModule = __webpack_require__(27);
10007
10008var setInternalState = InternalStateModule.set;
10009var internalStateGetterFor = InternalStateModule.getterFor;
10010module.exports = {
10011 getConstructor: function getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
10012 var C = wrapper(function (that, iterable) {
10013 anInstance(that, C, CONSTRUCTOR_NAME);
10014 setInternalState(that, {
10015 type: CONSTRUCTOR_NAME,
10016 index: create(null),
10017 first: undefined,
10018 last: undefined,
10019 size: 0
10020 });
10021 if (!DESCRIPTORS) that.size = 0;
10022 if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP);
10023 });
10024 var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
10025
10026 var define = function define(that, key, value) {
10027 var state = getInternalState(that);
10028 var entry = getEntry(that, key);
10029 var previous, index; // change existing entry
10030
10031 if (entry) {
10032 entry.value = value; // create new entry
10033 } else {
10034 state.last = entry = {
10035 index: index = fastKey(key, true),
10036 key: key,
10037 value: value,
10038 previous: previous = state.last,
10039 next: undefined,
10040 removed: false
10041 };
10042 if (!state.first) state.first = entry;
10043 if (previous) previous.next = entry;
10044 if (DESCRIPTORS) state.size++;else that.size++; // add to index
10045
10046 if (index !== 'F') state.index[index] = entry;
10047 }
10048
10049 return that;
10050 };
10051
10052 var getEntry = function getEntry(that, key) {
10053 var state = getInternalState(that); // fast case
10054
10055 var index = fastKey(key);
10056 var entry;
10057 if (index !== 'F') return state.index[index]; // frozen object case
10058
10059 for (entry = state.first; entry; entry = entry.next) {
10060 if (entry.key == key) return entry;
10061 }
10062 };
10063
10064 redefineAll(C.prototype, {
10065 // 23.1.3.1 Map.prototype.clear()
10066 // 23.2.3.2 Set.prototype.clear()
10067 clear: function clear() {
10068 var that = this;
10069 var state = getInternalState(that);
10070 var data = state.index;
10071 var entry = state.first;
10072
10073 while (entry) {
10074 entry.removed = true;
10075 if (entry.previous) entry.previous = entry.previous.next = undefined;
10076 delete data[entry.index];
10077 entry = entry.next;
10078 }
10079
10080 state.first = state.last = undefined;
10081 if (DESCRIPTORS) state.size = 0;else that.size = 0;
10082 },
10083 // 23.1.3.3 Map.prototype.delete(key)
10084 // 23.2.3.4 Set.prototype.delete(value)
10085 'delete': function _delete(key) {
10086 var that = this;
10087 var state = getInternalState(that);
10088 var entry = getEntry(that, key);
10089
10090 if (entry) {
10091 var next = entry.next;
10092 var prev = entry.previous;
10093 delete state.index[entry.index];
10094 entry.removed = true;
10095 if (prev) prev.next = next;
10096 if (next) next.previous = prev;
10097 if (state.first == entry) state.first = next;
10098 if (state.last == entry) state.last = prev;
10099 if (DESCRIPTORS) state.size--;else that.size--;
10100 }
10101
10102 return !!entry;
10103 },
10104 // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
10105 // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
10106 forEach: function forEach(callbackfn
10107 /* , that = undefined */
10108 ) {
10109 var state = getInternalState(this);
10110 var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
10111 var entry;
10112
10113 while (entry = entry ? entry.next : state.first) {
10114 boundFunction(entry.value, entry.key, this); // revert to the last existing entry
10115
10116 while (entry && entry.removed) entry = entry.previous;
10117 }
10118 },
10119 // 23.1.3.7 Map.prototype.has(key)
10120 // 23.2.3.7 Set.prototype.has(value)
10121 has: function has(key) {
10122 return !!getEntry(this, key);
10123 }
10124 });
10125 redefineAll(C.prototype, IS_MAP ? {
10126 // 23.1.3.6 Map.prototype.get(key)
10127 get: function get(key) {
10128 var entry = getEntry(this, key);
10129 return entry && entry.value;
10130 },
10131 // 23.1.3.9 Map.prototype.set(key, value)
10132 set: function set(key, value) {
10133 return define(this, key === 0 ? 0 : key, value);
10134 }
10135 } : {
10136 // 23.2.3.1 Set.prototype.add(value)
10137 add: function add(value) {
10138 return define(this, value = value === 0 ? 0 : value, value);
10139 }
10140 });
10141 if (DESCRIPTORS) defineProperty(C.prototype, 'size', {
10142 get: function get() {
10143 return getInternalState(this).size;
10144 }
10145 });
10146 return C;
10147 },
10148 setStrong: function setStrong(C, CONSTRUCTOR_NAME, IS_MAP) {
10149 var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';
10150 var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME);
10151 var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); // add .keys, .values, .entries, [@@iterator]
10152 // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
10153
10154 defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) {
10155 setInternalState(this, {
10156 type: ITERATOR_NAME,
10157 target: iterated,
10158 state: getInternalCollectionState(iterated),
10159 kind: kind,
10160 last: undefined
10161 });
10162 }, function () {
10163 var state = getInternalIteratorState(this);
10164 var kind = state.kind;
10165 var entry = state.last; // revert to the last existing entry
10166
10167 while (entry && entry.removed) entry = entry.previous; // get next entry
10168
10169
10170 if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {
10171 // or finish the iteration
10172 state.target = undefined;
10173 return {
10174 value: undefined,
10175 done: true
10176 };
10177 } // return step by kind
10178
10179
10180 if (kind == 'keys') return {
10181 value: entry.key,
10182 done: false
10183 };
10184 if (kind == 'values') return {
10185 value: entry.value,
10186 done: false
10187 };
10188 return {
10189 value: [entry.key, entry.value],
10190 done: false
10191 };
10192 }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2
10193
10194 setSpecies(CONSTRUCTOR_NAME);
10195 }
10196};
10197
10198/***/ }),
10199/* 297 */
10200/***/ (function(module, exports, __webpack_require__) {
10201
10202"use strict";
10203
10204
10205var collection = __webpack_require__(295);
10206
10207var collectionStrong = __webpack_require__(296); // `Set` constructor
10208// https://tc39.github.io/ecma262/#sec-set-objects
10209
10210
10211module.exports = collection('Set', function (init) {
10212 return function Set() {
10213 return init(this, arguments.length ? arguments[0] : undefined);
10214 };
10215}, collectionStrong);
10216
10217/***/ }),
10218/* 298 */
10219/***/ (function(module, exports, __webpack_require__) {
10220
10221"use strict";
10222
10223
10224var global = __webpack_require__(5);
10225
10226var redefineAll = __webpack_require__(283);
10227
10228var InternalMetadataModule = __webpack_require__(87);
10229
10230var collection = __webpack_require__(295);
10231
10232var collectionWeak = __webpack_require__(299);
10233
10234var isObject = __webpack_require__(16);
10235
10236var enforceIternalState = __webpack_require__(27).enforce;
10237
10238var NATIVE_WEAK_MAP = __webpack_require__(28);
10239
10240var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global;
10241var isExtensible = Object.isExtensible;
10242var InternalWeakMap;
10243
10244var wrapper = function wrapper(init) {
10245 return function WeakMap() {
10246 return init(this, arguments.length ? arguments[0] : undefined);
10247 };
10248}; // `WeakMap` constructor
10249// https://tc39.github.io/ecma262/#sec-weakmap-constructor
10250
10251
10252var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak); // IE11 WeakMap frozen keys fix
10253// We can't use feature detection because it crash some old IE builds
10254// https://github.com/zloirock/core-js/issues/485
10255
10256if (NATIVE_WEAK_MAP && IS_IE11) {
10257 InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true);
10258 InternalMetadataModule.REQUIRED = true;
10259 var WeakMapPrototype = $WeakMap.prototype;
10260 var nativeDelete = WeakMapPrototype['delete'];
10261 var nativeHas = WeakMapPrototype.has;
10262 var nativeGet = WeakMapPrototype.get;
10263 var nativeSet = WeakMapPrototype.set;
10264 redefineAll(WeakMapPrototype, {
10265 'delete': function _delete(key) {
10266 if (isObject(key) && !isExtensible(key)) {
10267 var state = enforceIternalState(this);
10268 if (!state.frozen) state.frozen = new InternalWeakMap();
10269 return nativeDelete.call(this, key) || state.frozen['delete'](key);
10270 }
10271
10272 return nativeDelete.call(this, key);
10273 },
10274 has: function has(key) {
10275 if (isObject(key) && !isExtensible(key)) {
10276 var state = enforceIternalState(this);
10277 if (!state.frozen) state.frozen = new InternalWeakMap();
10278 return nativeHas.call(this, key) || state.frozen.has(key);
10279 }
10280
10281 return nativeHas.call(this, key);
10282 },
10283 get: function get(key) {
10284 if (isObject(key) && !isExtensible(key)) {
10285 var state = enforceIternalState(this);
10286 if (!state.frozen) state.frozen = new InternalWeakMap();
10287 return nativeHas.call(this, key) ? nativeGet.call(this, key) : state.frozen.get(key);
10288 }
10289
10290 return nativeGet.call(this, key);
10291 },
10292 set: function set(key, value) {
10293 if (isObject(key) && !isExtensible(key)) {
10294 var state = enforceIternalState(this);
10295 if (!state.frozen) state.frozen = new InternalWeakMap();
10296 nativeHas.call(this, key) ? nativeSet.call(this, key, value) : state.frozen.set(key, value);
10297 } else nativeSet.call(this, key, value);
10298
10299 return this;
10300 }
10301 });
10302}
10303
10304/***/ }),
10305/* 299 */
10306/***/ (function(module, exports, __webpack_require__) {
10307
10308"use strict";
10309
10310
10311var redefineAll = __webpack_require__(283);
10312
10313var getWeakData = __webpack_require__(87).getWeakData;
10314
10315var anObject = __webpack_require__(22);
10316
10317var isObject = __webpack_require__(16);
10318
10319var anInstance = __webpack_require__(284);
10320
10321var iterate = __webpack_require__(89);
10322
10323var ArrayIterationModule = __webpack_require__(60);
10324
10325var $has = __webpack_require__(17);
10326
10327var InternalStateModule = __webpack_require__(27);
10328
10329var setInternalState = InternalStateModule.set;
10330var internalStateGetterFor = InternalStateModule.getterFor;
10331var find = ArrayIterationModule.find;
10332var findIndex = ArrayIterationModule.findIndex;
10333var id = 0; // fallback for uncaught frozen keys
10334
10335var uncaughtFrozenStore = function uncaughtFrozenStore(store) {
10336 return store.frozen || (store.frozen = new UncaughtFrozenStore());
10337};
10338
10339var UncaughtFrozenStore = function UncaughtFrozenStore() {
10340 this.entries = [];
10341};
10342
10343var findUncaughtFrozen = function findUncaughtFrozen(store, key) {
10344 return find(store.entries, function (it) {
10345 return it[0] === key;
10346 });
10347};
10348
10349UncaughtFrozenStore.prototype = {
10350 get: function get(key) {
10351 var entry = findUncaughtFrozen(this, key);
10352 if (entry) return entry[1];
10353 },
10354 has: function has(key) {
10355 return !!findUncaughtFrozen(this, key);
10356 },
10357 set: function set(key, value) {
10358 var entry = findUncaughtFrozen(this, key);
10359 if (entry) entry[1] = value;else this.entries.push([key, value]);
10360 },
10361 'delete': function _delete(key) {
10362 var index = findIndex(this.entries, function (it) {
10363 return it[0] === key;
10364 });
10365 if (~index) this.entries.splice(index, 1);
10366 return !!~index;
10367 }
10368};
10369module.exports = {
10370 getConstructor: function getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
10371 var C = wrapper(function (that, iterable) {
10372 anInstance(that, C, CONSTRUCTOR_NAME);
10373 setInternalState(that, {
10374 type: CONSTRUCTOR_NAME,
10375 id: id++,
10376 frozen: undefined
10377 });
10378 if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP);
10379 });
10380 var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
10381
10382 var define = function define(that, key, value) {
10383 var state = getInternalState(that);
10384 var data = getWeakData(anObject(key), true);
10385 if (data === true) uncaughtFrozenStore(state).set(key, value);else data[state.id] = value;
10386 return that;
10387 };
10388
10389 redefineAll(C.prototype, {
10390 // 23.3.3.2 WeakMap.prototype.delete(key)
10391 // 23.4.3.3 WeakSet.prototype.delete(value)
10392 'delete': function _delete(key) {
10393 var state = getInternalState(this);
10394 if (!isObject(key)) return false;
10395 var data = getWeakData(key);
10396 if (data === true) return uncaughtFrozenStore(state)['delete'](key);
10397 return data && $has(data, state.id) && delete data[state.id];
10398 },
10399 // 23.3.3.4 WeakMap.prototype.has(key)
10400 // 23.4.3.4 WeakSet.prototype.has(value)
10401 has: function has(key) {
10402 var state = getInternalState(this);
10403 if (!isObject(key)) return false;
10404 var data = getWeakData(key);
10405 if (data === true) return uncaughtFrozenStore(state).has(key);
10406 return data && $has(data, state.id);
10407 }
10408 });
10409 redefineAll(C.prototype, IS_MAP ? {
10410 // 23.3.3.3 WeakMap.prototype.get(key)
10411 get: function get(key) {
10412 var state = getInternalState(this);
10413
10414 if (isObject(key)) {
10415 var data = getWeakData(key);
10416 if (data === true) return uncaughtFrozenStore(state).get(key);
10417 return data ? data[state.id] : undefined;
10418 }
10419 },
10420 // 23.3.3.5 WeakMap.prototype.set(key, value)
10421 set: function set(key, value) {
10422 return define(this, key, value);
10423 }
10424 } : {
10425 // 23.4.3.1 WeakSet.prototype.add(value)
10426 add: function add(value) {
10427 return define(this, value, true);
10428 }
10429 });
10430 return C;
10431 }
10432};
10433
10434/***/ }),
10435/* 300 */
10436/***/ (function(module, exports, __webpack_require__) {
10437
10438"use strict";
10439
10440
10441var collection = __webpack_require__(295);
10442
10443var collectionWeak = __webpack_require__(299); // `WeakSet` constructor
10444// https://tc39.github.io/ecma262/#sec-weakset-constructor
10445
10446
10447collection('WeakSet', function (init) {
10448 return function WeakSet() {
10449 return init(this, arguments.length ? arguments[0] : undefined);
10450 };
10451}, collectionWeak);
10452
10453/***/ }),
10454/* 301 */
10455/***/ (function(module, exports, __webpack_require__) {
10456
10457"use strict";
10458
10459
10460var $ = __webpack_require__(4);
10461
10462var global = __webpack_require__(5);
10463
10464var arrayBufferModule = __webpack_require__(302);
10465
10466var setSpecies = __webpack_require__(167);
10467
10468var ARRAY_BUFFER = 'ArrayBuffer';
10469var ArrayBuffer = arrayBufferModule[ARRAY_BUFFER];
10470var NativeArrayBuffer = global[ARRAY_BUFFER]; // `ArrayBuffer` constructor
10471// https://tc39.github.io/ecma262/#sec-arraybuffer-constructor
10472
10473$({
10474 global: true,
10475 forced: NativeArrayBuffer !== ArrayBuffer
10476}, {
10477 ArrayBuffer: ArrayBuffer
10478});
10479setSpecies(ARRAY_BUFFER);
10480
10481/***/ }),
10482/* 302 */
10483/***/ (function(module, exports, __webpack_require__) {
10484
10485"use strict";
10486
10487
10488var global = __webpack_require__(5);
10489
10490var DESCRIPTORS = __webpack_require__(7);
10491
10492var NATIVE_ARRAY_BUFFER = __webpack_require__(303);
10493
10494var createNonEnumerableProperty = __webpack_require__(20);
10495
10496var redefineAll = __webpack_require__(283);
10497
10498var fails = __webpack_require__(8);
10499
10500var anInstance = __webpack_require__(284);
10501
10502var toInteger = __webpack_require__(42);
10503
10504var toLength = __webpack_require__(41);
10505
10506var toIndex = __webpack_require__(304);
10507
10508var IEEE754 = __webpack_require__(305);
10509
10510var getPrototypeOf = __webpack_require__(101);
10511
10512var setPrototypeOf = __webpack_require__(112);
10513
10514var getOwnPropertyNames = __webpack_require__(38).f;
10515
10516var defineProperty = __webpack_require__(21).f;
10517
10518var arrayFill = __webpack_require__(143);
10519
10520var setToStringTag = __webpack_require__(59);
10521
10522var InternalStateModule = __webpack_require__(27);
10523
10524var getInternalState = InternalStateModule.get;
10525var setInternalState = InternalStateModule.set;
10526var ARRAY_BUFFER = 'ArrayBuffer';
10527var DATA_VIEW = 'DataView';
10528var PROTOTYPE = 'prototype';
10529var WRONG_LENGTH = 'Wrong length';
10530var WRONG_INDEX = 'Wrong index';
10531var NativeArrayBuffer = global[ARRAY_BUFFER];
10532var $ArrayBuffer = NativeArrayBuffer;
10533var $DataView = global[DATA_VIEW];
10534var $DataViewPrototype = $DataView && $DataView[PROTOTYPE];
10535var ObjectPrototype = Object.prototype;
10536var RangeError = global.RangeError;
10537var packIEEE754 = IEEE754.pack;
10538var unpackIEEE754 = IEEE754.unpack;
10539
10540var packInt8 = function packInt8(number) {
10541 return [number & 0xFF];
10542};
10543
10544var packInt16 = function packInt16(number) {
10545 return [number & 0xFF, number >> 8 & 0xFF];
10546};
10547
10548var packInt32 = function packInt32(number) {
10549 return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF];
10550};
10551
10552var unpackInt32 = function unpackInt32(buffer) {
10553 return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
10554};
10555
10556var packFloat32 = function packFloat32(number) {
10557 return packIEEE754(number, 23, 4);
10558};
10559
10560var packFloat64 = function packFloat64(number) {
10561 return packIEEE754(number, 52, 8);
10562};
10563
10564var addGetter = function addGetter(Constructor, key) {
10565 defineProperty(Constructor[PROTOTYPE], key, {
10566 get: function get() {
10567 return getInternalState(this)[key];
10568 }
10569 });
10570};
10571
10572var get = function get(view, count, index, isLittleEndian) {
10573 var intIndex = toIndex(index);
10574 var store = getInternalState(view);
10575 if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);
10576 var bytes = getInternalState(store.buffer).bytes;
10577 var start = intIndex + store.byteOffset;
10578 var pack = bytes.slice(start, start + count);
10579 return isLittleEndian ? pack : pack.reverse();
10580};
10581
10582var set = function set(view, count, index, conversion, value, isLittleEndian) {
10583 var intIndex = toIndex(index);
10584 var store = getInternalState(view);
10585 if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);
10586 var bytes = getInternalState(store.buffer).bytes;
10587 var start = intIndex + store.byteOffset;
10588 var pack = conversion(+value);
10589
10590 for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1];
10591};
10592
10593if (!NATIVE_ARRAY_BUFFER) {
10594 $ArrayBuffer = function ArrayBuffer(length) {
10595 anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
10596 var byteLength = toIndex(length);
10597 setInternalState(this, {
10598 bytes: arrayFill.call(new Array(byteLength), 0),
10599 byteLength: byteLength
10600 });
10601 if (!DESCRIPTORS) this.byteLength = byteLength;
10602 };
10603
10604 $DataView = function DataView(buffer, byteOffset, byteLength) {
10605 anInstance(this, $DataView, DATA_VIEW);
10606 anInstance(buffer, $ArrayBuffer, DATA_VIEW);
10607 var bufferLength = getInternalState(buffer).byteLength;
10608 var offset = toInteger(byteOffset);
10609 if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset');
10610 byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
10611 if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
10612 setInternalState(this, {
10613 buffer: buffer,
10614 byteLength: byteLength,
10615 byteOffset: offset
10616 });
10617
10618 if (!DESCRIPTORS) {
10619 this.buffer = buffer;
10620 this.byteLength = byteLength;
10621 this.byteOffset = offset;
10622 }
10623 };
10624
10625 if (DESCRIPTORS) {
10626 addGetter($ArrayBuffer, 'byteLength');
10627 addGetter($DataView, 'buffer');
10628 addGetter($DataView, 'byteLength');
10629 addGetter($DataView, 'byteOffset');
10630 }
10631
10632 redefineAll($DataView[PROTOTYPE], {
10633 getInt8: function getInt8(byteOffset) {
10634 return get(this, 1, byteOffset)[0] << 24 >> 24;
10635 },
10636 getUint8: function getUint8(byteOffset) {
10637 return get(this, 1, byteOffset)[0];
10638 },
10639 getInt16: function getInt16(byteOffset
10640 /* , littleEndian */
10641 ) {
10642 var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
10643 return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
10644 },
10645 getUint16: function getUint16(byteOffset
10646 /* , littleEndian */
10647 ) {
10648 var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
10649 return bytes[1] << 8 | bytes[0];
10650 },
10651 getInt32: function getInt32(byteOffset
10652 /* , littleEndian */
10653 ) {
10654 return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined));
10655 },
10656 getUint32: function getUint32(byteOffset
10657 /* , littleEndian */
10658 ) {
10659 return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0;
10660 },
10661 getFloat32: function getFloat32(byteOffset
10662 /* , littleEndian */
10663 ) {
10664 return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23);
10665 },
10666 getFloat64: function getFloat64(byteOffset
10667 /* , littleEndian */
10668 ) {
10669 return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52);
10670 },
10671 setInt8: function setInt8(byteOffset, value) {
10672 set(this, 1, byteOffset, packInt8, value);
10673 },
10674 setUint8: function setUint8(byteOffset, value) {
10675 set(this, 1, byteOffset, packInt8, value);
10676 },
10677 setInt16: function setInt16(byteOffset, value
10678 /* , littleEndian */
10679 ) {
10680 set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
10681 },
10682 setUint16: function setUint16(byteOffset, value
10683 /* , littleEndian */
10684 ) {
10685 set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
10686 },
10687 setInt32: function setInt32(byteOffset, value
10688 /* , littleEndian */
10689 ) {
10690 set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
10691 },
10692 setUint32: function setUint32(byteOffset, value
10693 /* , littleEndian */
10694 ) {
10695 set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
10696 },
10697 setFloat32: function setFloat32(byteOffset, value
10698 /* , littleEndian */
10699 ) {
10700 set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined);
10701 },
10702 setFloat64: function setFloat64(byteOffset, value
10703 /* , littleEndian */
10704 ) {
10705 set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined);
10706 }
10707 });
10708} else {
10709 if (!fails(function () {
10710 NativeArrayBuffer(1);
10711 }) || !fails(function () {
10712 new NativeArrayBuffer(-1); // eslint-disable-line no-new
10713 }) || fails(function () {
10714 new NativeArrayBuffer(); // eslint-disable-line no-new
10715
10716 new NativeArrayBuffer(1.5); // eslint-disable-line no-new
10717
10718 new NativeArrayBuffer(NaN); // eslint-disable-line no-new
10719
10720 return NativeArrayBuffer.name != ARRAY_BUFFER;
10721 })) {
10722 $ArrayBuffer = function ArrayBuffer(length) {
10723 anInstance(this, $ArrayBuffer);
10724 return new NativeArrayBuffer(toIndex(length));
10725 };
10726
10727 var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer[PROTOTYPE];
10728
10729 for (var keys = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys.length > j;) {
10730 if (!((key = keys[j++]) in $ArrayBuffer)) {
10731 createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]);
10732 }
10733 }
10734
10735 ArrayBufferPrototype.constructor = $ArrayBuffer;
10736 } // WebKit bug - the same parent prototype for typed arrays and data view
10737
10738
10739 if (setPrototypeOf && getPrototypeOf($DataViewPrototype) !== ObjectPrototype) {
10740 setPrototypeOf($DataViewPrototype, ObjectPrototype);
10741 } // iOS Safari 7.x bug
10742
10743
10744 var testView = new $DataView(new $ArrayBuffer(2));
10745 var nativeSetInt8 = $DataViewPrototype.setInt8;
10746 testView.setInt8(0, 2147483648);
10747 testView.setInt8(1, 2147483649);
10748 if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataViewPrototype, {
10749 setInt8: function setInt8(byteOffset, value) {
10750 nativeSetInt8.call(this, byteOffset, value << 24 >> 24);
10751 },
10752 setUint8: function setUint8(byteOffset, value) {
10753 nativeSetInt8.call(this, byteOffset, value << 24 >> 24);
10754 }
10755 }, {
10756 unsafe: true
10757 });
10758}
10759
10760setToStringTag($ArrayBuffer, ARRAY_BUFFER);
10761setToStringTag($DataView, DATA_VIEW);
10762module.exports = {
10763 ArrayBuffer: $ArrayBuffer,
10764 DataView: $DataView
10765};
10766
10767/***/ }),
10768/* 303 */
10769/***/ (function(module, exports) {
10770
10771module.exports = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined';
10772
10773/***/ }),
10774/* 304 */
10775/***/ (function(module, exports, __webpack_require__) {
10776
10777var toInteger = __webpack_require__(42);
10778
10779var toLength = __webpack_require__(41); // `ToIndex` abstract operation
10780// https://tc39.github.io/ecma262/#sec-toindex
10781
10782
10783module.exports = function (it) {
10784 if (it === undefined) return 0;
10785 var number = toInteger(it);
10786 var length = toLength(number);
10787 if (number !== length) throw RangeError('Wrong length or index');
10788 return length;
10789};
10790
10791/***/ }),
10792/* 305 */
10793/***/ (function(module, exports) {
10794
10795// IEEE754 conversions based on https://github.com/feross/ieee754
10796// eslint-disable-next-line no-shadow-restricted-names
10797var Infinity = 1 / 0;
10798var abs = Math.abs;
10799var pow = Math.pow;
10800var floor = Math.floor;
10801var log = Math.log;
10802var LN2 = Math.LN2;
10803
10804var pack = function pack(number, mantissaLength, bytes) {
10805 var buffer = new Array(bytes);
10806 var exponentLength = bytes * 8 - mantissaLength - 1;
10807 var eMax = (1 << exponentLength) - 1;
10808 var eBias = eMax >> 1;
10809 var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0;
10810 var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;
10811 var index = 0;
10812 var exponent, mantissa, c;
10813 number = abs(number); // eslint-disable-next-line no-self-compare
10814
10815 if (number != number || number === Infinity) {
10816 // eslint-disable-next-line no-self-compare
10817 mantissa = number != number ? 1 : 0;
10818 exponent = eMax;
10819 } else {
10820 exponent = floor(log(number) / LN2);
10821
10822 if (number * (c = pow(2, -exponent)) < 1) {
10823 exponent--;
10824 c *= 2;
10825 }
10826
10827 if (exponent + eBias >= 1) {
10828 number += rt / c;
10829 } else {
10830 number += rt * pow(2, 1 - eBias);
10831 }
10832
10833 if (number * c >= 2) {
10834 exponent++;
10835 c /= 2;
10836 }
10837
10838 if (exponent + eBias >= eMax) {
10839 mantissa = 0;
10840 exponent = eMax;
10841 } else if (exponent + eBias >= 1) {
10842 mantissa = (number * c - 1) * pow(2, mantissaLength);
10843 exponent = exponent + eBias;
10844 } else {
10845 mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);
10846 exponent = 0;
10847 }
10848 }
10849
10850 for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8);
10851
10852 exponent = exponent << mantissaLength | mantissa;
10853 exponentLength += mantissaLength;
10854
10855 for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8);
10856
10857 buffer[--index] |= sign * 128;
10858 return buffer;
10859};
10860
10861var unpack = function unpack(buffer, mantissaLength) {
10862 var bytes = buffer.length;
10863 var exponentLength = bytes * 8 - mantissaLength - 1;
10864 var eMax = (1 << exponentLength) - 1;
10865 var eBias = eMax >> 1;
10866 var nBits = exponentLength - 7;
10867 var index = bytes - 1;
10868 var sign = buffer[index--];
10869 var exponent = sign & 127;
10870 var mantissa;
10871 sign >>= 7;
10872
10873 for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8);
10874
10875 mantissa = exponent & (1 << -nBits) - 1;
10876 exponent >>= -nBits;
10877 nBits += mantissaLength;
10878
10879 for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8);
10880
10881 if (exponent === 0) {
10882 exponent = 1 - eBias;
10883 } else if (exponent === eMax) {
10884 return mantissa ? NaN : sign ? -Infinity : Infinity;
10885 } else {
10886 mantissa = mantissa + pow(2, mantissaLength);
10887 exponent = exponent - eBias;
10888 }
10889
10890 return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength);
10891};
10892
10893module.exports = {
10894 pack: pack,
10895 unpack: unpack
10896};
10897
10898/***/ }),
10899/* 306 */
10900/***/ (function(module, exports, __webpack_require__) {
10901
10902var $ = __webpack_require__(4);
10903
10904var ArrayBufferViewCore = __webpack_require__(307);
10905
10906var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; // `ArrayBuffer.isView` method
10907// https://tc39.github.io/ecma262/#sec-arraybuffer.isview
10908
10909$({
10910 target: 'ArrayBuffer',
10911 stat: true,
10912 forced: !NATIVE_ARRAY_BUFFER_VIEWS
10913}, {
10914 isView: ArrayBufferViewCore.isView
10915});
10916
10917/***/ }),
10918/* 307 */
10919/***/ (function(module, exports, __webpack_require__) {
10920
10921"use strict";
10922
10923
10924var NATIVE_ARRAY_BUFFER = __webpack_require__(303);
10925
10926var DESCRIPTORS = __webpack_require__(7);
10927
10928var global = __webpack_require__(5);
10929
10930var isObject = __webpack_require__(16);
10931
10932var has = __webpack_require__(17);
10933
10934var classof = __webpack_require__(93);
10935
10936var createNonEnumerableProperty = __webpack_require__(20);
10937
10938var redefine = __webpack_require__(23);
10939
10940var defineProperty = __webpack_require__(21).f;
10941
10942var getPrototypeOf = __webpack_require__(101);
10943
10944var setPrototypeOf = __webpack_require__(112);
10945
10946var wellKnownSymbol = __webpack_require__(56);
10947
10948var uid = __webpack_require__(32);
10949
10950var Int8Array = global.Int8Array;
10951var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
10952var Uint8ClampedArray = global.Uint8ClampedArray;
10953var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
10954var TypedArray = Int8Array && getPrototypeOf(Int8Array);
10955var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
10956var ObjectPrototype = Object.prototype;
10957var isPrototypeOf = ObjectPrototype.isPrototypeOf;
10958var TO_STRING_TAG = wellKnownSymbol('toStringTag');
10959var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); // Fixing native typed arrays in Opera Presto crashes the browser, see #595
10960
10961var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
10962var TYPED_ARRAY_TAG_REQIRED = false;
10963var NAME;
10964var TypedArrayConstructorsList = {
10965 Int8Array: 1,
10966 Uint8Array: 1,
10967 Uint8ClampedArray: 1,
10968 Int16Array: 2,
10969 Uint16Array: 2,
10970 Int32Array: 4,
10971 Uint32Array: 4,
10972 Float32Array: 4,
10973 Float64Array: 8
10974};
10975
10976var isView = function isView(it) {
10977 var klass = classof(it);
10978 return klass === 'DataView' || has(TypedArrayConstructorsList, klass);
10979};
10980
10981var isTypedArray = function isTypedArray(it) {
10982 return isObject(it) && has(TypedArrayConstructorsList, classof(it));
10983};
10984
10985var aTypedArray = function aTypedArray(it) {
10986 if (isTypedArray(it)) return it;
10987 throw TypeError('Target is not a typed array');
10988};
10989
10990var aTypedArrayConstructor = function aTypedArrayConstructor(C) {
10991 if (setPrototypeOf) {
10992 if (isPrototypeOf.call(TypedArray, C)) return C;
10993 } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) {
10994 var TypedArrayConstructor = global[ARRAY];
10995
10996 if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) {
10997 return C;
10998 }
10999 }
11000
11001 throw TypeError('Target is not a typed array constructor');
11002};
11003
11004var exportTypedArrayMethod = function exportTypedArrayMethod(KEY, property, forced) {
11005 if (!DESCRIPTORS) return;
11006 if (forced) for (var ARRAY in TypedArrayConstructorsList) {
11007 var TypedArrayConstructor = global[ARRAY];
11008
11009 if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) {
11010 delete TypedArrayConstructor.prototype[KEY];
11011 }
11012 }
11013
11014 if (!TypedArrayPrototype[KEY] || forced) {
11015 redefine(TypedArrayPrototype, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);
11016 }
11017};
11018
11019var exportTypedArrayStaticMethod = function exportTypedArrayStaticMethod(KEY, property, forced) {
11020 var ARRAY, TypedArrayConstructor;
11021 if (!DESCRIPTORS) return;
11022
11023 if (setPrototypeOf) {
11024 if (forced) for (ARRAY in TypedArrayConstructorsList) {
11025 TypedArrayConstructor = global[ARRAY];
11026
11027 if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) {
11028 delete TypedArrayConstructor[KEY];
11029 }
11030 }
11031
11032 if (!TypedArray[KEY] || forced) {
11033 // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
11034 try {
11035 return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property);
11036 } catch (error) {
11037 /* empty */
11038 }
11039 } else return;
11040 }
11041
11042 for (ARRAY in TypedArrayConstructorsList) {
11043 TypedArrayConstructor = global[ARRAY];
11044
11045 if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
11046 redefine(TypedArrayConstructor, KEY, property);
11047 }
11048 }
11049};
11050
11051for (NAME in TypedArrayConstructorsList) {
11052 if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false;
11053} // WebKit bug - typed arrays constructors prototype is Object.prototype
11054
11055
11056if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) {
11057 // eslint-disable-next-line no-shadow
11058 TypedArray = function TypedArray() {
11059 throw TypeError('Incorrect invocation');
11060 };
11061
11062 if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
11063 if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
11064 }
11065}
11066
11067if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
11068 TypedArrayPrototype = TypedArray.prototype;
11069 if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
11070 if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
11071 }
11072} // WebKit bug - one more object in Uint8ClampedArray prototype chain
11073
11074
11075if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
11076 setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
11077}
11078
11079if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) {
11080 TYPED_ARRAY_TAG_REQIRED = true;
11081 defineProperty(TypedArrayPrototype, TO_STRING_TAG, {
11082 get: function get() {
11083 return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
11084 }
11085 });
11086
11087 for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
11088 createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
11089 }
11090}
11091
11092module.exports = {
11093 NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
11094 TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,
11095 aTypedArray: aTypedArray,
11096 aTypedArrayConstructor: aTypedArrayConstructor,
11097 exportTypedArrayMethod: exportTypedArrayMethod,
11098 exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
11099 isView: isView,
11100 isTypedArray: isTypedArray,
11101 TypedArray: TypedArray,
11102 TypedArrayPrototype: TypedArrayPrototype
11103};
11104
11105/***/ }),
11106/* 308 */
11107/***/ (function(module, exports, __webpack_require__) {
11108
11109"use strict";
11110
11111
11112var $ = __webpack_require__(4);
11113
11114var fails = __webpack_require__(8);
11115
11116var ArrayBufferModule = __webpack_require__(302);
11117
11118var anObject = __webpack_require__(22);
11119
11120var toAbsoluteIndex = __webpack_require__(43);
11121
11122var toLength = __webpack_require__(41);
11123
11124var speciesConstructor = __webpack_require__(192);
11125
11126var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
11127var DataView = ArrayBufferModule.DataView;
11128var nativeArrayBufferSlice = ArrayBuffer.prototype.slice;
11129var INCORRECT_SLICE = fails(function () {
11130 return !new ArrayBuffer(2).slice(1, undefined).byteLength;
11131}); // `ArrayBuffer.prototype.slice` method
11132// https://tc39.github.io/ecma262/#sec-arraybuffer.prototype.slice
11133
11134$({
11135 target: 'ArrayBuffer',
11136 proto: true,
11137 unsafe: true,
11138 forced: INCORRECT_SLICE
11139}, {
11140 slice: function slice(start, end) {
11141 if (nativeArrayBufferSlice !== undefined && end === undefined) {
11142 return nativeArrayBufferSlice.call(anObject(this), start); // FF fix
11143 }
11144
11145 var length = anObject(this).byteLength;
11146 var first = toAbsoluteIndex(start, length);
11147 var fin = toAbsoluteIndex(end === undefined ? length : end, length);
11148 var result = new (speciesConstructor(this, ArrayBuffer))(toLength(fin - first));
11149 var viewSource = new DataView(this);
11150 var viewTarget = new DataView(result);
11151 var index = 0;
11152
11153 while (first < fin) {
11154 viewTarget.setUint8(index++, viewSource.getUint8(first++));
11155 }
11156
11157 return result;
11158 }
11159});
11160
11161/***/ }),
11162/* 309 */
11163/***/ (function(module, exports, __webpack_require__) {
11164
11165var $ = __webpack_require__(4);
11166
11167var ArrayBufferModule = __webpack_require__(302);
11168
11169var NATIVE_ARRAY_BUFFER = __webpack_require__(303); // `DataView` constructor
11170// https://tc39.github.io/ecma262/#sec-dataview-constructor
11171
11172
11173$({
11174 global: true,
11175 forced: !NATIVE_ARRAY_BUFFER
11176}, {
11177 DataView: ArrayBufferModule.DataView
11178});
11179
11180/***/ }),
11181/* 310 */
11182/***/ (function(module, exports, __webpack_require__) {
11183
11184var createTypedArrayConstructor = __webpack_require__(311); // `Int8Array` constructor
11185// https://tc39.github.io/ecma262/#sec-typedarray-objects
11186
11187
11188createTypedArrayConstructor('Int8', function (init) {
11189 return function Int8Array(data, byteOffset, length) {
11190 return init(this, data, byteOffset, length);
11191 };
11192});
11193
11194/***/ }),
11195/* 311 */
11196/***/ (function(module, exports, __webpack_require__) {
11197
11198"use strict";
11199
11200
11201var $ = __webpack_require__(4);
11202
11203var global = __webpack_require__(5);
11204
11205var DESCRIPTORS = __webpack_require__(7);
11206
11207var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(312);
11208
11209var ArrayBufferViewCore = __webpack_require__(307);
11210
11211var ArrayBufferModule = __webpack_require__(302);
11212
11213var anInstance = __webpack_require__(284);
11214
11215var createPropertyDescriptor = __webpack_require__(10);
11216
11217var createNonEnumerableProperty = __webpack_require__(20);
11218
11219var toLength = __webpack_require__(41);
11220
11221var toIndex = __webpack_require__(304);
11222
11223var toOffset = __webpack_require__(313);
11224
11225var toPrimitive = __webpack_require__(15);
11226
11227var has = __webpack_require__(17);
11228
11229var classof = __webpack_require__(93);
11230
11231var isObject = __webpack_require__(16);
11232
11233var create = __webpack_require__(51);
11234
11235var setPrototypeOf = __webpack_require__(112);
11236
11237var getOwnPropertyNames = __webpack_require__(38).f;
11238
11239var typedArrayFrom = __webpack_require__(315);
11240
11241var forEach = __webpack_require__(60).forEach;
11242
11243var setSpecies = __webpack_require__(167);
11244
11245var definePropertyModule = __webpack_require__(21);
11246
11247var getOwnPropertyDescriptorModule = __webpack_require__(6);
11248
11249var InternalStateModule = __webpack_require__(27);
11250
11251var inheritIfRequired = __webpack_require__(226);
11252
11253var getInternalState = InternalStateModule.get;
11254var setInternalState = InternalStateModule.set;
11255var nativeDefineProperty = definePropertyModule.f;
11256var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
11257var round = Math.round;
11258var RangeError = global.RangeError;
11259var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
11260var DataView = ArrayBufferModule.DataView;
11261var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;
11262var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG;
11263var TypedArray = ArrayBufferViewCore.TypedArray;
11264var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype;
11265var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
11266var isTypedArray = ArrayBufferViewCore.isTypedArray;
11267var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
11268var WRONG_LENGTH = 'Wrong length';
11269
11270var fromList = function fromList(C, list) {
11271 var index = 0;
11272 var length = list.length;
11273 var result = new (aTypedArrayConstructor(C))(length);
11274
11275 while (length > index) result[index] = list[index++];
11276
11277 return result;
11278};
11279
11280var addGetter = function addGetter(it, key) {
11281 nativeDefineProperty(it, key, {
11282 get: function get() {
11283 return getInternalState(this)[key];
11284 }
11285 });
11286};
11287
11288var isArrayBuffer = function isArrayBuffer(it) {
11289 var klass;
11290 return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer';
11291};
11292
11293var isTypedArrayIndex = function isTypedArrayIndex(target, key) {
11294 return isTypedArray(target) && typeof key != 'symbol' && key in target && String(+key) == String(key);
11295};
11296
11297var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {
11298 return isTypedArrayIndex(target, key = toPrimitive(key, true)) ? createPropertyDescriptor(2, target[key]) : nativeGetOwnPropertyDescriptor(target, key);
11299};
11300
11301var wrappedDefineProperty = function defineProperty(target, key, descriptor) {
11302 if (isTypedArrayIndex(target, key = toPrimitive(key, true)) && isObject(descriptor) && has(descriptor, 'value') && !has(descriptor, 'get') && !has(descriptor, 'set') // TODO: add validation descriptor w/o calling accessors
11303 && !descriptor.configurable && (!has(descriptor, 'writable') || descriptor.writable) && (!has(descriptor, 'enumerable') || descriptor.enumerable)) {
11304 target[key] = descriptor.value;
11305 return target;
11306 }
11307
11308 return nativeDefineProperty(target, key, descriptor);
11309};
11310
11311if (DESCRIPTORS) {
11312 if (!NATIVE_ARRAY_BUFFER_VIEWS) {
11313 getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor;
11314 definePropertyModule.f = wrappedDefineProperty;
11315 addGetter(TypedArrayPrototype, 'buffer');
11316 addGetter(TypedArrayPrototype, 'byteOffset');
11317 addGetter(TypedArrayPrototype, 'byteLength');
11318 addGetter(TypedArrayPrototype, 'length');
11319 }
11320
11321 $({
11322 target: 'Object',
11323 stat: true,
11324 forced: !NATIVE_ARRAY_BUFFER_VIEWS
11325 }, {
11326 getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,
11327 defineProperty: wrappedDefineProperty
11328 });
11329
11330 module.exports = function (TYPE, wrapper, CLAMPED) {
11331 var BYTES = TYPE.match(/\d+$/)[0] / 8;
11332 var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';
11333 var GETTER = 'get' + TYPE;
11334 var SETTER = 'set' + TYPE;
11335 var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME];
11336 var TypedArrayConstructor = NativeTypedArrayConstructor;
11337 var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;
11338 var exported = {};
11339
11340 var getter = function getter(that, index) {
11341 var data = getInternalState(that);
11342 return data.view[GETTER](index * BYTES + data.byteOffset, true);
11343 };
11344
11345 var setter = function setter(that, index, value) {
11346 var data = getInternalState(that);
11347 if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;
11348 data.view[SETTER](index * BYTES + data.byteOffset, value, true);
11349 };
11350
11351 var addElement = function addElement(that, index) {
11352 nativeDefineProperty(that, index, {
11353 get: function get() {
11354 return getter(this, index);
11355 },
11356 set: function set(value) {
11357 return setter(this, index, value);
11358 },
11359 enumerable: true
11360 });
11361 };
11362
11363 if (!NATIVE_ARRAY_BUFFER_VIEWS) {
11364 TypedArrayConstructor = wrapper(function (that, data, offset, $length) {
11365 anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME);
11366 var index = 0;
11367 var byteOffset = 0;
11368 var buffer, byteLength, length;
11369
11370 if (!isObject(data)) {
11371 length = toIndex(data);
11372 byteLength = length * BYTES;
11373 buffer = new ArrayBuffer(byteLength);
11374 } else if (isArrayBuffer(data)) {
11375 buffer = data;
11376 byteOffset = toOffset(offset, BYTES);
11377 var $len = data.byteLength;
11378
11379 if ($length === undefined) {
11380 if ($len % BYTES) throw RangeError(WRONG_LENGTH);
11381 byteLength = $len - byteOffset;
11382 if (byteLength < 0) throw RangeError(WRONG_LENGTH);
11383 } else {
11384 byteLength = toLength($length) * BYTES;
11385 if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH);
11386 }
11387
11388 length = byteLength / BYTES;
11389 } else if (isTypedArray(data)) {
11390 return fromList(TypedArrayConstructor, data);
11391 } else {
11392 return typedArrayFrom.call(TypedArrayConstructor, data);
11393 }
11394
11395 setInternalState(that, {
11396 buffer: buffer,
11397 byteOffset: byteOffset,
11398 byteLength: byteLength,
11399 length: length,
11400 view: new DataView(buffer)
11401 });
11402
11403 while (index < length) addElement(that, index++);
11404 });
11405 if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);
11406 TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype);
11407 } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) {
11408 TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {
11409 anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME);
11410 return inheritIfRequired(function () {
11411 if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data));
11412 if (isArrayBuffer(data)) return $length !== undefined ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) : typedArrayOffset !== undefined ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) : new NativeTypedArrayConstructor(data);
11413 if (isTypedArray(data)) return fromList(TypedArrayConstructor, data);
11414 return typedArrayFrom.call(TypedArrayConstructor, data);
11415 }(), dummy, TypedArrayConstructor);
11416 });
11417 if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);
11418 forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) {
11419 if (!(key in TypedArrayConstructor)) {
11420 createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);
11421 }
11422 });
11423 TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;
11424 }
11425
11426 if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {
11427 createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);
11428 }
11429
11430 if (TYPED_ARRAY_TAG) {
11431 createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);
11432 }
11433
11434 exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;
11435 $({
11436 global: true,
11437 forced: TypedArrayConstructor != NativeTypedArrayConstructor,
11438 sham: !NATIVE_ARRAY_BUFFER_VIEWS
11439 }, exported);
11440
11441 if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {
11442 createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);
11443 }
11444
11445 if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {
11446 createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);
11447 }
11448
11449 setSpecies(CONSTRUCTOR_NAME);
11450 };
11451} else module.exports = function () {
11452 /* empty */
11453};
11454
11455/***/ }),
11456/* 312 */
11457/***/ (function(module, exports, __webpack_require__) {
11458
11459/* eslint-disable no-new */
11460var global = __webpack_require__(5);
11461
11462var fails = __webpack_require__(8);
11463
11464var checkCorrectnessOfIteration = __webpack_require__(129);
11465
11466var NATIVE_ARRAY_BUFFER_VIEWS = __webpack_require__(307).NATIVE_ARRAY_BUFFER_VIEWS;
11467
11468var ArrayBuffer = global.ArrayBuffer;
11469var Int8Array = global.Int8Array;
11470module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () {
11471 Int8Array(1);
11472}) || !fails(function () {
11473 new Int8Array(-1);
11474}) || !checkCorrectnessOfIteration(function (iterable) {
11475 new Int8Array();
11476 new Int8Array(null);
11477 new Int8Array(1.5);
11478 new Int8Array(iterable);
11479}, true) || fails(function () {
11480 // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill
11481 return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1;
11482});
11483
11484/***/ }),
11485/* 313 */
11486/***/ (function(module, exports, __webpack_require__) {
11487
11488var toPositiveInteger = __webpack_require__(314);
11489
11490module.exports = function (it, BYTES) {
11491 var offset = toPositiveInteger(it);
11492 if (offset % BYTES) throw RangeError('Wrong offset');
11493 return offset;
11494};
11495
11496/***/ }),
11497/* 314 */
11498/***/ (function(module, exports, __webpack_require__) {
11499
11500var toInteger = __webpack_require__(42);
11501
11502module.exports = function (it) {
11503 var result = toInteger(it);
11504 if (result < 0) throw RangeError("The argument can't be less than 0");
11505 return result;
11506};
11507
11508/***/ }),
11509/* 315 */
11510/***/ (function(module, exports, __webpack_require__) {
11511
11512var toObject = __webpack_require__(50);
11513
11514var toLength = __webpack_require__(41);
11515
11516var getIteratorMethod = __webpack_require__(92);
11517
11518var isArrayIteratorMethod = __webpack_require__(90);
11519
11520var bind = __webpack_require__(61);
11521
11522var aTypedArrayConstructor = __webpack_require__(307).aTypedArrayConstructor;
11523
11524module.exports = function from(source
11525/* , mapfn, thisArg */
11526) {
11527 var O = toObject(source);
11528 var argumentsLength = arguments.length;
11529 var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
11530 var mapping = mapfn !== undefined;
11531 var iteratorMethod = getIteratorMethod(O);
11532 var i, length, result, step, iterator, next;
11533
11534 if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) {
11535 iterator = iteratorMethod.call(O);
11536 next = iterator.next;
11537 O = [];
11538
11539 while (!(step = next.call(iterator)).done) {
11540 O.push(step.value);
11541 }
11542 }
11543
11544 if (mapping && argumentsLength > 2) {
11545 mapfn = bind(mapfn, arguments[2], 2);
11546 }
11547
11548 length = toLength(O.length);
11549 result = new (aTypedArrayConstructor(this))(length);
11550
11551 for (i = 0; length > i; i++) {
11552 result[i] = mapping ? mapfn(O[i], i) : O[i];
11553 }
11554
11555 return result;
11556};
11557
11558/***/ }),
11559/* 316 */
11560/***/ (function(module, exports, __webpack_require__) {
11561
11562var createTypedArrayConstructor = __webpack_require__(311); // `Uint8Array` constructor
11563// https://tc39.github.io/ecma262/#sec-typedarray-objects
11564
11565
11566createTypedArrayConstructor('Uint8', function (init) {
11567 return function Uint8Array(data, byteOffset, length) {
11568 return init(this, data, byteOffset, length);
11569 };
11570});
11571
11572/***/ }),
11573/* 317 */
11574/***/ (function(module, exports, __webpack_require__) {
11575
11576var createTypedArrayConstructor = __webpack_require__(311); // `Uint8ClampedArray` constructor
11577// https://tc39.github.io/ecma262/#sec-typedarray-objects
11578
11579
11580createTypedArrayConstructor('Uint8', function (init) {
11581 return function Uint8ClampedArray(data, byteOffset, length) {
11582 return init(this, data, byteOffset, length);
11583 };
11584}, true);
11585
11586/***/ }),
11587/* 318 */
11588/***/ (function(module, exports, __webpack_require__) {
11589
11590var createTypedArrayConstructor = __webpack_require__(311); // `Int16Array` constructor
11591// https://tc39.github.io/ecma262/#sec-typedarray-objects
11592
11593
11594createTypedArrayConstructor('Int16', function (init) {
11595 return function Int16Array(data, byteOffset, length) {
11596 return init(this, data, byteOffset, length);
11597 };
11598});
11599
11600/***/ }),
11601/* 319 */
11602/***/ (function(module, exports, __webpack_require__) {
11603
11604var createTypedArrayConstructor = __webpack_require__(311); // `Uint16Array` constructor
11605// https://tc39.github.io/ecma262/#sec-typedarray-objects
11606
11607
11608createTypedArrayConstructor('Uint16', function (init) {
11609 return function Uint16Array(data, byteOffset, length) {
11610 return init(this, data, byteOffset, length);
11611 };
11612});
11613
11614/***/ }),
11615/* 320 */
11616/***/ (function(module, exports, __webpack_require__) {
11617
11618var createTypedArrayConstructor = __webpack_require__(311); // `Int32Array` constructor
11619// https://tc39.github.io/ecma262/#sec-typedarray-objects
11620
11621
11622createTypedArrayConstructor('Int32', function (init) {
11623 return function Int32Array(data, byteOffset, length) {
11624 return init(this, data, byteOffset, length);
11625 };
11626});
11627
11628/***/ }),
11629/* 321 */
11630/***/ (function(module, exports, __webpack_require__) {
11631
11632var createTypedArrayConstructor = __webpack_require__(311); // `Uint32Array` constructor
11633// https://tc39.github.io/ecma262/#sec-typedarray-objects
11634
11635
11636createTypedArrayConstructor('Uint32', function (init) {
11637 return function Uint32Array(data, byteOffset, length) {
11638 return init(this, data, byteOffset, length);
11639 };
11640});
11641
11642/***/ }),
11643/* 322 */
11644/***/ (function(module, exports, __webpack_require__) {
11645
11646var createTypedArrayConstructor = __webpack_require__(311); // `Float32Array` constructor
11647// https://tc39.github.io/ecma262/#sec-typedarray-objects
11648
11649
11650createTypedArrayConstructor('Float32', function (init) {
11651 return function Float32Array(data, byteOffset, length) {
11652 return init(this, data, byteOffset, length);
11653 };
11654});
11655
11656/***/ }),
11657/* 323 */
11658/***/ (function(module, exports, __webpack_require__) {
11659
11660var createTypedArrayConstructor = __webpack_require__(311); // `Float64Array` constructor
11661// https://tc39.github.io/ecma262/#sec-typedarray-objects
11662
11663
11664createTypedArrayConstructor('Float64', function (init) {
11665 return function Float64Array(data, byteOffset, length) {
11666 return init(this, data, byteOffset, length);
11667 };
11668});
11669
11670/***/ }),
11671/* 324 */
11672/***/ (function(module, exports, __webpack_require__) {
11673
11674"use strict";
11675
11676
11677var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(312);
11678
11679var exportTypedArrayStaticMethod = __webpack_require__(307).exportTypedArrayStaticMethod;
11680
11681var typedArrayFrom = __webpack_require__(315); // `%TypedArray%.from` method
11682// https://tc39.github.io/ecma262/#sec-%typedarray%.from
11683
11684
11685exportTypedArrayStaticMethod('from', typedArrayFrom, TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS);
11686
11687/***/ }),
11688/* 325 */
11689/***/ (function(module, exports, __webpack_require__) {
11690
11691"use strict";
11692
11693
11694var ArrayBufferViewCore = __webpack_require__(307);
11695
11696var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = __webpack_require__(312);
11697
11698var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
11699var exportTypedArrayStaticMethod = ArrayBufferViewCore.exportTypedArrayStaticMethod; // `%TypedArray%.of` method
11700// https://tc39.github.io/ecma262/#sec-%typedarray%.of
11701
11702exportTypedArrayStaticMethod('of', function of()
11703/* ...items */
11704{
11705 var index = 0;
11706 var length = arguments.length;
11707 var result = new (aTypedArrayConstructor(this))(length);
11708
11709 while (length > index) result[index] = arguments[index++];
11710
11711 return result;
11712}, TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS);
11713
11714/***/ }),
11715/* 326 */
11716/***/ (function(module, exports, __webpack_require__) {
11717
11718"use strict";
11719
11720
11721var ArrayBufferViewCore = __webpack_require__(307);
11722
11723var $copyWithin = __webpack_require__(137);
11724
11725var aTypedArray = ArrayBufferViewCore.aTypedArray;
11726var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.copyWithin` method
11727// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin
11728
11729exportTypedArrayMethod('copyWithin', function copyWithin(target, start
11730/* , end */
11731) {
11732 return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
11733});
11734
11735/***/ }),
11736/* 327 */
11737/***/ (function(module, exports, __webpack_require__) {
11738
11739"use strict";
11740
11741
11742var ArrayBufferViewCore = __webpack_require__(307);
11743
11744var $every = __webpack_require__(60).every;
11745
11746var aTypedArray = ArrayBufferViewCore.aTypedArray;
11747var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.every` method
11748// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every
11749
11750exportTypedArrayMethod('every', function every(callbackfn
11751/* , thisArg */
11752) {
11753 return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
11754});
11755
11756/***/ }),
11757/* 328 */
11758/***/ (function(module, exports, __webpack_require__) {
11759
11760"use strict";
11761
11762
11763var ArrayBufferViewCore = __webpack_require__(307);
11764
11765var $fill = __webpack_require__(143);
11766
11767var aTypedArray = ArrayBufferViewCore.aTypedArray;
11768var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.fill` method
11769// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill
11770// eslint-disable-next-line no-unused-vars
11771
11772exportTypedArrayMethod('fill', function fill(value
11773/* , start, end */
11774) {
11775 return $fill.apply(aTypedArray(this), arguments);
11776});
11777
11778/***/ }),
11779/* 329 */
11780/***/ (function(module, exports, __webpack_require__) {
11781
11782"use strict";
11783
11784
11785var ArrayBufferViewCore = __webpack_require__(307);
11786
11787var $filter = __webpack_require__(60).filter;
11788
11789var speciesConstructor = __webpack_require__(192);
11790
11791var aTypedArray = ArrayBufferViewCore.aTypedArray;
11792var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
11793var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.filter` method
11794// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter
11795
11796exportTypedArrayMethod('filter', function filter(callbackfn
11797/* , thisArg */
11798) {
11799 var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
11800 var C = speciesConstructor(this, this.constructor);
11801 var index = 0;
11802 var length = list.length;
11803 var result = new (aTypedArrayConstructor(C))(length);
11804
11805 while (length > index) result[index] = list[index++];
11806
11807 return result;
11808});
11809
11810/***/ }),
11811/* 330 */
11812/***/ (function(module, exports, __webpack_require__) {
11813
11814"use strict";
11815
11816
11817var ArrayBufferViewCore = __webpack_require__(307);
11818
11819var $find = __webpack_require__(60).find;
11820
11821var aTypedArray = ArrayBufferViewCore.aTypedArray;
11822var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.find` method
11823// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find
11824
11825exportTypedArrayMethod('find', function find(predicate
11826/* , thisArg */
11827) {
11828 return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
11829});
11830
11831/***/ }),
11832/* 331 */
11833/***/ (function(module, exports, __webpack_require__) {
11834
11835"use strict";
11836
11837
11838var ArrayBufferViewCore = __webpack_require__(307);
11839
11840var $findIndex = __webpack_require__(60).findIndex;
11841
11842var aTypedArray = ArrayBufferViewCore.aTypedArray;
11843var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.findIndex` method
11844// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex
11845
11846exportTypedArrayMethod('findIndex', function findIndex(predicate
11847/* , thisArg */
11848) {
11849 return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
11850});
11851
11852/***/ }),
11853/* 332 */
11854/***/ (function(module, exports, __webpack_require__) {
11855
11856"use strict";
11857
11858
11859var ArrayBufferViewCore = __webpack_require__(307);
11860
11861var $forEach = __webpack_require__(60).forEach;
11862
11863var aTypedArray = ArrayBufferViewCore.aTypedArray;
11864var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.forEach` method
11865// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach
11866
11867exportTypedArrayMethod('forEach', function forEach(callbackfn
11868/* , thisArg */
11869) {
11870 $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
11871});
11872
11873/***/ }),
11874/* 333 */
11875/***/ (function(module, exports, __webpack_require__) {
11876
11877"use strict";
11878
11879
11880var ArrayBufferViewCore = __webpack_require__(307);
11881
11882var $includes = __webpack_require__(40).includes;
11883
11884var aTypedArray = ArrayBufferViewCore.aTypedArray;
11885var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.includes` method
11886// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes
11887
11888exportTypedArrayMethod('includes', function includes(searchElement
11889/* , fromIndex */
11890) {
11891 return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
11892});
11893
11894/***/ }),
11895/* 334 */
11896/***/ (function(module, exports, __webpack_require__) {
11897
11898"use strict";
11899
11900
11901var ArrayBufferViewCore = __webpack_require__(307);
11902
11903var $indexOf = __webpack_require__(40).indexOf;
11904
11905var aTypedArray = ArrayBufferViewCore.aTypedArray;
11906var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.indexOf` method
11907// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof
11908
11909exportTypedArrayMethod('indexOf', function indexOf(searchElement
11910/* , fromIndex */
11911) {
11912 return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
11913});
11914
11915/***/ }),
11916/* 335 */
11917/***/ (function(module, exports, __webpack_require__) {
11918
11919"use strict";
11920
11921
11922var global = __webpack_require__(5);
11923
11924var ArrayBufferViewCore = __webpack_require__(307);
11925
11926var ArrayIterators = __webpack_require__(170);
11927
11928var wellKnownSymbol = __webpack_require__(56);
11929
11930var ITERATOR = wellKnownSymbol('iterator');
11931var Uint8Array = global.Uint8Array;
11932var arrayValues = ArrayIterators.values;
11933var arrayKeys = ArrayIterators.keys;
11934var arrayEntries = ArrayIterators.entries;
11935var aTypedArray = ArrayBufferViewCore.aTypedArray;
11936var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
11937var nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR];
11938var CORRECT_ITER_NAME = !!nativeTypedArrayIterator && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined);
11939
11940var typedArrayValues = function values() {
11941 return arrayValues.call(aTypedArray(this));
11942}; // `%TypedArray%.prototype.entries` method
11943// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries
11944
11945
11946exportTypedArrayMethod('entries', function entries() {
11947 return arrayEntries.call(aTypedArray(this));
11948}); // `%TypedArray%.prototype.keys` method
11949// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys
11950
11951exportTypedArrayMethod('keys', function keys() {
11952 return arrayKeys.call(aTypedArray(this));
11953}); // `%TypedArray%.prototype.values` method
11954// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values
11955
11956exportTypedArrayMethod('values', typedArrayValues, !CORRECT_ITER_NAME); // `%TypedArray%.prototype[@@iterator]` method
11957// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator
11958
11959exportTypedArrayMethod(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME);
11960
11961/***/ }),
11962/* 336 */
11963/***/ (function(module, exports, __webpack_require__) {
11964
11965"use strict";
11966
11967
11968var ArrayBufferViewCore = __webpack_require__(307);
11969
11970var aTypedArray = ArrayBufferViewCore.aTypedArray;
11971var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
11972var $join = [].join; // `%TypedArray%.prototype.join` method
11973// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join
11974// eslint-disable-next-line no-unused-vars
11975
11976exportTypedArrayMethod('join', function join(separator) {
11977 return $join.apply(aTypedArray(this), arguments);
11978});
11979
11980/***/ }),
11981/* 337 */
11982/***/ (function(module, exports, __webpack_require__) {
11983
11984"use strict";
11985
11986
11987var ArrayBufferViewCore = __webpack_require__(307);
11988
11989var $lastIndexOf = __webpack_require__(156);
11990
11991var aTypedArray = ArrayBufferViewCore.aTypedArray;
11992var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.lastIndexOf` method
11993// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof
11994// eslint-disable-next-line no-unused-vars
11995
11996exportTypedArrayMethod('lastIndexOf', function lastIndexOf(searchElement
11997/* , fromIndex */
11998) {
11999 return $lastIndexOf.apply(aTypedArray(this), arguments);
12000});
12001
12002/***/ }),
12003/* 338 */
12004/***/ (function(module, exports, __webpack_require__) {
12005
12006"use strict";
12007
12008
12009var ArrayBufferViewCore = __webpack_require__(307);
12010
12011var $map = __webpack_require__(60).map;
12012
12013var speciesConstructor = __webpack_require__(192);
12014
12015var aTypedArray = ArrayBufferViewCore.aTypedArray;
12016var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
12017var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.map` method
12018// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map
12019
12020exportTypedArrayMethod('map', function map(mapfn
12021/* , thisArg */
12022) {
12023 return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) {
12024 return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor)))(length);
12025 });
12026});
12027
12028/***/ }),
12029/* 339 */
12030/***/ (function(module, exports, __webpack_require__) {
12031
12032"use strict";
12033
12034
12035var ArrayBufferViewCore = __webpack_require__(307);
12036
12037var $reduce = __webpack_require__(159).left;
12038
12039var aTypedArray = ArrayBufferViewCore.aTypedArray;
12040var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.reduce` method
12041// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce
12042
12043exportTypedArrayMethod('reduce', function reduce(callbackfn
12044/* , initialValue */
12045) {
12046 return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
12047});
12048
12049/***/ }),
12050/* 340 */
12051/***/ (function(module, exports, __webpack_require__) {
12052
12053"use strict";
12054
12055
12056var ArrayBufferViewCore = __webpack_require__(307);
12057
12058var $reduceRight = __webpack_require__(159).right;
12059
12060var aTypedArray = ArrayBufferViewCore.aTypedArray;
12061var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.reduceRicht` method
12062// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright
12063
12064exportTypedArrayMethod('reduceRight', function reduceRight(callbackfn
12065/* , initialValue */
12066) {
12067 return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
12068});
12069
12070/***/ }),
12071/* 341 */
12072/***/ (function(module, exports, __webpack_require__) {
12073
12074"use strict";
12075
12076
12077var ArrayBufferViewCore = __webpack_require__(307);
12078
12079var aTypedArray = ArrayBufferViewCore.aTypedArray;
12080var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
12081var floor = Math.floor; // `%TypedArray%.prototype.reverse` method
12082// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse
12083
12084exportTypedArrayMethod('reverse', function reverse() {
12085 var that = this;
12086 var length = aTypedArray(that).length;
12087 var middle = floor(length / 2);
12088 var index = 0;
12089 var value;
12090
12091 while (index < middle) {
12092 value = that[index];
12093 that[index++] = that[--length];
12094 that[length] = value;
12095 }
12096
12097 return that;
12098});
12099
12100/***/ }),
12101/* 342 */
12102/***/ (function(module, exports, __webpack_require__) {
12103
12104"use strict";
12105
12106
12107var ArrayBufferViewCore = __webpack_require__(307);
12108
12109var toLength = __webpack_require__(41);
12110
12111var toOffset = __webpack_require__(313);
12112
12113var toObject = __webpack_require__(50);
12114
12115var fails = __webpack_require__(8);
12116
12117var aTypedArray = ArrayBufferViewCore.aTypedArray;
12118var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
12119var FORCED = fails(function () {
12120 // eslint-disable-next-line no-undef
12121 new Int8Array(1).set({});
12122}); // `%TypedArray%.prototype.set` method
12123// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set
12124
12125exportTypedArrayMethod('set', function set(arrayLike
12126/* , offset */
12127) {
12128 aTypedArray(this);
12129 var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);
12130 var length = this.length;
12131 var src = toObject(arrayLike);
12132 var len = toLength(src.length);
12133 var index = 0;
12134 if (len + offset > length) throw RangeError('Wrong length');
12135
12136 while (index < len) this[offset + index] = src[index++];
12137}, FORCED);
12138
12139/***/ }),
12140/* 343 */
12141/***/ (function(module, exports, __webpack_require__) {
12142
12143"use strict";
12144
12145
12146var ArrayBufferViewCore = __webpack_require__(307);
12147
12148var speciesConstructor = __webpack_require__(192);
12149
12150var fails = __webpack_require__(8);
12151
12152var aTypedArray = ArrayBufferViewCore.aTypedArray;
12153var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
12154var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
12155var $slice = [].slice;
12156var FORCED = fails(function () {
12157 // eslint-disable-next-line no-undef
12158 new Int8Array(1).slice();
12159}); // `%TypedArray%.prototype.slice` method
12160// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice
12161
12162exportTypedArrayMethod('slice', function slice(start, end) {
12163 var list = $slice.call(aTypedArray(this), start, end);
12164 var C = speciesConstructor(this, this.constructor);
12165 var index = 0;
12166 var length = list.length;
12167 var result = new (aTypedArrayConstructor(C))(length);
12168
12169 while (length > index) result[index] = list[index++];
12170
12171 return result;
12172}, FORCED);
12173
12174/***/ }),
12175/* 344 */
12176/***/ (function(module, exports, __webpack_require__) {
12177
12178"use strict";
12179
12180
12181var ArrayBufferViewCore = __webpack_require__(307);
12182
12183var $some = __webpack_require__(60).some;
12184
12185var aTypedArray = ArrayBufferViewCore.aTypedArray;
12186var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.some` method
12187// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some
12188
12189exportTypedArrayMethod('some', function some(callbackfn
12190/* , thisArg */
12191) {
12192 return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
12193});
12194
12195/***/ }),
12196/* 345 */
12197/***/ (function(module, exports, __webpack_require__) {
12198
12199"use strict";
12200
12201
12202var ArrayBufferViewCore = __webpack_require__(307);
12203
12204var aTypedArray = ArrayBufferViewCore.aTypedArray;
12205var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
12206var $sort = [].sort; // `%TypedArray%.prototype.sort` method
12207// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort
12208
12209exportTypedArrayMethod('sort', function sort(comparefn) {
12210 return $sort.call(aTypedArray(this), comparefn);
12211});
12212
12213/***/ }),
12214/* 346 */
12215/***/ (function(module, exports, __webpack_require__) {
12216
12217"use strict";
12218
12219
12220var ArrayBufferViewCore = __webpack_require__(307);
12221
12222var toLength = __webpack_require__(41);
12223
12224var toAbsoluteIndex = __webpack_require__(43);
12225
12226var speciesConstructor = __webpack_require__(192);
12227
12228var aTypedArray = ArrayBufferViewCore.aTypedArray;
12229var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.subarray` method
12230// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray
12231
12232exportTypedArrayMethod('subarray', function subarray(begin, end) {
12233 var O = aTypedArray(this);
12234 var length = O.length;
12235 var beginIndex = toAbsoluteIndex(begin, length);
12236 return new (speciesConstructor(O, O.constructor))(O.buffer, O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT, toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex));
12237});
12238
12239/***/ }),
12240/* 347 */
12241/***/ (function(module, exports, __webpack_require__) {
12242
12243"use strict";
12244
12245
12246var global = __webpack_require__(5);
12247
12248var ArrayBufferViewCore = __webpack_require__(307);
12249
12250var fails = __webpack_require__(8);
12251
12252var Int8Array = global.Int8Array;
12253var aTypedArray = ArrayBufferViewCore.aTypedArray;
12254var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
12255var $toLocaleString = [].toLocaleString;
12256var $slice = [].slice; // iOS Safari 6.x fails here
12257
12258var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {
12259 $toLocaleString.call(new Int8Array(1));
12260});
12261var FORCED = fails(function () {
12262 return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();
12263}) || !fails(function () {
12264 Int8Array.prototype.toLocaleString.call([1, 2]);
12265}); // `%TypedArray%.prototype.toLocaleString` method
12266// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring
12267
12268exportTypedArrayMethod('toLocaleString', function toLocaleString() {
12269 return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);
12270}, FORCED);
12271
12272/***/ }),
12273/* 348 */
12274/***/ (function(module, exports, __webpack_require__) {
12275
12276"use strict";
12277
12278
12279var exportTypedArrayMethod = __webpack_require__(307).exportTypedArrayMethod;
12280
12281var fails = __webpack_require__(8);
12282
12283var global = __webpack_require__(5);
12284
12285var Uint8Array = global.Uint8Array;
12286var Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype || {};
12287var arrayToString = [].toString;
12288var arrayJoin = [].join;
12289
12290if (fails(function () {
12291 arrayToString.call({});
12292})) {
12293 arrayToString = function toString() {
12294 return arrayJoin.call(this);
12295 };
12296}
12297
12298var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; // `%TypedArray%.prototype.toString` method
12299// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring
12300
12301exportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD);
12302
12303/***/ }),
12304/* 349 */
12305/***/ (function(module, exports, __webpack_require__) {
12306
12307var $ = __webpack_require__(4);
12308
12309var getBuiltIn = __webpack_require__(36);
12310
12311var aFunction = __webpack_require__(62);
12312
12313var anObject = __webpack_require__(22);
12314
12315var fails = __webpack_require__(8);
12316
12317var nativeApply = getBuiltIn('Reflect', 'apply');
12318var functionApply = Function.apply; // MS Edge argumentsList argument is optional
12319
12320var OPTIONAL_ARGUMENTS_LIST = !fails(function () {
12321 nativeApply(function () {
12322 /* empty */
12323 });
12324}); // `Reflect.apply` method
12325// https://tc39.github.io/ecma262/#sec-reflect.apply
12326
12327$({
12328 target: 'Reflect',
12329 stat: true,
12330 forced: OPTIONAL_ARGUMENTS_LIST
12331}, {
12332 apply: function apply(target, thisArgument, argumentsList) {
12333 aFunction(target);
12334 anObject(argumentsList);
12335 return nativeApply ? nativeApply(target, thisArgument, argumentsList) : functionApply.call(target, thisArgument, argumentsList);
12336 }
12337});
12338
12339/***/ }),
12340/* 350 */
12341/***/ (function(module, exports, __webpack_require__) {
12342
12343var $ = __webpack_require__(4);
12344
12345var getBuiltIn = __webpack_require__(36);
12346
12347var aFunction = __webpack_require__(62);
12348
12349var anObject = __webpack_require__(22);
12350
12351var isObject = __webpack_require__(16);
12352
12353var create = __webpack_require__(51);
12354
12355var bind = __webpack_require__(123);
12356
12357var fails = __webpack_require__(8);
12358
12359var nativeConstruct = getBuiltIn('Reflect', 'construct'); // `Reflect.construct` method
12360// https://tc39.github.io/ecma262/#sec-reflect.construct
12361// MS Edge supports only 2 arguments and argumentsList argument is optional
12362// FF Nightly sets third argument as `new.target`, but does not create `this` from it
12363
12364var NEW_TARGET_BUG = fails(function () {
12365 function F() {
12366 /* empty */
12367 }
12368
12369 return !(nativeConstruct(function () {
12370 /* empty */
12371 }, [], F) instanceof F);
12372});
12373var ARGS_BUG = !fails(function () {
12374 nativeConstruct(function () {
12375 /* empty */
12376 });
12377});
12378var FORCED = NEW_TARGET_BUG || ARGS_BUG;
12379$({
12380 target: 'Reflect',
12381 stat: true,
12382 forced: FORCED,
12383 sham: FORCED
12384}, {
12385 construct: function construct(Target, args
12386 /* , newTarget */
12387 ) {
12388 aFunction(Target);
12389 anObject(args);
12390 var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
12391 if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget);
12392
12393 if (Target == newTarget) {
12394 // w/o altered newTarget, optimization for 0-4 arguments
12395 switch (args.length) {
12396 case 0:
12397 return new Target();
12398
12399 case 1:
12400 return new Target(args[0]);
12401
12402 case 2:
12403 return new Target(args[0], args[1]);
12404
12405 case 3:
12406 return new Target(args[0], args[1], args[2]);
12407
12408 case 4:
12409 return new Target(args[0], args[1], args[2], args[3]);
12410 } // w/o altered newTarget, lot of arguments case
12411
12412
12413 var $args = [null];
12414 $args.push.apply($args, args);
12415 return new (bind.apply(Target, $args))();
12416 } // with altered newTarget, not support built-in constructors
12417
12418
12419 var proto = newTarget.prototype;
12420 var instance = create(isObject(proto) ? proto : Object.prototype);
12421 var result = Function.apply.call(Target, instance, args);
12422 return isObject(result) ? result : instance;
12423 }
12424});
12425
12426/***/ }),
12427/* 351 */
12428/***/ (function(module, exports, __webpack_require__) {
12429
12430var $ = __webpack_require__(4);
12431
12432var DESCRIPTORS = __webpack_require__(7);
12433
12434var anObject = __webpack_require__(22);
12435
12436var toPrimitive = __webpack_require__(15);
12437
12438var definePropertyModule = __webpack_require__(21);
12439
12440var fails = __webpack_require__(8); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false
12441
12442
12443var ERROR_INSTEAD_OF_FALSE = fails(function () {
12444 // eslint-disable-next-line no-undef
12445 Reflect.defineProperty(definePropertyModule.f({}, 1, {
12446 value: 1
12447 }), 1, {
12448 value: 2
12449 });
12450}); // `Reflect.defineProperty` method
12451// https://tc39.github.io/ecma262/#sec-reflect.defineproperty
12452
12453$({
12454 target: 'Reflect',
12455 stat: true,
12456 forced: ERROR_INSTEAD_OF_FALSE,
12457 sham: !DESCRIPTORS
12458}, {
12459 defineProperty: function defineProperty(target, propertyKey, attributes) {
12460 anObject(target);
12461 var key = toPrimitive(propertyKey, true);
12462 anObject(attributes);
12463
12464 try {
12465 definePropertyModule.f(target, key, attributes);
12466 return true;
12467 } catch (error) {
12468 return false;
12469 }
12470 }
12471});
12472
12473/***/ }),
12474/* 352 */
12475/***/ (function(module, exports, __webpack_require__) {
12476
12477var $ = __webpack_require__(4);
12478
12479var anObject = __webpack_require__(22);
12480
12481var getOwnPropertyDescriptor = __webpack_require__(6).f; // `Reflect.deleteProperty` method
12482// https://tc39.github.io/ecma262/#sec-reflect.deleteproperty
12483
12484
12485$({
12486 target: 'Reflect',
12487 stat: true
12488}, {
12489 deleteProperty: function deleteProperty(target, propertyKey) {
12490 var descriptor = getOwnPropertyDescriptor(anObject(target), propertyKey);
12491 return descriptor && !descriptor.configurable ? false : delete target[propertyKey];
12492 }
12493});
12494
12495/***/ }),
12496/* 353 */
12497/***/ (function(module, exports, __webpack_require__) {
12498
12499var $ = __webpack_require__(4);
12500
12501var isObject = __webpack_require__(16);
12502
12503var anObject = __webpack_require__(22);
12504
12505var has = __webpack_require__(17);
12506
12507var getOwnPropertyDescriptorModule = __webpack_require__(6);
12508
12509var getPrototypeOf = __webpack_require__(101); // `Reflect.get` method
12510// https://tc39.github.io/ecma262/#sec-reflect.get
12511
12512
12513function get(target, propertyKey
12514/* , receiver */
12515) {
12516 var receiver = arguments.length < 3 ? target : arguments[2];
12517 var descriptor, prototype;
12518 if (anObject(target) === receiver) return target[propertyKey];
12519 if (descriptor = getOwnPropertyDescriptorModule.f(target, propertyKey)) return has(descriptor, 'value') ? descriptor.value : descriptor.get === undefined ? undefined : descriptor.get.call(receiver);
12520 if (isObject(prototype = getPrototypeOf(target))) return get(prototype, propertyKey, receiver);
12521}
12522
12523$({
12524 target: 'Reflect',
12525 stat: true
12526}, {
12527 get: get
12528});
12529
12530/***/ }),
12531/* 354 */
12532/***/ (function(module, exports, __webpack_require__) {
12533
12534var $ = __webpack_require__(4);
12535
12536var DESCRIPTORS = __webpack_require__(7);
12537
12538var anObject = __webpack_require__(22);
12539
12540var getOwnPropertyDescriptorModule = __webpack_require__(6); // `Reflect.getOwnPropertyDescriptor` method
12541// https://tc39.github.io/ecma262/#sec-reflect.getownpropertydescriptor
12542
12543
12544$({
12545 target: 'Reflect',
12546 stat: true,
12547 sham: !DESCRIPTORS
12548}, {
12549 getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) {
12550 return getOwnPropertyDescriptorModule.f(anObject(target), propertyKey);
12551 }
12552});
12553
12554/***/ }),
12555/* 355 */
12556/***/ (function(module, exports, __webpack_require__) {
12557
12558var $ = __webpack_require__(4);
12559
12560var anObject = __webpack_require__(22);
12561
12562var objectGetPrototypeOf = __webpack_require__(101);
12563
12564var CORRECT_PROTOTYPE_GETTER = __webpack_require__(102); // `Reflect.getPrototypeOf` method
12565// https://tc39.github.io/ecma262/#sec-reflect.getprototypeof
12566
12567
12568$({
12569 target: 'Reflect',
12570 stat: true,
12571 sham: !CORRECT_PROTOTYPE_GETTER
12572}, {
12573 getPrototypeOf: function getPrototypeOf(target) {
12574 return objectGetPrototypeOf(anObject(target));
12575 }
12576});
12577
12578/***/ }),
12579/* 356 */
12580/***/ (function(module, exports, __webpack_require__) {
12581
12582var $ = __webpack_require__(4); // `Reflect.has` method
12583// https://tc39.github.io/ecma262/#sec-reflect.has
12584
12585
12586$({
12587 target: 'Reflect',
12588 stat: true
12589}, {
12590 has: function has(target, propertyKey) {
12591 return propertyKey in target;
12592 }
12593});
12594
12595/***/ }),
12596/* 357 */
12597/***/ (function(module, exports, __webpack_require__) {
12598
12599var $ = __webpack_require__(4);
12600
12601var anObject = __webpack_require__(22);
12602
12603var objectIsExtensible = Object.isExtensible; // `Reflect.isExtensible` method
12604// https://tc39.github.io/ecma262/#sec-reflect.isextensible
12605
12606$({
12607 target: 'Reflect',
12608 stat: true
12609}, {
12610 isExtensible: function isExtensible(target) {
12611 anObject(target);
12612 return objectIsExtensible ? objectIsExtensible(target) : true;
12613 }
12614});
12615
12616/***/ }),
12617/* 358 */
12618/***/ (function(module, exports, __webpack_require__) {
12619
12620var $ = __webpack_require__(4);
12621
12622var ownKeys = __webpack_require__(35); // `Reflect.ownKeys` method
12623// https://tc39.github.io/ecma262/#sec-reflect.ownkeys
12624
12625
12626$({
12627 target: 'Reflect',
12628 stat: true
12629}, {
12630 ownKeys: ownKeys
12631});
12632
12633/***/ }),
12634/* 359 */
12635/***/ (function(module, exports, __webpack_require__) {
12636
12637var $ = __webpack_require__(4);
12638
12639var getBuiltIn = __webpack_require__(36);
12640
12641var anObject = __webpack_require__(22);
12642
12643var FREEZING = __webpack_require__(86); // `Reflect.preventExtensions` method
12644// https://tc39.github.io/ecma262/#sec-reflect.preventextensions
12645
12646
12647$({
12648 target: 'Reflect',
12649 stat: true,
12650 sham: !FREEZING
12651}, {
12652 preventExtensions: function preventExtensions(target) {
12653 anObject(target);
12654
12655 try {
12656 var objectPreventExtensions = getBuiltIn('Object', 'preventExtensions');
12657 if (objectPreventExtensions) objectPreventExtensions(target);
12658 return true;
12659 } catch (error) {
12660 return false;
12661 }
12662 }
12663});
12664
12665/***/ }),
12666/* 360 */
12667/***/ (function(module, exports, __webpack_require__) {
12668
12669var $ = __webpack_require__(4);
12670
12671var anObject = __webpack_require__(22);
12672
12673var isObject = __webpack_require__(16);
12674
12675var has = __webpack_require__(17);
12676
12677var fails = __webpack_require__(8);
12678
12679var definePropertyModule = __webpack_require__(21);
12680
12681var getOwnPropertyDescriptorModule = __webpack_require__(6);
12682
12683var getPrototypeOf = __webpack_require__(101);
12684
12685var createPropertyDescriptor = __webpack_require__(10); // `Reflect.set` method
12686// https://tc39.github.io/ecma262/#sec-reflect.set
12687
12688
12689function set(target, propertyKey, V
12690/* , receiver */
12691) {
12692 var receiver = arguments.length < 4 ? target : arguments[3];
12693 var ownDescriptor = getOwnPropertyDescriptorModule.f(anObject(target), propertyKey);
12694 var existingDescriptor, prototype;
12695
12696 if (!ownDescriptor) {
12697 if (isObject(prototype = getPrototypeOf(target))) {
12698 return set(prototype, propertyKey, V, receiver);
12699 }
12700
12701 ownDescriptor = createPropertyDescriptor(0);
12702 }
12703
12704 if (has(ownDescriptor, 'value')) {
12705 if (ownDescriptor.writable === false || !isObject(receiver)) return false;
12706
12707 if (existingDescriptor = getOwnPropertyDescriptorModule.f(receiver, propertyKey)) {
12708 if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false;
12709 existingDescriptor.value = V;
12710 definePropertyModule.f(receiver, propertyKey, existingDescriptor);
12711 } else definePropertyModule.f(receiver, propertyKey, createPropertyDescriptor(0, V));
12712
12713 return true;
12714 }
12715
12716 return ownDescriptor.set === undefined ? false : (ownDescriptor.set.call(receiver, V), true);
12717} // MS Edge 17-18 Reflect.set allows setting the property to object
12718// with non-writable property on the prototype
12719
12720
12721var MS_EDGE_BUG = fails(function () {
12722 var object = definePropertyModule.f({}, 'a', {
12723 configurable: true
12724 }); // eslint-disable-next-line no-undef
12725
12726 return Reflect.set(getPrototypeOf(object), 'a', 1, object) !== false;
12727});
12728$({
12729 target: 'Reflect',
12730 stat: true,
12731 forced: MS_EDGE_BUG
12732}, {
12733 set: set
12734});
12735
12736/***/ }),
12737/* 361 */
12738/***/ (function(module, exports, __webpack_require__) {
12739
12740var $ = __webpack_require__(4);
12741
12742var anObject = __webpack_require__(22);
12743
12744var aPossiblePrototype = __webpack_require__(113);
12745
12746var objectSetPrototypeOf = __webpack_require__(112); // `Reflect.setPrototypeOf` method
12747// https://tc39.github.io/ecma262/#sec-reflect.setprototypeof
12748
12749
12750if (objectSetPrototypeOf) $({
12751 target: 'Reflect',
12752 stat: true
12753}, {
12754 setPrototypeOf: function setPrototypeOf(target, proto) {
12755 anObject(target);
12756 aPossiblePrototype(proto);
12757
12758 try {
12759 objectSetPrototypeOf(target, proto);
12760 return true;
12761 } catch (error) {
12762 return false;
12763 }
12764 }
12765});
12766
12767/***/ }),
12768/* 362 */
12769/***/ (function(module, exports, __webpack_require__) {
12770
12771__webpack_require__(363);
12772
12773__webpack_require__(365);
12774
12775__webpack_require__(366);
12776
12777__webpack_require__(367);
12778
12779__webpack_require__(368);
12780
12781__webpack_require__(369);
12782
12783__webpack_require__(374);
12784
12785__webpack_require__(372);
12786
12787var path = __webpack_require__(37);
12788
12789module.exports = path;
12790
12791/***/ }),
12792/* 363 */
12793/***/ (function(module, exports, __webpack_require__) {
12794
12795var global = __webpack_require__(5);
12796
12797var DOMIterables = __webpack_require__(364);
12798
12799var forEach = __webpack_require__(151);
12800
12801var createNonEnumerableProperty = __webpack_require__(20);
12802
12803for (var COLLECTION_NAME in DOMIterables) {
12804 var Collection = global[COLLECTION_NAME];
12805 var CollectionPrototype = Collection && Collection.prototype; // some Chrome versions have non-configurable methods on DOMTokenList
12806
12807 if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {
12808 createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach);
12809 } catch (error) {
12810 CollectionPrototype.forEach = forEach;
12811 }
12812}
12813
12814/***/ }),
12815/* 364 */
12816/***/ (function(module, exports) {
12817
12818// iterable DOM collections
12819// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
12820module.exports = {
12821 CSSRuleList: 0,
12822 CSSStyleDeclaration: 0,
12823 CSSValueList: 0,
12824 ClientRectList: 0,
12825 DOMRectList: 0,
12826 DOMStringList: 0,
12827 DOMTokenList: 1,
12828 DataTransferItemList: 0,
12829 FileList: 0,
12830 HTMLAllCollection: 0,
12831 HTMLCollection: 0,
12832 HTMLFormElement: 0,
12833 HTMLSelectElement: 0,
12834 MediaList: 0,
12835 MimeTypeArray: 0,
12836 NamedNodeMap: 0,
12837 NodeList: 1,
12838 PaintRequestList: 0,
12839 Plugin: 0,
12840 PluginArray: 0,
12841 SVGLengthList: 0,
12842 SVGNumberList: 0,
12843 SVGPathSegList: 0,
12844 SVGPointList: 0,
12845 SVGStringList: 0,
12846 SVGTransformList: 0,
12847 SourceBufferList: 0,
12848 StyleSheetList: 0,
12849 TextTrackCueList: 0,
12850 TextTrackList: 0,
12851 TouchList: 0
12852};
12853
12854/***/ }),
12855/* 365 */
12856/***/ (function(module, exports, __webpack_require__) {
12857
12858var global = __webpack_require__(5);
12859
12860var DOMIterables = __webpack_require__(364);
12861
12862var ArrayIteratorMethods = __webpack_require__(170);
12863
12864var createNonEnumerableProperty = __webpack_require__(20);
12865
12866var wellKnownSymbol = __webpack_require__(56);
12867
12868var ITERATOR = wellKnownSymbol('iterator');
12869var TO_STRING_TAG = wellKnownSymbol('toStringTag');
12870var ArrayValues = ArrayIteratorMethods.values;
12871
12872for (var COLLECTION_NAME in DOMIterables) {
12873 var Collection = global[COLLECTION_NAME];
12874 var CollectionPrototype = Collection && Collection.prototype;
12875
12876 if (CollectionPrototype) {
12877 // some Chrome versions have non-configurable methods on DOMTokenList
12878 if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
12879 createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);
12880 } catch (error) {
12881 CollectionPrototype[ITERATOR] = ArrayValues;
12882 }
12883
12884 if (!CollectionPrototype[TO_STRING_TAG]) {
12885 createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
12886 }
12887
12888 if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
12889 // some Chrome versions have non-configurable methods on DOMTokenList
12890 if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
12891 createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
12892 } catch (error) {
12893 CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
12894 }
12895 }
12896 }
12897}
12898
12899/***/ }),
12900/* 366 */
12901/***/ (function(module, exports, __webpack_require__) {
12902
12903var $ = __webpack_require__(4);
12904
12905var global = __webpack_require__(5);
12906
12907var task = __webpack_require__(285);
12908
12909var FORCED = !global.setImmediate || !global.clearImmediate; // http://w3c.github.io/setImmediate/
12910
12911$({
12912 global: true,
12913 bind: true,
12914 enumerable: true,
12915 forced: FORCED
12916}, {
12917 // `setImmediate` method
12918 // http://w3c.github.io/setImmediate/#si-setImmediate
12919 setImmediate: task.set,
12920 // `clearImmediate` method
12921 // http://w3c.github.io/setImmediate/#si-clearImmediate
12922 clearImmediate: task.clear
12923});
12924
12925/***/ }),
12926/* 367 */
12927/***/ (function(module, exports, __webpack_require__) {
12928
12929var $ = __webpack_require__(4);
12930
12931var global = __webpack_require__(5);
12932
12933var microtask = __webpack_require__(287);
12934
12935var classof = __webpack_require__(13);
12936
12937var process = global.process;
12938var isNode = classof(process) == 'process'; // `queueMicrotask` method
12939// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
12940
12941$({
12942 global: true,
12943 enumerable: true,
12944 noTargetGet: true
12945}, {
12946 queueMicrotask: function queueMicrotask(fn) {
12947 var domain = isNode && process.domain;
12948 microtask(domain ? domain.bind(fn) : fn);
12949 }
12950});
12951
12952/***/ }),
12953/* 368 */
12954/***/ (function(module, exports, __webpack_require__) {
12955
12956var $ = __webpack_require__(4);
12957
12958var global = __webpack_require__(5);
12959
12960var userAgent = __webpack_require__(135);
12961
12962var slice = [].slice;
12963var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check
12964
12965var wrap = function wrap(scheduler) {
12966 return function (handler, timeout
12967 /* , ...arguments */
12968 ) {
12969 var boundArgs = arguments.length > 2;
12970 var args = boundArgs ? slice.call(arguments, 2) : undefined;
12971 return scheduler(boundArgs ? function () {
12972 // eslint-disable-next-line no-new-func
12973 (typeof handler == 'function' ? handler : Function(handler)).apply(this, args);
12974 } : handler, timeout);
12975 };
12976}; // ie9- setTimeout & setInterval additional parameters fix
12977// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
12978
12979
12980$({
12981 global: true,
12982 bind: true,
12983 forced: MSIE
12984}, {
12985 // `setTimeout` method
12986 // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
12987 setTimeout: wrap(global.setTimeout),
12988 // `setInterval` method
12989 // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
12990 setInterval: wrap(global.setInterval)
12991});
12992
12993/***/ }),
12994/* 369 */
12995/***/ (function(module, exports, __webpack_require__) {
12996
12997"use strict";
12998 // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
12999
13000__webpack_require__(209);
13001
13002var $ = __webpack_require__(4);
13003
13004var DESCRIPTORS = __webpack_require__(7);
13005
13006var USE_NATIVE_URL = __webpack_require__(370);
13007
13008var global = __webpack_require__(5);
13009
13010var defineProperties = __webpack_require__(52);
13011
13012var redefine = __webpack_require__(23);
13013
13014var anInstance = __webpack_require__(284);
13015
13016var has = __webpack_require__(17);
13017
13018var assign = __webpack_require__(79);
13019
13020var arrayFrom = __webpack_require__(128);
13021
13022var codeAt = __webpack_require__(177).codeAt;
13023
13024var toASCII = __webpack_require__(371);
13025
13026var setToStringTag = __webpack_require__(59);
13027
13028var URLSearchParamsModule = __webpack_require__(372);
13029
13030var InternalStateModule = __webpack_require__(27);
13031
13032var NativeURL = global.URL;
13033var URLSearchParams = URLSearchParamsModule.URLSearchParams;
13034var getInternalSearchParamsState = URLSearchParamsModule.getState;
13035var setInternalState = InternalStateModule.set;
13036var getInternalURLState = InternalStateModule.getterFor('URL');
13037var floor = Math.floor;
13038var pow = Math.pow;
13039var INVALID_AUTHORITY = 'Invalid authority';
13040var INVALID_SCHEME = 'Invalid scheme';
13041var INVALID_HOST = 'Invalid host';
13042var INVALID_PORT = 'Invalid port';
13043var ALPHA = /[A-Za-z]/;
56c4a2cb 13044var ALPHANUMERIC = /[\d+-.A-Za-z]/;
eb39fafa
DC
13045var DIGIT = /\d/;
13046var HEX_START = /^(0x|0X)/;
13047var OCT = /^[0-7]+$/;
13048var DEC = /^\d+$/;
13049var HEX = /^[\dA-Fa-f]+$/; // eslint-disable-next-line no-control-regex
13050
13051var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; // eslint-disable-next-line no-control-regex
13052
13053var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; // eslint-disable-next-line no-control-regex
13054
13055var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; // eslint-disable-next-line no-control-regex
13056
13057var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g;
13058var EOF;
13059
13060var parseHost = function parseHost(url, input) {
13061 var result, codePoints, index;
13062
13063 if (input.charAt(0) == '[') {
13064 if (input.charAt(input.length - 1) != ']') return INVALID_HOST;
13065 result = parseIPv6(input.slice(1, -1));
13066 if (!result) return INVALID_HOST;
13067 url.host = result; // opaque host
13068 } else if (!isSpecial(url)) {
13069 if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST;
13070 result = '';
13071 codePoints = arrayFrom(input);
13072
13073 for (index = 0; index < codePoints.length; index++) {
13074 result += percentEncode(codePoints[index], C0ControlPercentEncodeSet);
13075 }
13076
13077 url.host = result;
13078 } else {
13079 input = toASCII(input);
13080 if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST;
13081 result = parseIPv4(input);
13082 if (result === null) return INVALID_HOST;
13083 url.host = result;
13084 }
13085};
13086
13087var parseIPv4 = function parseIPv4(input) {
13088 var parts = input.split('.');
13089 var partsLength, numbers, index, part, radix, number, ipv4;
13090
13091 if (parts.length && parts[parts.length - 1] == '') {
13092 parts.pop();
13093 }
13094
13095 partsLength = parts.length;
13096 if (partsLength > 4) return input;
13097 numbers = [];
13098
13099 for (index = 0; index < partsLength; index++) {
13100 part = parts[index];
13101 if (part == '') return input;
13102 radix = 10;
13103
13104 if (part.length > 1 && part.charAt(0) == '0') {
13105 radix = HEX_START.test(part) ? 16 : 8;
13106 part = part.slice(radix == 8 ? 1 : 2);
13107 }
13108
13109 if (part === '') {
13110 number = 0;
13111 } else {
13112 if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input;
13113 number = parseInt(part, radix);
13114 }
13115
13116 numbers.push(number);
13117 }
13118
13119 for (index = 0; index < partsLength; index++) {
13120 number = numbers[index];
13121
13122 if (index == partsLength - 1) {
13123 if (number >= pow(256, 5 - partsLength)) return null;
13124 } else if (number > 255) return null;
13125 }
13126
13127 ipv4 = numbers.pop();
13128
13129 for (index = 0; index < numbers.length; index++) {
13130 ipv4 += numbers[index] * pow(256, 3 - index);
13131 }
13132
13133 return ipv4;
13134}; // eslint-disable-next-line max-statements
13135
13136
13137var parseIPv6 = function parseIPv6(input) {
13138 var address = [0, 0, 0, 0, 0, 0, 0, 0];
13139 var pieceIndex = 0;
13140 var compress = null;
13141 var pointer = 0;
13142 var value, length, numbersSeen, ipv4Piece, number, swaps, swap;
13143
13144 var char = function char() {
13145 return input.charAt(pointer);
13146 };
13147
13148 if (char() == ':') {
13149 if (input.charAt(1) != ':') return;
13150 pointer += 2;
13151 pieceIndex++;
13152 compress = pieceIndex;
13153 }
13154
13155 while (char()) {
13156 if (pieceIndex == 8) return;
13157
13158 if (char() == ':') {
13159 if (compress !== null) return;
13160 pointer++;
13161 pieceIndex++;
13162 compress = pieceIndex;
13163 continue;
13164 }
13165
13166 value = length = 0;
13167
13168 while (length < 4 && HEX.test(char())) {
13169 value = value * 16 + parseInt(char(), 16);
13170 pointer++;
13171 length++;
13172 }
13173
13174 if (char() == '.') {
13175 if (length == 0) return;
13176 pointer -= length;
13177 if (pieceIndex > 6) return;
13178 numbersSeen = 0;
13179
13180 while (char()) {
13181 ipv4Piece = null;
13182
13183 if (numbersSeen > 0) {
13184 if (char() == '.' && numbersSeen < 4) pointer++;else return;
13185 }
13186
13187 if (!DIGIT.test(char())) return;
13188
13189 while (DIGIT.test(char())) {
13190 number = parseInt(char(), 10);
13191 if (ipv4Piece === null) ipv4Piece = number;else if (ipv4Piece == 0) return;else ipv4Piece = ipv4Piece * 10 + number;
13192 if (ipv4Piece > 255) return;
13193 pointer++;
13194 }
13195
13196 address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
13197 numbersSeen++;
13198 if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++;
13199 }
13200
13201 if (numbersSeen != 4) return;
13202 break;
13203 } else if (char() == ':') {
13204 pointer++;
13205 if (!char()) return;
13206 } else if (char()) return;
13207
13208 address[pieceIndex++] = value;
13209 }
13210
13211 if (compress !== null) {
13212 swaps = pieceIndex - compress;
13213 pieceIndex = 7;
13214
13215 while (pieceIndex != 0 && swaps > 0) {
13216 swap = address[pieceIndex];
13217 address[pieceIndex--] = address[compress + swaps - 1];
13218 address[compress + --swaps] = swap;
13219 }
13220 } else if (pieceIndex != 8) return;
13221
13222 return address;
13223};
13224
13225var findLongestZeroSequence = function findLongestZeroSequence(ipv6) {
13226 var maxIndex = null;
13227 var maxLength = 1;
13228 var currStart = null;
13229 var currLength = 0;
13230 var index = 0;
13231
13232 for (; index < 8; index++) {
13233 if (ipv6[index] !== 0) {
13234 if (currLength > maxLength) {
13235 maxIndex = currStart;
13236 maxLength = currLength;
13237 }
13238
13239 currStart = null;
13240 currLength = 0;
13241 } else {
13242 if (currStart === null) currStart = index;
13243 ++currLength;
13244 }
13245 }
13246
13247 if (currLength > maxLength) {
13248 maxIndex = currStart;
13249 maxLength = currLength;
13250 }
13251
13252 return maxIndex;
13253};
13254
13255var serializeHost = function serializeHost(host) {
13256 var result, index, compress, ignore0; // ipv4
13257
13258 if (typeof host == 'number') {
13259 result = [];
13260
13261 for (index = 0; index < 4; index++) {
13262 result.unshift(host % 256);
13263 host = floor(host / 256);
13264 }
13265
13266 return result.join('.'); // ipv6
13267 } else if (typeof host == 'object') {
13268 result = '';
13269 compress = findLongestZeroSequence(host);
13270
13271 for (index = 0; index < 8; index++) {
13272 if (ignore0 && host[index] === 0) continue;
13273 if (ignore0) ignore0 = false;
13274
13275 if (compress === index) {
13276 result += index ? ':' : '::';
13277 ignore0 = true;
13278 } else {
13279 result += host[index].toString(16);
13280 if (index < 7) result += ':';
13281 }
13282 }
13283
13284 return '[' + result + ']';
13285 }
13286
13287 return host;
13288};
13289
13290var C0ControlPercentEncodeSet = {};
13291var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, {
13292 ' ': 1,
13293 '"': 1,
13294 '<': 1,
13295 '>': 1,
13296 '`': 1
13297});
13298var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, {
13299 '#': 1,
13300 '?': 1,
13301 '{': 1,
13302 '}': 1
13303});
13304var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, {
13305 '/': 1,
13306 ':': 1,
13307 ';': 1,
13308 '=': 1,
13309 '@': 1,
13310 '[': 1,
13311 '\\': 1,
13312 ']': 1,
13313 '^': 1,
13314 '|': 1
13315});
13316
13317var percentEncode = function percentEncode(char, set) {
13318 var code = codeAt(char, 0);
13319 return code > 0x20 && code < 0x7F && !has(set, char) ? char : encodeURIComponent(char);
13320};
13321
13322var specialSchemes = {
13323 ftp: 21,
13324 file: null,
13325 http: 80,
13326 https: 443,
13327 ws: 80,
13328 wss: 443
13329};
13330
13331var isSpecial = function isSpecial(url) {
13332 return has(specialSchemes, url.scheme);
13333};
13334
13335var includesCredentials = function includesCredentials(url) {
13336 return url.username != '' || url.password != '';
13337};
13338
13339var cannotHaveUsernamePasswordPort = function cannotHaveUsernamePasswordPort(url) {
13340 return !url.host || url.cannotBeABaseURL || url.scheme == 'file';
13341};
13342
13343var isWindowsDriveLetter = function isWindowsDriveLetter(string, normalized) {
13344 var second;
13345 return string.length == 2 && ALPHA.test(string.charAt(0)) && ((second = string.charAt(1)) == ':' || !normalized && second == '|');
13346};
13347
13348var startsWithWindowsDriveLetter = function startsWithWindowsDriveLetter(string) {
13349 var third;
13350 return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && (string.length == 2 || (third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#');
13351};
13352
13353var shortenURLsPath = function shortenURLsPath(url) {
13354 var path = url.path;
13355 var pathSize = path.length;
13356
13357 if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) {
13358 path.pop();
13359 }
13360};
13361
13362var isSingleDot = function isSingleDot(segment) {
13363 return segment === '.' || segment.toLowerCase() === '%2e';
13364};
13365
13366var isDoubleDot = function isDoubleDot(segment) {
13367 segment = segment.toLowerCase();
13368 return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e';
13369}; // States:
13370
13371
13372var SCHEME_START = {};
13373var SCHEME = {};
13374var NO_SCHEME = {};
13375var SPECIAL_RELATIVE_OR_AUTHORITY = {};
13376var PATH_OR_AUTHORITY = {};
13377var RELATIVE = {};
13378var RELATIVE_SLASH = {};
13379var SPECIAL_AUTHORITY_SLASHES = {};
13380var SPECIAL_AUTHORITY_IGNORE_SLASHES = {};
13381var AUTHORITY = {};
13382var HOST = {};
13383var HOSTNAME = {};
13384var PORT = {};
13385var FILE = {};
13386var FILE_SLASH = {};
13387var FILE_HOST = {};
13388var PATH_START = {};
13389var PATH = {};
13390var CANNOT_BE_A_BASE_URL_PATH = {};
13391var QUERY = {};
13392var FRAGMENT = {}; // eslint-disable-next-line max-statements
13393
13394var parseURL = function parseURL(url, input, stateOverride, base) {
13395 var state = stateOverride || SCHEME_START;
13396 var pointer = 0;
13397 var buffer = '';
13398 var seenAt = false;
13399 var seenBracket = false;
13400 var seenPasswordToken = false;
13401 var codePoints, char, bufferCodePoints, failure;
13402
13403 if (!stateOverride) {
13404 url.scheme = '';
13405 url.username = '';
13406 url.password = '';
13407 url.host = null;
13408 url.port = null;
13409 url.path = [];
13410 url.query = null;
13411 url.fragment = null;
13412 url.cannotBeABaseURL = false;
13413 input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, '');
13414 }
13415
13416 input = input.replace(TAB_AND_NEW_LINE, '');
13417 codePoints = arrayFrom(input);
13418
13419 while (pointer <= codePoints.length) {
13420 char = codePoints[pointer];
13421
13422 switch (state) {
13423 case SCHEME_START:
13424 if (char && ALPHA.test(char)) {
13425 buffer += char.toLowerCase();
13426 state = SCHEME;
13427 } else if (!stateOverride) {
13428 state = NO_SCHEME;
13429 continue;
13430 } else return INVALID_SCHEME;
13431
13432 break;
13433
13434 case SCHEME:
13435 if (char && (ALPHANUMERIC.test(char) || char == '+' || char == '-' || char == '.')) {
13436 buffer += char.toLowerCase();
13437 } else if (char == ':') {
13438 if (stateOverride && (isSpecial(url) != has(specialSchemes, buffer) || buffer == 'file' && (includesCredentials(url) || url.port !== null) || url.scheme == 'file' && !url.host)) return;
13439 url.scheme = buffer;
13440
13441 if (stateOverride) {
13442 if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null;
13443 return;
13444 }
13445
13446 buffer = '';
13447
13448 if (url.scheme == 'file') {
13449 state = FILE;
13450 } else if (isSpecial(url) && base && base.scheme == url.scheme) {
13451 state = SPECIAL_RELATIVE_OR_AUTHORITY;
13452 } else if (isSpecial(url)) {
13453 state = SPECIAL_AUTHORITY_SLASHES;
13454 } else if (codePoints[pointer + 1] == '/') {
13455 state = PATH_OR_AUTHORITY;
13456 pointer++;
13457 } else {
13458 url.cannotBeABaseURL = true;
13459 url.path.push('');
13460 state = CANNOT_BE_A_BASE_URL_PATH;
13461 }
13462 } else if (!stateOverride) {
13463 buffer = '';
13464 state = NO_SCHEME;
13465 pointer = 0;
13466 continue;
13467 } else return INVALID_SCHEME;
13468
13469 break;
13470
13471 case NO_SCHEME:
13472 if (!base || base.cannotBeABaseURL && char != '#') return INVALID_SCHEME;
13473
13474 if (base.cannotBeABaseURL && char == '#') {
13475 url.scheme = base.scheme;
13476 url.path = base.path.slice();
13477 url.query = base.query;
13478 url.fragment = '';
13479 url.cannotBeABaseURL = true;
13480 state = FRAGMENT;
13481 break;
13482 }
13483
13484 state = base.scheme == 'file' ? FILE : RELATIVE;
13485 continue;
13486
13487 case SPECIAL_RELATIVE_OR_AUTHORITY:
13488 if (char == '/' && codePoints[pointer + 1] == '/') {
13489 state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
13490 pointer++;
13491 } else {
13492 state = RELATIVE;
13493 continue;
13494 }
13495
13496 break;
13497
13498 case PATH_OR_AUTHORITY:
13499 if (char == '/') {
13500 state = AUTHORITY;
13501 break;
13502 } else {
13503 state = PATH;
13504 continue;
13505 }
13506
13507 case RELATIVE:
13508 url.scheme = base.scheme;
13509
13510 if (char == EOF) {
13511 url.username = base.username;
13512 url.password = base.password;
13513 url.host = base.host;
13514 url.port = base.port;
13515 url.path = base.path.slice();
13516 url.query = base.query;
13517 } else if (char == '/' || char == '\\' && isSpecial(url)) {
13518 state = RELATIVE_SLASH;
13519 } else if (char == '?') {
13520 url.username = base.username;
13521 url.password = base.password;
13522 url.host = base.host;
13523 url.port = base.port;
13524 url.path = base.path.slice();
13525 url.query = '';
13526 state = QUERY;
13527 } else if (char == '#') {
13528 url.username = base.username;
13529 url.password = base.password;
13530 url.host = base.host;
13531 url.port = base.port;
13532 url.path = base.path.slice();
13533 url.query = base.query;
13534 url.fragment = '';
13535 state = FRAGMENT;
13536 } else {
13537 url.username = base.username;
13538 url.password = base.password;
13539 url.host = base.host;
13540 url.port = base.port;
13541 url.path = base.path.slice();
13542 url.path.pop();
13543 state = PATH;
13544 continue;
13545 }
13546
13547 break;
13548
13549 case RELATIVE_SLASH:
13550 if (isSpecial(url) && (char == '/' || char == '\\')) {
13551 state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
13552 } else if (char == '/') {
13553 state = AUTHORITY;
13554 } else {
13555 url.username = base.username;
13556 url.password = base.password;
13557 url.host = base.host;
13558 url.port = base.port;
13559 state = PATH;
13560 continue;
13561 }
13562
13563 break;
13564
13565 case SPECIAL_AUTHORITY_SLASHES:
13566 state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
13567 if (char != '/' || buffer.charAt(pointer + 1) != '/') continue;
13568 pointer++;
13569 break;
13570
13571 case SPECIAL_AUTHORITY_IGNORE_SLASHES:
13572 if (char != '/' && char != '\\') {
13573 state = AUTHORITY;
13574 continue;
13575 }
13576
13577 break;
13578
13579 case AUTHORITY:
13580 if (char == '@') {
13581 if (seenAt) buffer = '%40' + buffer;
13582 seenAt = true;
13583 bufferCodePoints = arrayFrom(buffer);
13584
13585 for (var i = 0; i < bufferCodePoints.length; i++) {
13586 var codePoint = bufferCodePoints[i];
13587
13588 if (codePoint == ':' && !seenPasswordToken) {
13589 seenPasswordToken = true;
13590 continue;
13591 }
13592
13593 var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet);
13594 if (seenPasswordToken) url.password += encodedCodePoints;else url.username += encodedCodePoints;
13595 }
13596
13597 buffer = '';
13598 } else if (char == EOF || char == '/' || char == '?' || char == '#' || char == '\\' && isSpecial(url)) {
13599 if (seenAt && buffer == '') return INVALID_AUTHORITY;
13600 pointer -= arrayFrom(buffer).length + 1;
13601 buffer = '';
13602 state = HOST;
13603 } else buffer += char;
13604
13605 break;
13606
13607 case HOST:
13608 case HOSTNAME:
13609 if (stateOverride && url.scheme == 'file') {
13610 state = FILE_HOST;
13611 continue;
13612 } else if (char == ':' && !seenBracket) {
13613 if (buffer == '') return INVALID_HOST;
13614 failure = parseHost(url, buffer);
13615 if (failure) return failure;
13616 buffer = '';
13617 state = PORT;
13618 if (stateOverride == HOSTNAME) return;
13619 } else if (char == EOF || char == '/' || char == '?' || char == '#' || char == '\\' && isSpecial(url)) {
13620 if (isSpecial(url) && buffer == '') return INVALID_HOST;
13621 if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return;
13622 failure = parseHost(url, buffer);
13623 if (failure) return failure;
13624 buffer = '';
13625 state = PATH_START;
13626 if (stateOverride) return;
13627 continue;
13628 } else {
13629 if (char == '[') seenBracket = true;else if (char == ']') seenBracket = false;
13630 buffer += char;
13631 }
13632
13633 break;
13634
13635 case PORT:
13636 if (DIGIT.test(char)) {
13637 buffer += char;
13638 } else if (char == EOF || char == '/' || char == '?' || char == '#' || char == '\\' && isSpecial(url) || stateOverride) {
13639 if (buffer != '') {
13640 var port = parseInt(buffer, 10);
13641 if (port > 0xFFFF) return INVALID_PORT;
13642 url.port = isSpecial(url) && port === specialSchemes[url.scheme] ? null : port;
13643 buffer = '';
13644 }
13645
13646 if (stateOverride) return;
13647 state = PATH_START;
13648 continue;
13649 } else return INVALID_PORT;
13650
13651 break;
13652
13653 case FILE:
13654 url.scheme = 'file';
13655 if (char == '/' || char == '\\') state = FILE_SLASH;else if (base && base.scheme == 'file') {
13656 if (char == EOF) {
13657 url.host = base.host;
13658 url.path = base.path.slice();
13659 url.query = base.query;
13660 } else if (char == '?') {
13661 url.host = base.host;
13662 url.path = base.path.slice();
13663 url.query = '';
13664 state = QUERY;
13665 } else if (char == '#') {
13666 url.host = base.host;
13667 url.path = base.path.slice();
13668 url.query = base.query;
13669 url.fragment = '';
13670 state = FRAGMENT;
13671 } else {
13672 if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) {
13673 url.host = base.host;
13674 url.path = base.path.slice();
13675 shortenURLsPath(url);
13676 }
13677
13678 state = PATH;
13679 continue;
13680 }
13681 } else {
13682 state = PATH;
13683 continue;
13684 }
13685 break;
13686
13687 case FILE_SLASH:
13688 if (char == '/' || char == '\\') {
13689 state = FILE_HOST;
13690 break;
13691 }
13692
13693 if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) {
13694 if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]);else url.host = base.host;
13695 }
13696
13697 state = PATH;
13698 continue;
13699
13700 case FILE_HOST:
13701 if (char == EOF || char == '/' || char == '\\' || char == '?' || char == '#') {
13702 if (!stateOverride && isWindowsDriveLetter(buffer)) {
13703 state = PATH;
13704 } else if (buffer == '') {
13705 url.host = '';
13706 if (stateOverride) return;
13707 state = PATH_START;
13708 } else {
13709 failure = parseHost(url, buffer);
13710 if (failure) return failure;
13711 if (url.host == 'localhost') url.host = '';
13712 if (stateOverride) return;
13713 buffer = '';
13714 state = PATH_START;
13715 }
13716
13717 continue;
13718 } else buffer += char;
13719
13720 break;
13721
13722 case PATH_START:
13723 if (isSpecial(url)) {
13724 state = PATH;
13725 if (char != '/' && char != '\\') continue;
13726 } else if (!stateOverride && char == '?') {
13727 url.query = '';
13728 state = QUERY;
13729 } else if (!stateOverride && char == '#') {
13730 url.fragment = '';
13731 state = FRAGMENT;
13732 } else if (char != EOF) {
13733 state = PATH;
13734 if (char != '/') continue;
13735 }
13736
13737 break;
13738
13739 case PATH:
13740 if (char == EOF || char == '/' || char == '\\' && isSpecial(url) || !stateOverride && (char == '?' || char == '#')) {
13741 if (isDoubleDot(buffer)) {
13742 shortenURLsPath(url);
13743
13744 if (char != '/' && !(char == '\\' && isSpecial(url))) {
13745 url.path.push('');
13746 }
13747 } else if (isSingleDot(buffer)) {
13748 if (char != '/' && !(char == '\\' && isSpecial(url))) {
13749 url.path.push('');
13750 }
13751 } else {
13752 if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) {
13753 if (url.host) url.host = '';
13754 buffer = buffer.charAt(0) + ':'; // normalize windows drive letter
13755 }
13756
13757 url.path.push(buffer);
13758 }
13759
13760 buffer = '';
13761
13762 if (url.scheme == 'file' && (char == EOF || char == '?' || char == '#')) {
13763 while (url.path.length > 1 && url.path[0] === '') {
13764 url.path.shift();
13765 }
13766 }
13767
13768 if (char == '?') {
13769 url.query = '';
13770 state = QUERY;
13771 } else if (char == '#') {
13772 url.fragment = '';
13773 state = FRAGMENT;
13774 }
13775 } else {
13776 buffer += percentEncode(char, pathPercentEncodeSet);
13777 }
13778
13779 break;
13780
13781 case CANNOT_BE_A_BASE_URL_PATH:
13782 if (char == '?') {
13783 url.query = '';
13784 state = QUERY;
13785 } else if (char == '#') {
13786 url.fragment = '';
13787 state = FRAGMENT;
13788 } else if (char != EOF) {
13789 url.path[0] += percentEncode(char, C0ControlPercentEncodeSet);
13790 }
13791
13792 break;
13793
13794 case QUERY:
13795 if (!stateOverride && char == '#') {
13796 url.fragment = '';
13797 state = FRAGMENT;
13798 } else if (char != EOF) {
13799 if (char == "'" && isSpecial(url)) url.query += '%27';else if (char == '#') url.query += '%23';else url.query += percentEncode(char, C0ControlPercentEncodeSet);
13800 }
13801
13802 break;
13803
13804 case FRAGMENT:
13805 if (char != EOF) url.fragment += percentEncode(char, fragmentPercentEncodeSet);
13806 break;
13807 }
13808
13809 pointer++;
13810 }
13811}; // `URL` constructor
13812// https://url.spec.whatwg.org/#url-class
13813
13814
13815var URLConstructor = function URL(url
13816/* , base */
13817) {
13818 var that = anInstance(this, URLConstructor, 'URL');
13819 var base = arguments.length > 1 ? arguments[1] : undefined;
13820 var urlString = String(url);
13821 var state = setInternalState(that, {
13822 type: 'URL'
13823 });
13824 var baseState, failure;
13825
13826 if (base !== undefined) {
13827 if (base instanceof URLConstructor) baseState = getInternalURLState(base);else {
13828 failure = parseURL(baseState = {}, String(base));
13829 if (failure) throw TypeError(failure);
13830 }
13831 }
13832
13833 failure = parseURL(state, urlString, null, baseState);
13834 if (failure) throw TypeError(failure);
13835 var searchParams = state.searchParams = new URLSearchParams();
13836 var searchParamsState = getInternalSearchParamsState(searchParams);
13837 searchParamsState.updateSearchParams(state.query);
13838
13839 searchParamsState.updateURL = function () {
13840 state.query = String(searchParams) || null;
13841 };
13842
13843 if (!DESCRIPTORS) {
13844 that.href = serializeURL.call(that);
13845 that.origin = getOrigin.call(that);
13846 that.protocol = getProtocol.call(that);
13847 that.username = getUsername.call(that);
13848 that.password = getPassword.call(that);
13849 that.host = getHost.call(that);
13850 that.hostname = getHostname.call(that);
13851 that.port = getPort.call(that);
13852 that.pathname = getPathname.call(that);
13853 that.search = getSearch.call(that);
13854 that.searchParams = getSearchParams.call(that);
13855 that.hash = getHash.call(that);
13856 }
13857};
13858
13859var URLPrototype = URLConstructor.prototype;
13860
13861var serializeURL = function serializeURL() {
13862 var url = getInternalURLState(this);
13863 var scheme = url.scheme;
13864 var username = url.username;
13865 var password = url.password;
13866 var host = url.host;
13867 var port = url.port;
13868 var path = url.path;
13869 var query = url.query;
13870 var fragment = url.fragment;
13871 var output = scheme + ':';
13872
13873 if (host !== null) {
13874 output += '//';
13875
13876 if (includesCredentials(url)) {
13877 output += username + (password ? ':' + password : '') + '@';
13878 }
13879
13880 output += serializeHost(host);
13881 if (port !== null) output += ':' + port;
13882 } else if (scheme == 'file') output += '//';
13883
13884 output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : '';
13885 if (query !== null) output += '?' + query;
13886 if (fragment !== null) output += '#' + fragment;
13887 return output;
13888};
13889
13890var getOrigin = function getOrigin() {
13891 var url = getInternalURLState(this);
13892 var scheme = url.scheme;
13893 var port = url.port;
13894 if (scheme == 'blob') try {
13895 return new URL(scheme.path[0]).origin;
13896 } catch (error) {
13897 return 'null';
13898 }
13899 if (scheme == 'file' || !isSpecial(url)) return 'null';
13900 return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : '');
13901};
13902
13903var getProtocol = function getProtocol() {
13904 return getInternalURLState(this).scheme + ':';
13905};
13906
13907var getUsername = function getUsername() {
13908 return getInternalURLState(this).username;
13909};
13910
13911var getPassword = function getPassword() {
13912 return getInternalURLState(this).password;
13913};
13914
13915var getHost = function getHost() {
13916 var url = getInternalURLState(this);
13917 var host = url.host;
13918 var port = url.port;
13919 return host === null ? '' : port === null ? serializeHost(host) : serializeHost(host) + ':' + port;
13920};
13921
13922var getHostname = function getHostname() {
13923 var host = getInternalURLState(this).host;
13924 return host === null ? '' : serializeHost(host);
13925};
13926
13927var getPort = function getPort() {
13928 var port = getInternalURLState(this).port;
13929 return port === null ? '' : String(port);
13930};
13931
13932var getPathname = function getPathname() {
13933 var url = getInternalURLState(this);
13934 var path = url.path;
13935 return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : '';
13936};
13937
13938var getSearch = function getSearch() {
13939 var query = getInternalURLState(this).query;
13940 return query ? '?' + query : '';
13941};
13942
13943var getSearchParams = function getSearchParams() {
13944 return getInternalURLState(this).searchParams;
13945};
13946
13947var getHash = function getHash() {
13948 var fragment = getInternalURLState(this).fragment;
13949 return fragment ? '#' + fragment : '';
13950};
13951
13952var accessorDescriptor = function accessorDescriptor(getter, setter) {
13953 return {
13954 get: getter,
13955 set: setter,
13956 configurable: true,
13957 enumerable: true
13958 };
13959};
13960
13961if (DESCRIPTORS) {
13962 defineProperties(URLPrototype, {
13963 // `URL.prototype.href` accessors pair
13964 // https://url.spec.whatwg.org/#dom-url-href
13965 href: accessorDescriptor(serializeURL, function (href) {
13966 var url = getInternalURLState(this);
13967 var urlString = String(href);
13968 var failure = parseURL(url, urlString);
13969 if (failure) throw TypeError(failure);
13970 getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query);
13971 }),
13972 // `URL.prototype.origin` getter
13973 // https://url.spec.whatwg.org/#dom-url-origin
13974 origin: accessorDescriptor(getOrigin),
13975 // `URL.prototype.protocol` accessors pair
13976 // https://url.spec.whatwg.org/#dom-url-protocol
13977 protocol: accessorDescriptor(getProtocol, function (protocol) {
13978 var url = getInternalURLState(this);
13979 parseURL(url, String(protocol) + ':', SCHEME_START);
13980 }),
13981 // `URL.prototype.username` accessors pair
13982 // https://url.spec.whatwg.org/#dom-url-username
13983 username: accessorDescriptor(getUsername, function (username) {
13984 var url = getInternalURLState(this);
13985 var codePoints = arrayFrom(String(username));
13986 if (cannotHaveUsernamePasswordPort(url)) return;
13987 url.username = '';
13988
13989 for (var i = 0; i < codePoints.length; i++) {
13990 url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet);
13991 }
13992 }),
13993 // `URL.prototype.password` accessors pair
13994 // https://url.spec.whatwg.org/#dom-url-password
13995 password: accessorDescriptor(getPassword, function (password) {
13996 var url = getInternalURLState(this);
13997 var codePoints = arrayFrom(String(password));
13998 if (cannotHaveUsernamePasswordPort(url)) return;
13999 url.password = '';
14000
14001 for (var i = 0; i < codePoints.length; i++) {
14002 url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet);
14003 }
14004 }),
14005 // `URL.prototype.host` accessors pair
14006 // https://url.spec.whatwg.org/#dom-url-host
14007 host: accessorDescriptor(getHost, function (host) {
14008 var url = getInternalURLState(this);
14009 if (url.cannotBeABaseURL) return;
14010 parseURL(url, String(host), HOST);
14011 }),
14012 // `URL.prototype.hostname` accessors pair
14013 // https://url.spec.whatwg.org/#dom-url-hostname
14014 hostname: accessorDescriptor(getHostname, function (hostname) {
14015 var url = getInternalURLState(this);
14016 if (url.cannotBeABaseURL) return;
14017 parseURL(url, String(hostname), HOSTNAME);
14018 }),
14019 // `URL.prototype.port` accessors pair
14020 // https://url.spec.whatwg.org/#dom-url-port
14021 port: accessorDescriptor(getPort, function (port) {
14022 var url = getInternalURLState(this);
14023 if (cannotHaveUsernamePasswordPort(url)) return;
14024 port = String(port);
14025 if (port == '') url.port = null;else parseURL(url, port, PORT);
14026 }),
14027 // `URL.prototype.pathname` accessors pair
14028 // https://url.spec.whatwg.org/#dom-url-pathname
14029 pathname: accessorDescriptor(getPathname, function (pathname) {
14030 var url = getInternalURLState(this);
14031 if (url.cannotBeABaseURL) return;
14032 url.path = [];
14033 parseURL(url, pathname + '', PATH_START);
14034 }),
14035 // `URL.prototype.search` accessors pair
14036 // https://url.spec.whatwg.org/#dom-url-search
14037 search: accessorDescriptor(getSearch, function (search) {
14038 var url = getInternalURLState(this);
14039 search = String(search);
14040
14041 if (search == '') {
14042 url.query = null;
14043 } else {
14044 if ('?' == search.charAt(0)) search = search.slice(1);
14045 url.query = '';
14046 parseURL(url, search, QUERY);
14047 }
14048
14049 getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query);
14050 }),
14051 // `URL.prototype.searchParams` getter
14052 // https://url.spec.whatwg.org/#dom-url-searchparams
14053 searchParams: accessorDescriptor(getSearchParams),
14054 // `URL.prototype.hash` accessors pair
14055 // https://url.spec.whatwg.org/#dom-url-hash
14056 hash: accessorDescriptor(getHash, function (hash) {
14057 var url = getInternalURLState(this);
14058 hash = String(hash);
14059
14060 if (hash == '') {
14061 url.fragment = null;
14062 return;
14063 }
14064
14065 if ('#' == hash.charAt(0)) hash = hash.slice(1);
14066 url.fragment = '';
14067 parseURL(url, hash, FRAGMENT);
14068 })
14069 });
14070} // `URL.prototype.toJSON` method
14071// https://url.spec.whatwg.org/#dom-url-tojson
14072
14073
14074redefine(URLPrototype, 'toJSON', function toJSON() {
14075 return serializeURL.call(this);
14076}, {
14077 enumerable: true
14078}); // `URL.prototype.toString` method
14079// https://url.spec.whatwg.org/#URL-stringification-behavior
14080
14081redefine(URLPrototype, 'toString', function toString() {
14082 return serializeURL.call(this);
14083}, {
14084 enumerable: true
14085});
14086
14087if (NativeURL) {
14088 var nativeCreateObjectURL = NativeURL.createObjectURL;
14089 var nativeRevokeObjectURL = NativeURL.revokeObjectURL; // `URL.createObjectURL` method
14090 // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
14091 // eslint-disable-next-line no-unused-vars
14092
14093 if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) {
14094 return nativeCreateObjectURL.apply(NativeURL, arguments);
14095 }); // `URL.revokeObjectURL` method
14096 // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
14097 // eslint-disable-next-line no-unused-vars
14098
14099 if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) {
14100 return nativeRevokeObjectURL.apply(NativeURL, arguments);
14101 });
14102}
14103
14104setToStringTag(URLConstructor, 'URL');
14105$({
14106 global: true,
14107 forced: !USE_NATIVE_URL,
14108 sham: !DESCRIPTORS
14109}, {
14110 URL: URLConstructor
14111});
14112
14113/***/ }),
14114/* 370 */
14115/***/ (function(module, exports, __webpack_require__) {
14116
14117var fails = __webpack_require__(8);
14118
14119var wellKnownSymbol = __webpack_require__(56);
14120
14121var IS_PURE = __webpack_require__(31);
14122
14123var ITERATOR = wellKnownSymbol('iterator');
14124module.exports = !fails(function () {
14125 var url = new URL('b?a=1&b=2&c=3', 'http://a');
14126 var searchParams = url.searchParams;
14127 var result = '';
14128 url.pathname = 'c%20d';
14129 searchParams.forEach(function (value, key) {
14130 searchParams['delete']('b');
14131 result += key + value;
14132 });
14133 return IS_PURE && !url.toJSON || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR] // throws in Edge
14134 || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge
14135 || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62-
14136 || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66-
14137 || result !== 'a1c3' // throws in Safari
14138 || new URL('http://x', undefined).host !== 'x';
14139});
14140
14141/***/ }),
14142/* 371 */
14143/***/ (function(module, exports, __webpack_require__) {
14144
14145"use strict";
14146 // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
14147
14148var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
14149
14150var base = 36;
14151var tMin = 1;
14152var tMax = 26;
14153var skew = 38;
14154var damp = 700;
14155var initialBias = 72;
14156var initialN = 128; // 0x80
14157
14158var delimiter = '-'; // '\x2D'
14159
14160var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars
14161
14162var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
14163
14164var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
14165var baseMinusTMin = base - tMin;
14166var floor = Math.floor;
14167var stringFromCharCode = String.fromCharCode;
14168/**
14169 * Creates an array containing the numeric code points of each Unicode
14170 * character in the string. While JavaScript uses UCS-2 internally,
14171 * this function will convert a pair of surrogate halves (each of which
14172 * UCS-2 exposes as separate characters) into a single code point,
14173 * matching UTF-16.
14174 */
14175
14176var ucs2decode = function ucs2decode(string) {
14177 var output = [];
14178 var counter = 0;
14179 var length = string.length;
14180
14181 while (counter < length) {
14182 var value = string.charCodeAt(counter++);
14183
14184 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
14185 // It's a high surrogate, and there is a next character.
14186 var extra = string.charCodeAt(counter++);
14187
14188 if ((extra & 0xFC00) == 0xDC00) {
14189 // Low surrogate.
14190 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
14191 } else {
14192 // It's an unmatched surrogate; only append this code unit, in case the
14193 // next code unit is the high surrogate of a surrogate pair.
14194 output.push(value);
14195 counter--;
14196 }
14197 } else {
14198 output.push(value);
14199 }
14200 }
14201
14202 return output;
14203};
14204/**
14205 * Converts a digit/integer into a basic code point.
14206 */
14207
14208
14209var digitToBasic = function digitToBasic(digit) {
14210 // 0..25 map to ASCII a..z or A..Z
14211 // 26..35 map to ASCII 0..9
14212 return digit + 22 + 75 * (digit < 26);
14213};
14214/**
14215 * Bias adaptation function as per section 3.4 of RFC 3492.
14216 * https://tools.ietf.org/html/rfc3492#section-3.4
14217 */
14218
14219
14220var adapt = function adapt(delta, numPoints, firstTime) {
14221 var k = 0;
14222 delta = firstTime ? floor(delta / damp) : delta >> 1;
14223 delta += floor(delta / numPoints);
14224
14225 for (; delta > baseMinusTMin * tMax >> 1; k += base) {
14226 delta = floor(delta / baseMinusTMin);
14227 }
14228
14229 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
14230};
14231/**
14232 * Converts a string of Unicode symbols (e.g. a domain name label) to a
14233 * Punycode string of ASCII-only symbols.
14234 */
14235// eslint-disable-next-line max-statements
14236
14237
14238var encode = function encode(input) {
14239 var output = []; // Convert the input in UCS-2 to an array of Unicode code points.
14240
14241 input = ucs2decode(input); // Cache the length.
14242
14243 var inputLength = input.length; // Initialize the state.
14244
14245 var n = initialN;
14246 var delta = 0;
14247 var bias = initialBias;
14248 var i, currentValue; // Handle the basic code points.
14249
14250 for (i = 0; i < input.length; i++) {
14251 currentValue = input[i];
14252
14253 if (currentValue < 0x80) {
14254 output.push(stringFromCharCode(currentValue));
14255 }
14256 }
14257
14258 var basicLength = output.length; // number of basic code points.
14259
14260 var handledCPCount = basicLength; // number of code points that have been handled;
14261 // Finish the basic string with a delimiter unless it's empty.
14262
14263 if (basicLength) {
14264 output.push(delimiter);
14265 } // Main encoding loop:
14266
14267
14268 while (handledCPCount < inputLength) {
14269 // All non-basic code points < n have been handled already. Find the next larger one:
14270 var m = maxInt;
14271
14272 for (i = 0; i < input.length; i++) {
14273 currentValue = input[i];
14274
14275 if (currentValue >= n && currentValue < m) {
14276 m = currentValue;
14277 }
14278 } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, but guard against overflow.
14279
14280
14281 var handledCPCountPlusOne = handledCPCount + 1;
14282
14283 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
14284 throw RangeError(OVERFLOW_ERROR);
14285 }
14286
14287 delta += (m - n) * handledCPCountPlusOne;
14288 n = m;
14289
14290 for (i = 0; i < input.length; i++) {
14291 currentValue = input[i];
14292
14293 if (currentValue < n && ++delta > maxInt) {
14294 throw RangeError(OVERFLOW_ERROR);
14295 }
14296
14297 if (currentValue == n) {
14298 // Represent delta as a generalized variable-length integer.
14299 var q = delta;
14300
14301 for (var k = base;;
14302 /* no condition */
14303 k += base) {
14304 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
14305 if (q < t) break;
14306 var qMinusT = q - t;
14307 var baseMinusT = base - t;
14308 output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT)));
14309 q = floor(qMinusT / baseMinusT);
14310 }
14311
14312 output.push(stringFromCharCode(digitToBasic(q)));
14313 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
14314 delta = 0;
14315 ++handledCPCount;
14316 }
14317 }
14318
14319 ++delta;
14320 ++n;
14321 }
14322
14323 return output.join('');
14324};
14325
14326module.exports = function (input) {
14327 var encoded = [];
14328 var labels = input.toLowerCase().replace(regexSeparators, '\u002E').split('.');
14329 var i, label;
14330
14331 for (i = 0; i < labels.length; i++) {
14332 label = labels[i];
14333 encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label);
14334 }
14335
14336 return encoded.join('.');
14337};
14338
14339/***/ }),
14340/* 372 */
14341/***/ (function(module, exports, __webpack_require__) {
14342
14343"use strict";
14344 // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
14345
14346__webpack_require__(170);
14347
14348var $ = __webpack_require__(4);
14349
14350var getBuiltIn = __webpack_require__(36);
14351
14352var USE_NATIVE_URL = __webpack_require__(370);
14353
14354var redefine = __webpack_require__(23);
14355
14356var redefineAll = __webpack_require__(283);
14357
14358var setToStringTag = __webpack_require__(59);
14359
14360var createIteratorConstructor = __webpack_require__(172);
14361
14362var InternalStateModule = __webpack_require__(27);
14363
14364var anInstance = __webpack_require__(284);
14365
14366var hasOwn = __webpack_require__(17);
14367
14368var bind = __webpack_require__(61);
14369
14370var classof = __webpack_require__(93);
14371
14372var anObject = __webpack_require__(22);
14373
14374var isObject = __webpack_require__(16);
14375
14376var create = __webpack_require__(51);
14377
14378var createPropertyDescriptor = __webpack_require__(10);
14379
14380var getIterator = __webpack_require__(373);
14381
14382var getIteratorMethod = __webpack_require__(92);
14383
14384var wellKnownSymbol = __webpack_require__(56);
14385
14386var $fetch = getBuiltIn('fetch');
14387var Headers = getBuiltIn('Headers');
14388var ITERATOR = wellKnownSymbol('iterator');
14389var URL_SEARCH_PARAMS = 'URLSearchParams';
14390var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator';
14391var setInternalState = InternalStateModule.set;
14392var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS);
14393var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR);
14394var plus = /\+/g;
14395var sequences = Array(4);
14396
14397var percentSequence = function percentSequence(bytes) {
14398 return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi'));
14399};
14400
14401var percentDecode = function percentDecode(sequence) {
14402 try {
14403 return decodeURIComponent(sequence);
14404 } catch (error) {
14405 return sequence;
14406 }
14407};
14408
14409var deserialize = function deserialize(it) {
14410 var result = it.replace(plus, ' ');
14411 var bytes = 4;
14412
14413 try {
14414 return decodeURIComponent(result);
14415 } catch (error) {
14416 while (bytes) {
14417 result = result.replace(percentSequence(bytes--), percentDecode);
14418 }
14419
14420 return result;
14421 }
14422};
14423
14424var find = /[!'()~]|%20/g;
14425var replace = {
14426 '!': '%21',
14427 "'": '%27',
14428 '(': '%28',
14429 ')': '%29',
14430 '~': '%7E',
14431 '%20': '+'
14432};
14433
14434var replacer = function replacer(match) {
14435 return replace[match];
14436};
14437
14438var serialize = function serialize(it) {
14439 return encodeURIComponent(it).replace(find, replacer);
14440};
14441
14442var parseSearchParams = function parseSearchParams(result, query) {
14443 if (query) {
14444 var attributes = query.split('&');
14445 var index = 0;
14446 var attribute, entry;
14447
14448 while (index < attributes.length) {
14449 attribute = attributes[index++];
14450
14451 if (attribute.length) {
14452 entry = attribute.split('=');
14453 result.push({
14454 key: deserialize(entry.shift()),
14455 value: deserialize(entry.join('='))
14456 });
14457 }
14458 }
14459 }
14460};
14461
14462var updateSearchParams = function updateSearchParams(query) {
14463 this.entries.length = 0;
14464 parseSearchParams(this.entries, query);
14465};
14466
14467var validateArgumentsLength = function validateArgumentsLength(passed, required) {
14468 if (passed < required) throw TypeError('Not enough arguments');
14469};
14470
14471var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
14472 setInternalState(this, {
14473 type: URL_SEARCH_PARAMS_ITERATOR,
14474 iterator: getIterator(getInternalParamsState(params).entries),
14475 kind: kind
14476 });
14477}, 'Iterator', function next() {
14478 var state = getInternalIteratorState(this);
14479 var kind = state.kind;
14480 var step = state.iterator.next();
14481 var entry = step.value;
14482
14483 if (!step.done) {
14484 step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value];
14485 }
14486
14487 return step;
14488}); // `URLSearchParams` constructor
14489// https://url.spec.whatwg.org/#interface-urlsearchparams
14490
14491var URLSearchParamsConstructor = function URLSearchParams()
14492/* init */
14493{
14494 anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS);
14495 var init = arguments.length > 0 ? arguments[0] : undefined;
14496 var that = this;
14497 var entries = [];
14498 var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key;
14499 setInternalState(that, {
14500 type: URL_SEARCH_PARAMS,
14501 entries: entries,
14502 updateURL: function updateURL() {
14503 /* empty */
14504 },
14505 updateSearchParams: updateSearchParams
14506 });
14507
14508 if (init !== undefined) {
14509 if (isObject(init)) {
14510 iteratorMethod = getIteratorMethod(init);
14511
14512 if (typeof iteratorMethod === 'function') {
14513 iterator = iteratorMethod.call(init);
14514 next = iterator.next;
14515
14516 while (!(step = next.call(iterator)).done) {
14517 entryIterator = getIterator(anObject(step.value));
14518 entryNext = entryIterator.next;
14519 if ((first = entryNext.call(entryIterator)).done || (second = entryNext.call(entryIterator)).done || !entryNext.call(entryIterator).done) throw TypeError('Expected sequence with length 2');
14520 entries.push({
14521 key: first.value + '',
14522 value: second.value + ''
14523 });
14524 }
14525 } else for (key in init) if (hasOwn(init, key)) entries.push({
14526 key: key,
14527 value: init[key] + ''
14528 });
14529 } else {
14530 parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + '');
14531 }
14532 }
14533};
14534
14535var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype;
14536redefineAll(URLSearchParamsPrototype, {
14537 // `URLSearchParams.prototype.appent` method
14538 // https://url.spec.whatwg.org/#dom-urlsearchparams-append
14539 append: function append(name, value) {
14540 validateArgumentsLength(arguments.length, 2);
14541 var state = getInternalParamsState(this);
14542 state.entries.push({
14543 key: name + '',
14544 value: value + ''
14545 });
14546 state.updateURL();
14547 },
14548 // `URLSearchParams.prototype.delete` method
14549 // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
14550 'delete': function _delete(name) {
14551 validateArgumentsLength(arguments.length, 1);
14552 var state = getInternalParamsState(this);
14553 var entries = state.entries;
14554 var key = name + '';
14555 var index = 0;
14556
14557 while (index < entries.length) {
14558 if (entries[index].key === key) entries.splice(index, 1);else index++;
14559 }
14560
14561 state.updateURL();
14562 },
14563 // `URLSearchParams.prototype.get` method
14564 // https://url.spec.whatwg.org/#dom-urlsearchparams-get
14565 get: function get(name) {
14566 validateArgumentsLength(arguments.length, 1);
14567 var entries = getInternalParamsState(this).entries;
14568 var key = name + '';
14569 var index = 0;
14570
14571 for (; index < entries.length; index++) {
14572 if (entries[index].key === key) return entries[index].value;
14573 }
14574
14575 return null;
14576 },
14577 // `URLSearchParams.prototype.getAll` method
14578 // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
14579 getAll: function getAll(name) {
14580 validateArgumentsLength(arguments.length, 1);
14581 var entries = getInternalParamsState(this).entries;
14582 var key = name + '';
14583 var result = [];
14584 var index = 0;
14585
14586 for (; index < entries.length; index++) {
14587 if (entries[index].key === key) result.push(entries[index].value);
14588 }
14589
14590 return result;
14591 },
14592 // `URLSearchParams.prototype.has` method
14593 // https://url.spec.whatwg.org/#dom-urlsearchparams-has
14594 has: function has(name) {
14595 validateArgumentsLength(arguments.length, 1);
14596 var entries = getInternalParamsState(this).entries;
14597 var key = name + '';
14598 var index = 0;
14599
14600 while (index < entries.length) {
14601 if (entries[index++].key === key) return true;
14602 }
14603
14604 return false;
14605 },
14606 // `URLSearchParams.prototype.set` method
14607 // https://url.spec.whatwg.org/#dom-urlsearchparams-set
14608 set: function set(name, value) {
14609 validateArgumentsLength(arguments.length, 1);
14610 var state = getInternalParamsState(this);
14611 var entries = state.entries;
14612 var found = false;
14613 var key = name + '';
14614 var val = value + '';
14615 var index = 0;
14616 var entry;
14617
14618 for (; index < entries.length; index++) {
14619 entry = entries[index];
14620
14621 if (entry.key === key) {
14622 if (found) entries.splice(index--, 1);else {
14623 found = true;
14624 entry.value = val;
14625 }
14626 }
14627 }
14628
14629 if (!found) entries.push({
14630 key: key,
14631 value: val
14632 });
14633 state.updateURL();
14634 },
14635 // `URLSearchParams.prototype.sort` method
14636 // https://url.spec.whatwg.org/#dom-urlsearchparams-sort
14637 sort: function sort() {
14638 var state = getInternalParamsState(this);
14639 var entries = state.entries; // Array#sort is not stable in some engines
14640
14641 var slice = entries.slice();
14642 var entry, entriesIndex, sliceIndex;
14643 entries.length = 0;
14644
14645 for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) {
14646 entry = slice[sliceIndex];
14647
14648 for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) {
14649 if (entries[entriesIndex].key > entry.key) {
14650 entries.splice(entriesIndex, 0, entry);
14651 break;
14652 }
14653 }
14654
14655 if (entriesIndex === sliceIndex) entries.push(entry);
14656 }
14657
14658 state.updateURL();
14659 },
14660 // `URLSearchParams.prototype.forEach` method
14661 forEach: function forEach(callback
14662 /* , thisArg */
14663 ) {
14664 var entries = getInternalParamsState(this).entries;
14665 var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3);
14666 var index = 0;
14667 var entry;
14668
14669 while (index < entries.length) {
14670 entry = entries[index++];
14671 boundFunction(entry.value, entry.key, this);
14672 }
14673 },
14674 // `URLSearchParams.prototype.keys` method
14675 keys: function keys() {
14676 return new URLSearchParamsIterator(this, 'keys');
14677 },
14678 // `URLSearchParams.prototype.values` method
14679 values: function values() {
14680 return new URLSearchParamsIterator(this, 'values');
14681 },
14682 // `URLSearchParams.prototype.entries` method
14683 entries: function entries() {
14684 return new URLSearchParamsIterator(this, 'entries');
14685 }
14686}, {
14687 enumerable: true
14688}); // `URLSearchParams.prototype[@@iterator]` method
14689
14690redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); // `URLSearchParams.prototype.toString` method
14691// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
14692
14693redefine(URLSearchParamsPrototype, 'toString', function toString() {
14694 var entries = getInternalParamsState(this).entries;
14695 var result = [];
14696 var index = 0;
14697 var entry;
14698
14699 while (index < entries.length) {
14700 entry = entries[index++];
14701 result.push(serialize(entry.key) + '=' + serialize(entry.value));
14702 }
14703
14704 return result.join('&');
14705}, {
14706 enumerable: true
14707});
14708setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
14709$({
14710 global: true,
14711 forced: !USE_NATIVE_URL
14712}, {
14713 URLSearchParams: URLSearchParamsConstructor
14714}); // Wrap `fetch` for correct work with polyfilled `URLSearchParams`
14715// https://github.com/zloirock/core-js/issues/674
14716
14717if (!USE_NATIVE_URL && typeof $fetch == 'function' && typeof Headers == 'function') {
14718 $({
14719 global: true,
14720 enumerable: true,
14721 forced: true
14722 }, {
14723 fetch: function fetch(input
14724 /* , init */
14725 ) {
14726 var args = [input];
14727 var init, body, headers;
14728
14729 if (arguments.length > 1) {
14730 init = arguments[1];
14731
14732 if (isObject(init)) {
14733 body = init.body;
14734
14735 if (classof(body) === URL_SEARCH_PARAMS) {
14736 headers = init.headers ? new Headers(init.headers) : new Headers();
14737
14738 if (!headers.has('content-type')) {
14739 headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
14740 }
14741
14742 init = create(init, {
14743 body: createPropertyDescriptor(0, String(body)),
14744 headers: createPropertyDescriptor(0, headers)
14745 });
14746 }
14747 }
14748
14749 args.push(init);
14750 }
14751
14752 return $fetch.apply(this, args);
14753 }
14754 });
14755}
14756
14757module.exports = {
14758 URLSearchParams: URLSearchParamsConstructor,
14759 getState: getInternalParamsState
14760};
14761
14762/***/ }),
14763/* 373 */
14764/***/ (function(module, exports, __webpack_require__) {
14765
14766var anObject = __webpack_require__(22);
14767
14768var getIteratorMethod = __webpack_require__(92);
14769
14770module.exports = function (it) {
14771 var iteratorMethod = getIteratorMethod(it);
14772
14773 if (typeof iteratorMethod != 'function') {
14774 throw TypeError(String(it) + ' is not iterable');
14775 }
14776
14777 return anObject(iteratorMethod.call(it));
14778};
14779
14780/***/ }),
14781/* 374 */
14782/***/ (function(module, exports, __webpack_require__) {
14783
14784"use strict";
14785
14786
14787var $ = __webpack_require__(4); // `URL.prototype.toJSON` method
14788// https://url.spec.whatwg.org/#dom-url-tojson
14789
14790
14791$({
14792 target: 'URL',
14793 proto: true,
14794 enumerable: true
14795}, {
14796 toJSON: function toJSON() {
14797 return URL.prototype.toString.call(this);
14798 }
14799});
14800
14801/***/ }),
14802/* 375 */
14803/***/ (function(module, exports, __webpack_require__) {
14804
14805/**
14806 * Copyright (c) 2014-present, Facebook, Inc.
14807 *
14808 * This source code is licensed under the MIT license found in the
14809 * LICENSE file in the root directory of this source tree.
14810 */
14811var runtime = function (exports) {
14812 "use strict";
14813
14814 var Op = Object.prototype;
14815 var hasOwn = Op.hasOwnProperty;
14816 var undefined; // More compressible than void 0.
14817
14818 var $Symbol = typeof Symbol === "function" ? Symbol : {};
14819 var iteratorSymbol = $Symbol.iterator || "@@iterator";
14820 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
14821 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
14822
14823 function wrap(innerFn, outerFn, self, tryLocsList) {
14824 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
14825 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
14826 var generator = Object.create(protoGenerator.prototype);
14827 var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
14828 // .throw, and .return methods.
14829
14830 generator._invoke = makeInvokeMethod(innerFn, self, context);
14831 return generator;
14832 }
14833
14834 exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
14835 // record like context.tryEntries[i].completion. This interface could
14836 // have been (and was previously) designed to take a closure to be
14837 // invoked without arguments, but in all the cases we care about we
14838 // already have an existing method we want to call, so there's no need
14839 // to create a new function object. We can even get away with assuming
14840 // the method takes exactly one argument, since that happens to be true
14841 // in every case, so we don't have to touch the arguments object. The
14842 // only additional allocation required is the completion record, which
14843 // has a stable shape and so hopefully should be cheap to allocate.
14844
14845 function tryCatch(fn, obj, arg) {
14846 try {
14847 return {
14848 type: "normal",
14849 arg: fn.call(obj, arg)
14850 };
14851 } catch (err) {
14852 return {
14853 type: "throw",
14854 arg: err
14855 };
14856 }
14857 }
14858
14859 var GenStateSuspendedStart = "suspendedStart";
14860 var GenStateSuspendedYield = "suspendedYield";
14861 var GenStateExecuting = "executing";
14862 var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
14863 // breaking out of the dispatch switch statement.
14864
14865 var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
14866 // .constructor.prototype properties for functions that return Generator
14867 // objects. For full spec compliance, you may wish to configure your
14868 // minifier not to mangle the names of these two functions.
14869
14870 function Generator() {}
14871
14872 function GeneratorFunction() {}
14873
14874 function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
14875 // don't natively support it.
14876
14877
14878 var IteratorPrototype = {};
14879
14880 IteratorPrototype[iteratorSymbol] = function () {
14881 return this;
14882 };
14883
14884 var getProto = Object.getPrototypeOf;
14885 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
14886
14887 if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
14888 // This environment has a native %IteratorPrototype%; use it instead
14889 // of the polyfill.
14890 IteratorPrototype = NativeIteratorPrototype;
14891 }
14892
14893 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
14894 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
14895 GeneratorFunctionPrototype.constructor = GeneratorFunction;
14896 GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the
14897 // Iterator interface in terms of a single ._invoke method.
14898
14899 function defineIteratorMethods(prototype) {
14900 ["next", "throw", "return"].forEach(function (method) {
14901 prototype[method] = function (arg) {
14902 return this._invoke(method, arg);
14903 };
14904 });
14905 }
14906
14907 exports.isGeneratorFunction = function (genFun) {
14908 var ctor = typeof genFun === "function" && genFun.constructor;
14909 return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
14910 // do is to check its .name property.
14911 (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
14912 };
14913
14914 exports.mark = function (genFun) {
14915 if (Object.setPrototypeOf) {
14916 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
14917 } else {
14918 genFun.__proto__ = GeneratorFunctionPrototype;
14919
14920 if (!(toStringTagSymbol in genFun)) {
14921 genFun[toStringTagSymbol] = "GeneratorFunction";
14922 }
14923 }
14924
14925 genFun.prototype = Object.create(Gp);
14926 return genFun;
14927 }; // Within the body of any async function, `await x` is transformed to
14928 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
14929 // `hasOwn.call(value, "__await")` to determine if the yielded value is
14930 // meant to be awaited.
14931
14932
14933 exports.awrap = function (arg) {
14934 return {
14935 __await: arg
14936 };
14937 };
14938
14939 function AsyncIterator(generator, PromiseImpl) {
14940 function invoke(method, arg, resolve, reject) {
14941 var record = tryCatch(generator[method], generator, arg);
14942
14943 if (record.type === "throw") {
14944 reject(record.arg);
14945 } else {
14946 var result = record.arg;
14947 var value = result.value;
14948
14949 if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
14950 return PromiseImpl.resolve(value.__await).then(function (value) {
14951 invoke("next", value, resolve, reject);
14952 }, function (err) {
14953 invoke("throw", err, resolve, reject);
14954 });
14955 }
14956
14957 return PromiseImpl.resolve(value).then(function (unwrapped) {
14958 // When a yielded Promise is resolved, its final value becomes
14959 // the .value of the Promise<{value,done}> result for the
14960 // current iteration.
14961 result.value = unwrapped;
14962 resolve(result);
14963 }, function (error) {
14964 // If a rejected Promise was yielded, throw the rejection back
14965 // into the async generator function so it can be handled there.
14966 return invoke("throw", error, resolve, reject);
14967 });
14968 }
14969 }
14970
14971 var previousPromise;
14972
14973 function enqueue(method, arg) {
14974 function callInvokeWithMethodAndArg() {
14975 return new PromiseImpl(function (resolve, reject) {
14976 invoke(method, arg, resolve, reject);
14977 });
14978 }
14979
14980 return previousPromise = // If enqueue has been called before, then we want to wait until
14981 // all previous Promises have been resolved before calling invoke,
14982 // so that results are always delivered in the correct order. If
14983 // enqueue has not been called before, then it is important to
14984 // call invoke immediately, without waiting on a callback to fire,
14985 // so that the async generator function has the opportunity to do
14986 // any necessary setup in a predictable way. This predictability
14987 // is why the Promise constructor synchronously invokes its
14988 // executor callback, and why async functions synchronously
14989 // execute code before the first await. Since we implement simple
14990 // async functions in terms of async generators, it is especially
14991 // important to get this right, even though it requires care.
14992 previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
14993 // invocations of the iterator.
14994 callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
14995 } // Define the unified helper method that is used to implement .next,
14996 // .throw, and .return (see defineIteratorMethods).
14997
14998
14999 this._invoke = enqueue;
15000 }
15001
15002 defineIteratorMethods(AsyncIterator.prototype);
15003
15004 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
15005 return this;
15006 };
15007
15008 exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
15009 // AsyncIterator objects; they just return a Promise for the value of
15010 // the final result produced by the iterator.
15011
15012 exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
15013 if (PromiseImpl === void 0) PromiseImpl = Promise;
15014 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
15015 return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
15016 : iter.next().then(function (result) {
15017 return result.done ? result.value : iter.next();
15018 });
15019 };
15020
15021 function makeInvokeMethod(innerFn, self, context) {
15022 var state = GenStateSuspendedStart;
15023 return function invoke(method, arg) {
15024 if (state === GenStateExecuting) {
15025 throw new Error("Generator is already running");
15026 }
15027
15028 if (state === GenStateCompleted) {
15029 if (method === "throw") {
15030 throw arg;
15031 } // Be forgiving, per 25.3.3.3.3 of the spec:
15032 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
15033
15034
15035 return doneResult();
15036 }
15037
15038 context.method = method;
15039 context.arg = arg;
15040
15041 while (true) {
15042 var delegate = context.delegate;
15043
15044 if (delegate) {
15045 var delegateResult = maybeInvokeDelegate(delegate, context);
15046
15047 if (delegateResult) {
15048 if (delegateResult === ContinueSentinel) continue;
15049 return delegateResult;
15050 }
15051 }
15052
15053 if (context.method === "next") {
15054 // Setting context._sent for legacy support of Babel's
15055 // function.sent implementation.
15056 context.sent = context._sent = context.arg;
15057 } else if (context.method === "throw") {
15058 if (state === GenStateSuspendedStart) {
15059 state = GenStateCompleted;
15060 throw context.arg;
15061 }
15062
15063 context.dispatchException(context.arg);
15064 } else if (context.method === "return") {
15065 context.abrupt("return", context.arg);
15066 }
15067
15068 state = GenStateExecuting;
15069 var record = tryCatch(innerFn, self, context);
15070
15071 if (record.type === "normal") {
15072 // If an exception is thrown from innerFn, we leave state ===
15073 // GenStateExecuting and loop back for another invocation.
15074 state = context.done ? GenStateCompleted : GenStateSuspendedYield;
15075
15076 if (record.arg === ContinueSentinel) {
15077 continue;
15078 }
15079
15080 return {
15081 value: record.arg,
15082 done: context.done
15083 };
15084 } else if (record.type === "throw") {
15085 state = GenStateCompleted; // Dispatch the exception by looping back around to the
15086 // context.dispatchException(context.arg) call above.
15087
15088 context.method = "throw";
15089 context.arg = record.arg;
15090 }
15091 }
15092 };
15093 } // Call delegate.iterator[context.method](context.arg) and handle the
15094 // result, either by returning a { value, done } result from the
15095 // delegate iterator, or by modifying context.method and context.arg,
15096 // setting context.delegate to null, and returning the ContinueSentinel.
15097
15098
15099 function maybeInvokeDelegate(delegate, context) {
15100 var method = delegate.iterator[context.method];
15101
15102 if (method === undefined) {
15103 // A .throw or .return when the delegate iterator has no .throw
15104 // method always terminates the yield* loop.
15105 context.delegate = null;
15106
15107 if (context.method === "throw") {
15108 // Note: ["return"] must be used for ES3 parsing compatibility.
15109 if (delegate.iterator["return"]) {
15110 // If the delegate iterator has a return method, give it a
15111 // chance to clean up.
15112 context.method = "return";
15113 context.arg = undefined;
15114 maybeInvokeDelegate(delegate, context);
15115
15116 if (context.method === "throw") {
15117 // If maybeInvokeDelegate(context) changed context.method from
15118 // "return" to "throw", let that override the TypeError below.
15119 return ContinueSentinel;
15120 }
15121 }
15122
15123 context.method = "throw";
15124 context.arg = new TypeError("The iterator does not provide a 'throw' method");
15125 }
15126
15127 return ContinueSentinel;
15128 }
15129
15130 var record = tryCatch(method, delegate.iterator, context.arg);
15131
15132 if (record.type === "throw") {
15133 context.method = "throw";
15134 context.arg = record.arg;
15135 context.delegate = null;
15136 return ContinueSentinel;
15137 }
15138
15139 var info = record.arg;
15140
15141 if (!info) {
15142 context.method = "throw";
15143 context.arg = new TypeError("iterator result is not an object");
15144 context.delegate = null;
15145 return ContinueSentinel;
15146 }
15147
15148 if (info.done) {
15149 // Assign the result of the finished delegate to the temporary
15150 // variable specified by delegate.resultName (see delegateYield).
15151 context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
15152
15153 context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
15154 // exception, let the outer generator proceed normally. If
15155 // context.method was "next", forget context.arg since it has been
15156 // "consumed" by the delegate iterator. If context.method was
15157 // "return", allow the original .return call to continue in the
15158 // outer generator.
15159
15160 if (context.method !== "return") {
15161 context.method = "next";
15162 context.arg = undefined;
15163 }
15164 } else {
15165 // Re-yield the result returned by the delegate method.
15166 return info;
15167 } // The delegate iterator is finished, so forget it and continue with
15168 // the outer generator.
15169
15170
15171 context.delegate = null;
15172 return ContinueSentinel;
15173 } // Define Generator.prototype.{next,throw,return} in terms of the
15174 // unified ._invoke helper method.
15175
15176
15177 defineIteratorMethods(Gp);
15178 Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the
15179 // @@iterator function is called on it. Some browsers' implementations of the
15180 // iterator prototype chain incorrectly implement this, causing the Generator
15181 // object to not be returned from this call. This ensures that doesn't happen.
15182 // See https://github.com/facebook/regenerator/issues/274 for more details.
15183
15184 Gp[iteratorSymbol] = function () {
15185 return this;
15186 };
15187
15188 Gp.toString = function () {
15189 return "[object Generator]";
15190 };
15191
15192 function pushTryEntry(locs) {
15193 var entry = {
15194 tryLoc: locs[0]
15195 };
15196
15197 if (1 in locs) {
15198 entry.catchLoc = locs[1];
15199 }
15200
15201 if (2 in locs) {
15202 entry.finallyLoc = locs[2];
15203 entry.afterLoc = locs[3];
15204 }
15205
15206 this.tryEntries.push(entry);
15207 }
15208
15209 function resetTryEntry(entry) {
15210 var record = entry.completion || {};
15211 record.type = "normal";
15212 delete record.arg;
15213 entry.completion = record;
15214 }
15215
15216 function Context(tryLocsList) {
15217 // The root entry object (effectively a try statement without a catch
15218 // or a finally block) gives us a place to store values thrown from
15219 // locations where there is no enclosing try statement.
15220 this.tryEntries = [{
15221 tryLoc: "root"
15222 }];
15223 tryLocsList.forEach(pushTryEntry, this);
15224 this.reset(true);
15225 }
15226
15227 exports.keys = function (object) {
15228 var keys = [];
15229
15230 for (var key in object) {
15231 keys.push(key);
15232 }
15233
15234 keys.reverse(); // Rather than returning an object with a next method, we keep
15235 // things simple and return the next function itself.
15236
15237 return function next() {
15238 while (keys.length) {
15239 var key = keys.pop();
15240
15241 if (key in object) {
15242 next.value = key;
15243 next.done = false;
15244 return next;
15245 }
15246 } // To avoid creating an additional object, we just hang the .value
15247 // and .done properties off the next function object itself. This
15248 // also ensures that the minifier will not anonymize the function.
15249
15250
15251 next.done = true;
15252 return next;
15253 };
15254 };
15255
15256 function values(iterable) {
15257 if (iterable) {
15258 var iteratorMethod = iterable[iteratorSymbol];
15259
15260 if (iteratorMethod) {
15261 return iteratorMethod.call(iterable);
15262 }
15263
15264 if (typeof iterable.next === "function") {
15265 return iterable;
15266 }
15267
15268 if (!isNaN(iterable.length)) {
15269 var i = -1,
15270 next = function next() {
15271 while (++i < iterable.length) {
15272 if (hasOwn.call(iterable, i)) {
15273 next.value = iterable[i];
15274 next.done = false;
15275 return next;
15276 }
15277 }
15278
15279 next.value = undefined;
15280 next.done = true;
15281 return next;
15282 };
15283
15284 return next.next = next;
15285 }
15286 } // Return an iterator with no values.
15287
15288
15289 return {
15290 next: doneResult
15291 };
15292 }
15293
15294 exports.values = values;
15295
15296 function doneResult() {
15297 return {
15298 value: undefined,
15299 done: true
15300 };
15301 }
15302
15303 Context.prototype = {
15304 constructor: Context,
15305 reset: function reset(skipTempReset) {
15306 this.prev = 0;
15307 this.next = 0; // Resetting context._sent for legacy support of Babel's
15308 // function.sent implementation.
15309
15310 this.sent = this._sent = undefined;
15311 this.done = false;
15312 this.delegate = null;
15313 this.method = "next";
15314 this.arg = undefined;
15315 this.tryEntries.forEach(resetTryEntry);
15316
15317 if (!skipTempReset) {
15318 for (var name in this) {
15319 // Not sure about the optimal order of these conditions:
15320 if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
15321 this[name] = undefined;
15322 }
15323 }
15324 }
15325 },
15326 stop: function stop() {
15327 this.done = true;
15328 var rootEntry = this.tryEntries[0];
15329 var rootRecord = rootEntry.completion;
15330
15331 if (rootRecord.type === "throw") {
15332 throw rootRecord.arg;
15333 }
15334
15335 return this.rval;
15336 },
15337 dispatchException: function dispatchException(exception) {
15338 if (this.done) {
15339 throw exception;
15340 }
15341
15342 var context = this;
15343
15344 function handle(loc, caught) {
15345 record.type = "throw";
15346 record.arg = exception;
15347 context.next = loc;
15348
15349 if (caught) {
15350 // If the dispatched exception was caught by a catch block,
15351 // then let that catch block handle the exception normally.
15352 context.method = "next";
15353 context.arg = undefined;
15354 }
15355
15356 return !!caught;
15357 }
15358
15359 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
15360 var entry = this.tryEntries[i];
15361 var record = entry.completion;
15362
15363 if (entry.tryLoc === "root") {
15364 // Exception thrown outside of any try block that could handle
15365 // it, so set the completion value of the entire function to
15366 // throw the exception.
15367 return handle("end");
15368 }
15369
15370 if (entry.tryLoc <= this.prev) {
15371 var hasCatch = hasOwn.call(entry, "catchLoc");
15372 var hasFinally = hasOwn.call(entry, "finallyLoc");
15373
15374 if (hasCatch && hasFinally) {
15375 if (this.prev < entry.catchLoc) {
15376 return handle(entry.catchLoc, true);
15377 } else if (this.prev < entry.finallyLoc) {
15378 return handle(entry.finallyLoc);
15379 }
15380 } else if (hasCatch) {
15381 if (this.prev < entry.catchLoc) {
15382 return handle(entry.catchLoc, true);
15383 }
15384 } else if (hasFinally) {
15385 if (this.prev < entry.finallyLoc) {
15386 return handle(entry.finallyLoc);
15387 }
15388 } else {
15389 throw new Error("try statement without catch or finally");
15390 }
15391 }
15392 }
15393 },
15394 abrupt: function abrupt(type, arg) {
15395 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
15396 var entry = this.tryEntries[i];
15397
15398 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
15399 var finallyEntry = entry;
15400 break;
15401 }
15402 }
15403
15404 if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
15405 // Ignore the finally entry if control is not jumping to a
15406 // location outside the try/catch block.
15407 finallyEntry = null;
15408 }
15409
15410 var record = finallyEntry ? finallyEntry.completion : {};
15411 record.type = type;
15412 record.arg = arg;
15413
15414 if (finallyEntry) {
15415 this.method = "next";
15416 this.next = finallyEntry.finallyLoc;
15417 return ContinueSentinel;
15418 }
15419
15420 return this.complete(record);
15421 },
15422 complete: function complete(record, afterLoc) {
15423 if (record.type === "throw") {
15424 throw record.arg;
15425 }
15426
15427 if (record.type === "break" || record.type === "continue") {
15428 this.next = record.arg;
15429 } else if (record.type === "return") {
15430 this.rval = this.arg = record.arg;
15431 this.method = "return";
15432 this.next = "end";
15433 } else if (record.type === "normal" && afterLoc) {
15434 this.next = afterLoc;
15435 }
15436
15437 return ContinueSentinel;
15438 },
15439 finish: function finish(finallyLoc) {
15440 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
15441 var entry = this.tryEntries[i];
15442
15443 if (entry.finallyLoc === finallyLoc) {
15444 this.complete(entry.completion, entry.afterLoc);
15445 resetTryEntry(entry);
15446 return ContinueSentinel;
15447 }
15448 }
15449 },
15450 "catch": function _catch(tryLoc) {
15451 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
15452 var entry = this.tryEntries[i];
15453
15454 if (entry.tryLoc === tryLoc) {
15455 var record = entry.completion;
15456
15457 if (record.type === "throw") {
15458 var thrown = record.arg;
15459 resetTryEntry(entry);
15460 }
15461
15462 return thrown;
15463 }
15464 } // The context.catch method must only be called with a location
15465 // argument that corresponds to a known catch block.
15466
15467
15468 throw new Error("illegal catch attempt");
15469 },
15470 delegateYield: function delegateYield(iterable, resultName, nextLoc) {
15471 this.delegate = {
15472 iterator: values(iterable),
15473 resultName: resultName,
15474 nextLoc: nextLoc
15475 };
15476
15477 if (this.method === "next") {
15478 // Deliberately forget the last sent value so that we don't
15479 // accidentally pass it on to the delegate.
15480 this.arg = undefined;
15481 }
15482
15483 return ContinueSentinel;
15484 }
15485 }; // Regardless of whether this script is executing as a CommonJS module
15486 // or not, return the runtime object so that we can declare the variable
15487 // regeneratorRuntime in the outer scope, which allows this module to be
15488 // injected easily by `bin/regenerator --include-runtime script.js`.
15489
15490 return exports;
15491}( // If this script is executing as a CommonJS module, use module.exports
15492// as the regeneratorRuntime namespace. Otherwise create a new empty
15493// object. Either way, the resulting object will be used to initialize
15494// the regeneratorRuntime variable at the top of this file.
15495 true ? module.exports : undefined);
15496
15497try {
15498 regeneratorRuntime = runtime;
15499} catch (accidentalStrictMode) {
15500 // This module should not be running in strict mode, so the above
15501 // assignment should always work unless something is misconfigured. Just
15502 // in case runtime.js accidentally runs in strict mode, we can escape
15503 // strict mode using a global Function call. This could conceivably fail
15504 // if a Content Security Policy forbids using Function, but in that case
15505 // the proper solution is to fix the accidental strict mode problem. If
15506 // you've misconfigured your bundler to force strict mode and applied a
15507 // CSP to forbid Function, and you're not willing to fix either of those
15508 // problems, please detail your unique predicament in a GitHub issue.
15509 Function("r", "regeneratorRuntime = r")(runtime);
15510}
15511
15512/***/ }),
15513/* 376 */
15514/***/ (function(module, exports, __webpack_require__) {
15515
15516"use strict";
15517/**
15518 * @fileoverview Main Linter Class
15519 * @author Gyandeep Singh
15520 * @author aladdin-add
15521 */
15522 //------------------------------------------------------------------------------
15523// Requirements
15524//------------------------------------------------------------------------------
15525
15526function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
15527
15528function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
15529
15530function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
15531
15532const path = __webpack_require__(377),
15533 eslintScope = __webpack_require__(378),
15534 evk = __webpack_require__(392),
15535 espree = __webpack_require__(394),
15536 lodash = __webpack_require__(403),
15537 BuiltInEnvironments = __webpack_require__(405),
15538 pkg = __webpack_require__(408),
15539 astUtils = __webpack_require__(409),
15540 ConfigOps = __webpack_require__(410),
15541 validator = __webpack_require__(411),
6a5a0f88 15542 Traverser = __webpack_require__(640),
eb39fafa
DC
15543 {
15544 SourceCode
6a5a0f88
TL
15545} = __webpack_require__(776),
15546 CodePathAnalyzer = __webpack_require__(791),
15547 applyDisableDirectives = __webpack_require__(798),
15548 ConfigCommentParser = __webpack_require__(799),
15549 NodeEventGenerator = __webpack_require__(812),
15550 createReportTranslator = __webpack_require__(814),
15551 Rules = __webpack_require__(817),
15552 createEmitter = __webpack_require__(819),
15553 SourceCodeFixer = __webpack_require__(820),
15554 timing = __webpack_require__(821),
15555 ruleReplacements = __webpack_require__(822);
eb39fafa
DC
15556
15557const debug = __webpack_require__(416)("eslint:linter");
15558
15559const MAX_AUTOFIX_PASSES = 10;
15560const DEFAULT_PARSER_NAME = "espree";
15561const commentParser = new ConfigCommentParser();
15562const DEFAULT_ERROR_LOC = {
15563 start: {
15564 line: 1,
15565 column: 0
15566 },
15567 end: {
15568 line: 1,
15569 column: 1
15570 }
15571}; //------------------------------------------------------------------------------
15572// Typedefs
15573//------------------------------------------------------------------------------
15574
15575/** @typedef {InstanceType<import("../cli-engine/config-array")["ConfigArray"]>} ConfigArray */
15576
15577/** @typedef {InstanceType<import("../cli-engine/config-array")["ExtractedConfig"]>} ExtractedConfig */
15578
15579/** @typedef {import("../shared/types").ConfigData} ConfigData */
15580
15581/** @typedef {import("../shared/types").Environment} Environment */
15582
15583/** @typedef {import("../shared/types").GlobalConf} GlobalConf */
15584
15585/** @typedef {import("../shared/types").LintMessage} LintMessage */
15586
15587/** @typedef {import("../shared/types").ParserOptions} ParserOptions */
15588
15589/** @typedef {import("../shared/types").Processor} Processor */
15590
15591/** @typedef {import("../shared/types").Rule} Rule */
15592
15593/**
15594 * @template T
15595 * @typedef {{ [P in keyof T]-?: T[P] }} Required
15596 */
15597
15598/**
15599 * @typedef {Object} DisableDirective
15600 * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type
15601 * @property {number} line
15602 * @property {number} column
15603 * @property {(string|null)} ruleId
15604 */
15605
15606/**
15607 * The private data for `Linter` instance.
15608 * @typedef {Object} LinterInternalSlots
15609 * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used.
15610 * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used.
15611 * @property {Map<string, Parser>} parserMap The loaded parsers.
15612 * @property {Rules} ruleMap The loaded rules.
15613 */
15614
15615/**
15616 * @typedef {Object} VerifyOptions
15617 * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability
15618 * to change config once it is set. Defaults to true if not supplied.
15619 * Useful if you want to validate JS without comments overriding rules.
15620 * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix`
15621 * properties into the lint result.
15622 * @property {string} [filename] the filename of the source code.
15623 * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for
15624 * unused `eslint-disable` directives.
15625 */
15626
15627/**
15628 * @typedef {Object} ProcessorOptions
15629 * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
15630 * predicate function that selects adopt code blocks.
15631 * @property {Processor["postprocess"]} [postprocess] postprocessor for report
15632 * messages. If provided, this should accept an array of the message lists
15633 * for each code block returned from the preprocessor, apply a mapping to
15634 * the messages as appropriate, and return a one-dimensional array of
15635 * messages.
15636 * @property {Processor["preprocess"]} [preprocess] preprocessor for source text.
15637 * If provided, this should accept a string of source text, and return an
15638 * array of code blocks to lint.
15639 */
15640
15641/**
15642 * @typedef {Object} FixOptions
15643 * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
15644 * whether fixes should be applied.
15645 */
15646
15647/**
15648 * @typedef {Object} InternalOptions
15649 * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments.
15650 * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized)
15651 */
15652//------------------------------------------------------------------------------
15653// Helpers
15654//------------------------------------------------------------------------------
15655
15656/**
15657 * Ensures that variables representing built-in properties of the Global Object,
15658 * and any globals declared by special block comments, are present in the global
15659 * scope.
15660 * @param {Scope} globalScope The global scope.
15661 * @param {Object} configGlobals The globals declared in configuration
15662 * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration
15663 * @returns {void}
15664 */
15665
15666function addDeclaredGlobals(globalScope, configGlobals, {
15667 exportedVariables,
15668 enabledGlobals
15669}) {
15670 // Define configured global variables.
15671 for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
15672 /*
15673 * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
15674 * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
15675 */
15676 const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
15677 const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
15678 const value = commentValue || configValue;
15679 const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments;
15680
15681 if (value === "off") {
15682 continue;
15683 }
15684
15685 let variable = globalScope.set.get(id);
15686
15687 if (!variable) {
15688 variable = new eslintScope.Variable(id, globalScope);
15689 globalScope.variables.push(variable);
15690 globalScope.set.set(id, variable);
15691 }
15692
15693 variable.eslintImplicitGlobalSetting = configValue;
15694 variable.eslintExplicitGlobal = sourceComments !== void 0;
15695 variable.eslintExplicitGlobalComments = sourceComments;
15696 variable.writeable = value === "writable";
15697 } // mark all exported variables as such
15698
15699
15700 Object.keys(exportedVariables).forEach(name => {
15701 const variable = globalScope.set.get(name);
15702
15703 if (variable) {
15704 variable.eslintUsed = true;
15705 }
15706 });
15707 /*
15708 * "through" contains all references which definitions cannot be found.
15709 * Since we augment the global scope using configuration, we need to update
15710 * references and remove the ones that were added by configuration.
15711 */
15712
15713 globalScope.through = globalScope.through.filter(reference => {
15714 const name = reference.identifier.name;
15715 const variable = globalScope.set.get(name);
15716
15717 if (variable) {
15718 /*
15719 * Links the variable and the reference.
15720 * And this reference is removed from `Scope#through`.
15721 */
15722 reference.resolved = variable;
15723 variable.references.push(reference);
15724 return false;
15725 }
15726
15727 return true;
15728 });
15729}
15730/**
15731 * creates a missing-rule message.
15732 * @param {string} ruleId the ruleId to create
15733 * @returns {string} created error message
15734 * @private
15735 */
15736
15737
15738function createMissingRuleMessage(ruleId) {
15739 return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId) ? "Rule '".concat(ruleId, "' was removed and replaced by: ").concat(ruleReplacements.rules[ruleId].join(", ")) : "Definition for rule '".concat(ruleId, "' was not found.");
15740}
15741/**
15742 * creates a linting problem
15743 * @param {Object} options to create linting error
15744 * @param {string} [options.ruleId] the ruleId to report
15745 * @param {Object} [options.loc] the loc to report
15746 * @param {string} [options.message] the error message to report
15747 * @param {string} [options.severity] the error message to report
15748 * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId.
15749 * @private
15750 */
15751
15752
15753function createLintingProblem(options) {
15754 const {
15755 ruleId = null,
15756 loc = DEFAULT_ERROR_LOC,
15757 message = createMissingRuleMessage(options.ruleId),
15758 severity = 2
15759 } = options;
15760 return {
15761 ruleId,
15762 message,
15763 line: loc.start.line,
15764 column: loc.start.column + 1,
15765 endLine: loc.end.line,
15766 endColumn: loc.end.column + 1,
15767 severity,
15768 nodeType: null
15769 };
15770}
15771/**
15772 * Creates a collection of disable directives from a comment
15773 * @param {Object} options to create disable directives
15774 * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
15775 * @param {{line: number, column: number}} options.loc The 0-based location of the comment token
15776 * @param {string} options.value The value after the directive in the comment
15777 * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
15778 * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules
15779 * @returns {Object} Directives and problems from the comment
15780 */
15781
15782
15783function createDisableDirectives(options) {
15784 const {
15785 type,
15786 loc,
15787 value,
15788 ruleMapper
15789 } = options;
15790 const ruleIds = Object.keys(commentParser.parseListConfig(value));
15791 const directiveRules = ruleIds.length ? ruleIds : [null];
15792 const result = {
15793 directives: [],
15794 // valid disable directives
15795 directiveProblems: [] // problems in directives
15796
15797 };
15798
15799 for (const ruleId of directiveRules) {
15800 // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
15801 if (ruleId === null || ruleMapper(ruleId) !== null) {
15802 result.directives.push({
15803 type,
15804 line: loc.start.line,
15805 column: loc.start.column + 1,
15806 ruleId
15807 });
15808 } else {
15809 result.directiveProblems.push(createLintingProblem({
15810 ruleId,
15811 loc
15812 }));
15813 }
15814 }
15815
15816 return result;
15817}
15818/**
15819 * Remove the ignored part from a given directive comment and trim it.
15820 * @param {string} value The comment text to strip.
15821 * @returns {string} The stripped text.
15822 */
15823
15824
15825function stripDirectiveComment(value) {
15826 return value.split(/\s-{2,}\s/u)[0].trim();
15827}
15828/**
15829 * Parses comments in file to extract file-specific config of rules, globals
15830 * and environments and merges them with global config; also code blocks
15831 * where reporting is disabled or enabled and merges them with reporting config.
15832 * @param {string} filename The file being checked.
15833 * @param {ASTNode} ast The top node of the AST.
15834 * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
15835 * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from.
15836 * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: Problem[], disableDirectives: DisableDirective[]}}
15837 * A collection of the directive comments that were found, along with any problems that occurred when parsing
15838 */
15839
15840
15841function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
15842 const configuredRules = {};
15843 const enabledGlobals = Object.create(null);
15844 const exportedVariables = {};
15845 const problems = [];
15846 const disableDirectives = [];
15847 ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
15848 const trimmedCommentText = stripDirectiveComment(comment.value);
15849 const match = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u.exec(trimmedCommentText);
15850
15851 if (!match) {
15852 return;
15853 }
15854
15855 const directiveText = match[1];
15856 const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
15857
15858 if (comment.type === "Line" && !lineCommentSupported) {
15859 return;
15860 }
15861
15862 if (warnInlineConfig) {
15863 const kind = comment.type === "Block" ? "/*".concat(directiveText, "*/") : "//".concat(directiveText);
15864 problems.push(createLintingProblem({
15865 ruleId: null,
15866 message: "'".concat(kind, "' has no effect because you have 'noInlineConfig' setting in ").concat(warnInlineConfig, "."),
15867 loc: comment.loc,
15868 severity: 1
15869 }));
15870 return;
15871 }
15872
15873 if (lineCommentSupported && comment.loc.start.line !== comment.loc.end.line) {
15874 const message = "".concat(directiveText, " comment should not span multiple lines.");
15875 problems.push(createLintingProblem({
15876 ruleId: null,
15877 message,
15878 loc: comment.loc
15879 }));
15880 return;
15881 }
15882
15883 const directiveValue = trimmedCommentText.slice(match.index + directiveText.length);
15884
15885 switch (directiveText) {
15886 case "eslint-disable":
15887 case "eslint-enable":
15888 case "eslint-disable-next-line":
15889 case "eslint-disable-line":
15890 {
15891 const directiveType = directiveText.slice("eslint-".length);
15892 const options = {
15893 type: directiveType,
15894 loc: comment.loc,
15895 value: directiveValue,
15896 ruleMapper
15897 };
15898 const {
15899 directives,
15900 directiveProblems
15901 } = createDisableDirectives(options);
15902 disableDirectives.push(...directives);
15903 problems.push(...directiveProblems);
15904 break;
15905 }
15906
15907 case "exported":
15908 Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
15909 break;
15910
15911 case "globals":
15912 case "global":
15913 for (const [id, {
15914 value
15915 }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) {
15916 let normalizedValue;
15917
15918 try {
15919 normalizedValue = ConfigOps.normalizeConfigGlobal(value);
15920 } catch (err) {
15921 problems.push(createLintingProblem({
15922 ruleId: null,
15923 loc: comment.loc,
15924 message: err.message
15925 }));
15926 continue;
15927 }
15928
15929 if (enabledGlobals[id]) {
15930 enabledGlobals[id].comments.push(comment);
15931 enabledGlobals[id].value = normalizedValue;
15932 } else {
15933 enabledGlobals[id] = {
15934 comments: [comment],
15935 value: normalizedValue
15936 };
15937 }
15938 }
15939
15940 break;
15941
15942 case "eslint":
15943 {
15944 const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
15945
15946 if (parseResult.success) {
15947 Object.keys(parseResult.config).forEach(name => {
15948 const rule = ruleMapper(name);
15949 const ruleValue = parseResult.config[name];
15950
15951 if (rule === null) {
15952 problems.push(createLintingProblem({
15953 ruleId: name,
15954 loc: comment.loc
15955 }));
15956 return;
15957 }
15958
15959 try {
15960 validator.validateRuleOptions(rule, name, ruleValue);
15961 } catch (err) {
15962 problems.push(createLintingProblem({
15963 ruleId: name,
15964 message: err.message,
15965 loc: comment.loc
15966 })); // do not apply the config, if found invalid options.
15967
15968 return;
15969 }
15970
15971 configuredRules[name] = ruleValue;
15972 });
15973 } else {
15974 problems.push(parseResult.error);
15975 }
15976
15977 break;
15978 }
15979 // no default
15980 }
15981 });
15982 return {
15983 configuredRules,
15984 enabledGlobals,
15985 exportedVariables,
15986 problems,
15987 disableDirectives
15988 };
15989}
15990/**
15991 * Normalize ECMAScript version from the initial config
15992 * @param {number} ecmaVersion ECMAScript version from the initial config
15993 * @returns {number} normalized ECMAScript version
15994 */
15995
15996
15997function normalizeEcmaVersion(ecmaVersion) {
15998 /*
15999 * Calculate ECMAScript edition number from official year version starting with
16000 * ES2015, which corresponds with ES6 (or a difference of 2009).
16001 */
16002 return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
16003}
16004
16005const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu;
16006/**
16007 * Checks whether or not there is a comment which has "eslint-env *" in a given text.
16008 * @param {string} text A source code text to check.
16009 * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
16010 */
16011
16012function findEslintEnv(text) {
16013 let match, retv;
16014 eslintEnvPattern.lastIndex = 0;
16015
16016 while ((match = eslintEnvPattern.exec(text)) !== null) {
16017 retv = Object.assign(retv || {}, commentParser.parseListConfig(stripDirectiveComment(match[1])));
16018 }
16019
16020 return retv;
16021}
16022/**
16023 * Convert "/path/to/<text>" to "<text>".
16024 * `CLIEngine#executeOnText()` method gives "/path/to/<text>" if the filename
16025 * was omitted because `configArray.extractConfig()` requires an absolute path.
16026 * But the linter should pass `<text>` to `RuleContext#getFilename()` in that
16027 * case.
16028 * Also, code blocks can have their virtual filename. If the parent filename was
16029 * `<text>`, the virtual filename is `<text>/0_foo.js` or something like (i.e.,
16030 * it's not an absolute path).
16031 * @param {string} filename The filename to normalize.
16032 * @returns {string} The normalized filename.
16033 */
16034
16035
16036function normalizeFilename(filename) {
16037 const parts = filename.split(path.sep);
16038 const index = parts.lastIndexOf("<text>");
16039 return index === -1 ? filename : parts.slice(index).join(path.sep);
16040}
16041/**
16042 * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
16043 * consistent shape.
16044 * @param {VerifyOptions} providedOptions Options
16045 * @param {ConfigData} config Config.
16046 * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
16047 */
16048
16049
16050function normalizeVerifyOptions(providedOptions, config) {
16051 const disableInlineConfig = config.noInlineConfig === true;
16052 const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
16053 const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig ? " (".concat(config.configNameOfNoInlineConfig, ")") : "";
16054 let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
16055
16056 if (typeof reportUnusedDisableDirectives === "boolean") {
16057 reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
16058 }
16059
16060 if (typeof reportUnusedDisableDirectives !== "string") {
16061 reportUnusedDisableDirectives = config.reportUnusedDisableDirectives ? "warn" : "off";
16062 }
16063
16064 return {
16065 filename: normalizeFilename(providedOptions.filename || "<input>"),
16066 allowInlineConfig: !ignoreInlineConfig,
16067 warnInlineConfig: disableInlineConfig && !ignoreInlineConfig ? "your config".concat(configNameOfNoInlineConfig) : null,
16068 reportUnusedDisableDirectives,
16069 disableFixes: Boolean(providedOptions.disableFixes)
16070 };
16071}
16072/**
16073 * Combines the provided parserOptions with the options from environments
16074 * @param {string} parserName The parser name which uses this options.
16075 * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
16076 * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
16077 * @returns {ParserOptions} Resulting parser options after merge
16078 */
16079
16080
16081function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
16082 const parserOptionsFromEnv = enabledEnvironments.filter(env => env.parserOptions).reduce((parserOptions, env) => lodash.merge(parserOptions, env.parserOptions), {});
16083 const mergedParserOptions = lodash.merge(parserOptionsFromEnv, providedOptions || {});
16084 const isModule = mergedParserOptions.sourceType === "module";
16085
16086 if (isModule) {
16087 /*
16088 * can't have global return inside of modules
16089 * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
16090 */
16091 mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, {
16092 globalReturn: false
16093 });
16094 }
16095 /*
16096 * TODO: @aladdin-add
16097 * 1. for a 3rd-party parser, do not normalize parserOptions
16098 * 2. for espree, no need to do this (espree will do it)
16099 */
16100
16101
16102 mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion);
16103 return mergedParserOptions;
16104}
16105/**
16106 * Combines the provided globals object with the globals from environments
16107 * @param {Record<string, GlobalConf>} providedGlobals The 'globals' key in a config
16108 * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
16109 * @returns {Record<string, GlobalConf>} The resolved globals object
16110 */
16111
16112
16113function resolveGlobals(providedGlobals, enabledEnvironments) {
16114 return Object.assign({}, ...enabledEnvironments.filter(env => env.globals).map(env => env.globals), providedGlobals);
16115}
16116/**
16117 * Strips Unicode BOM from a given text.
16118 * @param {string} text A text to strip.
16119 * @returns {string} The stripped text.
16120 */
16121
16122
16123function stripUnicodeBOM(text) {
16124 /*
16125 * Check Unicode BOM.
16126 * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF.
16127 * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters
16128 */
16129 if (text.charCodeAt(0) === 0xFEFF) {
16130 return text.slice(1);
16131 }
16132
16133 return text;
16134}
16135/**
16136 * Get the options for a rule (not including severity), if any
16137 * @param {Array|number} ruleConfig rule configuration
16138 * @returns {Array} of rule options, empty Array if none
16139 */
16140
16141
16142function getRuleOptions(ruleConfig) {
16143 if (Array.isArray(ruleConfig)) {
16144 return ruleConfig.slice(1);
16145 }
16146
16147 return [];
16148}
16149/**
16150 * Analyze scope of the given AST.
16151 * @param {ASTNode} ast The `Program` node to analyze.
16152 * @param {ParserOptions} parserOptions The parser options.
16153 * @param {Record<string, string[]>} visitorKeys The visitor keys.
16154 * @returns {ScopeManager} The analysis result.
16155 */
16156
16157
16158function analyzeScope(ast, parserOptions, visitorKeys) {
16159 const ecmaFeatures = parserOptions.ecmaFeatures || {};
16160 const ecmaVersion = parserOptions.ecmaVersion || 5;
16161 return eslintScope.analyze(ast, {
16162 ignoreEval: true,
16163 nodejsScope: ecmaFeatures.globalReturn,
16164 impliedStrict: ecmaFeatures.impliedStrict,
16165 ecmaVersion,
16166 sourceType: parserOptions.sourceType || "script",
16167 childVisitorKeys: visitorKeys || evk.KEYS,
16168 fallback: Traverser.getKeys
16169 });
16170}
16171/**
16172 * Parses text into an AST. Moved out here because the try-catch prevents
16173 * optimization of functions, so it's best to keep the try-catch as isolated
16174 * as possible
16175 * @param {string} text The text to parse.
16176 * @param {Parser} parser The parser to parse.
16177 * @param {ParserOptions} providedParserOptions Options to pass to the parser
16178 * @param {string} filePath The path to the file being parsed.
16179 * @returns {{success: false, error: Problem}|{success: true, sourceCode: SourceCode}}
16180 * An object containing the AST and parser services if parsing was successful, or the error if parsing failed
16181 * @private
16182 */
16183
16184
16185function parse(text, parser, providedParserOptions, filePath) {
16186 const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => "//".concat(captured));
16187 const parserOptions = Object.assign({}, providedParserOptions, {
16188 loc: true,
16189 range: true,
16190 raw: true,
16191 tokens: true,
16192 comment: true,
16193 eslintVisitorKeys: true,
16194 eslintScopeManager: true,
16195 filePath
16196 });
16197 /*
16198 * Check for parsing errors first. If there's a parsing error, nothing
16199 * else can happen. However, a parsing error does not throw an error
16200 * from this method - it's just considered a fatal error message, a
16201 * problem that ESLint identified just like any other.
16202 */
16203
16204 try {
16205 const parseResult = typeof parser.parseForESLint === "function" ? parser.parseForESLint(textToParse, parserOptions) : {
16206 ast: parser.parse(textToParse, parserOptions)
16207 };
16208 const ast = parseResult.ast;
16209 const parserServices = parseResult.services || {};
16210 const visitorKeys = parseResult.visitorKeys || evk.KEYS;
16211 const scopeManager = parseResult.scopeManager || analyzeScope(ast, parserOptions, visitorKeys);
16212 return {
16213 success: true,
16214
16215 /*
16216 * Save all values that `parseForESLint()` returned.
16217 * If a `SourceCode` object is given as the first parameter instead of source code text,
16218 * linter skips the parsing process and reuses the source code object.
16219 * In that case, linter needs all the values that `parseForESLint()` returned.
16220 */
16221 sourceCode: new SourceCode({
16222 text,
16223 ast,
16224 parserServices,
16225 scopeManager,
16226 visitorKeys
16227 })
16228 };
16229 } catch (ex) {
16230 // If the message includes a leading line number, strip it:
16231 const message = "Parsing error: ".concat(ex.message.replace(/^line \d+:/iu, "").trim());
16232 debug("%s\n%s", message, ex.stack);
16233 return {
16234 success: false,
16235 error: {
16236 ruleId: null,
16237 fatal: true,
16238 severity: 2,
16239 message,
16240 line: ex.lineNumber,
16241 column: ex.column
16242 }
16243 };
16244 }
16245}
16246/**
16247 * Gets the scope for the current node
16248 * @param {ScopeManager} scopeManager The scope manager for this AST
16249 * @param {ASTNode} currentNode The node to get the scope of
16250 * @returns {eslint-scope.Scope} The scope information for this node
16251 */
16252
16253
16254function _getScope(scopeManager, currentNode) {
16255 // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
16256 const inner = currentNode.type !== "Program";
16257
16258 for (let node = currentNode; node; node = node.parent) {
16259 const scope = scopeManager.acquire(node, inner);
16260
16261 if (scope) {
16262 if (scope.type === "function-expression-name") {
16263 return scope.childScopes[0];
16264 }
16265
16266 return scope;
16267 }
16268 }
16269
16270 return scopeManager.scopes[0];
16271}
16272/**
16273 * Marks a variable as used in the current scope
16274 * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function.
16275 * @param {ASTNode} currentNode The node currently being traversed
16276 * @param {Object} parserOptions The options used to parse this text
16277 * @param {string} name The name of the variable that should be marked as used.
16278 * @returns {boolean} True if the variable was found and marked as used, false if not.
16279 */
16280
16281
16282function _markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
16283 const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
16284 const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
16285
16286 const currentScope = _getScope(scopeManager, currentNode); // Special Node.js scope means we need to start one level deeper
16287
16288
16289 const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
16290
16291 for (let scope = initialScope; scope; scope = scope.upper) {
16292 const variable = scope.variables.find(scopeVar => scopeVar.name === name);
16293
16294 if (variable) {
16295 variable.eslintUsed = true;
16296 return true;
16297 }
16298 }
16299
16300 return false;
16301}
16302/**
16303 * Runs a rule, and gets its listeners
16304 * @param {Rule} rule A normalized rule with a `create` method
16305 * @param {Context} ruleContext The context that should be passed to the rule
16306 * @returns {Object} A map of selector listeners provided by the rule
16307 */
16308
16309
16310function createRuleListeners(rule, ruleContext) {
16311 try {
16312 return rule.create(ruleContext);
16313 } catch (ex) {
16314 ex.message = "Error while loading rule '".concat(ruleContext.id, "': ").concat(ex.message);
16315 throw ex;
16316 }
16317}
16318/**
16319 * Gets all the ancestors of a given node
16320 * @param {ASTNode} node The node
16321 * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
16322 * from the root node and going inwards to the parent node.
16323 */
16324
16325
16326function _getAncestors(node) {
16327 const ancestorsStartingAtParent = [];
16328
16329 for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
16330 ancestorsStartingAtParent.push(ancestor);
16331 }
16332
16333 return ancestorsStartingAtParent.reverse();
16334} // methods that exist on SourceCode object
16335
16336
16337const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
16338 getSource: "getText",
16339 getSourceLines: "getLines",
16340 getAllComments: "getAllComments",
16341 getNodeByRangeIndex: "getNodeByRangeIndex",
16342 getComments: "getComments",
16343 getCommentsBefore: "getCommentsBefore",
16344 getCommentsAfter: "getCommentsAfter",
16345 getCommentsInside: "getCommentsInside",
16346 getJSDocComment: "getJSDocComment",
16347 getFirstToken: "getFirstToken",
16348 getFirstTokens: "getFirstTokens",
16349 getLastToken: "getLastToken",
16350 getLastTokens: "getLastTokens",
16351 getTokenAfter: "getTokenAfter",
16352 getTokenBefore: "getTokenBefore",
16353 getTokenByRangeStart: "getTokenByRangeStart",
16354 getTokens: "getTokens",
16355 getTokensAfter: "getTokensAfter",
16356 getTokensBefore: "getTokensBefore",
16357 getTokensBetween: "getTokensBetween"
16358};
16359const BASE_TRAVERSAL_CONTEXT = Object.freeze(Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce((contextInfo, methodName) => Object.assign(contextInfo, {
16360 [methodName](...args) {
16361 return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
16362 }
16363
16364}), {}));
16365/**
16366 * Runs the given rules on the given SourceCode object
16367 * @param {SourceCode} sourceCode A SourceCode object for the given text
16368 * @param {Object} configuredRules The rules configuration
16369 * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
16370 * @param {Object} parserOptions The options that were passed to the parser
16371 * @param {string} parserName The name of the parser in the config
16372 * @param {Object} settings The settings that were enabled in the config
16373 * @param {string} filename The reported filename of the code
16374 * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
16375 * @param {string | undefined} cwd cwd of the cli
16376 * @returns {Problem[]} An array of reported problems
16377 */
16378
16379function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes, cwd) {
16380 const emitter = createEmitter();
16381 const nodeQueue = [];
16382 let currentNode = sourceCode.ast;
16383 Traverser.traverse(sourceCode.ast, {
16384 enter(node, parent) {
16385 node.parent = parent;
16386 nodeQueue.push({
16387 isEntering: true,
16388 node
16389 });
16390 },
16391
16392 leave(node) {
16393 nodeQueue.push({
16394 isEntering: false,
16395 node
16396 });
16397 },
16398
16399 visitorKeys: sourceCode.visitorKeys
16400 });
16401 /*
16402 * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
16403 * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
16404 * properties once for each rule.
16405 */
16406
16407 const sharedTraversalContext = Object.freeze(Object.assign(Object.create(BASE_TRAVERSAL_CONTEXT), {
16408 getAncestors: () => _getAncestors(currentNode),
16409 getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
16410 getCwd: () => cwd,
16411 getFilename: () => filename,
16412 getScope: () => _getScope(sourceCode.scopeManager, currentNode),
16413 getSourceCode: () => sourceCode,
16414 markVariableAsUsed: name => _markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name),
16415 parserOptions,
16416 parserPath: parserName,
16417 parserServices: sourceCode.parserServices,
16418 settings
16419 }));
16420 const lintingProblems = [];
16421 Object.keys(configuredRules).forEach(ruleId => {
16422 const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]); // not load disabled rules
16423
16424 if (severity === 0) {
16425 return;
16426 }
16427
16428 const rule = ruleMapper(ruleId);
16429
16430 if (rule === null) {
16431 lintingProblems.push(createLintingProblem({
16432 ruleId
16433 }));
16434 return;
16435 }
16436
16437 const messageIds = rule.meta && rule.meta.messages;
16438 let reportTranslator = null;
16439 const ruleContext = Object.freeze(Object.assign(Object.create(sharedTraversalContext), {
16440 id: ruleId,
16441 options: getRuleOptions(configuredRules[ruleId]),
16442
16443 report(...args) {
16444 /*
16445 * Create a report translator lazily.
16446 * In a vast majority of cases, any given rule reports zero errors on a given
16447 * piece of code. Creating a translator lazily avoids the performance cost of
16448 * creating a new translator function for each rule that usually doesn't get
16449 * called.
16450 *
16451 * Using lazy report translators improves end-to-end performance by about 3%
16452 * with Node 8.4.0.
16453 */
16454 if (reportTranslator === null) {
16455 reportTranslator = createReportTranslator({
16456 ruleId,
16457 severity,
16458 sourceCode,
16459 messageIds,
16460 disableFixes
16461 });
16462 }
16463
16464 const problem = reportTranslator(...args);
16465
16466 if (problem.fix && rule.meta && !rule.meta.fixable) {
16467 throw new Error("Fixable rules should export a `meta.fixable` property.");
16468 }
16469
16470 lintingProblems.push(problem);
16471 }
16472
16473 }));
16474 const ruleListeners = createRuleListeners(rule, ruleContext); // add all the selectors from the rule as listeners
16475
16476 Object.keys(ruleListeners).forEach(selector => {
16477 emitter.on(selector, timing.enabled ? timing.time(ruleId, ruleListeners[selector]) : ruleListeners[selector]);
16478 });
6a5a0f88
TL
16479 }); // only run code path analyzer if the top level node is "Program", skip otherwise
16480
16481 const eventGenerator = nodeQueue[0].node.type === "Program" ? new CodePathAnalyzer(new NodeEventGenerator(emitter)) : new NodeEventGenerator(emitter);
eb39fafa
DC
16482 nodeQueue.forEach(traversalInfo => {
16483 currentNode = traversalInfo.node;
16484
16485 try {
16486 if (traversalInfo.isEntering) {
16487 eventGenerator.enterNode(currentNode);
16488 } else {
16489 eventGenerator.leaveNode(currentNode);
16490 }
16491 } catch (err) {
16492 err.currentNode = currentNode;
16493 throw err;
16494 }
16495 });
16496 return lintingProblems;
16497}
16498/**
16499 * Ensure the source code to be a string.
16500 * @param {string|SourceCode} textOrSourceCode The text or source code object.
16501 * @returns {string} The source code text.
16502 */
16503
16504
16505function ensureText(textOrSourceCode) {
16506 if (typeof textOrSourceCode === "object") {
16507 const {
16508 hasBOM,
16509 text
16510 } = textOrSourceCode;
16511 const bom = hasBOM ? "\uFEFF" : "";
16512 return bom + text;
16513 }
16514
16515 return String(textOrSourceCode);
16516}
16517/**
16518 * Get an environment.
16519 * @param {LinterInternalSlots} slots The internal slots of Linter.
16520 * @param {string} envId The environment ID to get.
16521 * @returns {Environment|null} The environment.
16522 */
16523
16524
16525function getEnv(slots, envId) {
16526 return slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId) || BuiltInEnvironments.get(envId) || null;
16527}
16528/**
16529 * Get a rule.
16530 * @param {LinterInternalSlots} slots The internal slots of Linter.
16531 * @param {string} ruleId The rule ID to get.
16532 * @returns {Rule|null} The rule.
16533 */
16534
16535
16536function getRule(slots, ruleId) {
16537 return slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId) || slots.ruleMap.get(ruleId);
16538}
16539/**
16540 * Normalize the value of the cwd
16541 * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined.
16542 * @returns {string | undefined} normalized cwd
16543 */
16544
16545
16546function normalizeCwd(cwd) {
16547 if (cwd) {
16548 return cwd;
16549 }
16550
16551 if (typeof process === "object") {
16552 return process.cwd();
16553 } // It's more explicit to assign the undefined
16554 // eslint-disable-next-line no-undefined
16555
16556
16557 return undefined;
16558}
16559/**
16560 * The map to store private data.
16561 * @type {WeakMap<Linter, LinterInternalSlots>}
16562 */
16563
16564
16565const internalSlotsMap = new WeakMap(); //------------------------------------------------------------------------------
16566// Public Interface
16567//------------------------------------------------------------------------------
16568
16569/**
16570 * Object that is responsible for verifying JavaScript text
16571 * @name eslint
16572 */
16573
16574class Linter {
16575 /**
16576 * Initialize the Linter.
16577 * @param {Object} [config] the config object
16578 * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
16579 */
16580 constructor({
16581 cwd
16582 } = {}) {
16583 internalSlotsMap.set(this, {
16584 cwd: normalizeCwd(cwd),
16585 lastConfigArray: null,
16586 lastSourceCode: null,
16587 parserMap: new Map([["espree", espree]]),
16588 ruleMap: new Rules()
16589 });
16590 this.version = pkg.version;
16591 }
16592 /**
16593 * Getter for package version.
16594 * @static
16595 * @returns {string} The version from package.json.
16596 */
16597
16598
16599 static get version() {
16600 return pkg.version;
16601 }
16602 /**
16603 * Same as linter.verify, except without support for processors.
16604 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
16605 * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
16606 * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
16607 * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
16608 */
16609
16610
16611 _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
16612 const slots = internalSlotsMap.get(this);
16613 const config = providedConfig || {};
16614 const options = normalizeVerifyOptions(providedOptions, config);
16615 let text; // evaluate arguments
16616
16617 if (typeof textOrSourceCode === "string") {
16618 slots.lastSourceCode = null;
16619 text = textOrSourceCode;
16620 } else {
16621 slots.lastSourceCode = textOrSourceCode;
16622 text = textOrSourceCode.text;
16623 } // Resolve parser.
16624
16625
16626 let parserName = DEFAULT_PARSER_NAME;
16627 let parser = espree;
16628
16629 if (typeof config.parser === "object" && config.parser !== null) {
16630 parserName = config.parser.filePath;
16631 parser = config.parser.definition;
16632 } else if (typeof config.parser === "string") {
16633 if (!slots.parserMap.has(config.parser)) {
16634 return [{
16635 ruleId: null,
16636 fatal: true,
16637 severity: 2,
16638 message: "Configured parser '".concat(config.parser, "' was not found."),
16639 line: 0,
16640 column: 0
16641 }];
16642 }
16643
16644 parserName = config.parser;
16645 parser = slots.parserMap.get(config.parser);
16646 } // search and apply "eslint-env *".
16647
16648
16649 const envInFile = options.allowInlineConfig && !options.warnInlineConfig ? findEslintEnv(text) : {};
16650 const resolvedEnvConfig = Object.assign({
16651 builtin: true
16652 }, config.env, envInFile);
16653 const enabledEnvs = Object.keys(resolvedEnvConfig).filter(envName => resolvedEnvConfig[envName]).map(envName => getEnv(slots, envName)).filter(env => env);
16654 const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs);
16655 const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
16656 const settings = config.settings || {};
16657
16658 if (!slots.lastSourceCode) {
16659 const parseResult = parse(text, parser, parserOptions, options.filename);
16660
16661 if (!parseResult.success) {
16662 return [parseResult.error];
16663 }
16664
16665 slots.lastSourceCode = parseResult.sourceCode;
16666 } else {
16667 /*
16668 * If the given source code object as the first argument does not have scopeManager, analyze the scope.
16669 * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
16670 */
16671 if (!slots.lastSourceCode.scopeManager) {
16672 slots.lastSourceCode = new SourceCode({
16673 text: slots.lastSourceCode.text,
16674 ast: slots.lastSourceCode.ast,
16675 parserServices: slots.lastSourceCode.parserServices,
16676 visitorKeys: slots.lastSourceCode.visitorKeys,
16677 scopeManager: analyzeScope(slots.lastSourceCode.ast, parserOptions)
16678 });
16679 }
16680 }
16681
16682 const sourceCode = slots.lastSourceCode;
16683 const commentDirectives = options.allowInlineConfig ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig) : {
16684 configuredRules: {},
16685 enabledGlobals: {},
16686 exportedVariables: {},
16687 problems: [],
16688 disableDirectives: []
16689 }; // augment global scope with declared global variables
16690
16691 addDeclaredGlobals(sourceCode.scopeManager.scopes[0], configuredGlobals, {
16692 exportedVariables: commentDirectives.exportedVariables,
16693 enabledGlobals: commentDirectives.enabledGlobals
16694 });
16695 const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
16696 let lintingProblems;
16697
16698 try {
16699 lintingProblems = runRules(sourceCode, configuredRules, ruleId => getRule(slots, ruleId), parserOptions, parserName, settings, options.filename, options.disableFixes, slots.cwd);
16700 } catch (err) {
16701 err.message += "\nOccurred while linting ".concat(options.filename);
16702 debug("An error occurred while traversing");
16703 debug("Filename:", options.filename);
16704
16705 if (err.currentNode) {
16706 const {
16707 line
16708 } = err.currentNode.loc.start;
16709 debug("Line:", line);
16710 err.message += ":".concat(line);
16711 }
16712
16713 debug("Parser Options:", parserOptions);
16714 debug("Parser Path:", parserName);
16715 debug("Settings:", settings);
16716 throw err;
16717 }
16718
16719 return applyDisableDirectives({
16720 directives: commentDirectives.disableDirectives,
16721 problems: lintingProblems.concat(commentDirectives.problems).sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
16722 reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
16723 });
16724 }
16725 /**
16726 * Verifies the text against the rules specified by the second argument.
16727 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
16728 * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
16729 * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
16730 * If this is not set, the filename will default to '<input>' in the rule context. If
16731 * an object, then it has "filename", "allowInlineConfig", and some properties.
16732 * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
16733 */
16734
16735
16736 verify(textOrSourceCode, config, filenameOrOptions) {
16737 debug("Verify");
16738 const options = typeof filenameOrOptions === "string" ? {
16739 filename: filenameOrOptions
16740 } : filenameOrOptions || {}; // CLIEngine passes a `ConfigArray` object.
16741
16742 if (config && typeof config.extractConfig === "function") {
16743 return this._verifyWithConfigArray(textOrSourceCode, config, options);
16744 }
16745 /*
16746 * `Linter` doesn't support `overrides` property in configuration.
16747 * So we cannot apply multiple processors.
16748 */
16749
16750
16751 if (options.preprocess || options.postprocess) {
16752 return this._verifyWithProcessor(textOrSourceCode, config, options);
16753 }
16754
16755 return this._verifyWithoutProcessors(textOrSourceCode, config, options);
16756 }
16757 /**
16758 * Verify a given code with `ConfigArray`.
16759 * @param {string|SourceCode} textOrSourceCode The source code.
16760 * @param {ConfigArray} configArray The config array.
16761 * @param {VerifyOptions&ProcessorOptions} options The options.
16762 * @returns {LintMessage[]} The found problems.
16763 */
16764
16765
16766 _verifyWithConfigArray(textOrSourceCode, configArray, options) {
16767 debug("With ConfigArray: %s", options.filename); // Store the config array in order to get plugin envs and rules later.
16768
16769 internalSlotsMap.get(this).lastConfigArray = configArray; // Extract the final config for this file.
16770
16771 const config = configArray.extractConfig(options.filename);
16772 const processor = config.processor && configArray.pluginProcessors.get(config.processor); // Verify.
16773
16774 if (processor) {
16775 debug("Apply the processor: %o", config.processor);
16776 const {
16777 preprocess,
16778 postprocess,
16779 supportsAutofix
16780 } = processor;
16781 const disableFixes = options.disableFixes || !supportsAutofix;
56c4a2cb 16782 return this._verifyWithProcessor(textOrSourceCode, config, _objectSpread(_objectSpread({}, options), {}, {
eb39fafa
DC
16783 disableFixes,
16784 postprocess,
16785 preprocess
16786 }), configArray);
16787 }
16788
16789 return this._verifyWithoutProcessors(textOrSourceCode, config, options);
16790 }
16791 /**
16792 * Verify with a processor.
16793 * @param {string|SourceCode} textOrSourceCode The source code.
16794 * @param {ConfigData|ExtractedConfig} config The config array.
16795 * @param {VerifyOptions&ProcessorOptions} options The options.
16796 * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
16797 * @returns {LintMessage[]} The found problems.
16798 */
16799
16800
16801 _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
16802 const filename = options.filename || "<input>";
16803 const filenameToExpose = normalizeFilename(filename);
16804 const text = ensureText(textOrSourceCode);
16805
16806 const preprocess = options.preprocess || (rawText => [rawText]);
16807
16808 const postprocess = options.postprocess || lodash.flatten;
16809
16810 const filterCodeBlock = options.filterCodeBlock || (blockFilename => blockFilename.endsWith(".js"));
16811
16812 const originalExtname = path.extname(filename);
16813 const messageLists = preprocess(text, filenameToExpose).map((block, i) => {
16814 debug("A code block was found: %o", block.filename || "(unnamed)"); // Keep the legacy behavior.
16815
16816 if (typeof block === "string") {
16817 return this._verifyWithoutProcessors(block, config, options);
16818 }
16819
16820 const blockText = block.text;
16821 const blockName = path.join(filename, "".concat(i, "_").concat(block.filename)); // Skip this block if filtered.
16822
16823 if (!filterCodeBlock(blockName, blockText)) {
16824 debug("This code block was skipped.");
16825 return [];
16826 } // Resolve configuration again if the file extension was changed.
16827
16828
16829 if (configForRecursive && path.extname(blockName) !== originalExtname) {
16830 debug("Resolving configuration again because the file extension was changed.");
56c4a2cb 16831 return this._verifyWithConfigArray(blockText, configForRecursive, _objectSpread(_objectSpread({}, options), {}, {
eb39fafa
DC
16832 filename: blockName
16833 }));
16834 } // Does lint.
16835
16836
56c4a2cb 16837 return this._verifyWithoutProcessors(blockText, config, _objectSpread(_objectSpread({}, options), {}, {
eb39fafa
DC
16838 filename: blockName
16839 }));
16840 });
16841 return postprocess(messageLists, filenameToExpose);
16842 }
16843 /**
16844 * Gets the SourceCode object representing the parsed source.
16845 * @returns {SourceCode} The SourceCode object.
16846 */
16847
16848
16849 getSourceCode() {
16850 return internalSlotsMap.get(this).lastSourceCode;
16851 }
16852 /**
16853 * Defines a new linting rule.
16854 * @param {string} ruleId A unique rule identifier
16855 * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
16856 * @returns {void}
16857 */
16858
16859
16860 defineRule(ruleId, ruleModule) {
16861 internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
16862 }
16863 /**
16864 * Defines many new linting rules.
16865 * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
16866 * @returns {void}
16867 */
16868
16869
16870 defineRules(rulesToDefine) {
16871 Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
16872 this.defineRule(ruleId, rulesToDefine[ruleId]);
16873 });
16874 }
16875 /**
16876 * Gets an object with all loaded rules.
16877 * @returns {Map<string, Rule>} All loaded rules
16878 */
16879
16880
16881 getRules() {
16882 const {
16883 lastConfigArray,
16884 ruleMap
16885 } = internalSlotsMap.get(this);
16886 return new Map(function* () {
16887 yield* ruleMap;
16888
16889 if (lastConfigArray) {
16890 yield* lastConfigArray.pluginRules;
16891 }
16892 }());
16893 }
16894 /**
16895 * Define a new parser module
16896 * @param {string} parserId Name of the parser
16897 * @param {Parser} parserModule The parser object
16898 * @returns {void}
16899 */
16900
16901
16902 defineParser(parserId, parserModule) {
16903 internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
16904 }
16905 /**
16906 * Performs multiple autofix passes over the text until as many fixes as possible
16907 * have been applied.
16908 * @param {string} text The source text to apply fixes to.
16909 * @param {ConfigData|ConfigArray} config The ESLint config object to use.
16910 * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
16911 * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
16912 * SourceCodeFixer.
16913 */
16914
16915
16916 verifyAndFix(text, config, options) {
16917 let messages = [],
16918 fixedResult,
16919 fixed = false,
16920 passNumber = 0,
16921 currentText = text;
16922 const debugTextDescription = options && options.filename || "".concat(text.slice(0, 10), "...");
16923 const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
16924 /**
16925 * This loop continues until one of the following is true:
16926 *
16927 * 1. No more fixes have been applied.
16928 * 2. Ten passes have been made.
16929 *
16930 * That means anytime a fix is successfully applied, there will be another pass.
16931 * Essentially, guaranteeing a minimum of two passes.
16932 */
16933
16934 do {
16935 passNumber++;
16936 debug("Linting code for ".concat(debugTextDescription, " (pass ").concat(passNumber, ")"));
16937 messages = this.verify(currentText, config, options);
16938 debug("Generating fixed text for ".concat(debugTextDescription, " (pass ").concat(passNumber, ")"));
16939 fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
16940 /*
16941 * stop if there are any syntax errors.
16942 * 'fixedResult.output' is a empty string.
16943 */
16944
16945 if (messages.length === 1 && messages[0].fatal) {
16946 break;
16947 } // keep track if any fixes were ever applied - important for return value
16948
16949
16950 fixed = fixed || fixedResult.fixed; // update to use the fixed output instead of the original text
16951
16952 currentText = fixedResult.output;
16953 } while (fixedResult.fixed && passNumber < MAX_AUTOFIX_PASSES);
16954 /*
16955 * If the last result had fixes, we need to lint again to be sure we have
16956 * the most up-to-date information.
16957 */
16958
16959
16960 if (fixedResult.fixed) {
16961 fixedResult.messages = this.verify(currentText, config, options);
16962 } // ensure the last result properly reflects if fixes were done
16963
16964
16965 fixedResult.fixed = fixed;
16966 fixedResult.output = currentText;
16967 return fixedResult;
16968 }
16969
16970}
16971
16972module.exports = {
16973 Linter,
16974
16975 /**
16976 * Get the internal slots of a given Linter instance for tests.
16977 * @param {Linter} instance The Linter instance to get.
16978 * @returns {LinterInternalSlots} The internal slots.
16979 */
16980 getLinterInternalSlots(instance) {
16981 return internalSlotsMap.get(instance);
16982 }
16983
16984};
16985
16986/***/ }),
16987/* 377 */
16988/***/ (function(module, exports) {
16989
16990module.exports = require("path");
16991
16992/***/ }),
16993/* 378 */
16994/***/ (function(module, exports, __webpack_require__) {
16995
16996"use strict";
16997/*
16998 Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
16999 Copyright (C) 2013 Alex Seville <hi@alexanderseville.com>
17000 Copyright (C) 2014 Thiago de Arruda <tpadilha84@gmail.com>
17001
17002 Redistribution and use in source and binary forms, with or without
17003 modification, are permitted provided that the following conditions are met:
17004
17005 * Redistributions of source code must retain the above copyright
17006 notice, this list of conditions and the following disclaimer.
17007 * Redistributions in binary form must reproduce the above copyright
17008 notice, this list of conditions and the following disclaimer in the
17009 documentation and/or other materials provided with the distribution.
17010
17011 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17012 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17013 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17014 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
17015 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17016 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
17017 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
17018 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
17019 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
17020 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17021*/
17022
17023/**
17024 * Escope (<a href="http://github.com/estools/escope">escope</a>) is an <a
17025 * href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a>
17026 * scope analyzer extracted from the <a
17027 * href="http://github.com/estools/esmangle">esmangle project</a/>.
17028 * <p>
17029 * <em>escope</em> finds lexical scopes in a source program, i.e. areas of that
17030 * program where different occurrences of the same identifier refer to the same
17031 * variable. With each scope the contained variables are collected, and each
17032 * identifier reference in code is linked to its corresponding variable (if
17033 * possible).
17034 * <p>
17035 * <em>escope</em> works on a syntax tree of the parsed source code which has
17036 * to adhere to the <a
17037 * href="https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API">
17038 * Mozilla Parser API</a>. E.g. <a href="https://github.com/eslint/espree">espree</a> is a parser
17039 * that produces such syntax trees.
17040 * <p>
17041 * The main interface is the {@link analyze} function.
17042 * @module escope
17043 */
17044
17045/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */
17046
17047const assert = __webpack_require__(379);
17048
17049const ScopeManager = __webpack_require__(380);
17050
17051const Referencer = __webpack_require__(387);
17052
17053const Reference = __webpack_require__(384);
17054
17055const Variable = __webpack_require__(385);
17056
17057const Scope = __webpack_require__(381).Scope;
17058
17059const version = __webpack_require__(391).version;
17060/**
17061 * Set the default options
17062 * @returns {Object} options
17063 */
17064
17065
17066function defaultOptions() {
17067 return {
17068 optimistic: false,
17069 directive: false,
17070 nodejsScope: false,
17071 impliedStrict: false,
17072 sourceType: "script",
17073 // one of ['script', 'module']
17074 ecmaVersion: 5,
17075 childVisitorKeys: null,
17076 fallback: "iteration"
17077 };
17078}
17079/**
17080 * Preform deep update on option object
17081 * @param {Object} target - Options
17082 * @param {Object} override - Updates
17083 * @returns {Object} Updated options
17084 */
17085
17086
17087function updateDeeply(target, override) {
17088 /**
17089 * Is hash object
17090 * @param {Object} value - Test value
17091 * @returns {boolean} Result
17092 */
17093 function isHashObject(value) {
17094 return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp);
17095 }
17096
17097 for (const key in override) {
17098 if (Object.prototype.hasOwnProperty.call(override, key)) {
17099 const val = override[key];
17100
17101 if (isHashObject(val)) {
17102 if (isHashObject(target[key])) {
17103 updateDeeply(target[key], val);
17104 } else {
17105 target[key] = updateDeeply({}, val);
17106 }
17107 } else {
17108 target[key] = val;
17109 }
17110 }
17111 }
17112
17113 return target;
17114}
17115/**
17116 * Main interface function. Takes an Espree syntax tree and returns the
17117 * analyzed scopes.
17118 * @function analyze
17119 * @param {espree.Tree} tree - Abstract Syntax Tree
17120 * @param {Object} providedOptions - Options that tailor the scope analysis
17121 * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag
17122 * @param {boolean} [providedOptions.directive=false]- the directive flag
17123 * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls
17124 * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole
17125 * script is executed under node.js environment. When enabled, escope adds
17126 * a function scope immediately following the global scope.
17127 * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode
17128 * (if ecmaVersion >= 5).
17129 * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module'
17130 * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered
17131 * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option.
17132 * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option.
17133 * @returns {ScopeManager} ScopeManager
17134 */
17135
17136
17137function analyze(tree, providedOptions) {
17138 const options = updateDeeply(defaultOptions(), providedOptions);
17139 const scopeManager = new ScopeManager(options);
17140 const referencer = new Referencer(options, scopeManager);
17141 referencer.visit(tree);
17142 assert(scopeManager.__currentScope === null, "currentScope should be null.");
17143 return scopeManager;
17144}
17145
17146module.exports = {
17147 /** @name module:escope.version */
17148 version,
17149
17150 /** @name module:escope.Reference */
17151 Reference,
17152
17153 /** @name module:escope.Variable */
17154 Variable,
17155
17156 /** @name module:escope.Scope */
17157 Scope,
17158
17159 /** @name module:escope.ScopeManager */
17160 ScopeManager,
17161 analyze
17162};
17163/* vim: set sw=4 ts=4 et tw=80 : */
17164
17165/***/ }),
17166/* 379 */
17167/***/ (function(module, exports) {
17168
17169module.exports = require("assert");
17170
17171/***/ }),
17172/* 380 */
17173/***/ (function(module, exports, __webpack_require__) {
17174
17175"use strict";
17176/*
17177 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
17178
17179 Redistribution and use in source and binary forms, with or without
17180 modification, are permitted provided that the following conditions are met:
17181
17182 * Redistributions of source code must retain the above copyright
17183 notice, this list of conditions and the following disclaimer.
17184 * Redistributions in binary form must reproduce the above copyright
17185 notice, this list of conditions and the following disclaimer in the
17186 documentation and/or other materials provided with the distribution.
17187
17188 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17189 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17190 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17191 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
17192 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17193 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
17194 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
17195 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
17196 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
17197 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17198*/
17199
17200/* eslint-disable no-underscore-dangle */
17201
17202const Scope = __webpack_require__(381);
17203
17204const assert = __webpack_require__(379);
17205
17206const GlobalScope = Scope.GlobalScope;
17207const CatchScope = Scope.CatchScope;
17208const WithScope = Scope.WithScope;
17209const ModuleScope = Scope.ModuleScope;
17210const ClassScope = Scope.ClassScope;
17211const SwitchScope = Scope.SwitchScope;
17212const FunctionScope = Scope.FunctionScope;
17213const ForScope = Scope.ForScope;
17214const FunctionExpressionNameScope = Scope.FunctionExpressionNameScope;
17215const BlockScope = Scope.BlockScope;
17216/**
17217 * @class ScopeManager
17218 */
17219
17220class ScopeManager {
17221 constructor(options) {
17222 this.scopes = [];
17223 this.globalScope = null;
17224 this.__nodeToScope = new WeakMap();
17225 this.__currentScope = null;
17226 this.__options = options;
17227 this.__declaredVariables = new WeakMap();
17228 }
17229
17230 __useDirective() {
17231 return this.__options.directive;
17232 }
17233
17234 __isOptimistic() {
17235 return this.__options.optimistic;
17236 }
17237
17238 __ignoreEval() {
17239 return this.__options.ignoreEval;
17240 }
17241
17242 __isNodejsScope() {
17243 return this.__options.nodejsScope;
17244 }
17245
17246 isModule() {
17247 return this.__options.sourceType === "module";
17248 }
17249
17250 isImpliedStrict() {
17251 return this.__options.impliedStrict;
17252 }
17253
17254 isStrictModeSupported() {
17255 return this.__options.ecmaVersion >= 5;
17256 } // Returns appropriate scope for this node.
17257
17258
17259 __get(node) {
17260 return this.__nodeToScope.get(node);
17261 }
17262 /**
17263 * Get variables that are declared by the node.
17264 *
17265 * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`.
17266 * If the node declares nothing, this method returns an empty array.
17267 * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details.
17268 *
17269 * @param {Espree.Node} node - a node to get.
17270 * @returns {Variable[]} variables that declared by the node.
17271 */
17272
17273
17274 getDeclaredVariables(node) {
17275 return this.__declaredVariables.get(node) || [];
17276 }
17277 /**
17278 * acquire scope from node.
17279 * @method ScopeManager#acquire
17280 * @param {Espree.Node} node - node for the acquired scope.
17281 * @param {boolean=} inner - look up the most inner scope, default value is false.
17282 * @returns {Scope?} Scope from node
17283 */
17284
17285
17286 acquire(node, inner) {
17287 /**
17288 * predicate
17289 * @param {Scope} testScope - scope to test
17290 * @returns {boolean} predicate
17291 */
17292 function predicate(testScope) {
17293 if (testScope.type === "function" && testScope.functionExpressionScope) {
17294 return false;
17295 }
17296
17297 return true;
17298 }
17299
17300 const scopes = this.__get(node);
17301
17302 if (!scopes || scopes.length === 0) {
17303 return null;
17304 } // Heuristic selection from all scopes.
17305 // If you would like to get all scopes, please use ScopeManager#acquireAll.
17306
17307
17308 if (scopes.length === 1) {
17309 return scopes[0];
17310 }
17311
17312 if (inner) {
17313 for (let i = scopes.length - 1; i >= 0; --i) {
17314 const scope = scopes[i];
17315
17316 if (predicate(scope)) {
17317 return scope;
17318 }
17319 }
17320 } else {
17321 for (let i = 0, iz = scopes.length; i < iz; ++i) {
17322 const scope = scopes[i];
17323
17324 if (predicate(scope)) {
17325 return scope;
17326 }
17327 }
17328 }
17329
17330 return null;
17331 }
17332 /**
17333 * acquire all scopes from node.
17334 * @method ScopeManager#acquireAll
17335 * @param {Espree.Node} node - node for the acquired scope.
17336 * @returns {Scopes?} Scope array
17337 */
17338
17339
17340 acquireAll(node) {
17341 return this.__get(node);
17342 }
17343 /**
17344 * release the node.
17345 * @method ScopeManager#release
17346 * @param {Espree.Node} node - releasing node.
17347 * @param {boolean=} inner - look up the most inner scope, default value is false.
17348 * @returns {Scope?} upper scope for the node.
17349 */
17350
17351
17352 release(node, inner) {
17353 const scopes = this.__get(node);
17354
17355 if (scopes && scopes.length) {
17356 const scope = scopes[0].upper;
17357
17358 if (!scope) {
17359 return null;
17360 }
17361
17362 return this.acquire(scope.block, inner);
17363 }
17364
17365 return null;
17366 }
17367
17368 attach() {} // eslint-disable-line class-methods-use-this
17369
17370
17371 detach() {} // eslint-disable-line class-methods-use-this
17372
17373
17374 __nestScope(scope) {
17375 if (scope instanceof GlobalScope) {
17376 assert(this.__currentScope === null);
17377 this.globalScope = scope;
17378 }
17379
17380 this.__currentScope = scope;
17381 return scope;
17382 }
17383
17384 __nestGlobalScope(node) {
17385 return this.__nestScope(new GlobalScope(this, node));
17386 }
17387
17388 __nestBlockScope(node) {
17389 return this.__nestScope(new BlockScope(this, this.__currentScope, node));
17390 }
17391
17392 __nestFunctionScope(node, isMethodDefinition) {
17393 return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition));
17394 }
17395
17396 __nestForScope(node) {
17397 return this.__nestScope(new ForScope(this, this.__currentScope, node));
17398 }
17399
17400 __nestCatchScope(node) {
17401 return this.__nestScope(new CatchScope(this, this.__currentScope, node));
17402 }
17403
17404 __nestWithScope(node) {
17405 return this.__nestScope(new WithScope(this, this.__currentScope, node));
17406 }
17407
17408 __nestClassScope(node) {
17409 return this.__nestScope(new ClassScope(this, this.__currentScope, node));
17410 }
17411
17412 __nestSwitchScope(node) {
17413 return this.__nestScope(new SwitchScope(this, this.__currentScope, node));
17414 }
17415
17416 __nestModuleScope(node) {
17417 return this.__nestScope(new ModuleScope(this, this.__currentScope, node));
17418 }
17419
17420 __nestFunctionExpressionNameScope(node) {
17421 return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node));
17422 }
17423
17424 __isES6() {
17425 return this.__options.ecmaVersion >= 6;
17426 }
17427
17428}
17429
17430module.exports = ScopeManager;
17431/* vim: set sw=4 ts=4 et tw=80 : */
17432
17433/***/ }),
17434/* 381 */
17435/***/ (function(module, exports, __webpack_require__) {
17436
17437"use strict";
17438/*
17439 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
17440
17441 Redistribution and use in source and binary forms, with or without
17442 modification, are permitted provided that the following conditions are met:
17443
17444 * Redistributions of source code must retain the above copyright
17445 notice, this list of conditions and the following disclaimer.
17446 * Redistributions in binary form must reproduce the above copyright
17447 notice, this list of conditions and the following disclaimer in the
17448 documentation and/or other materials provided with the distribution.
17449
17450 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17451 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17452 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17453 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
17454 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17455 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
17456 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
17457 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
17458 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
17459 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17460*/
17461
17462/* eslint-disable no-underscore-dangle */
17463
17464/* eslint-disable no-undefined */
17465
17466const Syntax = __webpack_require__(382).Syntax;
17467
17468const Reference = __webpack_require__(384);
17469
17470const Variable = __webpack_require__(385);
17471
17472const Definition = __webpack_require__(386).Definition;
17473
17474const assert = __webpack_require__(379);
17475/**
17476 * Test if scope is struct
17477 * @param {Scope} scope - scope
17478 * @param {Block} block - block
17479 * @param {boolean} isMethodDefinition - is method definiton
17480 * @param {boolean} useDirective - use directive
17481 * @returns {boolean} is strict scope
17482 */
17483
17484
17485function isStrictScope(scope, block, isMethodDefinition, useDirective) {
17486 let body; // When upper scope is exists and strict, inner scope is also strict.
17487
17488 if (scope.upper && scope.upper.isStrict) {
17489 return true;
17490 }
17491
17492 if (isMethodDefinition) {
17493 return true;
17494 }
17495
17496 if (scope.type === "class" || scope.type === "module") {
17497 return true;
17498 }
17499
17500 if (scope.type === "block" || scope.type === "switch") {
17501 return false;
17502 }
17503
17504 if (scope.type === "function") {
17505 if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) {
17506 return false;
17507 }
17508
17509 if (block.type === Syntax.Program) {
17510 body = block;
17511 } else {
17512 body = block.body;
17513 }
17514
17515 if (!body) {
17516 return false;
17517 }
17518 } else if (scope.type === "global") {
17519 body = block;
17520 } else {
17521 return false;
17522 } // Search 'use strict' directive.
17523
17524
17525 if (useDirective) {
17526 for (let i = 0, iz = body.body.length; i < iz; ++i) {
17527 const stmt = body.body[i];
17528
17529 if (stmt.type !== Syntax.DirectiveStatement) {
17530 break;
17531 }
17532
17533 if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") {
17534 return true;
17535 }
17536 }
17537 } else {
17538 for (let i = 0, iz = body.body.length; i < iz; ++i) {
17539 const stmt = body.body[i];
17540
17541 if (stmt.type !== Syntax.ExpressionStatement) {
17542 break;
17543 }
17544
17545 const expr = stmt.expression;
17546
17547 if (expr.type !== Syntax.Literal || typeof expr.value !== "string") {
17548 break;
17549 }
17550
17551 if (expr.raw !== null && expr.raw !== undefined) {
17552 if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") {
17553 return true;
17554 }
17555 } else {
17556 if (expr.value === "use strict") {
17557 return true;
17558 }
17559 }
17560 }
17561 }
17562
17563 return false;
17564}
17565/**
17566 * Register scope
17567 * @param {ScopeManager} scopeManager - scope manager
17568 * @param {Scope} scope - scope
17569 * @returns {void}
17570 */
17571
17572
17573function registerScope(scopeManager, scope) {
17574 scopeManager.scopes.push(scope);
17575
17576 const scopes = scopeManager.__nodeToScope.get(scope.block);
17577
17578 if (scopes) {
17579 scopes.push(scope);
17580 } else {
17581 scopeManager.__nodeToScope.set(scope.block, [scope]);
17582 }
17583}
17584/**
17585 * Should be statically
17586 * @param {Object} def - def
17587 * @returns {boolean} should be statically
17588 */
17589
17590
17591function shouldBeStatically(def) {
17592 return def.type === Variable.ClassName || def.type === Variable.Variable && def.parent.kind !== "var";
17593}
17594/**
17595 * @class Scope
17596 */
17597
17598
17599class Scope {
17600 constructor(scopeManager, type, upperScope, block, isMethodDefinition) {
17601 /**
17602 * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'.
17603 * @member {String} Scope#type
17604 */
17605 this.type = type;
17606 /**
17607 * The scoped {@link Variable}s of this scope, as <code>{ Variable.name
17608 * : Variable }</code>.
17609 * @member {Map} Scope#set
17610 */
17611
17612 this.set = new Map();
17613 /**
17614 * The tainted variables of this scope, as <code>{ Variable.name :
17615 * boolean }</code>.
17616 * @member {Map} Scope#taints */
17617
17618 this.taints = new Map();
17619 /**
17620 * Generally, through the lexical scoping of JS you can always know
17621 * which variable an identifier in the source code refers to. There are
17622 * a few exceptions to this rule. With 'global' and 'with' scopes you
17623 * can only decide at runtime which variable a reference refers to.
17624 * Moreover, if 'eval()' is used in a scope, it might introduce new
17625 * bindings in this or its parent scopes.
17626 * All those scopes are considered 'dynamic'.
17627 * @member {boolean} Scope#dynamic
17628 */
17629
17630 this.dynamic = this.type === "global" || this.type === "with";
17631 /**
17632 * A reference to the scope-defining syntax node.
17633 * @member {espree.Node} Scope#block
17634 */
17635
17636 this.block = block;
17637 /**
17638 * The {@link Reference|references} that are not resolved with this scope.
17639 * @member {Reference[]} Scope#through
17640 */
17641
17642 this.through = [];
17643 /**
17644 * The scoped {@link Variable}s of this scope. In the case of a
17645 * 'function' scope this includes the automatic argument <em>arguments</em> as
17646 * its first element, as well as all further formal arguments.
17647 * @member {Variable[]} Scope#variables
17648 */
17649
17650 this.variables = [];
17651 /**
17652 * Any variable {@link Reference|reference} found in this scope. This
17653 * includes occurrences of local variables as well as variables from
17654 * parent scopes (including the global scope). For local variables
17655 * this also includes defining occurrences (like in a 'var' statement).
17656 * In a 'function' scope this does not include the occurrences of the
17657 * formal parameter in the parameter list.
17658 * @member {Reference[]} Scope#references
17659 */
17660
17661 this.references = [];
17662 /**
17663 * For 'global' and 'function' scopes, this is a self-reference. For
17664 * other scope types this is the <em>variableScope</em> value of the
17665 * parent scope.
17666 * @member {Scope} Scope#variableScope
17667 */
17668
17669 this.variableScope = this.type === "global" || this.type === "function" || this.type === "module" ? this : upperScope.variableScope;
17670 /**
17671 * Whether this scope is created by a FunctionExpression.
17672 * @member {boolean} Scope#functionExpressionScope
17673 */
17674
17675 this.functionExpressionScope = false;
17676 /**
17677 * Whether this is a scope that contains an 'eval()' invocation.
17678 * @member {boolean} Scope#directCallToEvalScope
17679 */
17680
17681 this.directCallToEvalScope = false;
17682 /**
17683 * @member {boolean} Scope#thisFound
17684 */
17685
17686 this.thisFound = false;
17687 this.__left = [];
17688 /**
17689 * Reference to the parent {@link Scope|scope}.
17690 * @member {Scope} Scope#upper
17691 */
17692
17693 this.upper = upperScope;
17694 /**
17695 * Whether 'use strict' is in effect in this scope.
17696 * @member {boolean} Scope#isStrict
17697 */
17698
17699 this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective());
17700 /**
17701 * List of nested {@link Scope}s.
17702 * @member {Scope[]} Scope#childScopes
17703 */
17704
17705 this.childScopes = [];
17706
17707 if (this.upper) {
17708 this.upper.childScopes.push(this);
17709 }
17710
17711 this.__declaredVariables = scopeManager.__declaredVariables;
17712 registerScope(scopeManager, this);
17713 }
17714
17715 __shouldStaticallyClose(scopeManager) {
17716 return !this.dynamic || scopeManager.__isOptimistic();
17717 }
17718
17719 __shouldStaticallyCloseForGlobal(ref) {
17720 // On global scope, let/const/class declarations should be resolved statically.
17721 const name = ref.identifier.name;
17722
17723 if (!this.set.has(name)) {
17724 return false;
17725 }
17726
17727 const variable = this.set.get(name);
17728 const defs = variable.defs;
17729 return defs.length > 0 && defs.every(shouldBeStatically);
17730 }
17731
17732 __staticCloseRef(ref) {
17733 if (!this.__resolve(ref)) {
17734 this.__delegateToUpperScope(ref);
17735 }
17736 }
17737
17738 __dynamicCloseRef(ref) {
17739 // notify all names are through to global
17740 let current = this;
17741
17742 do {
17743 current.through.push(ref);
17744 current = current.upper;
17745 } while (current);
17746 }
17747
17748 __globalCloseRef(ref) {
17749 // let/const/class declarations should be resolved statically.
17750 // others should be resolved dynamically.
17751 if (this.__shouldStaticallyCloseForGlobal(ref)) {
17752 this.__staticCloseRef(ref);
17753 } else {
17754 this.__dynamicCloseRef(ref);
17755 }
17756 }
17757
17758 __close(scopeManager) {
17759 let closeRef;
17760
17761 if (this.__shouldStaticallyClose(scopeManager)) {
17762 closeRef = this.__staticCloseRef;
17763 } else if (this.type !== "global") {
17764 closeRef = this.__dynamicCloseRef;
17765 } else {
17766 closeRef = this.__globalCloseRef;
17767 } // Try Resolving all references in this scope.
17768
17769
17770 for (let i = 0, iz = this.__left.length; i < iz; ++i) {
17771 const ref = this.__left[i];
17772 closeRef.call(this, ref);
17773 }
17774
17775 this.__left = null;
17776 return this.upper;
17777 } // To override by function scopes.
17778 // References in default parameters isn't resolved to variables which are in their function body.
17779
17780
17781 __isValidResolution(ref, variable) {
17782 // eslint-disable-line class-methods-use-this, no-unused-vars
17783 return true;
17784 }
17785
17786 __resolve(ref) {
17787 const name = ref.identifier.name;
17788
17789 if (!this.set.has(name)) {
17790 return false;
17791 }
17792
17793 const variable = this.set.get(name);
17794
17795 if (!this.__isValidResolution(ref, variable)) {
17796 return false;
17797 }
17798
17799 variable.references.push(ref);
17800 variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
17801
17802 if (ref.tainted) {
17803 variable.tainted = true;
17804 this.taints.set(variable.name, true);
17805 }
17806
17807 ref.resolved = variable;
17808 return true;
17809 }
17810
17811 __delegateToUpperScope(ref) {
17812 if (this.upper) {
17813 this.upper.__left.push(ref);
17814 }
17815
17816 this.through.push(ref);
17817 }
17818
17819 __addDeclaredVariablesOfNode(variable, node) {
17820 if (node === null || node === undefined) {
17821 return;
17822 }
17823
17824 let variables = this.__declaredVariables.get(node);
17825
17826 if (variables === null || variables === undefined) {
17827 variables = [];
17828
17829 this.__declaredVariables.set(node, variables);
17830 }
17831
17832 if (variables.indexOf(variable) === -1) {
17833 variables.push(variable);
17834 }
17835 }
17836
17837 __defineGeneric(name, set, variables, node, def) {
17838 let variable;
17839 variable = set.get(name);
17840
17841 if (!variable) {
17842 variable = new Variable(name, this);
17843 set.set(name, variable);
17844 variables.push(variable);
17845 }
17846
17847 if (def) {
17848 variable.defs.push(def);
17849
17850 this.__addDeclaredVariablesOfNode(variable, def.node);
17851
17852 this.__addDeclaredVariablesOfNode(variable, def.parent);
17853 }
17854
17855 if (node) {
17856 variable.identifiers.push(node);
17857 }
17858 }
17859
17860 __define(node, def) {
17861 if (node && node.type === Syntax.Identifier) {
17862 this.__defineGeneric(node.name, this.set, this.variables, node, def);
17863 }
17864 }
17865
17866 __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
17867 // because Array element may be null
17868 if (!node || node.type !== Syntax.Identifier) {
17869 return;
17870 } // Specially handle like `this`.
17871
17872
17873 if (node.name === "super") {
17874 return;
17875 }
17876
17877 const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
17878 this.references.push(ref);
17879
17880 this.__left.push(ref);
17881 }
17882
17883 __detectEval() {
17884 let current = this;
17885 this.directCallToEvalScope = true;
17886
17887 do {
17888 current.dynamic = true;
17889 current = current.upper;
17890 } while (current);
17891 }
17892
17893 __detectThis() {
17894 this.thisFound = true;
17895 }
17896
17897 __isClosed() {
17898 return this.__left === null;
17899 }
17900 /**
17901 * returns resolved {Reference}
17902 * @method Scope#resolve
17903 * @param {Espree.Identifier} ident - identifier to be resolved.
17904 * @returns {Reference} reference
17905 */
17906
17907
17908 resolve(ident) {
17909 let ref, i, iz;
17910 assert(this.__isClosed(), "Scope should be closed.");
17911 assert(ident.type === Syntax.Identifier, "Target should be identifier.");
17912
17913 for (i = 0, iz = this.references.length; i < iz; ++i) {
17914 ref = this.references[i];
17915
17916 if (ref.identifier === ident) {
17917 return ref;
17918 }
17919 }
17920
17921 return null;
17922 }
17923 /**
17924 * returns this scope is static
17925 * @method Scope#isStatic
17926 * @returns {boolean} static
17927 */
17928
17929
17930 isStatic() {
17931 return !this.dynamic;
17932 }
17933 /**
17934 * returns this scope has materialized arguments
17935 * @method Scope#isArgumentsMaterialized
17936 * @returns {boolean} arguemnts materialized
17937 */
17938
17939
17940 isArgumentsMaterialized() {
17941 // eslint-disable-line class-methods-use-this
17942 return true;
17943 }
17944 /**
17945 * returns this scope has materialized `this` reference
17946 * @method Scope#isThisMaterialized
17947 * @returns {boolean} this materialized
17948 */
17949
17950
17951 isThisMaterialized() {
17952 // eslint-disable-line class-methods-use-this
17953 return true;
17954 }
17955
17956 isUsedName(name) {
17957 if (this.set.has(name)) {
17958 return true;
17959 }
17960
17961 for (let i = 0, iz = this.through.length; i < iz; ++i) {
17962 if (this.through[i].identifier.name === name) {
17963 return true;
17964 }
17965 }
17966
17967 return false;
17968 }
17969
17970}
17971
17972class GlobalScope extends Scope {
17973 constructor(scopeManager, block) {
17974 super(scopeManager, "global", null, block, false);
17975 this.implicit = {
17976 set: new Map(),
17977 variables: [],
17978
17979 /**
17980 * List of {@link Reference}s that are left to be resolved (i.e. which
17981 * need to be linked to the variable they refer to).
17982 * @member {Reference[]} Scope#implicit#left
17983 */
17984 left: []
17985 };
17986 }
17987
17988 __close(scopeManager) {
17989 const implicit = [];
17990
17991 for (let i = 0, iz = this.__left.length; i < iz; ++i) {
17992 const ref = this.__left[i];
17993
17994 if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
17995 implicit.push(ref.__maybeImplicitGlobal);
17996 }
17997 } // create an implicit global variable from assignment expression
17998
17999
18000 for (let i = 0, iz = implicit.length; i < iz; ++i) {
18001 const info = implicit[i];
18002
18003 this.__defineImplicit(info.pattern, new Definition(Variable.ImplicitGlobalVariable, info.pattern, info.node, null, null, null));
18004 }
18005
18006 this.implicit.left = this.__left;
18007 return super.__close(scopeManager);
18008 }
18009
18010 __defineImplicit(node, def) {
18011 if (node && node.type === Syntax.Identifier) {
18012 this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, def);
18013 }
18014 }
18015
18016}
18017
18018class ModuleScope extends Scope {
18019 constructor(scopeManager, upperScope, block) {
18020 super(scopeManager, "module", upperScope, block, false);
18021 }
18022
18023}
18024
18025class FunctionExpressionNameScope extends Scope {
18026 constructor(scopeManager, upperScope, block) {
18027 super(scopeManager, "function-expression-name", upperScope, block, false);
18028
18029 this.__define(block.id, new Definition(Variable.FunctionName, block.id, block, null, null, null));
18030
18031 this.functionExpressionScope = true;
18032 }
18033
18034}
18035
18036class CatchScope extends Scope {
18037 constructor(scopeManager, upperScope, block) {
18038 super(scopeManager, "catch", upperScope, block, false);
18039 }
18040
18041}
18042
18043class WithScope extends Scope {
18044 constructor(scopeManager, upperScope, block) {
18045 super(scopeManager, "with", upperScope, block, false);
18046 }
18047
18048 __close(scopeManager) {
18049 if (this.__shouldStaticallyClose(scopeManager)) {
18050 return super.__close(scopeManager);
18051 }
18052
18053 for (let i = 0, iz = this.__left.length; i < iz; ++i) {
18054 const ref = this.__left[i];
18055 ref.tainted = true;
18056
18057 this.__delegateToUpperScope(ref);
18058 }
18059
18060 this.__left = null;
18061 return this.upper;
18062 }
18063
18064}
18065
18066class BlockScope extends Scope {
18067 constructor(scopeManager, upperScope, block) {
18068 super(scopeManager, "block", upperScope, block, false);
18069 }
18070
18071}
18072
18073class SwitchScope extends Scope {
18074 constructor(scopeManager, upperScope, block) {
18075 super(scopeManager, "switch", upperScope, block, false);
18076 }
18077
18078}
18079
18080class FunctionScope extends Scope {
18081 constructor(scopeManager, upperScope, block, isMethodDefinition) {
18082 super(scopeManager, "function", upperScope, block, isMethodDefinition); // section 9.2.13, FunctionDeclarationInstantiation.
18083 // NOTE Arrow functions never have an arguments objects.
18084
18085 if (this.block.type !== Syntax.ArrowFunctionExpression) {
18086 this.__defineArguments();
18087 }
18088 }
18089
18090 isArgumentsMaterialized() {
18091 // TODO(Constellation)
18092 // We can more aggressive on this condition like this.
18093 //
18094 // function t() {
18095 // // arguments of t is always hidden.
18096 // function arguments() {
18097 // }
18098 // }
18099 if (this.block.type === Syntax.ArrowFunctionExpression) {
18100 return false;
18101 }
18102
18103 if (!this.isStatic()) {
18104 return true;
18105 }
18106
18107 const variable = this.set.get("arguments");
18108 assert(variable, "Always have arguments variable.");
18109 return variable.tainted || variable.references.length !== 0;
18110 }
18111
18112 isThisMaterialized() {
18113 if (!this.isStatic()) {
18114 return true;
18115 }
18116
18117 return this.thisFound;
18118 }
18119
18120 __defineArguments() {
18121 this.__defineGeneric("arguments", this.set, this.variables, null, null);
18122
18123 this.taints.set("arguments", true);
18124 } // References in default parameters isn't resolved to variables which are in their function body.
18125 // const x = 1
18126 // function f(a = x) { // This `x` is resolved to the `x` in the outer scope.
18127 // const x = 2
18128 // console.log(a)
18129 // }
18130
18131
18132 __isValidResolution(ref, variable) {
18133 // If `options.nodejsScope` is true, `this.block` becomes a Program node.
18134 if (this.block.type === "Program") {
18135 return true;
18136 }
18137
18138 const bodyStart = this.block.body.range[0]; // It's invalid resolution in the following case:
18139
18140 return !(variable.scope === this && ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.
18141 variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.
18142 );
18143 }
18144
18145}
18146
18147class ForScope extends Scope {
18148 constructor(scopeManager, upperScope, block) {
18149 super(scopeManager, "for", upperScope, block, false);
18150 }
18151
18152}
18153
18154class ClassScope extends Scope {
18155 constructor(scopeManager, upperScope, block) {
18156 super(scopeManager, "class", upperScope, block, false);
18157 }
18158
18159}
18160
18161module.exports = {
18162 Scope,
18163 GlobalScope,
18164 ModuleScope,
18165 FunctionExpressionNameScope,
18166 CatchScope,
18167 WithScope,
18168 BlockScope,
18169 SwitchScope,
18170 FunctionScope,
18171 ForScope,
18172 ClassScope
18173};
18174/* vim: set sw=4 ts=4 et tw=80 : */
18175
18176/***/ }),
18177/* 382 */
18178/***/ (function(module, exports, __webpack_require__) {
18179
18180/*
18181 Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
18182 Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
18183
18184 Redistribution and use in source and binary forms, with or without
18185 modification, are permitted provided that the following conditions are met:
18186
18187 * Redistributions of source code must retain the above copyright
18188 notice, this list of conditions and the following disclaimer.
18189 * Redistributions in binary form must reproduce the above copyright
18190 notice, this list of conditions and the following disclaimer in the
18191 documentation and/or other materials provided with the distribution.
18192
18193 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18194 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18195 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18196 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
18197 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18198 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
18199 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
18200 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
18201 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
18202 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
18203*/
18204
18205/*jslint vars:false, bitwise:true*/
18206
18207/*jshint indent:4*/
18208
18209/*global exports:true*/
18210(function clone(exports) {
18211 'use strict';
18212
18213 var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE;
18214
18215 function deepCopy(obj) {
18216 var ret = {},
18217 key,
18218 val;
18219
18220 for (key in obj) {
18221 if (obj.hasOwnProperty(key)) {
18222 val = obj[key];
18223
18224 if (typeof val === 'object' && val !== null) {
18225 ret[key] = deepCopy(val);
18226 } else {
18227 ret[key] = val;
18228 }
18229 }
18230 }
18231
18232 return ret;
18233 } // based on LLVM libc++ upper_bound / lower_bound
18234 // MIT License
18235
18236
18237 function upperBound(array, func) {
18238 var diff, len, i, current;
18239 len = array.length;
18240 i = 0;
18241
18242 while (len) {
18243 diff = len >>> 1;
18244 current = i + diff;
18245
18246 if (func(array[current])) {
18247 len = diff;
18248 } else {
18249 i = current + 1;
18250 len -= diff + 1;
18251 }
18252 }
18253
18254 return i;
18255 }
18256
18257 Syntax = {
18258 AssignmentExpression: 'AssignmentExpression',
18259 AssignmentPattern: 'AssignmentPattern',
18260 ArrayExpression: 'ArrayExpression',
18261 ArrayPattern: 'ArrayPattern',
18262 ArrowFunctionExpression: 'ArrowFunctionExpression',
18263 AwaitExpression: 'AwaitExpression',
18264 // CAUTION: It's deferred to ES7.
18265 BlockStatement: 'BlockStatement',
18266 BinaryExpression: 'BinaryExpression',
18267 BreakStatement: 'BreakStatement',
18268 CallExpression: 'CallExpression',
18269 CatchClause: 'CatchClause',
18270 ClassBody: 'ClassBody',
18271 ClassDeclaration: 'ClassDeclaration',
18272 ClassExpression: 'ClassExpression',
18273 ComprehensionBlock: 'ComprehensionBlock',
18274 // CAUTION: It's deferred to ES7.
18275 ComprehensionExpression: 'ComprehensionExpression',
18276 // CAUTION: It's deferred to ES7.
18277 ConditionalExpression: 'ConditionalExpression',
18278 ContinueStatement: 'ContinueStatement',
18279 DebuggerStatement: 'DebuggerStatement',
18280 DirectiveStatement: 'DirectiveStatement',
18281 DoWhileStatement: 'DoWhileStatement',
18282 EmptyStatement: 'EmptyStatement',
18283 ExportAllDeclaration: 'ExportAllDeclaration',
18284 ExportDefaultDeclaration: 'ExportDefaultDeclaration',
18285 ExportNamedDeclaration: 'ExportNamedDeclaration',
18286 ExportSpecifier: 'ExportSpecifier',
18287 ExpressionStatement: 'ExpressionStatement',
18288 ForStatement: 'ForStatement',
18289 ForInStatement: 'ForInStatement',
18290 ForOfStatement: 'ForOfStatement',
18291 FunctionDeclaration: 'FunctionDeclaration',
18292 FunctionExpression: 'FunctionExpression',
18293 GeneratorExpression: 'GeneratorExpression',
18294 // CAUTION: It's deferred to ES7.
18295 Identifier: 'Identifier',
18296 IfStatement: 'IfStatement',
18297 ImportExpression: 'ImportExpression',
18298 ImportDeclaration: 'ImportDeclaration',
18299 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
18300 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
18301 ImportSpecifier: 'ImportSpecifier',
18302 Literal: 'Literal',
18303 LabeledStatement: 'LabeledStatement',
18304 LogicalExpression: 'LogicalExpression',
18305 MemberExpression: 'MemberExpression',
18306 MetaProperty: 'MetaProperty',
18307 MethodDefinition: 'MethodDefinition',
18308 ModuleSpecifier: 'ModuleSpecifier',
18309 NewExpression: 'NewExpression',
18310 ObjectExpression: 'ObjectExpression',
18311 ObjectPattern: 'ObjectPattern',
18312 Program: 'Program',
18313 Property: 'Property',
18314 RestElement: 'RestElement',
18315 ReturnStatement: 'ReturnStatement',
18316 SequenceExpression: 'SequenceExpression',
18317 SpreadElement: 'SpreadElement',
18318 Super: 'Super',
18319 SwitchStatement: 'SwitchStatement',
18320 SwitchCase: 'SwitchCase',
18321 TaggedTemplateExpression: 'TaggedTemplateExpression',
18322 TemplateElement: 'TemplateElement',
18323 TemplateLiteral: 'TemplateLiteral',
18324 ThisExpression: 'ThisExpression',
18325 ThrowStatement: 'ThrowStatement',
18326 TryStatement: 'TryStatement',
18327 UnaryExpression: 'UnaryExpression',
18328 UpdateExpression: 'UpdateExpression',
18329 VariableDeclaration: 'VariableDeclaration',
18330 VariableDeclarator: 'VariableDeclarator',
18331 WhileStatement: 'WhileStatement',
18332 WithStatement: 'WithStatement',
18333 YieldExpression: 'YieldExpression'
18334 };
18335 VisitorKeys = {
18336 AssignmentExpression: ['left', 'right'],
18337 AssignmentPattern: ['left', 'right'],
18338 ArrayExpression: ['elements'],
18339 ArrayPattern: ['elements'],
18340 ArrowFunctionExpression: ['params', 'body'],
18341 AwaitExpression: ['argument'],
18342 // CAUTION: It's deferred to ES7.
18343 BlockStatement: ['body'],
18344 BinaryExpression: ['left', 'right'],
18345 BreakStatement: ['label'],
18346 CallExpression: ['callee', 'arguments'],
18347 CatchClause: ['param', 'body'],
18348 ClassBody: ['body'],
18349 ClassDeclaration: ['id', 'superClass', 'body'],
18350 ClassExpression: ['id', 'superClass', 'body'],
18351 ComprehensionBlock: ['left', 'right'],
18352 // CAUTION: It's deferred to ES7.
18353 ComprehensionExpression: ['blocks', 'filter', 'body'],
18354 // CAUTION: It's deferred to ES7.
18355 ConditionalExpression: ['test', 'consequent', 'alternate'],
18356 ContinueStatement: ['label'],
18357 DebuggerStatement: [],
18358 DirectiveStatement: [],
18359 DoWhileStatement: ['body', 'test'],
18360 EmptyStatement: [],
18361 ExportAllDeclaration: ['source'],
18362 ExportDefaultDeclaration: ['declaration'],
18363 ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
18364 ExportSpecifier: ['exported', 'local'],
18365 ExpressionStatement: ['expression'],
18366 ForStatement: ['init', 'test', 'update', 'body'],
18367 ForInStatement: ['left', 'right', 'body'],
18368 ForOfStatement: ['left', 'right', 'body'],
18369 FunctionDeclaration: ['id', 'params', 'body'],
18370 FunctionExpression: ['id', 'params', 'body'],
18371 GeneratorExpression: ['blocks', 'filter', 'body'],
18372 // CAUTION: It's deferred to ES7.
18373 Identifier: [],
18374 IfStatement: ['test', 'consequent', 'alternate'],
18375 ImportExpression: ['source'],
18376 ImportDeclaration: ['specifiers', 'source'],
18377 ImportDefaultSpecifier: ['local'],
18378 ImportNamespaceSpecifier: ['local'],
18379 ImportSpecifier: ['imported', 'local'],
18380 Literal: [],
18381 LabeledStatement: ['label', 'body'],
18382 LogicalExpression: ['left', 'right'],
18383 MemberExpression: ['object', 'property'],
18384 MetaProperty: ['meta', 'property'],
18385 MethodDefinition: ['key', 'value'],
18386 ModuleSpecifier: [],
18387 NewExpression: ['callee', 'arguments'],
18388 ObjectExpression: ['properties'],
18389 ObjectPattern: ['properties'],
18390 Program: ['body'],
18391 Property: ['key', 'value'],
18392 RestElement: ['argument'],
18393 ReturnStatement: ['argument'],
18394 SequenceExpression: ['expressions'],
18395 SpreadElement: ['argument'],
18396 Super: [],
18397 SwitchStatement: ['discriminant', 'cases'],
18398 SwitchCase: ['test', 'consequent'],
18399 TaggedTemplateExpression: ['tag', 'quasi'],
18400 TemplateElement: [],
18401 TemplateLiteral: ['quasis', 'expressions'],
18402 ThisExpression: [],
18403 ThrowStatement: ['argument'],
18404 TryStatement: ['block', 'handler', 'finalizer'],
18405 UnaryExpression: ['argument'],
18406 UpdateExpression: ['argument'],
18407 VariableDeclaration: ['declarations'],
18408 VariableDeclarator: ['id', 'init'],
18409 WhileStatement: ['test', 'body'],
18410 WithStatement: ['object', 'body'],
18411 YieldExpression: ['argument']
18412 }; // unique id
18413
18414 BREAK = {};
18415 SKIP = {};
18416 REMOVE = {};
18417 VisitorOption = {
18418 Break: BREAK,
18419 Skip: SKIP,
18420 Remove: REMOVE
18421 };
18422
18423 function Reference(parent, key) {
18424 this.parent = parent;
18425 this.key = key;
18426 }
18427
18428 Reference.prototype.replace = function replace(node) {
18429 this.parent[this.key] = node;
18430 };
18431
18432 Reference.prototype.remove = function remove() {
18433 if (Array.isArray(this.parent)) {
18434 this.parent.splice(this.key, 1);
18435 return true;
18436 } else {
18437 this.replace(null);
18438 return false;
18439 }
18440 };
18441
18442 function Element(node, path, wrap, ref) {
18443 this.node = node;
18444 this.path = path;
18445 this.wrap = wrap;
18446 this.ref = ref;
18447 }
18448
18449 function Controller() {} // API:
18450 // return property path array from root to current node
18451
18452
18453 Controller.prototype.path = function path() {
18454 var i, iz, j, jz, result, element;
18455
18456 function addToPath(result, path) {
18457 if (Array.isArray(path)) {
18458 for (j = 0, jz = path.length; j < jz; ++j) {
18459 result.push(path[j]);
18460 }
18461 } else {
18462 result.push(path);
18463 }
18464 } // root node
18465
18466
18467 if (!this.__current.path) {
18468 return null;
18469 } // first node is sentinel, second node is root element
18470
18471
18472 result = [];
18473
18474 for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
18475 element = this.__leavelist[i];
18476 addToPath(result, element.path);
18477 }
18478
18479 addToPath(result, this.__current.path);
18480 return result;
18481 }; // API:
18482 // return type of current node
18483
18484
18485 Controller.prototype.type = function () {
18486 var node = this.current();
18487 return node.type || this.__current.wrap;
18488 }; // API:
18489 // return array of parent elements
18490
18491
18492 Controller.prototype.parents = function parents() {
18493 var i, iz, result; // first node is sentinel
18494
18495 result = [];
18496
18497 for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
18498 result.push(this.__leavelist[i].node);
18499 }
18500
18501 return result;
18502 }; // API:
18503 // return current node
18504
18505
18506 Controller.prototype.current = function current() {
18507 return this.__current.node;
18508 };
18509
18510 Controller.prototype.__execute = function __execute(callback, element) {
18511 var previous, result;
18512 result = undefined;
18513 previous = this.__current;
18514 this.__current = element;
18515 this.__state = null;
18516
18517 if (callback) {
18518 result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
18519 }
18520
18521 this.__current = previous;
18522 return result;
18523 }; // API:
18524 // notify control skip / break
18525
18526
18527 Controller.prototype.notify = function notify(flag) {
18528 this.__state = flag;
18529 }; // API:
18530 // skip child nodes of current node
18531
18532
18533 Controller.prototype.skip = function () {
18534 this.notify(SKIP);
18535 }; // API:
18536 // break traversals
18537
18538
18539 Controller.prototype['break'] = function () {
18540 this.notify(BREAK);
18541 }; // API:
18542 // remove node
18543
18544
18545 Controller.prototype.remove = function () {
18546 this.notify(REMOVE);
18547 };
18548
18549 Controller.prototype.__initialize = function (root, visitor) {
18550 this.visitor = visitor;
18551 this.root = root;
18552 this.__worklist = [];
18553 this.__leavelist = [];
18554 this.__current = null;
18555 this.__state = null;
18556 this.__fallback = null;
18557
18558 if (visitor.fallback === 'iteration') {
18559 this.__fallback = Object.keys;
18560 } else if (typeof visitor.fallback === 'function') {
18561 this.__fallback = visitor.fallback;
18562 }
18563
18564 this.__keys = VisitorKeys;
18565
18566 if (visitor.keys) {
18567 this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);
18568 }
18569 };
18570
18571 function isNode(node) {
18572 if (node == null) {
18573 return false;
18574 }
18575
18576 return typeof node === 'object' && typeof node.type === 'string';
18577 }
18578
18579 function isProperty(nodeType, key) {
18580 return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
18581 }
18582
18583 Controller.prototype.traverse = function traverse(root, visitor) {
18584 var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel;
18585
18586 this.__initialize(root, visitor);
18587
18588 sentinel = {}; // reference
18589
18590 worklist = this.__worklist;
18591 leavelist = this.__leavelist; // initialize
18592
18593 worklist.push(new Element(root, null, null, null));
18594 leavelist.push(new Element(null, null, null, null));
18595
18596 while (worklist.length) {
18597 element = worklist.pop();
18598
18599 if (element === sentinel) {
18600 element = leavelist.pop();
18601 ret = this.__execute(visitor.leave, element);
18602
18603 if (this.__state === BREAK || ret === BREAK) {
18604 return;
18605 }
18606
18607 continue;
18608 }
18609
18610 if (element.node) {
18611 ret = this.__execute(visitor.enter, element);
18612
18613 if (this.__state === BREAK || ret === BREAK) {
18614 return;
18615 }
18616
18617 worklist.push(sentinel);
18618 leavelist.push(element);
18619
18620 if (this.__state === SKIP || ret === SKIP) {
18621 continue;
18622 }
18623
18624 node = element.node;
18625 nodeType = node.type || element.wrap;
18626 candidates = this.__keys[nodeType];
18627
18628 if (!candidates) {
18629 if (this.__fallback) {
18630 candidates = this.__fallback(node);
18631 } else {
18632 throw new Error('Unknown node type ' + nodeType + '.');
18633 }
18634 }
18635
18636 current = candidates.length;
18637
18638 while ((current -= 1) >= 0) {
18639 key = candidates[current];
18640 candidate = node[key];
18641
18642 if (!candidate) {
18643 continue;
18644 }
18645
18646 if (Array.isArray(candidate)) {
18647 current2 = candidate.length;
18648
18649 while ((current2 -= 1) >= 0) {
18650 if (!candidate[current2]) {
18651 continue;
18652 }
18653
18654 if (isProperty(nodeType, candidates[current])) {
18655 element = new Element(candidate[current2], [key, current2], 'Property', null);
18656 } else if (isNode(candidate[current2])) {
18657 element = new Element(candidate[current2], [key, current2], null, null);
18658 } else {
18659 continue;
18660 }
18661
18662 worklist.push(element);
18663 }
18664 } else if (isNode(candidate)) {
18665 worklist.push(new Element(candidate, key, null, null));
18666 }
18667 }
18668 }
18669 }
18670 };
18671
18672 Controller.prototype.replace = function replace(root, visitor) {
18673 var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key;
18674
18675 function removeElem(element) {
18676 var i, key, nextElem, parent;
18677
18678 if (element.ref.remove()) {
18679 // When the reference is an element of an array.
18680 key = element.ref.key;
18681 parent = element.ref.parent; // If removed from array, then decrease following items' keys.
18682
18683 i = worklist.length;
18684
18685 while (i--) {
18686 nextElem = worklist[i];
18687
18688 if (nextElem.ref && nextElem.ref.parent === parent) {
18689 if (nextElem.ref.key < key) {
18690 break;
18691 }
18692
18693 --nextElem.ref.key;
18694 }
18695 }
18696 }
18697 }
18698
18699 this.__initialize(root, visitor);
18700
18701 sentinel = {}; // reference
18702
18703 worklist = this.__worklist;
18704 leavelist = this.__leavelist; // initialize
18705
18706 outer = {
18707 root: root
18708 };
18709 element = new Element(root, null, null, new Reference(outer, 'root'));
18710 worklist.push(element);
18711 leavelist.push(element);
18712
18713 while (worklist.length) {
18714 element = worklist.pop();
18715
18716 if (element === sentinel) {
18717 element = leavelist.pop();
18718 target = this.__execute(visitor.leave, element); // node may be replaced with null,
18719 // so distinguish between undefined and null in this place
18720
18721 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
18722 // replace
18723 element.ref.replace(target);
18724 }
18725
18726 if (this.__state === REMOVE || target === REMOVE) {
18727 removeElem(element);
18728 }
18729
18730 if (this.__state === BREAK || target === BREAK) {
18731 return outer.root;
18732 }
18733
18734 continue;
18735 }
18736
18737 target = this.__execute(visitor.enter, element); // node may be replaced with null,
18738 // so distinguish between undefined and null in this place
18739
18740 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
18741 // replace
18742 element.ref.replace(target);
18743 element.node = target;
18744 }
18745
18746 if (this.__state === REMOVE || target === REMOVE) {
18747 removeElem(element);
18748 element.node = null;
18749 }
18750
18751 if (this.__state === BREAK || target === BREAK) {
18752 return outer.root;
18753 } // node may be null
18754
18755
18756 node = element.node;
18757
18758 if (!node) {
18759 continue;
18760 }
18761
18762 worklist.push(sentinel);
18763 leavelist.push(element);
18764
18765 if (this.__state === SKIP || target === SKIP) {
18766 continue;
18767 }
18768
18769 nodeType = node.type || element.wrap;
18770 candidates = this.__keys[nodeType];
18771
18772 if (!candidates) {
18773 if (this.__fallback) {
18774 candidates = this.__fallback(node);
18775 } else {
18776 throw new Error('Unknown node type ' + nodeType + '.');
18777 }
18778 }
18779
18780 current = candidates.length;
18781
18782 while ((current -= 1) >= 0) {
18783 key = candidates[current];
18784 candidate = node[key];
18785
18786 if (!candidate) {
18787 continue;
18788 }
18789
18790 if (Array.isArray(candidate)) {
18791 current2 = candidate.length;
18792
18793 while ((current2 -= 1) >= 0) {
18794 if (!candidate[current2]) {
18795 continue;
18796 }
18797
18798 if (isProperty(nodeType, candidates[current])) {
18799 element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
18800 } else if (isNode(candidate[current2])) {
18801 element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
18802 } else {
18803 continue;
18804 }
18805
18806 worklist.push(element);
18807 }
18808 } else if (isNode(candidate)) {
18809 worklist.push(new Element(candidate, key, null, new Reference(node, key)));
18810 }
18811 }
18812 }
18813
18814 return outer.root;
18815 };
18816
18817 function traverse(root, visitor) {
18818 var controller = new Controller();
18819 return controller.traverse(root, visitor);
18820 }
18821
18822 function replace(root, visitor) {
18823 var controller = new Controller();
18824 return controller.replace(root, visitor);
18825 }
18826
18827 function extendCommentRange(comment, tokens) {
18828 var target;
18829 target = upperBound(tokens, function search(token) {
18830 return token.range[0] > comment.range[0];
18831 });
18832 comment.extendedRange = [comment.range[0], comment.range[1]];
18833
18834 if (target !== tokens.length) {
18835 comment.extendedRange[1] = tokens[target].range[0];
18836 }
18837
18838 target -= 1;
18839
18840 if (target >= 0) {
18841 comment.extendedRange[0] = tokens[target].range[1];
18842 }
18843
18844 return comment;
18845 }
18846
18847 function attachComments(tree, providedComments, tokens) {
18848 // At first, we should calculate extended comment ranges.
18849 var comments = [],
18850 comment,
18851 len,
18852 i,
18853 cursor;
18854
18855 if (!tree.range) {
18856 throw new Error('attachComments needs range information');
18857 } // tokens array is empty, we attach comments to tree as 'leadingComments'
18858
18859
18860 if (!tokens.length) {
18861 if (providedComments.length) {
18862 for (i = 0, len = providedComments.length; i < len; i += 1) {
18863 comment = deepCopy(providedComments[i]);
18864 comment.extendedRange = [0, tree.range[0]];
18865 comments.push(comment);
18866 }
18867
18868 tree.leadingComments = comments;
18869 }
18870
18871 return tree;
18872 }
18873
18874 for (i = 0, len = providedComments.length; i < len; i += 1) {
18875 comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
18876 } // This is based on John Freeman's implementation.
18877
18878
18879 cursor = 0;
18880 traverse(tree, {
18881 enter: function enter(node) {
18882 var comment;
18883
18884 while (cursor < comments.length) {
18885 comment = comments[cursor];
18886
18887 if (comment.extendedRange[1] > node.range[0]) {
18888 break;
18889 }
18890
18891 if (comment.extendedRange[1] === node.range[0]) {
18892 if (!node.leadingComments) {
18893 node.leadingComments = [];
18894 }
18895
18896 node.leadingComments.push(comment);
18897 comments.splice(cursor, 1);
18898 } else {
18899 cursor += 1;
18900 }
18901 } // already out of owned node
18902
18903
18904 if (cursor === comments.length) {
18905 return VisitorOption.Break;
18906 }
18907
18908 if (comments[cursor].extendedRange[0] > node.range[1]) {
18909 return VisitorOption.Skip;
18910 }
18911 }
18912 });
18913 cursor = 0;
18914 traverse(tree, {
18915 leave: function leave(node) {
18916 var comment;
18917
18918 while (cursor < comments.length) {
18919 comment = comments[cursor];
18920
18921 if (node.range[1] < comment.extendedRange[0]) {
18922 break;
18923 }
18924
18925 if (node.range[1] === comment.extendedRange[0]) {
18926 if (!node.trailingComments) {
18927 node.trailingComments = [];
18928 }
18929
18930 node.trailingComments.push(comment);
18931 comments.splice(cursor, 1);
18932 } else {
18933 cursor += 1;
18934 }
18935 } // already out of owned node
18936
18937
18938 if (cursor === comments.length) {
18939 return VisitorOption.Break;
18940 }
18941
18942 if (comments[cursor].extendedRange[0] > node.range[1]) {
18943 return VisitorOption.Skip;
18944 }
18945 }
18946 });
18947 return tree;
18948 }
18949
18950 exports.version = __webpack_require__(383).version;
18951 exports.Syntax = Syntax;
18952 exports.traverse = traverse;
18953 exports.replace = replace;
18954 exports.attachComments = attachComments;
18955 exports.VisitorKeys = VisitorKeys;
18956 exports.VisitorOption = VisitorOption;
18957 exports.Controller = Controller;
18958
18959 exports.cloneEnvironment = function () {
18960 return clone({});
18961 };
18962
18963 return exports;
18964})(exports);
18965/* vim: set sw=4 ts=4 et tw=80 : */
18966
18967/***/ }),
18968/* 383 */
18969/***/ (function(module) {
18970
6a5a0f88 18971module.exports = JSON.parse("{\"_from\":\"estraverse@^4.1.1\",\"_id\":\"estraverse@4.3.0\",\"_inBundle\":false,\"_integrity\":\"sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==\",\"_location\":\"/estraverse\",\"_phantomChildren\":{},\"_requested\":{\"type\":\"range\",\"registry\":true,\"raw\":\"estraverse@^4.1.1\",\"name\":\"estraverse\",\"escapedName\":\"estraverse\",\"rawSpec\":\"^4.1.1\",\"saveSpec\":null,\"fetchSpec\":\"^4.1.1\"},\"_requiredBy\":[\"/babel-eslint/eslint-scope\",\"/eslint-scope\",\"/esrecurse\",\"/webpack/eslint-scope\"],\"_resolved\":\"https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz\",\"_shasum\":\"398ad3f3c5a24948be7725e83d11a7de28cdbd1d\",\"_spec\":\"estraverse@^4.1.1\",\"_where\":\"/root/sources/pve/pve-eslint/eslint-v7.1.0/node_modules/eslint-scope\",\"bugs\":{\"url\":\"https://github.com/estools/estraverse/issues\"},\"bundleDependencies\":false,\"deprecated\":false,\"description\":\"ECMAScript JS AST traversal functions\",\"devDependencies\":{\"babel-preset-env\":\"^1.6.1\",\"babel-register\":\"^6.3.13\",\"chai\":\"^2.1.1\",\"espree\":\"^1.11.0\",\"gulp\":\"^3.8.10\",\"gulp-bump\":\"^0.2.2\",\"gulp-filter\":\"^2.0.0\",\"gulp-git\":\"^1.0.1\",\"gulp-tag-version\":\"^1.3.0\",\"jshint\":\"^2.5.6\",\"mocha\":\"^2.1.0\"},\"engines\":{\"node\":\">=4.0\"},\"homepage\":\"https://github.com/estools/estraverse\",\"license\":\"BSD-2-Clause\",\"main\":\"estraverse.js\",\"maintainers\":[{\"name\":\"Yusuke Suzuki\",\"email\":\"utatane.tea@gmail.com\",\"url\":\"http://github.com/Constellation\"}],\"name\":\"estraverse\",\"repository\":{\"type\":\"git\",\"url\":\"git+ssh://git@github.com/estools/estraverse.git\"},\"scripts\":{\"lint\":\"jshint estraverse.js\",\"test\":\"npm run-script lint && npm run-script unit-test\",\"unit-test\":\"mocha --compilers js:babel-register\"},\"version\":\"4.3.0\"}");
eb39fafa
DC
18972
18973/***/ }),
18974/* 384 */
18975/***/ (function(module, exports, __webpack_require__) {
18976
18977"use strict";
18978/*
18979 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
18980
18981 Redistribution and use in source and binary forms, with or without
18982 modification, are permitted provided that the following conditions are met:
18983
18984 * Redistributions of source code must retain the above copyright
18985 notice, this list of conditions and the following disclaimer.
18986 * Redistributions in binary form must reproduce the above copyright
18987 notice, this list of conditions and the following disclaimer in the
18988 documentation and/or other materials provided with the distribution.
18989
18990 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18991 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18992 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18993 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
18994 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18995 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
18996 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
18997 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
18998 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
18999 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19000*/
19001
19002
19003const READ = 0x1;
19004const WRITE = 0x2;
19005const RW = READ | WRITE;
19006/**
19007 * A Reference represents a single occurrence of an identifier in code.
19008 * @class Reference
19009 */
19010
19011class Reference {
19012 constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) {
19013 /**
19014 * Identifier syntax node.
19015 * @member {espreeIdentifier} Reference#identifier
19016 */
19017 this.identifier = ident;
19018 /**
19019 * Reference to the enclosing Scope.
19020 * @member {Scope} Reference#from
19021 */
19022
19023 this.from = scope;
19024 /**
19025 * Whether the reference comes from a dynamic scope (such as 'eval',
19026 * 'with', etc.), and may be trapped by dynamic scopes.
19027 * @member {boolean} Reference#tainted
19028 */
19029
19030 this.tainted = false;
19031 /**
19032 * The variable this reference is resolved with.
19033 * @member {Variable} Reference#resolved
19034 */
19035
19036 this.resolved = null;
19037 /**
19038 * The read-write mode of the reference. (Value is one of {@link
19039 * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}).
19040 * @member {number} Reference#flag
19041 * @private
19042 */
19043
19044 this.flag = flag;
19045
19046 if (this.isWrite()) {
19047 /**
19048 * If reference is writeable, this is the tree being written to it.
19049 * @member {espreeNode} Reference#writeExpr
19050 */
19051 this.writeExpr = writeExpr;
19052 /**
19053 * Whether the Reference might refer to a partial value of writeExpr.
19054 * @member {boolean} Reference#partial
19055 */
19056
19057 this.partial = partial;
19058 /**
19059 * Whether the Reference is to write of initialization.
19060 * @member {boolean} Reference#init
19061 */
19062
19063 this.init = init;
19064 }
19065
19066 this.__maybeImplicitGlobal = maybeImplicitGlobal;
19067 }
19068 /**
19069 * Whether the reference is static.
19070 * @method Reference#isStatic
19071 * @returns {boolean} static
19072 */
19073
19074
19075 isStatic() {
19076 return !this.tainted && this.resolved && this.resolved.scope.isStatic();
19077 }
19078 /**
19079 * Whether the reference is writeable.
19080 * @method Reference#isWrite
19081 * @returns {boolean} write
19082 */
19083
19084
19085 isWrite() {
19086 return !!(this.flag & Reference.WRITE);
19087 }
19088 /**
19089 * Whether the reference is readable.
19090 * @method Reference#isRead
19091 * @returns {boolean} read
19092 */
19093
19094
19095 isRead() {
19096 return !!(this.flag & Reference.READ);
19097 }
19098 /**
19099 * Whether the reference is read-only.
19100 * @method Reference#isReadOnly
19101 * @returns {boolean} read only
19102 */
19103
19104
19105 isReadOnly() {
19106 return this.flag === Reference.READ;
19107 }
19108 /**
19109 * Whether the reference is write-only.
19110 * @method Reference#isWriteOnly
19111 * @returns {boolean} write only
19112 */
19113
19114
19115 isWriteOnly() {
19116 return this.flag === Reference.WRITE;
19117 }
19118 /**
19119 * Whether the reference is read-write.
19120 * @method Reference#isReadWrite
19121 * @returns {boolean} read write
19122 */
19123
19124
19125 isReadWrite() {
19126 return this.flag === Reference.RW;
19127 }
19128
19129}
19130/**
19131 * @constant Reference.READ
19132 * @private
19133 */
19134
19135
19136Reference.READ = READ;
19137/**
19138 * @constant Reference.WRITE
19139 * @private
19140 */
19141
19142Reference.WRITE = WRITE;
19143/**
19144 * @constant Reference.RW
19145 * @private
19146 */
19147
19148Reference.RW = RW;
19149module.exports = Reference;
19150/* vim: set sw=4 ts=4 et tw=80 : */
19151
19152/***/ }),
19153/* 385 */
19154/***/ (function(module, exports, __webpack_require__) {
19155
19156"use strict";
19157/*
19158 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
19159
19160 Redistribution and use in source and binary forms, with or without
19161 modification, are permitted provided that the following conditions are met:
19162
19163 * Redistributions of source code must retain the above copyright
19164 notice, this list of conditions and the following disclaimer.
19165 * Redistributions in binary form must reproduce the above copyright
19166 notice, this list of conditions and the following disclaimer in the
19167 documentation and/or other materials provided with the distribution.
19168
19169 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19170 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19171 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19172 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
19173 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19174 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19175 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19176 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
19177 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
19178 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19179*/
19180
19181/**
19182 * A Variable represents a locally scoped identifier. These include arguments to
19183 * functions.
19184 * @class Variable
19185 */
19186
19187class Variable {
19188 constructor(name, scope) {
19189 /**
19190 * The variable name, as given in the source code.
19191 * @member {String} Variable#name
19192 */
19193 this.name = name;
19194 /**
19195 * List of defining occurrences of this variable (like in 'var ...'
19196 * statements or as parameter), as AST nodes.
19197 * @member {espree.Identifier[]} Variable#identifiers
19198 */
19199
19200 this.identifiers = [];
19201 /**
19202 * List of {@link Reference|references} of this variable (excluding parameter entries)
19203 * in its defining scope and all nested scopes. For defining
19204 * occurrences only see {@link Variable#defs}.
19205 * @member {Reference[]} Variable#references
19206 */
19207
19208 this.references = [];
19209 /**
19210 * List of defining occurrences of this variable (like in 'var ...'
19211 * statements or as parameter), as custom objects.
19212 * @member {Definition[]} Variable#defs
19213 */
19214
19215 this.defs = [];
19216 this.tainted = false;
19217 /**
19218 * Whether this is a stack variable.
19219 * @member {boolean} Variable#stack
19220 */
19221
19222 this.stack = true;
19223 /**
19224 * Reference to the enclosing Scope.
19225 * @member {Scope} Variable#scope
19226 */
19227
19228 this.scope = scope;
19229 }
19230
19231}
19232
19233Variable.CatchClause = "CatchClause";
19234Variable.Parameter = "Parameter";
19235Variable.FunctionName = "FunctionName";
19236Variable.ClassName = "ClassName";
19237Variable.Variable = "Variable";
19238Variable.ImportBinding = "ImportBinding";
19239Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable";
19240module.exports = Variable;
19241/* vim: set sw=4 ts=4 et tw=80 : */
19242
19243/***/ }),
19244/* 386 */
19245/***/ (function(module, exports, __webpack_require__) {
19246
19247"use strict";
19248/*
19249 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
19250
19251 Redistribution and use in source and binary forms, with or without
19252 modification, are permitted provided that the following conditions are met:
19253
19254 * Redistributions of source code must retain the above copyright
19255 notice, this list of conditions and the following disclaimer.
19256 * Redistributions in binary form must reproduce the above copyright
19257 notice, this list of conditions and the following disclaimer in the
19258 documentation and/or other materials provided with the distribution.
19259
19260 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19261 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19262 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19263 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
19264 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19265 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19266 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19267 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
19268 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
19269 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19270*/
19271
19272
19273const Variable = __webpack_require__(385);
19274/**
19275 * @class Definition
19276 */
19277
19278
19279class Definition {
19280 constructor(type, name, node, parent, index, kind) {
19281 /**
19282 * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...).
19283 */
19284 this.type = type;
19285 /**
19286 * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence.
19287 */
19288
19289 this.name = name;
19290 /**
19291 * @member {espree.Node} Definition#node - the enclosing node of the identifier.
19292 */
19293
19294 this.node = node;
19295 /**
19296 * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier.
19297 */
19298
19299 this.parent = parent;
19300 /**
19301 * @member {Number?} Definition#index - the index in the declaration statement.
19302 */
19303
19304 this.index = index;
19305 /**
19306 * @member {String?} Definition#kind - the kind of the declaration statement.
19307 */
19308
19309 this.kind = kind;
19310 }
19311
19312}
19313/**
19314 * @class ParameterDefinition
19315 */
19316
19317
19318class ParameterDefinition extends Definition {
19319 constructor(name, node, index, rest) {
19320 super(Variable.Parameter, name, node, null, index, null);
19321 /**
19322 * Whether the parameter definition is a part of a rest parameter.
19323 * @member {boolean} ParameterDefinition#rest
19324 */
19325
19326 this.rest = rest;
19327 }
19328
19329}
19330
19331module.exports = {
19332 ParameterDefinition,
19333 Definition
19334};
19335/* vim: set sw=4 ts=4 et tw=80 : */
19336
19337/***/ }),
19338/* 387 */
19339/***/ (function(module, exports, __webpack_require__) {
19340
19341"use strict";
19342/*
19343 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
19344
19345 Redistribution and use in source and binary forms, with or without
19346 modification, are permitted provided that the following conditions are met:
19347
19348 * Redistributions of source code must retain the above copyright
19349 notice, this list of conditions and the following disclaimer.
19350 * Redistributions in binary form must reproduce the above copyright
19351 notice, this list of conditions and the following disclaimer in the
19352 documentation and/or other materials provided with the distribution.
19353
19354 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19355 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19356 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19357 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
19358 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19359 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19360 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19361 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
19362 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
19363 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19364*/
19365
19366/* eslint-disable no-underscore-dangle */
19367
19368/* eslint-disable no-undefined */
19369
19370const Syntax = __webpack_require__(382).Syntax;
19371
19372const esrecurse = __webpack_require__(388);
19373
19374const Reference = __webpack_require__(384);
19375
19376const Variable = __webpack_require__(385);
19377
19378const PatternVisitor = __webpack_require__(390);
19379
19380const definition = __webpack_require__(386);
19381
19382const assert = __webpack_require__(379);
19383
19384const ParameterDefinition = definition.ParameterDefinition;
19385const Definition = definition.Definition;
19386/**
19387 * Traverse identifier in pattern
19388 * @param {Object} options - options
19389 * @param {pattern} rootPattern - root pattern
19390 * @param {Refencer} referencer - referencer
19391 * @param {callback} callback - callback
19392 * @returns {void}
19393 */
19394
19395function traverseIdentifierInPattern(options, rootPattern, referencer, callback) {
19396 // Call the callback at left hand identifier nodes, and Collect right hand nodes.
19397 const visitor = new PatternVisitor(options, rootPattern, callback);
19398 visitor.visit(rootPattern); // Process the right hand nodes recursively.
19399
19400 if (referencer !== null && referencer !== undefined) {
19401 visitor.rightHandNodes.forEach(referencer.visit, referencer);
19402 }
19403} // Importing ImportDeclaration.
19404// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation
19405// https://github.com/estree/estree/blob/master/es6.md#importdeclaration
19406// FIXME: Now, we don't create module environment, because the context is
19407// implementation dependent.
19408
19409
19410class Importer extends esrecurse.Visitor {
19411 constructor(declaration, referencer) {
19412 super(null, referencer.options);
19413 this.declaration = declaration;
19414 this.referencer = referencer;
19415 }
19416
19417 visitImport(id, specifier) {
19418 this.referencer.visitPattern(id, pattern => {
19419 this.referencer.currentScope().__define(pattern, new Definition(Variable.ImportBinding, pattern, specifier, this.declaration, null, null));
19420 });
19421 }
19422
19423 ImportNamespaceSpecifier(node) {
19424 const local = node.local || node.id;
19425
19426 if (local) {
19427 this.visitImport(local, node);
19428 }
19429 }
19430
19431 ImportDefaultSpecifier(node) {
19432 const local = node.local || node.id;
19433 this.visitImport(local, node);
19434 }
19435
19436 ImportSpecifier(node) {
19437 const local = node.local || node.id;
19438
19439 if (node.name) {
19440 this.visitImport(node.name, node);
19441 } else {
19442 this.visitImport(local, node);
19443 }
19444 }
19445
19446} // Referencing variables and creating bindings.
19447
19448
19449class Referencer extends esrecurse.Visitor {
19450 constructor(options, scopeManager) {
19451 super(null, options);
19452 this.options = options;
19453 this.scopeManager = scopeManager;
19454 this.parent = null;
19455 this.isInnerMethodDefinition = false;
19456 }
19457
19458 currentScope() {
19459 return this.scopeManager.__currentScope;
19460 }
19461
19462 close(node) {
19463 while (this.currentScope() && node === this.currentScope().block) {
19464 this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager);
19465 }
19466 }
19467
19468 pushInnerMethodDefinition(isInnerMethodDefinition) {
19469 const previous = this.isInnerMethodDefinition;
19470 this.isInnerMethodDefinition = isInnerMethodDefinition;
19471 return previous;
19472 }
19473
19474 popInnerMethodDefinition(isInnerMethodDefinition) {
19475 this.isInnerMethodDefinition = isInnerMethodDefinition;
19476 }
19477
19478 referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {
19479 const scope = this.currentScope();
19480 assignments.forEach(assignment => {
19481 scope.__referencing(pattern, Reference.WRITE, assignment.right, maybeImplicitGlobal, pattern !== assignment.left, init);
19482 });
19483 }
19484
19485 visitPattern(node, options, callback) {
19486 let visitPatternOptions = options;
19487 let visitPatternCallback = callback;
19488
19489 if (typeof options === "function") {
19490 visitPatternCallback = options;
19491 visitPatternOptions = {
19492 processRightHandNodes: false
19493 };
19494 }
19495
19496 traverseIdentifierInPattern(this.options, node, visitPatternOptions.processRightHandNodes ? this : null, visitPatternCallback);
19497 }
19498
19499 visitFunction(node) {
19500 let i, iz; // FunctionDeclaration name is defined in upper scope
19501 // NOTE: Not referring variableScope. It is intended.
19502 // Since
19503 // in ES5, FunctionDeclaration should be in FunctionBody.
19504 // in ES6, FunctionDeclaration should be block scoped.
19505
19506 if (node.type === Syntax.FunctionDeclaration) {
19507 // id is defined in upper scope
19508 this.currentScope().__define(node.id, new Definition(Variable.FunctionName, node.id, node, null, null, null));
19509 } // FunctionExpression with name creates its special scope;
19510 // FunctionExpressionNameScope.
19511
19512
19513 if (node.type === Syntax.FunctionExpression && node.id) {
19514 this.scopeManager.__nestFunctionExpressionNameScope(node);
19515 } // Consider this function is in the MethodDefinition.
19516
19517
19518 this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition);
19519
19520 const that = this;
19521 /**
19522 * Visit pattern callback
19523 * @param {pattern} pattern - pattern
19524 * @param {Object} info - info
19525 * @returns {void}
19526 */
19527
19528 function visitPatternCallback(pattern, info) {
19529 that.currentScope().__define(pattern, new ParameterDefinition(pattern, node, i, info.rest));
19530
19531 that.referencingDefaultValue(pattern, info.assignments, null, true);
19532 } // Process parameter declarations.
19533
19534
19535 for (i = 0, iz = node.params.length; i < iz; ++i) {
19536 this.visitPattern(node.params[i], {
19537 processRightHandNodes: true
19538 }, visitPatternCallback);
19539 } // if there's a rest argument, add that
19540
19541
19542 if (node.rest) {
19543 this.visitPattern({
19544 type: "RestElement",
19545 argument: node.rest
19546 }, pattern => {
19547 this.currentScope().__define(pattern, new ParameterDefinition(pattern, node, node.params.length, true));
19548 });
19549 } // In TypeScript there are a number of function-like constructs which have no body,
19550 // so check it exists before traversing
19551
19552
19553 if (node.body) {
19554 // Skip BlockStatement to prevent creating BlockStatement scope.
19555 if (node.body.type === Syntax.BlockStatement) {
19556 this.visitChildren(node.body);
19557 } else {
19558 this.visit(node.body);
19559 }
19560 }
19561
19562 this.close(node);
19563 }
19564
19565 visitClass(node) {
19566 if (node.type === Syntax.ClassDeclaration) {
19567 this.currentScope().__define(node.id, new Definition(Variable.ClassName, node.id, node, null, null, null));
19568 }
19569
19570 this.visit(node.superClass);
19571
19572 this.scopeManager.__nestClassScope(node);
19573
19574 if (node.id) {
19575 this.currentScope().__define(node.id, new Definition(Variable.ClassName, node.id, node));
19576 }
19577
19578 this.visit(node.body);
19579 this.close(node);
19580 }
19581
19582 visitProperty(node) {
19583 let previous;
19584
19585 if (node.computed) {
19586 this.visit(node.key);
19587 }
19588
19589 const isMethodDefinition = node.type === Syntax.MethodDefinition;
19590
19591 if (isMethodDefinition) {
19592 previous = this.pushInnerMethodDefinition(true);
19593 }
19594
19595 this.visit(node.value);
19596
19597 if (isMethodDefinition) {
19598 this.popInnerMethodDefinition(previous);
19599 }
19600 }
19601
19602 visitForIn(node) {
19603 if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") {
19604 this.scopeManager.__nestForScope(node);
19605 }
19606
19607 if (node.left.type === Syntax.VariableDeclaration) {
19608 this.visit(node.left);
19609 this.visitPattern(node.left.declarations[0].id, pattern => {
19610 this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true);
19611 });
19612 } else {
19613 this.visitPattern(node.left, {
19614 processRightHandNodes: true
19615 }, (pattern, info) => {
19616 let maybeImplicitGlobal = null;
19617
19618 if (!this.currentScope().isStrict) {
19619 maybeImplicitGlobal = {
19620 pattern,
19621 node
19622 };
19623 }
19624
19625 this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
19626
19627 this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false);
19628 });
19629 }
19630
19631 this.visit(node.right);
19632 this.visit(node.body);
19633 this.close(node);
19634 }
19635
19636 visitVariableDeclaration(variableTargetScope, type, node, index) {
19637 const decl = node.declarations[index];
19638 const init = decl.init;
19639 this.visitPattern(decl.id, {
19640 processRightHandNodes: true
19641 }, (pattern, info) => {
19642 variableTargetScope.__define(pattern, new Definition(type, pattern, decl, node, index, node.kind));
19643
19644 this.referencingDefaultValue(pattern, info.assignments, null, true);
19645
19646 if (init) {
19647 this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true);
19648 }
19649 });
19650 }
19651
19652 AssignmentExpression(node) {
19653 if (PatternVisitor.isPattern(node.left)) {
19654 if (node.operator === "=") {
19655 this.visitPattern(node.left, {
19656 processRightHandNodes: true
19657 }, (pattern, info) => {
19658 let maybeImplicitGlobal = null;
19659
19660 if (!this.currentScope().isStrict) {
19661 maybeImplicitGlobal = {
19662 pattern,
19663 node
19664 };
19665 }
19666
19667 this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
19668
19669 this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false);
19670 });
19671 } else {
19672 this.currentScope().__referencing(node.left, Reference.RW, node.right);
19673 }
19674 } else {
19675 this.visit(node.left);
19676 }
19677
19678 this.visit(node.right);
19679 }
19680
19681 CatchClause(node) {
19682 this.scopeManager.__nestCatchScope(node);
19683
19684 this.visitPattern(node.param, {
19685 processRightHandNodes: true
19686 }, (pattern, info) => {
19687 this.currentScope().__define(pattern, new Definition(Variable.CatchClause, node.param, node, null, null, null));
19688
19689 this.referencingDefaultValue(pattern, info.assignments, null, true);
19690 });
19691 this.visit(node.body);
19692 this.close(node);
19693 }
19694
19695 Program(node) {
19696 this.scopeManager.__nestGlobalScope(node);
19697
19698 if (this.scopeManager.__isNodejsScope()) {
19699 // Force strictness of GlobalScope to false when using node.js scope.
19700 this.currentScope().isStrict = false;
19701
19702 this.scopeManager.__nestFunctionScope(node, false);
19703 }
19704
19705 if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {
19706 this.scopeManager.__nestModuleScope(node);
19707 }
19708
19709 if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) {
19710 this.currentScope().isStrict = true;
19711 }
19712
19713 this.visitChildren(node);
19714 this.close(node);
19715 }
19716
19717 Identifier(node) {
19718 this.currentScope().__referencing(node);
19719 }
19720
19721 UpdateExpression(node) {
19722 if (PatternVisitor.isPattern(node.argument)) {
19723 this.currentScope().__referencing(node.argument, Reference.RW, null);
19724 } else {
19725 this.visitChildren(node);
19726 }
19727 }
19728
19729 MemberExpression(node) {
19730 this.visit(node.object);
19731
19732 if (node.computed) {
19733 this.visit(node.property);
19734 }
19735 }
19736
19737 Property(node) {
19738 this.visitProperty(node);
19739 }
19740
19741 MethodDefinition(node) {
19742 this.visitProperty(node);
19743 }
19744
19745 BreakStatement() {} // eslint-disable-line class-methods-use-this
19746
19747
19748 ContinueStatement() {} // eslint-disable-line class-methods-use-this
19749
19750
19751 LabeledStatement(node) {
19752 this.visit(node.body);
19753 }
19754
19755 ForStatement(node) {
19756 // Create ForStatement declaration.
19757 // NOTE: In ES6, ForStatement dynamically generates
19758 // per iteration environment. However, escope is
19759 // a static analyzer, we only generate one scope for ForStatement.
19760 if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") {
19761 this.scopeManager.__nestForScope(node);
19762 }
19763
19764 this.visitChildren(node);
19765 this.close(node);
19766 }
19767
19768 ClassExpression(node) {
19769 this.visitClass(node);
19770 }
19771
19772 ClassDeclaration(node) {
19773 this.visitClass(node);
19774 }
19775
19776 CallExpression(node) {
19777 // Check this is direct call to eval
19778 if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") {
19779 // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and
19780 // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.
19781 this.currentScope().variableScope.__detectEval();
19782 }
19783
19784 this.visitChildren(node);
19785 }
19786
19787 BlockStatement(node) {
19788 if (this.scopeManager.__isES6()) {
19789 this.scopeManager.__nestBlockScope(node);
19790 }
19791
19792 this.visitChildren(node);
19793 this.close(node);
19794 }
19795
19796 ThisExpression() {
19797 this.currentScope().variableScope.__detectThis();
19798 }
19799
19800 WithStatement(node) {
19801 this.visit(node.object); // Then nest scope for WithStatement.
19802
19803 this.scopeManager.__nestWithScope(node);
19804
19805 this.visit(node.body);
19806 this.close(node);
19807 }
19808
19809 VariableDeclaration(node) {
19810 const variableTargetScope = node.kind === "var" ? this.currentScope().variableScope : this.currentScope();
19811
19812 for (let i = 0, iz = node.declarations.length; i < iz; ++i) {
19813 const decl = node.declarations[i];
19814 this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i);
19815
19816 if (decl.init) {
19817 this.visit(decl.init);
19818 }
19819 }
19820 } // sec 13.11.8
19821
19822
19823 SwitchStatement(node) {
19824 this.visit(node.discriminant);
19825
19826 if (this.scopeManager.__isES6()) {
19827 this.scopeManager.__nestSwitchScope(node);
19828 }
19829
19830 for (let i = 0, iz = node.cases.length; i < iz; ++i) {
19831 this.visit(node.cases[i]);
19832 }
19833
19834 this.close(node);
19835 }
19836
19837 FunctionDeclaration(node) {
19838 this.visitFunction(node);
19839 }
19840
19841 FunctionExpression(node) {
19842 this.visitFunction(node);
19843 }
19844
19845 ForOfStatement(node) {
19846 this.visitForIn(node);
19847 }
19848
19849 ForInStatement(node) {
19850 this.visitForIn(node);
19851 }
19852
19853 ArrowFunctionExpression(node) {
19854 this.visitFunction(node);
19855 }
19856
19857 ImportDeclaration(node) {
19858 assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context.");
19859 const importer = new Importer(node, this);
19860 importer.visit(node);
19861 }
19862
19863 visitExportDeclaration(node) {
19864 if (node.source) {
19865 return;
19866 }
19867
19868 if (node.declaration) {
19869 this.visit(node.declaration);
19870 return;
19871 }
19872
19873 this.visitChildren(node);
19874 }
19875
19876 ExportDeclaration(node) {
19877 this.visitExportDeclaration(node);
19878 }
19879
19880 ExportNamedDeclaration(node) {
19881 this.visitExportDeclaration(node);
19882 }
19883
19884 ExportSpecifier(node) {
19885 const local = node.id || node.local;
19886 this.visit(local);
19887 }
19888
19889 MetaProperty() {// eslint-disable-line class-methods-use-this
19890 // do nothing.
19891 }
19892
19893}
19894
19895module.exports = Referencer;
19896/* vim: set sw=4 ts=4 et tw=80 : */
19897
19898/***/ }),
19899/* 388 */
19900/***/ (function(module, exports, __webpack_require__) {
19901
19902/*
19903 Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
19904
19905 Redistribution and use in source and binary forms, with or without
19906 modification, are permitted provided that the following conditions are met:
19907
19908 * Redistributions of source code must retain the above copyright
19909 notice, this list of conditions and the following disclaimer.
19910 * Redistributions in binary form must reproduce the above copyright
19911 notice, this list of conditions and the following disclaimer in the
19912 documentation and/or other materials provided with the distribution.
19913
19914 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19915 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19916 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19917 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
19918 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19919 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19920 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19921 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
19922 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
19923 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19924*/
19925(function () {
19926 'use strict';
19927
19928 var estraverse = __webpack_require__(382);
19929
19930 function isNode(node) {
19931 if (node == null) {
19932 return false;
19933 }
19934
19935 return typeof node === 'object' && typeof node.type === 'string';
19936 }
19937
19938 function isProperty(nodeType, key) {
19939 return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties';
19940 }
19941
19942 function Visitor(visitor, options) {
19943 options = options || {};
19944 this.__visitor = visitor || this;
19945 this.__childVisitorKeys = options.childVisitorKeys ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) : estraverse.VisitorKeys;
19946
19947 if (options.fallback === 'iteration') {
19948 this.__fallback = Object.keys;
19949 } else if (typeof options.fallback === 'function') {
19950 this.__fallback = options.fallback;
19951 }
19952 }
19953 /* Default method for visiting children.
19954 * When you need to call default visiting operation inside custom visiting
19955 * operation, you can use it with `this.visitChildren(node)`.
19956 */
19957
19958
19959 Visitor.prototype.visitChildren = function (node) {
19960 var type, children, i, iz, j, jz, child;
19961
19962 if (node == null) {
19963 return;
19964 }
19965
19966 type = node.type || estraverse.Syntax.Property;
19967 children = this.__childVisitorKeys[type];
19968
19969 if (!children) {
19970 if (this.__fallback) {
19971 children = this.__fallback(node);
19972 } else {
19973 throw new Error('Unknown node type ' + type + '.');
19974 }
19975 }
19976
19977 for (i = 0, iz = children.length; i < iz; ++i) {
19978 child = node[children[i]];
19979
19980 if (child) {
19981 if (Array.isArray(child)) {
19982 for (j = 0, jz = child.length; j < jz; ++j) {
19983 if (child[j]) {
19984 if (isNode(child[j]) || isProperty(type, children[i])) {
19985 this.visit(child[j]);
19986 }
19987 }
19988 }
19989 } else if (isNode(child)) {
19990 this.visit(child);
19991 }
19992 }
19993 }
19994 };
19995 /* Dispatching node. */
19996
19997
19998 Visitor.prototype.visit = function (node) {
19999 var type;
20000
20001 if (node == null) {
20002 return;
20003 }
20004
20005 type = node.type || estraverse.Syntax.Property;
20006
20007 if (this.__visitor[type]) {
20008 this.__visitor[type].call(this, node);
20009
20010 return;
20011 }
20012
20013 this.visitChildren(node);
20014 };
20015
20016 exports.version = __webpack_require__(389).version;
20017 exports.Visitor = Visitor;
20018
20019 exports.visit = function (node, visitor, options) {
20020 var v = new Visitor(visitor, options);
20021 v.visit(node);
20022 };
20023})();
20024/* vim: set sw=4 ts=4 et tw=80 : */
20025
20026/***/ }),
20027/* 389 */
20028/***/ (function(module) {
20029
6a5a0f88 20030module.exports = JSON.parse("{\"_from\":\"esrecurse@^4.1.0\",\"_id\":\"esrecurse@4.2.1\",\"_inBundle\":false,\"_integrity\":\"sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==\",\"_location\":\"/esrecurse\",\"_phantomChildren\":{},\"_requested\":{\"type\":\"range\",\"registry\":true,\"raw\":\"esrecurse@^4.1.0\",\"name\":\"esrecurse\",\"escapedName\":\"esrecurse\",\"rawSpec\":\"^4.1.0\",\"saveSpec\":null,\"fetchSpec\":\"^4.1.0\"},\"_requiredBy\":[\"/babel-eslint/eslint-scope\",\"/eslint-scope\",\"/webpack/eslint-scope\"],\"_resolved\":\"https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz\",\"_shasum\":\"007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf\",\"_spec\":\"esrecurse@^4.1.0\",\"_where\":\"/root/sources/pve/pve-eslint/eslint-v7.1.0/node_modules/eslint-scope\",\"babel\":{\"presets\":[\"es2015\"]},\"bugs\":{\"url\":\"https://github.com/estools/esrecurse/issues\"},\"bundleDependencies\":false,\"dependencies\":{\"estraverse\":\"^4.1.0\"},\"deprecated\":false,\"description\":\"ECMAScript AST recursive visitor\",\"devDependencies\":{\"babel-cli\":\"^6.24.1\",\"babel-eslint\":\"^7.2.3\",\"babel-preset-es2015\":\"^6.24.1\",\"babel-register\":\"^6.24.1\",\"chai\":\"^4.0.2\",\"esprima\":\"^4.0.0\",\"gulp\":\"^3.9.0\",\"gulp-bump\":\"^2.7.0\",\"gulp-eslint\":\"^4.0.0\",\"gulp-filter\":\"^5.0.0\",\"gulp-git\":\"^2.4.1\",\"gulp-mocha\":\"^4.3.1\",\"gulp-tag-version\":\"^1.2.1\",\"jsdoc\":\"^3.3.0-alpha10\",\"minimist\":\"^1.1.0\"},\"engines\":{\"node\":\">=4.0\"},\"homepage\":\"https://github.com/estools/esrecurse\",\"license\":\"BSD-2-Clause\",\"main\":\"esrecurse.js\",\"maintainers\":[{\"name\":\"Yusuke Suzuki\",\"email\":\"utatane.tea@gmail.com\",\"url\":\"https://github.com/Constellation\"}],\"name\":\"esrecurse\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/estools/esrecurse.git\"},\"scripts\":{\"lint\":\"gulp lint\",\"test\":\"gulp travis\",\"unit-test\":\"gulp test\"},\"version\":\"4.2.1\"}");
eb39fafa
DC
20031
20032/***/ }),
20033/* 390 */
20034/***/ (function(module, exports, __webpack_require__) {
20035
20036"use strict";
20037/*
20038 Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
20039
20040 Redistribution and use in source and binary forms, with or without
20041 modification, are permitted provided that the following conditions are met:
20042
20043 * Redistributions of source code must retain the above copyright
20044 notice, this list of conditions and the following disclaimer.
20045 * Redistributions in binary form must reproduce the above copyright
20046 notice, this list of conditions and the following disclaimer in the
20047 documentation and/or other materials provided with the distribution.
20048
20049 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20050 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20051 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20052 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20053 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20054 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20055 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20056 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20057 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
20058 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
20059*/
20060
20061/* eslint-disable no-undefined */
20062
20063const Syntax = __webpack_require__(382).Syntax;
20064
20065const esrecurse = __webpack_require__(388);
20066/**
20067 * Get last array element
20068 * @param {array} xs - array
20069 * @returns {any} Last elment
20070 */
20071
20072
20073function getLast(xs) {
20074 return xs[xs.length - 1] || null;
20075}
20076
20077class PatternVisitor extends esrecurse.Visitor {
20078 static isPattern(node) {
20079 const nodeType = node.type;
20080 return nodeType === Syntax.Identifier || nodeType === Syntax.ObjectPattern || nodeType === Syntax.ArrayPattern || nodeType === Syntax.SpreadElement || nodeType === Syntax.RestElement || nodeType === Syntax.AssignmentPattern;
20081 }
20082
20083 constructor(options, rootPattern, callback) {
20084 super(null, options);
20085 this.rootPattern = rootPattern;
20086 this.callback = callback;
20087 this.assignments = [];
20088 this.rightHandNodes = [];
20089 this.restElements = [];
20090 }
20091
20092 Identifier(pattern) {
20093 const lastRestElement = getLast(this.restElements);
20094 this.callback(pattern, {
20095 topLevel: pattern === this.rootPattern,
20096 rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern,
20097 assignments: this.assignments
20098 });
20099 }
20100
20101 Property(property) {
20102 // Computed property's key is a right hand node.
20103 if (property.computed) {
20104 this.rightHandNodes.push(property.key);
20105 } // If it's shorthand, its key is same as its value.
20106 // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern).
20107 // If it's not shorthand, the name of new variable is its value's.
20108
20109
20110 this.visit(property.value);
20111 }
20112
20113 ArrayPattern(pattern) {
20114 for (let i = 0, iz = pattern.elements.length; i < iz; ++i) {
20115 const element = pattern.elements[i];
20116 this.visit(element);
20117 }
20118 }
20119
20120 AssignmentPattern(pattern) {
20121 this.assignments.push(pattern);
20122 this.visit(pattern.left);
20123 this.rightHandNodes.push(pattern.right);
20124 this.assignments.pop();
20125 }
20126
20127 RestElement(pattern) {
20128 this.restElements.push(pattern);
20129 this.visit(pattern.argument);
20130 this.restElements.pop();
20131 }
20132
20133 MemberExpression(node) {
20134 // Computed property's key is a right hand node.
20135 if (node.computed) {
20136 this.rightHandNodes.push(node.property);
20137 } // the object is only read, write to its property.
20138
20139
20140 this.rightHandNodes.push(node.object);
20141 } //
20142 // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression.
20143 // By spec, LeftHandSideExpression is Pattern or MemberExpression.
20144 // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758)
20145 // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc...
20146 //
20147
20148
20149 SpreadElement(node) {
20150 this.visit(node.argument);
20151 }
20152
20153 ArrayExpression(node) {
20154 node.elements.forEach(this.visit, this);
20155 }
20156
20157 AssignmentExpression(node) {
20158 this.assignments.push(node);
20159 this.visit(node.left);
20160 this.rightHandNodes.push(node.right);
20161 this.assignments.pop();
20162 }
20163
20164 CallExpression(node) {
20165 // arguments are right hand nodes.
20166 node.arguments.forEach(a => {
20167 this.rightHandNodes.push(a);
20168 });
20169 this.visit(node.callee);
20170 }
20171
20172}
20173
20174module.exports = PatternVisitor;
20175/* vim: set sw=4 ts=4 et tw=80 : */
20176
20177/***/ }),
20178/* 391 */
20179/***/ (function(module) {
20180
6a5a0f88 20181module.exports = JSON.parse("{\"_from\":\"eslint-scope@^5.0.0\",\"_id\":\"eslint-scope@5.0.0\",\"_inBundle\":false,\"_integrity\":\"sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw==\",\"_location\":\"/eslint-scope\",\"_phantomChildren\":{},\"_requested\":{\"type\":\"range\",\"registry\":true,\"raw\":\"eslint-scope@^5.0.0\",\"name\":\"eslint-scope\",\"escapedName\":\"eslint-scope\",\"rawSpec\":\"^5.0.0\",\"saveSpec\":null,\"fetchSpec\":\"^5.0.0\"},\"_requiredBy\":[\"/\",\"/eslint\"],\"_resolved\":\"https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz\",\"_shasum\":\"e87c8887c73e8d1ec84f1ca591645c358bfc8fb9\",\"_spec\":\"eslint-scope@^5.0.0\",\"_where\":\"/root/sources/pve/pve-eslint/eslint-v7.1.0\",\"bugs\":{\"url\":\"https://github.com/eslint/eslint-scope/issues\"},\"bundleDependencies\":false,\"dependencies\":{\"esrecurse\":\"^4.1.0\",\"estraverse\":\"^4.1.1\"},\"deprecated\":false,\"description\":\"ECMAScript scope analyzer for ESLint\",\"devDependencies\":{\"@typescript-eslint/parser\":\"^1.11.0\",\"chai\":\"^4.2.0\",\"eslint\":\"^6.0.1\",\"eslint-config-eslint\":\"^5.0.1\",\"eslint-plugin-node\":\"^9.1.0\",\"eslint-release\":\"^1.0.0\",\"espree\":\"^6.0.0\",\"istanbul\":\"^0.4.5\",\"mocha\":\"^6.1.4\",\"npm-license\":\"^0.3.3\",\"shelljs\":\"^0.8.3\",\"typescript\":\"^3.5.2\"},\"engines\":{\"node\":\">=8.0.0\"},\"files\":[\"LICENSE\",\"README.md\",\"lib\"],\"homepage\":\"http://github.com/eslint/eslint-scope\",\"license\":\"BSD-2-Clause\",\"main\":\"lib/index.js\",\"name\":\"eslint-scope\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/eslint/eslint-scope.git\"},\"scripts\":{\"generate-alpharelease\":\"eslint-generate-prerelease alpha\",\"generate-betarelease\":\"eslint-generate-prerelease beta\",\"generate-rcrelease\":\"eslint-generate-prerelease rc\",\"generate-release\":\"eslint-generate-release\",\"lint\":\"node Makefile.js lint\",\"publish-release\":\"eslint-publish-release\",\"test\":\"node Makefile.js test\"},\"version\":\"5.0.0\"}");
eb39fafa
DC
20182
20183/***/ }),
20184/* 392 */
20185/***/ (function(module, exports, __webpack_require__) {
20186
20187"use strict";
20188/**
20189 * @author Toru Nagashima <https://github.com/mysticatea>
20190 * See LICENSE file in root directory for full license.
20191 */
20192
20193
20194const KEYS = __webpack_require__(393); // Types.
20195
20196
20197const NODE_TYPES = Object.freeze(Object.keys(KEYS)); // Freeze the keys.
20198
20199for (const type of NODE_TYPES) {
20200 Object.freeze(KEYS[type]);
20201}
20202
20203Object.freeze(KEYS); // List to ignore keys.
20204
20205const KEY_BLACKLIST = new Set(["parent", "leadingComments", "trailingComments"]);
20206/**
20207 * Check whether a given key should be used or not.
20208 * @param {string} key The key to check.
20209 * @returns {boolean} `true` if the key should be used.
20210 */
20211
20212function filterKey(key) {
20213 return !KEY_BLACKLIST.has(key) && key[0] !== "_";
20214} //------------------------------------------------------------------------------
20215// Public interfaces
20216//------------------------------------------------------------------------------
20217
20218
20219module.exports = Object.freeze({
20220 /**
20221 * Visitor keys.
20222 * @type {{ [type: string]: string[] | undefined }}
20223 */
20224 KEYS,
20225
20226 /**
20227 * Get visitor keys of a given node.
20228 * @param {Object} node The AST node to get keys.
20229 * @returns {string[]} Visitor keys of the node.
20230 */
20231 getKeys(node) {
20232 return Object.keys(node).filter(filterKey);
20233 },
20234
20235 // Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
20236 // eslint-disable-next-line valid-jsdoc
20237
20238 /**
20239 * Make the union set with `KEYS` and given keys.
20240 * @param {Object} additionalKeys The additional keys.
20241 * @returns {{ [type: string]: string[] | undefined }} The union set.
20242 */
20243 unionWith(additionalKeys) {
20244 const retv = Object.assign({}, KEYS);
20245
20246 for (const type of Object.keys(additionalKeys)) {
20247 if (retv.hasOwnProperty(type)) {
20248 const keys = new Set(additionalKeys[type]);
20249
20250 for (const key of retv[type]) {
20251 keys.add(key);
20252 }
20253
20254 retv[type] = Object.freeze(Array.from(keys));
20255 } else {
20256 retv[type] = Object.freeze(Array.from(additionalKeys[type]));
20257 }
20258 }
20259
20260 return Object.freeze(retv);
20261 }
20262
20263});
20264
20265/***/ }),
20266/* 393 */
20267/***/ (function(module) {
20268
20269module.exports = JSON.parse("{\"AssignmentExpression\":[\"left\",\"right\"],\"AssignmentPattern\":[\"left\",\"right\"],\"ArrayExpression\":[\"elements\"],\"ArrayPattern\":[\"elements\"],\"ArrowFunctionExpression\":[\"params\",\"body\"],\"AwaitExpression\":[\"argument\"],\"BlockStatement\":[\"body\"],\"BinaryExpression\":[\"left\",\"right\"],\"BreakStatement\":[\"label\"],\"CallExpression\":[\"callee\",\"arguments\"],\"CatchClause\":[\"param\",\"body\"],\"ClassBody\":[\"body\"],\"ClassDeclaration\":[\"id\",\"superClass\",\"body\"],\"ClassExpression\":[\"id\",\"superClass\",\"body\"],\"ConditionalExpression\":[\"test\",\"consequent\",\"alternate\"],\"ContinueStatement\":[\"label\"],\"DebuggerStatement\":[],\"DoWhileStatement\":[\"body\",\"test\"],\"EmptyStatement\":[],\"ExportAllDeclaration\":[\"source\"],\"ExportDefaultDeclaration\":[\"declaration\"],\"ExportNamedDeclaration\":[\"declaration\",\"specifiers\",\"source\"],\"ExportSpecifier\":[\"exported\",\"local\"],\"ExpressionStatement\":[\"expression\"],\"ExperimentalRestProperty\":[\"argument\"],\"ExperimentalSpreadProperty\":[\"argument\"],\"ForStatement\":[\"init\",\"test\",\"update\",\"body\"],\"ForInStatement\":[\"left\",\"right\",\"body\"],\"ForOfStatement\":[\"left\",\"right\",\"body\"],\"FunctionDeclaration\":[\"id\",\"params\",\"body\"],\"FunctionExpression\":[\"id\",\"params\",\"body\"],\"Identifier\":[],\"IfStatement\":[\"test\",\"consequent\",\"alternate\"],\"ImportDeclaration\":[\"specifiers\",\"source\"],\"ImportDefaultSpecifier\":[\"local\"],\"ImportExpression\":[\"source\"],\"ImportNamespaceSpecifier\":[\"local\"],\"ImportSpecifier\":[\"imported\",\"local\"],\"JSXAttribute\":[\"name\",\"value\"],\"JSXClosingElement\":[\"name\"],\"JSXElement\":[\"openingElement\",\"children\",\"closingElement\"],\"JSXEmptyExpression\":[],\"JSXExpressionContainer\":[\"expression\"],\"JSXIdentifier\":[],\"JSXMemberExpression\":[\"object\",\"property\"],\"JSXNamespacedName\":[\"namespace\",\"name\"],\"JSXOpeningElement\":[\"name\",\"attributes\"],\"JSXSpreadAttribute\":[\"argument\"],\"JSXText\":[],\"JSXFragment\":[\"openingFragment\",\"children\",\"closingFragment\"],\"Literal\":[],\"LabeledStatement\":[\"label\",\"body\"],\"LogicalExpression\":[\"left\",\"right\"],\"MemberExpression\":[\"object\",\"property\"],\"MetaProperty\":[\"meta\",\"property\"],\"MethodDefinition\":[\"key\",\"value\"],\"NewExpression\":[\"callee\",\"arguments\"],\"ObjectExpression\":[\"properties\"],\"ObjectPattern\":[\"properties\"],\"Program\":[\"body\"],\"Property\":[\"key\",\"value\"],\"RestElement\":[\"argument\"],\"ReturnStatement\":[\"argument\"],\"SequenceExpression\":[\"expressions\"],\"SpreadElement\":[\"argument\"],\"Super\":[],\"SwitchStatement\":[\"discriminant\",\"cases\"],\"SwitchCase\":[\"test\",\"consequent\"],\"TaggedTemplateExpression\":[\"tag\",\"quasi\"],\"TemplateElement\":[],\"TemplateLiteral\":[\"quasis\",\"expressions\"],\"ThisExpression\":[],\"ThrowStatement\":[\"argument\"],\"TryStatement\":[\"block\",\"handler\",\"finalizer\"],\"UnaryExpression\":[\"argument\"],\"UpdateExpression\":[\"argument\"],\"VariableDeclaration\":[\"declarations\"],\"VariableDeclarator\":[\"id\",\"init\"],\"WhileStatement\":[\"test\",\"body\"],\"WithStatement\":[\"object\",\"body\"],\"YieldExpression\":[\"argument\"]}");
20270
20271/***/ }),
20272/* 394 */
20273/***/ (function(module, exports, __webpack_require__) {
20274
20275"use strict";
20276/**
20277 * @fileoverview Main Espree file that converts Acorn into Esprima output.
20278 *
20279 * This file contains code from the following MIT-licensed projects:
20280 * 1. Acorn
20281 * 2. Babylon
20282 * 3. Babel-ESLint
20283 *
20284 * This file also contains code from Esprima, which is BSD licensed.
20285 *
20286 * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS)
20287 * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS)
20288 * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie <sebmck@gmail.com>
20289 *
20290 * Redistribution and use in source and binary forms, with or without
20291 * modification, are permitted provided that the following conditions are met:
20292 *
20293 * * Redistributions of source code must retain the above copyright
20294 * notice, this list of conditions and the following disclaimer.
20295 * * Redistributions in binary form must reproduce the above copyright
20296 * notice, this list of conditions and the following disclaimer in the
20297 * documentation and/or other materials provided with the distribution.
20298 *
20299 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20300 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20301 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20302 * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20303 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20304 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20305 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20306 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20307 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
20308 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
20309 *
20310 * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
20311 *
20312 * Redistribution and use in source and binary forms, with or without
20313 * modification, are permitted provided that the following conditions are met:
20314 *
20315 * * Redistributions of source code must retain the above copyright
20316 * notice, this list of conditions and the following disclaimer.
20317 * * Redistributions in binary form must reproduce the above copyright
20318 * notice, this list of conditions and the following disclaimer in the
20319 * documentation and/or other materials provided with the distribution.
20320 *
20321 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20322 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20323 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20324 * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20325 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20326 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20327 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20328 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20329 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
20330 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
20331 */
20332
20333/* eslint no-undefined:0, no-use-before-define: 0 */
20334
20335
20336const acorn = __webpack_require__(395);
20337
20338const jsx = __webpack_require__(396);
20339
20340const astNodeTypes = __webpack_require__(398);
20341
20342const espree = __webpack_require__(399);
20343
20344const {
20345 getLatestEcmaVersion,
20346 getSupportedEcmaVersions
20347} = __webpack_require__(401); // To initialize lazily.
20348
20349
20350const parsers = {
20351 _regular: null,
20352 _jsx: null,
20353
20354 get regular() {
20355 if (this._regular === null) {
20356 this._regular = acorn.Parser.extend(espree());
20357 }
20358
20359 return this._regular;
20360 },
20361
20362 get jsx() {
20363 if (this._jsx === null) {
20364 this._jsx = acorn.Parser.extend(jsx(), espree());
20365 }
20366
20367 return this._jsx;
20368 },
20369
20370 get(options) {
20371 const useJsx = Boolean(options && options.ecmaFeatures && options.ecmaFeatures.jsx);
20372 return useJsx ? this.jsx : this.regular;
20373 }
20374
20375}; //------------------------------------------------------------------------------
20376// Tokenizer
20377//------------------------------------------------------------------------------
20378
20379/**
20380 * Tokenizes the given code.
20381 * @param {string} code The code to tokenize.
20382 * @param {Object} options Options defining how to tokenize.
20383 * @returns {Token[]} An array of tokens.
20384 * @throws {SyntaxError} If the input code is invalid.
20385 * @private
20386 */
20387
20388function tokenize(code, options) {
20389 const Parser = parsers.get(options); // Ensure to collect tokens.
20390
20391 if (!options || options.tokens !== true) {
20392 options = Object.assign({}, options, {
20393 tokens: true
20394 }); // eslint-disable-line no-param-reassign
20395 }
20396
20397 return new Parser(options, code).tokenize();
20398} //------------------------------------------------------------------------------
20399// Parser
20400//------------------------------------------------------------------------------
20401
20402/**
20403 * Parses the given code.
20404 * @param {string} code The code to tokenize.
20405 * @param {Object} options Options defining how to tokenize.
20406 * @returns {ASTNode} The "Program" AST node.
20407 * @throws {SyntaxError} If the input code is invalid.
20408 */
20409
20410
20411function parse(code, options) {
20412 const Parser = parsers.get(options);
20413 return new Parser(options, code).parse();
20414} //------------------------------------------------------------------------------
20415// Public
20416//------------------------------------------------------------------------------
20417
20418
20419exports.version = __webpack_require__(402).version;
20420exports.tokenize = tokenize;
20421exports.parse = parse; // Deep copy.
20422
20423/* istanbul ignore next */
20424
20425exports.Syntax = function () {
20426 let name,
20427 types = {};
20428
20429 if (typeof Object.create === "function") {
20430 types = Object.create(null);
20431 }
20432
20433 for (name in astNodeTypes) {
20434 if (Object.hasOwnProperty.call(astNodeTypes, name)) {
20435 types[name] = astNodeTypes[name];
20436 }
20437 }
20438
20439 if (typeof Object.freeze === "function") {
20440 Object.freeze(types);
20441 }
20442
20443 return types;
20444}();
20445/* istanbul ignore next */
20446
20447
20448exports.VisitorKeys = function () {
20449 return __webpack_require__(392).KEYS;
20450}();
20451
20452exports.latestEcmaVersion = getLatestEcmaVersion();
20453exports.supportedEcmaVersions = getSupportedEcmaVersions();
20454
20455/***/ }),
20456/* 395 */
20457/***/ (function(module, exports, __webpack_require__) {
20458
20459(function (global, factory) {
20460 true ? factory(exports) : undefined;
20461})(this, function (exports) {
20462 'use strict'; // Reserved word lists for various dialects of the language
20463
20464 var reservedWords = {
20465 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
20466 5: "class enum extends super const export import",
20467 6: "enum",
20468 strict: "implements interface let package private protected public static yield",
20469 strictBind: "eval arguments"
20470 }; // And the keywords
20471
20472 var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
20473 var keywords = {
20474 5: ecma5AndLessKeywords,
20475 "5module": ecma5AndLessKeywords + " export import",
20476 6: ecma5AndLessKeywords + " const class extends export import super"
20477 };
20478 var keywordRelationalOperator = /^in(stanceof)?$/; // ## Character categories
20479 // Big ugly regular expressions that match characters in the
20480 // whitespace, identifier, and identifier-start categories. These
20481 // are only applied when a character is found to actually have a
20482 // code point above 128.
20483 // Generated by `bin/generate-identifier-regex.js`.
20484
56c4a2cb
DC
20485 var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
20486 var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
eb39fafa
DC
20487 var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
20488 var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
20489 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; // These are a run-length and offset encoded representation of the
20490 // >0xffff code points that are a valid part of identifiers. The
20491 // offset starts at 0x10000, and each pair of numbers represents an
20492 // offset to the next range, and then a size of the range. They were
20493 // generated by bin/generate-identifier-regex.js
20494 // eslint-disable-next-line comma-spacing
20495
56c4a2cb 20496 var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; // eslint-disable-next-line comma-spacing
eb39fafa 20497
56c4a2cb 20498 var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; // This has a complexity linear to the value of the code. The
eb39fafa
DC
20499 // assumption is that looking up astral identifier characters is
20500 // rare.
20501
20502 function isInAstralSet(code, set) {
20503 var pos = 0x10000;
20504
20505 for (var i = 0; i < set.length; i += 2) {
20506 pos += set[i];
20507
20508 if (pos > code) {
20509 return false;
20510 }
20511
20512 pos += set[i + 1];
20513
20514 if (pos >= code) {
20515 return true;
20516 }
20517 }
20518 } // Test whether a given character code starts an identifier.
20519
20520
20521 function isIdentifierStart(code, astral) {
20522 if (code < 65) {
20523 return code === 36;
20524 }
20525
20526 if (code < 91) {
20527 return true;
20528 }
20529
20530 if (code < 97) {
20531 return code === 95;
20532 }
20533
20534 if (code < 123) {
20535 return true;
20536 }
20537
20538 if (code <= 0xffff) {
20539 return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
20540 }
20541
20542 if (astral === false) {
20543 return false;
20544 }
20545
20546 return isInAstralSet(code, astralIdentifierStartCodes);
20547 } // Test whether a given character is part of an identifier.
20548
20549
20550 function isIdentifierChar(code, astral) {
20551 if (code < 48) {
20552 return code === 36;
20553 }
20554
20555 if (code < 58) {
20556 return true;
20557 }
20558
20559 if (code < 65) {
20560 return false;
20561 }
20562
20563 if (code < 91) {
20564 return true;
20565 }
20566
20567 if (code < 97) {
20568 return code === 95;
20569 }
20570
20571 if (code < 123) {
20572 return true;
20573 }
20574
20575 if (code <= 0xffff) {
20576 return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
20577 }
20578
20579 if (astral === false) {
20580 return false;
20581 }
20582
20583 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
20584 } // ## Token types
20585 // The assignment of fine-grained, information-carrying type objects
20586 // allows the tokenizer to store the information it has about a
20587 // token in a way that is very cheap for the parser to look up.
20588 // All token type variables start with an underscore, to make them
20589 // easy to recognize.
20590 // The `beforeExpr` property is used to disambiguate between regular
20591 // expressions and divisions. It is set on all token types that can
20592 // be followed by an expression (thus, a slash after them would be a
20593 // regular expression).
20594 //
20595 // The `startsExpr` property is used to check if the token ends a
20596 // `yield` expression. It is set on all token types that either can
20597 // directly start an expression (like a quotation mark) or can
20598 // continue an expression (like the body of a string).
20599 //
20600 // `isLoop` marks a keyword as starting a loop, which is important
20601 // to know when parsing a label, in order to allow or disallow
20602 // continue jumps to that label.
20603
20604
20605 var TokenType = function TokenType(label, conf) {
20606 if (conf === void 0) conf = {};
20607 this.label = label;
20608 this.keyword = conf.keyword;
20609 this.beforeExpr = !!conf.beforeExpr;
20610 this.startsExpr = !!conf.startsExpr;
20611 this.isLoop = !!conf.isLoop;
20612 this.isAssign = !!conf.isAssign;
20613 this.prefix = !!conf.prefix;
20614 this.postfix = !!conf.postfix;
20615 this.binop = conf.binop || null;
20616 this.updateContext = null;
20617 };
20618
20619 function binop(name, prec) {
20620 return new TokenType(name, {
20621 beforeExpr: true,
20622 binop: prec
20623 });
20624 }
20625
20626 var beforeExpr = {
20627 beforeExpr: true
20628 },
20629 startsExpr = {
20630 startsExpr: true
20631 }; // Map keyword names to token types.
20632
20633 var keywords$1 = {}; // Succinct definitions of keyword token types
20634
20635 function kw(name, options) {
20636 if (options === void 0) options = {};
20637 options.keyword = name;
20638 return keywords$1[name] = new TokenType(name, options);
20639 }
20640
20641 var types = {
20642 num: new TokenType("num", startsExpr),
20643 regexp: new TokenType("regexp", startsExpr),
20644 string: new TokenType("string", startsExpr),
20645 name: new TokenType("name", startsExpr),
20646 eof: new TokenType("eof"),
20647 // Punctuation token types.
20648 bracketL: new TokenType("[", {
20649 beforeExpr: true,
20650 startsExpr: true
20651 }),
20652 bracketR: new TokenType("]"),
20653 braceL: new TokenType("{", {
20654 beforeExpr: true,
20655 startsExpr: true
20656 }),
20657 braceR: new TokenType("}"),
20658 parenL: new TokenType("(", {
20659 beforeExpr: true,
20660 startsExpr: true
20661 }),
20662 parenR: new TokenType(")"),
20663 comma: new TokenType(",", beforeExpr),
20664 semi: new TokenType(";", beforeExpr),
20665 colon: new TokenType(":", beforeExpr),
20666 dot: new TokenType("."),
20667 question: new TokenType("?", beforeExpr),
20668 arrow: new TokenType("=>", beforeExpr),
20669 template: new TokenType("template"),
20670 invalidTemplate: new TokenType("invalidTemplate"),
20671 ellipsis: new TokenType("...", beforeExpr),
20672 backQuote: new TokenType("`", startsExpr),
20673 dollarBraceL: new TokenType("${", {
20674 beforeExpr: true,
20675 startsExpr: true
20676 }),
20677 // Operators. These carry several kinds of properties to help the
20678 // parser use them properly (the presence of these properties is
20679 // what categorizes them as operators).
20680 //
20681 // `binop`, when present, specifies that this operator is a binary
20682 // operator, and will refer to its precedence.
20683 //
20684 // `prefix` and `postfix` mark the operator as a prefix or postfix
20685 // unary operator.
20686 //
20687 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
20688 // binary operators with a very low precedence, that should result
20689 // in AssignmentExpression nodes.
20690 eq: new TokenType("=", {
20691 beforeExpr: true,
20692 isAssign: true
20693 }),
20694 assign: new TokenType("_=", {
20695 beforeExpr: true,
20696 isAssign: true
20697 }),
20698 incDec: new TokenType("++/--", {
20699 prefix: true,
20700 postfix: true,
20701 startsExpr: true
20702 }),
20703 prefix: new TokenType("!/~", {
20704 beforeExpr: true,
20705 prefix: true,
20706 startsExpr: true
20707 }),
20708 logicalOR: binop("||", 1),
20709 logicalAND: binop("&&", 2),
20710 bitwiseOR: binop("|", 3),
20711 bitwiseXOR: binop("^", 4),
20712 bitwiseAND: binop("&", 5),
20713 equality: binop("==/!=/===/!==", 6),
20714 relational: binop("</>/<=/>=", 7),
20715 bitShift: binop("<</>>/>>>", 8),
20716 plusMin: new TokenType("+/-", {
20717 beforeExpr: true,
20718 binop: 9,
20719 prefix: true,
20720 startsExpr: true
20721 }),
20722 modulo: binop("%", 10),
20723 star: binop("*", 10),
20724 slash: binop("/", 10),
20725 starstar: new TokenType("**", {
20726 beforeExpr: true
20727 }),
56c4a2cb 20728 coalesce: binop("??", 1),
eb39fafa
DC
20729 // Keyword token types.
20730 _break: kw("break"),
20731 _case: kw("case", beforeExpr),
20732 _catch: kw("catch"),
20733 _continue: kw("continue"),
20734 _debugger: kw("debugger"),
20735 _default: kw("default", beforeExpr),
20736 _do: kw("do", {
20737 isLoop: true,
20738 beforeExpr: true
20739 }),
20740 _else: kw("else", beforeExpr),
20741 _finally: kw("finally"),
20742 _for: kw("for", {
20743 isLoop: true
20744 }),
20745 _function: kw("function", startsExpr),
20746 _if: kw("if"),
20747 _return: kw("return", beforeExpr),
20748 _switch: kw("switch"),
20749 _throw: kw("throw", beforeExpr),
20750 _try: kw("try"),
20751 _var: kw("var"),
20752 _const: kw("const"),
20753 _while: kw("while", {
20754 isLoop: true
20755 }),
20756 _with: kw("with"),
20757 _new: kw("new", {
20758 beforeExpr: true,
20759 startsExpr: true
20760 }),
20761 _this: kw("this", startsExpr),
20762 _super: kw("super", startsExpr),
20763 _class: kw("class", startsExpr),
20764 _extends: kw("extends", beforeExpr),
20765 _export: kw("export"),
20766 _import: kw("import", startsExpr),
20767 _null: kw("null", startsExpr),
20768 _true: kw("true", startsExpr),
20769 _false: kw("false", startsExpr),
20770 _in: kw("in", {
20771 beforeExpr: true,
20772 binop: 7
20773 }),
20774 _instanceof: kw("instanceof", {
20775 beforeExpr: true,
20776 binop: 7
20777 }),
20778 _typeof: kw("typeof", {
20779 beforeExpr: true,
20780 prefix: true,
20781 startsExpr: true
20782 }),
20783 _void: kw("void", {
20784 beforeExpr: true,
20785 prefix: true,
20786 startsExpr: true
20787 }),
20788 _delete: kw("delete", {
20789 beforeExpr: true,
20790 prefix: true,
20791 startsExpr: true
20792 })
20793 }; // Matches a whole line break (where CRLF is considered a single
20794 // line break). Used to count lines.
20795
20796 var lineBreak = /\r\n?|\n|\u2028|\u2029/;
20797 var lineBreakG = new RegExp(lineBreak.source, "g");
20798
20799 function isNewLine(code, ecma2019String) {
20800 return code === 10 || code === 13 || !ecma2019String && (code === 0x2028 || code === 0x2029);
20801 }
20802
20803 var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
20804 var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
20805 var ref = Object.prototype;
20806 var hasOwnProperty = ref.hasOwnProperty;
20807 var toString = ref.toString; // Checks if an object has a property.
20808
20809 function has(obj, propName) {
20810 return hasOwnProperty.call(obj, propName);
20811 }
20812
20813 var isArray = Array.isArray || function (obj) {
20814 return toString.call(obj) === "[object Array]";
20815 };
20816
20817 function wordsRegexp(words) {
20818 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$");
20819 } // These are used when `options.locations` is on, for the
20820 // `startLoc` and `endLoc` properties.
20821
20822
20823 var Position = function Position(line, col) {
20824 this.line = line;
20825 this.column = col;
20826 };
20827
20828 Position.prototype.offset = function offset(n) {
20829 return new Position(this.line, this.column + n);
20830 };
20831
20832 var SourceLocation = function SourceLocation(p, start, end) {
20833 this.start = start;
20834 this.end = end;
20835
20836 if (p.sourceFile !== null) {
20837 this.source = p.sourceFile;
20838 }
20839 }; // The `getLineInfo` function is mostly useful when the
20840 // `locations` option is off (for performance reasons) and you
20841 // want to find the line/column position for a given character
20842 // offset. `input` should be the code string that the offset refers
20843 // into.
20844
20845
20846 function getLineInfo(input, offset) {
20847 for (var line = 1, cur = 0;;) {
20848 lineBreakG.lastIndex = cur;
20849 var match = lineBreakG.exec(input);
20850
20851 if (match && match.index < offset) {
20852 ++line;
20853 cur = match.index + match[0].length;
20854 } else {
20855 return new Position(line, offset - cur);
20856 }
20857 }
20858 } // A second optional argument can be given to further configure
20859 // the parser process. These options are recognized:
20860
20861
20862 var defaultOptions = {
20863 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
20864 // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10
20865 // (2019). This influences support for strict mode, the set of
20866 // reserved words, and support for new syntax features. The default
20867 // is 10.
20868 ecmaVersion: 10,
20869 // `sourceType` indicates the mode the code should be parsed in.
20870 // Can be either `"script"` or `"module"`. This influences global
20871 // strict mode and parsing of `import` and `export` declarations.
20872 sourceType: "script",
20873 // `onInsertedSemicolon` can be a callback that will be called
20874 // when a semicolon is automatically inserted. It will be passed
20875 // the position of the comma as an offset, and if `locations` is
20876 // enabled, it is given the location as a `{line, column}` object
20877 // as second argument.
20878 onInsertedSemicolon: null,
20879 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
20880 // trailing commas.
20881 onTrailingComma: null,
20882 // By default, reserved words are only enforced if ecmaVersion >= 5.
20883 // Set `allowReserved` to a boolean value to explicitly turn this on
20884 // an off. When this option has the value "never", reserved words
20885 // and keywords can also not be used as property names.
20886 allowReserved: null,
20887 // When enabled, a return at the top level is not considered an
20888 // error.
20889 allowReturnOutsideFunction: false,
20890 // When enabled, import/export statements are not constrained to
20891 // appearing at the top of the program.
20892 allowImportExportEverywhere: false,
20893 // When enabled, await identifiers are allowed to appear at the top-level scope,
20894 // but they are still not allowed in non-async functions.
20895 allowAwaitOutsideFunction: false,
20896 // When enabled, hashbang directive in the beginning of file
20897 // is allowed and treated as a line comment.
20898 allowHashBang: false,
20899 // When `locations` is on, `loc` properties holding objects with
20900 // `start` and `end` properties in `{line, column}` form (with
20901 // line being 1-based and column 0-based) will be attached to the
20902 // nodes.
20903 locations: false,
20904 // A function can be passed as `onToken` option, which will
20905 // cause Acorn to call that function with object in the same
20906 // format as tokens returned from `tokenizer().getToken()`. Note
20907 // that you are not allowed to call the parser from the
20908 // callback—that will corrupt its internal state.
20909 onToken: null,
20910 // A function can be passed as `onComment` option, which will
20911 // cause Acorn to call that function with `(block, text, start,
20912 // end)` parameters whenever a comment is skipped. `block` is a
20913 // boolean indicating whether this is a block (`/* */`) comment,
20914 // `text` is the content of the comment, and `start` and `end` are
20915 // character offsets that denote the start and end of the comment.
20916 // When the `locations` option is on, two more parameters are
20917 // passed, the full `{line, column}` locations of the start and
20918 // end of the comments. Note that you are not allowed to call the
20919 // parser from the callback—that will corrupt its internal state.
20920 onComment: null,
20921 // Nodes have their start and end characters offsets recorded in
20922 // `start` and `end` properties (directly on the node, rather than
20923 // the `loc` object, which holds line/column data. To also add a
20924 // [semi-standardized][range] `range` property holding a `[start,
20925 // end]` array with the same numbers, set the `ranges` option to
20926 // `true`.
20927 //
20928 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
20929 ranges: false,
20930 // It is possible to parse multiple files into a single AST by
20931 // passing the tree produced by parsing the first file as
20932 // `program` option in subsequent parses. This will add the
20933 // toplevel forms of the parsed file to the `Program` (top) node
20934 // of an existing parse tree.
20935 program: null,
20936 // When `locations` is on, you can pass this to record the source
20937 // file in every node's `loc` object.
20938 sourceFile: null,
20939 // This value, if given, is stored in every node, whether
20940 // `locations` is on or off.
20941 directSourceFile: null,
20942 // When enabled, parenthesized expressions are represented by
20943 // (non-standard) ParenthesizedExpression nodes
20944 preserveParens: false
20945 }; // Interpret and default an options object
20946
20947 function getOptions(opts) {
20948 var options = {};
20949
20950 for (var opt in defaultOptions) {
20951 options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
20952 }
20953
20954 if (options.ecmaVersion >= 2015) {
20955 options.ecmaVersion -= 2009;
20956 }
20957
20958 if (options.allowReserved == null) {
20959 options.allowReserved = options.ecmaVersion < 5;
20960 }
20961
20962 if (isArray(options.onToken)) {
20963 var tokens = options.onToken;
20964
20965 options.onToken = function (token) {
20966 return tokens.push(token);
20967 };
20968 }
20969
20970 if (isArray(options.onComment)) {
20971 options.onComment = pushComment(options, options.onComment);
20972 }
20973
20974 return options;
20975 }
20976
20977 function pushComment(options, array) {
20978 return function (block, text, start, end, startLoc, endLoc) {
20979 var comment = {
20980 type: block ? "Block" : "Line",
20981 value: text,
20982 start: start,
20983 end: end
20984 };
20985
20986 if (options.locations) {
20987 comment.loc = new SourceLocation(this, startLoc, endLoc);
20988 }
20989
20990 if (options.ranges) {
20991 comment.range = [start, end];
20992 }
20993
20994 array.push(comment);
20995 };
20996 } // Each scope gets a bitset that may contain these flags
20997
20998
20999 var SCOPE_TOP = 1,
21000 SCOPE_FUNCTION = 2,
21001 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
21002 SCOPE_ASYNC = 4,
21003 SCOPE_GENERATOR = 8,
21004 SCOPE_ARROW = 16,
21005 SCOPE_SIMPLE_CATCH = 32,
21006 SCOPE_SUPER = 64,
21007 SCOPE_DIRECT_SUPER = 128;
21008
21009 function functionFlags(async, generator) {
21010 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
21011 } // Used in checkLVal and declareName to determine the type of a binding
21012
21013
21014 var BIND_NONE = 0,
21015 // Not a binding
21016 BIND_VAR = 1,
21017 // Var-style binding
21018 BIND_LEXICAL = 2,
21019 // Let- or const-style binding
21020 BIND_FUNCTION = 3,
21021 // Function declaration
21022 BIND_SIMPLE_CATCH = 4,
21023 // Simple (identifier pattern) catch binding
21024 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
21025
21026 var Parser = function Parser(options, input, startPos) {
21027 this.options = options = getOptions(options);
21028 this.sourceFile = options.sourceFile;
21029 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
21030 var reserved = "";
21031
21032 if (options.allowReserved !== true) {
21033 for (var v = options.ecmaVersion;; v--) {
21034 if (reserved = reservedWords[v]) {
21035 break;
21036 }
21037 }
21038
21039 if (options.sourceType === "module") {
21040 reserved += " await";
21041 }
21042 }
21043
21044 this.reservedWords = wordsRegexp(reserved);
21045 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
21046 this.reservedWordsStrict = wordsRegexp(reservedStrict);
21047 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
21048 this.input = String(input); // Used to signal to callers of `readWord1` whether the word
21049 // contained any escape sequences. This is needed because words with
21050 // escape sequences must not be interpreted as keywords.
21051
21052 this.containsEsc = false; // Set up token state
21053 // The current position of the tokenizer in the input.
21054
21055 if (startPos) {
21056 this.pos = startPos;
21057 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
21058 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
21059 } else {
21060 this.pos = this.lineStart = 0;
21061 this.curLine = 1;
21062 } // Properties of the current token:
21063 // Its type
21064
21065
21066 this.type = types.eof; // For tokens that include more information than their type, the value
21067
21068 this.value = null; // Its start and end offset
21069
21070 this.start = this.end = this.pos; // And, if locations are used, the {line, column} object
21071 // corresponding to those offsets
21072
21073 this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token
21074
21075 this.lastTokEndLoc = this.lastTokStartLoc = null;
21076 this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic
21077 // context to predict whether a regular expression is allowed in a
21078 // given position.
21079
21080 this.context = this.initialContext();
21081 this.exprAllowed = true; // Figure out if it's a module code.
21082
21083 this.inModule = options.sourceType === "module";
21084 this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function
21085
21086 this.potentialArrowAt = -1; // Positions to delayed-check that yield/await does not exist in default parameters.
21087
21088 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope.
21089
21090 this.labels = []; // Thus-far undefined exports.
21091
21092 this.undefinedExports = {}; // If enabled, skip leading hashbang line.
21093
21094 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
21095 this.skipLineComment(2);
21096 } // Scope tracking for duplicate variable names (see scope.js)
21097
21098
21099 this.scopeStack = [];
21100 this.enterScope(SCOPE_TOP); // For RegExp validation
21101
21102 this.regexpState = null;
21103 };
21104
21105 var prototypeAccessors = {
21106 inFunction: {
21107 configurable: true
21108 },
21109 inGenerator: {
21110 configurable: true
21111 },
21112 inAsync: {
21113 configurable: true
21114 },
21115 allowSuper: {
21116 configurable: true
21117 },
21118 allowDirectSuper: {
21119 configurable: true
21120 },
21121 treatFunctionsAsVar: {
21122 configurable: true
21123 }
21124 };
21125
21126 Parser.prototype.parse = function parse() {
21127 var node = this.options.program || this.startNode();
21128 this.nextToken();
21129 return this.parseTopLevel(node);
21130 };
21131
21132 prototypeAccessors.inFunction.get = function () {
21133 return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
21134 };
21135
21136 prototypeAccessors.inGenerator.get = function () {
21137 return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
21138 };
21139
21140 prototypeAccessors.inAsync.get = function () {
21141 return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
21142 };
21143
21144 prototypeAccessors.allowSuper.get = function () {
21145 return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
21146 };
21147
21148 prototypeAccessors.allowDirectSuper.get = function () {
21149 return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
21150 };
21151
21152 prototypeAccessors.treatFunctionsAsVar.get = function () {
21153 return this.treatFunctionsAsVarInScope(this.currentScope());
21154 }; // Switch to a getter for 7.0.0.
21155
21156
21157 Parser.prototype.inNonArrowFunction = function inNonArrowFunction() {
21158 return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
21159 };
21160
21161 Parser.extend = function extend() {
21162 var plugins = [],
21163 len = arguments.length;
21164
21165 while (len--) plugins[len] = arguments[len];
21166
21167 var cls = this;
21168
21169 for (var i = 0; i < plugins.length; i++) {
21170 cls = plugins[i](cls);
21171 }
21172
21173 return cls;
21174 };
21175
21176 Parser.parse = function parse(input, options) {
21177 return new this(options, input).parse();
21178 };
21179
21180 Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) {
21181 var parser = new this(options, input, pos);
21182 parser.nextToken();
21183 return parser.parseExpression();
21184 };
21185
21186 Parser.tokenizer = function tokenizer(input, options) {
21187 return new this(options, input);
21188 };
21189
21190 Object.defineProperties(Parser.prototype, prototypeAccessors);
21191 var pp = Parser.prototype; // ## Parser utilities
21192
21193 var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/;
21194
21195 pp.strictDirective = function (start) {
21196 for (;;) {
21197 // Try to find string literal.
21198 skipWhiteSpace.lastIndex = start;
21199 start += skipWhiteSpace.exec(this.input)[0].length;
21200 var match = literal.exec(this.input.slice(start));
21201
21202 if (!match) {
21203 return false;
21204 }
21205
21206 if ((match[1] || match[2]) === "use strict") {
56c4a2cb
DC
21207 skipWhiteSpace.lastIndex = start + match[0].length;
21208 var spaceAfter = skipWhiteSpace.exec(this.input),
21209 end = spaceAfter.index + spaceAfter[0].length;
21210 var next = this.input.charAt(end);
21211 return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
eb39fafa
DC
21212 }
21213
21214 start += match[0].length; // Skip semicolon, if any.
21215
21216 skipWhiteSpace.lastIndex = start;
21217 start += skipWhiteSpace.exec(this.input)[0].length;
21218
21219 if (this.input[start] === ";") {
21220 start++;
21221 }
21222 }
21223 }; // Predicate that tests whether the next token is of the given
21224 // type, and if yes, consumes it as a side effect.
21225
21226
21227 pp.eat = function (type) {
21228 if (this.type === type) {
21229 this.next();
21230 return true;
21231 } else {
21232 return false;
21233 }
21234 }; // Tests whether parsed token is a contextual keyword.
21235
21236
21237 pp.isContextual = function (name) {
21238 return this.type === types.name && this.value === name && !this.containsEsc;
21239 }; // Consumes contextual keyword if possible.
21240
21241
21242 pp.eatContextual = function (name) {
21243 if (!this.isContextual(name)) {
21244 return false;
21245 }
21246
21247 this.next();
21248 return true;
21249 }; // Asserts that following token is given contextual keyword.
21250
21251
21252 pp.expectContextual = function (name) {
21253 if (!this.eatContextual(name)) {
21254 this.unexpected();
21255 }
21256 }; // Test whether a semicolon can be inserted at the current position.
21257
21258
21259 pp.canInsertSemicolon = function () {
21260 return this.type === types.eof || this.type === types.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
21261 };
21262
21263 pp.insertSemicolon = function () {
21264 if (this.canInsertSemicolon()) {
21265 if (this.options.onInsertedSemicolon) {
21266 this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
21267 }
21268
21269 return true;
21270 }
21271 }; // Consume a semicolon, or, failing that, see if we are allowed to
21272 // pretend that there is a semicolon at this position.
21273
21274
21275 pp.semicolon = function () {
21276 if (!this.eat(types.semi) && !this.insertSemicolon()) {
21277 this.unexpected();
21278 }
21279 };
21280
21281 pp.afterTrailingComma = function (tokType, notNext) {
21282 if (this.type === tokType) {
21283 if (this.options.onTrailingComma) {
21284 this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
21285 }
21286
21287 if (!notNext) {
21288 this.next();
21289 }
21290
21291 return true;
21292 }
21293 }; // Expect a token of a given type. If found, consume it, otherwise,
21294 // raise an unexpected token error.
21295
21296
21297 pp.expect = function (type) {
21298 this.eat(type) || this.unexpected();
21299 }; // Raise an unexpected token error.
21300
21301
21302 pp.unexpected = function (pos) {
21303 this.raise(pos != null ? pos : this.start, "Unexpected token");
21304 };
21305
21306 function DestructuringErrors() {
21307 this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
21308 }
21309
21310 pp.checkPatternErrors = function (refDestructuringErrors, isAssign) {
21311 if (!refDestructuringErrors) {
21312 return;
21313 }
21314
21315 if (refDestructuringErrors.trailingComma > -1) {
21316 this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
21317 }
21318
21319 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
21320
21321 if (parens > -1) {
21322 this.raiseRecoverable(parens, "Parenthesized pattern");
21323 }
21324 };
21325
21326 pp.checkExpressionErrors = function (refDestructuringErrors, andThrow) {
21327 if (!refDestructuringErrors) {
21328 return false;
21329 }
21330
21331 var shorthandAssign = refDestructuringErrors.shorthandAssign;
21332 var doubleProto = refDestructuringErrors.doubleProto;
21333
21334 if (!andThrow) {
21335 return shorthandAssign >= 0 || doubleProto >= 0;
21336 }
21337
21338 if (shorthandAssign >= 0) {
21339 this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
21340 }
21341
21342 if (doubleProto >= 0) {
21343 this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
21344 }
21345 };
21346
21347 pp.checkYieldAwaitInDefaultParams = function () {
21348 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
21349 this.raise(this.yieldPos, "Yield expression cannot be a default value");
21350 }
21351
21352 if (this.awaitPos) {
21353 this.raise(this.awaitPos, "Await expression cannot be a default value");
21354 }
21355 };
21356
21357 pp.isSimpleAssignTarget = function (expr) {
21358 if (expr.type === "ParenthesizedExpression") {
21359 return this.isSimpleAssignTarget(expr.expression);
21360 }
21361
21362 return expr.type === "Identifier" || expr.type === "MemberExpression";
21363 };
21364
21365 var pp$1 = Parser.prototype; // ### Statement parsing
21366 // Parse a program. Initializes the parser, reads any number of
21367 // statements, and wraps them in a Program node. Optionally takes a
21368 // `program` argument. If present, the statements will be appended
21369 // to its body instead of creating a new node.
21370
21371 pp$1.parseTopLevel = function (node) {
21372 var exports = {};
21373
21374 if (!node.body) {
21375 node.body = [];
21376 }
21377
21378 while (this.type !== types.eof) {
21379 var stmt = this.parseStatement(null, true, exports);
21380 node.body.push(stmt);
21381 }
21382
21383 if (this.inModule) {
21384 for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
21385 var name = list[i];
21386 this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
21387 }
21388 }
21389
21390 this.adaptDirectivePrologue(node.body);
21391 this.next();
21392 node.sourceType = this.options.sourceType;
21393 return this.finishNode(node, "Program");
21394 };
21395
21396 var loopLabel = {
21397 kind: "loop"
21398 },
21399 switchLabel = {
21400 kind: "switch"
21401 };
21402
21403 pp$1.isLet = function (context) {
21404 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
21405 return false;
21406 }
21407
21408 skipWhiteSpace.lastIndex = this.pos;
21409 var skip = skipWhiteSpace.exec(this.input);
21410 var next = this.pos + skip[0].length,
21411 nextCh = this.input.charCodeAt(next); // For ambiguous cases, determine if a LexicalDeclaration (or only a
21412 // Statement) is allowed here. If context is not empty then only a Statement
21413 // is allowed. However, `let [` is an explicit negative lookahead for
21414 // ExpressionStatement, so special-case it first.
21415
21416 if (nextCh === 91) {
21417 return true;
21418 } // '['
21419
21420
21421 if (context) {
21422 return false;
21423 }
21424
21425 if (nextCh === 123) {
21426 return true;
21427 } // '{'
21428
21429
21430 if (isIdentifierStart(nextCh, true)) {
21431 var pos = next + 1;
21432
21433 while (isIdentifierChar(this.input.charCodeAt(pos), true)) {
21434 ++pos;
21435 }
21436
21437 var ident = this.input.slice(next, pos);
21438
21439 if (!keywordRelationalOperator.test(ident)) {
21440 return true;
21441 }
21442 }
21443
21444 return false;
21445 }; // check 'async [no LineTerminator here] function'
21446 // - 'async /*foo*/ function' is OK.
21447 // - 'async /*\n*/ function' is invalid.
21448
21449
21450 pp$1.isAsyncFunction = function () {
21451 if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
21452 return false;
21453 }
21454
21455 skipWhiteSpace.lastIndex = this.pos;
21456 var skip = skipWhiteSpace.exec(this.input);
21457 var next = this.pos + skip[0].length;
21458 return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)));
21459 }; // Parse a single statement.
21460 //
21461 // If expecting a statement and finding a slash operator, parse a
21462 // regular expression literal. This is to handle cases like
21463 // `if (foo) /blah/.exec(foo)`, where looking at the previous token
21464 // does not help.
21465
21466
21467 pp$1.parseStatement = function (context, topLevel, exports) {
21468 var starttype = this.type,
21469 node = this.startNode(),
21470 kind;
21471
21472 if (this.isLet(context)) {
21473 starttype = types._var;
21474 kind = "let";
21475 } // Most types of statements are recognized by the keyword they
21476 // start with. Many are trivial to parse, some require a bit of
21477 // complexity.
21478
21479
21480 switch (starttype) {
21481 case types._break:
21482 case types._continue:
21483 return this.parseBreakContinueStatement(node, starttype.keyword);
21484
21485 case types._debugger:
21486 return this.parseDebuggerStatement(node);
21487
21488 case types._do:
21489 return this.parseDoStatement(node);
21490
21491 case types._for:
21492 return this.parseForStatement(node);
21493
21494 case types._function:
21495 // Function as sole body of either an if statement or a labeled statement
21496 // works, but not when it is part of a labeled statement that is the sole
21497 // body of an if statement.
21498 if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
21499 this.unexpected();
21500 }
21501
21502 return this.parseFunctionStatement(node, false, !context);
21503
21504 case types._class:
21505 if (context) {
21506 this.unexpected();
21507 }
21508
21509 return this.parseClass(node, true);
21510
21511 case types._if:
21512 return this.parseIfStatement(node);
21513
21514 case types._return:
21515 return this.parseReturnStatement(node);
21516
21517 case types._switch:
21518 return this.parseSwitchStatement(node);
21519
21520 case types._throw:
21521 return this.parseThrowStatement(node);
21522
21523 case types._try:
21524 return this.parseTryStatement(node);
21525
21526 case types._const:
21527 case types._var:
21528 kind = kind || this.value;
21529
21530 if (context && kind !== "var") {
21531 this.unexpected();
21532 }
21533
21534 return this.parseVarStatement(node, kind);
21535
21536 case types._while:
21537 return this.parseWhileStatement(node);
21538
21539 case types._with:
21540 return this.parseWithStatement(node);
21541
21542 case types.braceL:
21543 return this.parseBlock(true, node);
21544
21545 case types.semi:
21546 return this.parseEmptyStatement(node);
21547
21548 case types._export:
21549 case types._import:
21550 if (this.options.ecmaVersion > 10 && starttype === types._import) {
21551 skipWhiteSpace.lastIndex = this.pos;
21552 var skip = skipWhiteSpace.exec(this.input);
21553 var next = this.pos + skip[0].length,
21554 nextCh = this.input.charCodeAt(next);
21555
56c4a2cb 21556 if (nextCh === 40 || nextCh === 46) // '(' or '.'
eb39fafa
DC
21557 {
21558 return this.parseExpressionStatement(node, this.parseExpression());
21559 }
21560 }
21561
21562 if (!this.options.allowImportExportEverywhere) {
21563 if (!topLevel) {
21564 this.raise(this.start, "'import' and 'export' may only appear at the top level");
21565 }
21566
21567 if (!this.inModule) {
21568 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
21569 }
21570 }
21571
21572 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports);
21573 // If the statement does not start with a statement keyword or a
21574 // brace, it's an ExpressionStatement or LabeledStatement. We
21575 // simply start parsing an expression, and afterwards, if the
21576 // next token is a colon and the expression was a simple
21577 // Identifier node, we switch to interpreting it as a label.
21578
21579 default:
21580 if (this.isAsyncFunction()) {
21581 if (context) {
21582 this.unexpected();
21583 }
21584
21585 this.next();
21586 return this.parseFunctionStatement(node, true, !context);
21587 }
21588
21589 var maybeName = this.value,
21590 expr = this.parseExpression();
21591
21592 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
21593 return this.parseLabeledStatement(node, maybeName, expr, context);
21594 } else {
21595 return this.parseExpressionStatement(node, expr);
21596 }
21597
21598 }
21599 };
21600
21601 pp$1.parseBreakContinueStatement = function (node, keyword) {
21602 var isBreak = keyword === "break";
21603 this.next();
21604
21605 if (this.eat(types.semi) || this.insertSemicolon()) {
21606 node.label = null;
21607 } else if (this.type !== types.name) {
21608 this.unexpected();
21609 } else {
21610 node.label = this.parseIdent();
21611 this.semicolon();
21612 } // Verify that there is an actual destination to break or
21613 // continue to.
21614
21615
21616 var i = 0;
21617
21618 for (; i < this.labels.length; ++i) {
21619 var lab = this.labels[i];
21620
21621 if (node.label == null || lab.name === node.label.name) {
21622 if (lab.kind != null && (isBreak || lab.kind === "loop")) {
21623 break;
21624 }
21625
21626 if (node.label && isBreak) {
21627 break;
21628 }
21629 }
21630 }
21631
21632 if (i === this.labels.length) {
21633 this.raise(node.start, "Unsyntactic " + keyword);
21634 }
21635
21636 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
21637 };
21638
21639 pp$1.parseDebuggerStatement = function (node) {
21640 this.next();
21641 this.semicolon();
21642 return this.finishNode(node, "DebuggerStatement");
21643 };
21644
21645 pp$1.parseDoStatement = function (node) {
21646 this.next();
21647 this.labels.push(loopLabel);
21648 node.body = this.parseStatement("do");
21649 this.labels.pop();
21650 this.expect(types._while);
21651 node.test = this.parseParenExpression();
21652
21653 if (this.options.ecmaVersion >= 6) {
21654 this.eat(types.semi);
21655 } else {
21656 this.semicolon();
21657 }
21658
21659 return this.finishNode(node, "DoWhileStatement");
21660 }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
21661 // loop is non-trivial. Basically, we have to parse the init `var`
21662 // statement or expression, disallowing the `in` operator (see
21663 // the second parameter to `parseExpression`), and then check
21664 // whether the next token is `in` or `of`. When there is no init
21665 // part (semicolon immediately after the opening parenthesis), it
21666 // is a regular `for` loop.
21667
21668
21669 pp$1.parseForStatement = function (node) {
21670 this.next();
21671 var awaitAt = this.options.ecmaVersion >= 9 && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction) && this.eatContextual("await") ? this.lastTokStart : -1;
21672 this.labels.push(loopLabel);
21673 this.enterScope(0);
21674 this.expect(types.parenL);
21675
21676 if (this.type === types.semi) {
21677 if (awaitAt > -1) {
21678 this.unexpected(awaitAt);
21679 }
21680
21681 return this.parseFor(node, null);
21682 }
21683
21684 var isLet = this.isLet();
21685
21686 if (this.type === types._var || this.type === types._const || isLet) {
21687 var init$1 = this.startNode(),
21688 kind = isLet ? "let" : this.value;
21689 this.next();
21690 this.parseVar(init$1, true, kind);
21691 this.finishNode(init$1, "VariableDeclaration");
21692
21693 if ((this.type === types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
21694 if (this.options.ecmaVersion >= 9) {
21695 if (this.type === types._in) {
21696 if (awaitAt > -1) {
21697 this.unexpected(awaitAt);
21698 }
21699 } else {
21700 node.await = awaitAt > -1;
21701 }
21702 }
21703
21704 return this.parseForIn(node, init$1);
21705 }
21706
21707 if (awaitAt > -1) {
21708 this.unexpected(awaitAt);
21709 }
21710
21711 return this.parseFor(node, init$1);
21712 }
21713
21714 var refDestructuringErrors = new DestructuringErrors();
21715 var init = this.parseExpression(true, refDestructuringErrors);
21716
21717 if (this.type === types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
21718 if (this.options.ecmaVersion >= 9) {
21719 if (this.type === types._in) {
21720 if (awaitAt > -1) {
21721 this.unexpected(awaitAt);
21722 }
21723 } else {
21724 node.await = awaitAt > -1;
21725 }
21726 }
21727
21728 this.toAssignable(init, false, refDestructuringErrors);
21729 this.checkLVal(init);
21730 return this.parseForIn(node, init);
21731 } else {
21732 this.checkExpressionErrors(refDestructuringErrors, true);
21733 }
21734
21735 if (awaitAt > -1) {
21736 this.unexpected(awaitAt);
21737 }
21738
21739 return this.parseFor(node, init);
21740 };
21741
21742 pp$1.parseFunctionStatement = function (node, isAsync, declarationPosition) {
21743 this.next();
21744 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync);
21745 };
21746
21747 pp$1.parseIfStatement = function (node) {
21748 this.next();
21749 node.test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode
21750
21751 node.consequent = this.parseStatement("if");
21752 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
21753 return this.finishNode(node, "IfStatement");
21754 };
21755
21756 pp$1.parseReturnStatement = function (node) {
21757 if (!this.inFunction && !this.options.allowReturnOutsideFunction) {
21758 this.raise(this.start, "'return' outside of function");
21759 }
21760
21761 this.next(); // In `return` (and `break`/`continue`), the keywords with
21762 // optional arguments, we eagerly look for a semicolon or the
21763 // possibility to insert one.
21764
21765 if (this.eat(types.semi) || this.insertSemicolon()) {
21766 node.argument = null;
21767 } else {
21768 node.argument = this.parseExpression();
21769 this.semicolon();
21770 }
21771
21772 return this.finishNode(node, "ReturnStatement");
21773 };
21774
21775 pp$1.parseSwitchStatement = function (node) {
21776 this.next();
21777 node.discriminant = this.parseParenExpression();
21778 node.cases = [];
21779 this.expect(types.braceL);
21780 this.labels.push(switchLabel);
21781 this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase
21782 // nodes. `cur` is used to keep the node that we are currently
21783 // adding statements to.
21784
21785 var cur;
21786
21787 for (var sawDefault = false; this.type !== types.braceR;) {
21788 if (this.type === types._case || this.type === types._default) {
21789 var isCase = this.type === types._case;
21790
21791 if (cur) {
21792 this.finishNode(cur, "SwitchCase");
21793 }
21794
21795 node.cases.push(cur = this.startNode());
21796 cur.consequent = [];
21797 this.next();
21798
21799 if (isCase) {
21800 cur.test = this.parseExpression();
21801 } else {
21802 if (sawDefault) {
21803 this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
21804 }
21805
21806 sawDefault = true;
21807 cur.test = null;
21808 }
21809
21810 this.expect(types.colon);
21811 } else {
21812 if (!cur) {
21813 this.unexpected();
21814 }
21815
21816 cur.consequent.push(this.parseStatement(null));
21817 }
21818 }
21819
21820 this.exitScope();
21821
21822 if (cur) {
21823 this.finishNode(cur, "SwitchCase");
21824 }
21825
21826 this.next(); // Closing brace
21827
21828 this.labels.pop();
21829 return this.finishNode(node, "SwitchStatement");
21830 };
21831
21832 pp$1.parseThrowStatement = function (node) {
21833 this.next();
21834
21835 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {
21836 this.raise(this.lastTokEnd, "Illegal newline after throw");
21837 }
21838
21839 node.argument = this.parseExpression();
21840 this.semicolon();
21841 return this.finishNode(node, "ThrowStatement");
21842 }; // Reused empty array added for node fields that are always empty.
21843
21844
21845 var empty = [];
21846
21847 pp$1.parseTryStatement = function (node) {
21848 this.next();
21849 node.block = this.parseBlock();
21850 node.handler = null;
21851
21852 if (this.type === types._catch) {
21853 var clause = this.startNode();
21854 this.next();
21855
21856 if (this.eat(types.parenL)) {
21857 clause.param = this.parseBindingAtom();
21858 var simple = clause.param.type === "Identifier";
21859 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
21860 this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
21861 this.expect(types.parenR);
21862 } else {
21863 if (this.options.ecmaVersion < 10) {
21864 this.unexpected();
21865 }
21866
21867 clause.param = null;
21868 this.enterScope(0);
21869 }
21870
21871 clause.body = this.parseBlock(false);
21872 this.exitScope();
21873 node.handler = this.finishNode(clause, "CatchClause");
21874 }
21875
21876 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
21877
21878 if (!node.handler && !node.finalizer) {
21879 this.raise(node.start, "Missing catch or finally clause");
21880 }
21881
21882 return this.finishNode(node, "TryStatement");
21883 };
21884
21885 pp$1.parseVarStatement = function (node, kind) {
21886 this.next();
21887 this.parseVar(node, false, kind);
21888 this.semicolon();
21889 return this.finishNode(node, "VariableDeclaration");
21890 };
21891
21892 pp$1.parseWhileStatement = function (node) {
21893 this.next();
21894 node.test = this.parseParenExpression();
21895 this.labels.push(loopLabel);
21896 node.body = this.parseStatement("while");
21897 this.labels.pop();
21898 return this.finishNode(node, "WhileStatement");
21899 };
21900
21901 pp$1.parseWithStatement = function (node) {
21902 if (this.strict) {
21903 this.raise(this.start, "'with' in strict mode");
21904 }
21905
21906 this.next();
21907 node.object = this.parseParenExpression();
21908 node.body = this.parseStatement("with");
21909 return this.finishNode(node, "WithStatement");
21910 };
21911
21912 pp$1.parseEmptyStatement = function (node) {
21913 this.next();
21914 return this.finishNode(node, "EmptyStatement");
21915 };
21916
21917 pp$1.parseLabeledStatement = function (node, maybeName, expr, context) {
21918 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) {
21919 var label = list[i$1];
21920
21921 if (label.name === maybeName) {
21922 this.raise(expr.start, "Label '" + maybeName + "' is already declared");
21923 }
21924 }
21925
21926 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
21927
21928 for (var i = this.labels.length - 1; i >= 0; i--) {
21929 var label$1 = this.labels[i];
21930
21931 if (label$1.statementStart === node.start) {
21932 // Update information about previous labels on this node
21933 label$1.statementStart = this.start;
21934 label$1.kind = kind;
21935 } else {
21936 break;
21937 }
21938 }
21939
21940 this.labels.push({
21941 name: maybeName,
21942 kind: kind,
21943 statementStart: this.start
21944 });
21945 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
21946 this.labels.pop();
21947 node.label = expr;
21948 return this.finishNode(node, "LabeledStatement");
21949 };
21950
21951 pp$1.parseExpressionStatement = function (node, expr) {
21952 node.expression = expr;
21953 this.semicolon();
21954 return this.finishNode(node, "ExpressionStatement");
21955 }; // Parse a semicolon-enclosed block of statements, handling `"use
21956 // strict"` declarations when `allowStrict` is true (used for
21957 // function bodies).
21958
21959
56c4a2cb 21960 pp$1.parseBlock = function (createNewLexicalScope, node, exitStrict) {
eb39fafa
DC
21961 if (createNewLexicalScope === void 0) createNewLexicalScope = true;
21962 if (node === void 0) node = this.startNode();
21963 node.body = [];
21964 this.expect(types.braceL);
21965
21966 if (createNewLexicalScope) {
21967 this.enterScope(0);
21968 }
21969
56c4a2cb 21970 while (this.type !== types.braceR) {
eb39fafa
DC
21971 var stmt = this.parseStatement(null);
21972 node.body.push(stmt);
21973 }
21974
56c4a2cb
DC
21975 if (exitStrict) {
21976 this.strict = false;
21977 }
21978
21979 this.next();
21980
eb39fafa
DC
21981 if (createNewLexicalScope) {
21982 this.exitScope();
21983 }
21984
21985 return this.finishNode(node, "BlockStatement");
21986 }; // Parse a regular `for` loop. The disambiguation code in
21987 // `parseStatement` will already have parsed the init statement or
21988 // expression.
21989
21990
21991 pp$1.parseFor = function (node, init) {
21992 node.init = init;
21993 this.expect(types.semi);
21994 node.test = this.type === types.semi ? null : this.parseExpression();
21995 this.expect(types.semi);
21996 node.update = this.type === types.parenR ? null : this.parseExpression();
21997 this.expect(types.parenR);
21998 node.body = this.parseStatement("for");
21999 this.exitScope();
22000 this.labels.pop();
22001 return this.finishNode(node, "ForStatement");
22002 }; // Parse a `for`/`in` and `for`/`of` loop, which are almost
22003 // same from parser's perspective.
22004
22005
22006 pp$1.parseForIn = function (node, init) {
22007 var isForIn = this.type === types._in;
22008 this.next();
22009
22010 if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
22011 this.raise(init.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
22012 } else if (init.type === "AssignmentPattern") {
22013 this.raise(init.start, "Invalid left-hand side in for-loop");
22014 }
22015
22016 node.left = init;
22017 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
22018 this.expect(types.parenR);
22019 node.body = this.parseStatement("for");
22020 this.exitScope();
22021 this.labels.pop();
22022 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
22023 }; // Parse a list of variable declarations.
22024
22025
22026 pp$1.parseVar = function (node, isFor, kind) {
22027 node.declarations = [];
22028 node.kind = kind;
22029
22030 for (;;) {
22031 var decl = this.startNode();
22032 this.parseVarId(decl, kind);
22033
22034 if (this.eat(types.eq)) {
22035 decl.init = this.parseMaybeAssign(isFor);
22036 } else if (kind === "const" && !(this.type === types._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
22037 this.unexpected();
22038 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
22039 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
22040 } else {
22041 decl.init = null;
22042 }
22043
22044 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
22045
22046 if (!this.eat(types.comma)) {
22047 break;
22048 }
22049 }
22050
22051 return node;
22052 };
22053
22054 pp$1.parseVarId = function (decl, kind) {
22055 decl.id = this.parseBindingAtom();
22056 this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
22057 };
22058
22059 var FUNC_STATEMENT = 1,
22060 FUNC_HANGING_STATEMENT = 2,
22061 FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the
22062 // `statement & FUNC_STATEMENT`).
22063 // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
22064
22065 pp$1.parseFunction = function (node, statement, allowExpressionBody, isAsync) {
22066 this.initFunction(node);
22067
22068 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
22069 if (this.type === types.star && statement & FUNC_HANGING_STATEMENT) {
22070 this.unexpected();
22071 }
22072
22073 node.generator = this.eat(types.star);
22074 }
22075
22076 if (this.options.ecmaVersion >= 8) {
22077 node.async = !!isAsync;
22078 }
22079
22080 if (statement & FUNC_STATEMENT) {
22081 node.id = statement & FUNC_NULLABLE_ID && this.type !== types.name ? null : this.parseIdent();
22082
22083 if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is
22084 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
22085 // mode depends on properties of the current scope (see
22086 // treatFunctionsAsVar).
22087 {
22088 this.checkLVal(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
22089 }
22090 }
22091
22092 var oldYieldPos = this.yieldPos,
22093 oldAwaitPos = this.awaitPos,
22094 oldAwaitIdentPos = this.awaitIdentPos;
22095 this.yieldPos = 0;
22096 this.awaitPos = 0;
22097 this.awaitIdentPos = 0;
22098 this.enterScope(functionFlags(node.async, node.generator));
22099
22100 if (!(statement & FUNC_STATEMENT)) {
22101 node.id = this.type === types.name ? this.parseIdent() : null;
22102 }
22103
22104 this.parseFunctionParams(node);
22105 this.parseFunctionBody(node, allowExpressionBody, false);
22106 this.yieldPos = oldYieldPos;
22107 this.awaitPos = oldAwaitPos;
22108 this.awaitIdentPos = oldAwaitIdentPos;
22109 return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
22110 };
22111
22112 pp$1.parseFunctionParams = function (node) {
22113 this.expect(types.parenL);
22114 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
22115 this.checkYieldAwaitInDefaultParams();
22116 }; // Parse a class declaration or literal (depending on the
22117 // `isStatement` parameter).
22118
22119
22120 pp$1.parseClass = function (node, isStatement) {
22121 this.next(); // ecma-262 14.6 Class Definitions
22122 // A class definition is always strict mode code.
22123
22124 var oldStrict = this.strict;
22125 this.strict = true;
22126 this.parseClassId(node, isStatement);
22127 this.parseClassSuper(node);
22128 var classBody = this.startNode();
22129 var hadConstructor = false;
22130 classBody.body = [];
22131 this.expect(types.braceL);
22132
56c4a2cb 22133 while (this.type !== types.braceR) {
eb39fafa
DC
22134 var element = this.parseClassElement(node.superClass !== null);
22135
22136 if (element) {
22137 classBody.body.push(element);
22138
22139 if (element.type === "MethodDefinition" && element.kind === "constructor") {
22140 if (hadConstructor) {
22141 this.raise(element.start, "Duplicate constructor in the same class");
22142 }
22143
22144 hadConstructor = true;
22145 }
22146 }
22147 }
22148
eb39fafa 22149 this.strict = oldStrict;
56c4a2cb
DC
22150 this.next();
22151 node.body = this.finishNode(classBody, "ClassBody");
eb39fafa
DC
22152 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
22153 };
22154
22155 pp$1.parseClassElement = function (constructorAllowsSuper) {
22156 var this$1 = this;
22157
22158 if (this.eat(types.semi)) {
22159 return null;
22160 }
22161
22162 var method = this.startNode();
22163
22164 var tryContextual = function tryContextual(k, noLineBreak) {
22165 if (noLineBreak === void 0) noLineBreak = false;
22166 var start = this$1.start,
22167 startLoc = this$1.startLoc;
22168
22169 if (!this$1.eatContextual(k)) {
22170 return false;
22171 }
22172
22173 if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) {
22174 return true;
22175 }
22176
22177 if (method.key) {
22178 this$1.unexpected();
22179 }
22180
22181 method.computed = false;
22182 method.key = this$1.startNodeAt(start, startLoc);
22183 method.key.name = k;
22184 this$1.finishNode(method.key, "Identifier");
22185 return false;
22186 };
22187
22188 method.kind = "method";
22189 method.static = tryContextual("static");
22190 var isGenerator = this.eat(types.star);
22191 var isAsync = false;
22192
22193 if (!isGenerator) {
22194 if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
22195 isAsync = true;
22196 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
22197 } else if (tryContextual("get")) {
22198 method.kind = "get";
22199 } else if (tryContextual("set")) {
22200 method.kind = "set";
22201 }
22202 }
22203
22204 if (!method.key) {
22205 this.parsePropertyName(method);
22206 }
22207
22208 var key = method.key;
22209 var allowsDirectSuper = false;
22210
22211 if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
22212 if (method.kind !== "method") {
22213 this.raise(key.start, "Constructor can't have get/set modifier");
22214 }
22215
22216 if (isGenerator) {
22217 this.raise(key.start, "Constructor can't be a generator");
22218 }
22219
22220 if (isAsync) {
22221 this.raise(key.start, "Constructor can't be an async method");
22222 }
22223
22224 method.kind = "constructor";
22225 allowsDirectSuper = constructorAllowsSuper;
22226 } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
22227 this.raise(key.start, "Classes may not have a static property named prototype");
22228 }
22229
22230 this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
22231
22232 if (method.kind === "get" && method.value.params.length !== 0) {
22233 this.raiseRecoverable(method.value.start, "getter should have no params");
22234 }
22235
22236 if (method.kind === "set" && method.value.params.length !== 1) {
22237 this.raiseRecoverable(method.value.start, "setter should have exactly one param");
22238 }
22239
22240 if (method.kind === "set" && method.value.params[0].type === "RestElement") {
22241 this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params");
22242 }
22243
22244 return method;
22245 };
22246
22247 pp$1.parseClassMethod = function (method, isGenerator, isAsync, allowsDirectSuper) {
22248 method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
22249 return this.finishNode(method, "MethodDefinition");
22250 };
22251
22252 pp$1.parseClassId = function (node, isStatement) {
22253 if (this.type === types.name) {
22254 node.id = this.parseIdent();
22255
22256 if (isStatement) {
22257 this.checkLVal(node.id, BIND_LEXICAL, false);
22258 }
22259 } else {
22260 if (isStatement === true) {
22261 this.unexpected();
22262 }
22263
22264 node.id = null;
22265 }
22266 };
22267
22268 pp$1.parseClassSuper = function (node) {
22269 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
22270 }; // Parses module export declaration.
22271
22272
22273 pp$1.parseExport = function (node, exports) {
22274 this.next(); // export * from '...'
22275
22276 if (this.eat(types.star)) {
56c4a2cb
DC
22277 if (this.options.ecmaVersion >= 11) {
22278 if (this.eatContextual("as")) {
22279 node.exported = this.parseIdent(true);
22280 this.checkExport(exports, node.exported.name, this.lastTokStart);
22281 } else {
22282 node.exported = null;
22283 }
22284 }
22285
eb39fafa
DC
22286 this.expectContextual("from");
22287
22288 if (this.type !== types.string) {
22289 this.unexpected();
22290 }
22291
22292 node.source = this.parseExprAtom();
22293 this.semicolon();
22294 return this.finishNode(node, "ExportAllDeclaration");
22295 }
22296
22297 if (this.eat(types._default)) {
22298 // export default ...
22299 this.checkExport(exports, "default", this.lastTokStart);
22300 var isAsync;
22301
22302 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
22303 var fNode = this.startNode();
22304 this.next();
22305
22306 if (isAsync) {
22307 this.next();
22308 }
22309
22310 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
22311 } else if (this.type === types._class) {
22312 var cNode = this.startNode();
22313 node.declaration = this.parseClass(cNode, "nullableID");
22314 } else {
22315 node.declaration = this.parseMaybeAssign();
22316 this.semicolon();
22317 }
22318
22319 return this.finishNode(node, "ExportDefaultDeclaration");
22320 } // export var|const|let|function|class ...
22321
22322
22323 if (this.shouldParseExportStatement()) {
22324 node.declaration = this.parseStatement(null);
22325
22326 if (node.declaration.type === "VariableDeclaration") {
22327 this.checkVariableExport(exports, node.declaration.declarations);
22328 } else {
22329 this.checkExport(exports, node.declaration.id.name, node.declaration.id.start);
22330 }
22331
22332 node.specifiers = [];
22333 node.source = null;
22334 } else {
22335 // export { x, y as z } [from '...']
22336 node.declaration = null;
22337 node.specifiers = this.parseExportSpecifiers(exports);
22338
22339 if (this.eatContextual("from")) {
22340 if (this.type !== types.string) {
22341 this.unexpected();
22342 }
22343
22344 node.source = this.parseExprAtom();
22345 } else {
22346 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
22347 // check for keywords used as local names
22348 var spec = list[i];
22349 this.checkUnreserved(spec.local); // check if export is defined
22350
22351 this.checkLocalExport(spec.local);
22352 }
22353
22354 node.source = null;
22355 }
22356
22357 this.semicolon();
22358 }
22359
22360 return this.finishNode(node, "ExportNamedDeclaration");
22361 };
22362
22363 pp$1.checkExport = function (exports, name, pos) {
22364 if (!exports) {
22365 return;
22366 }
22367
22368 if (has(exports, name)) {
22369 this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
22370 }
22371
22372 exports[name] = true;
22373 };
22374
22375 pp$1.checkPatternExport = function (exports, pat) {
22376 var type = pat.type;
22377
22378 if (type === "Identifier") {
22379 this.checkExport(exports, pat.name, pat.start);
22380 } else if (type === "ObjectPattern") {
22381 for (var i = 0, list = pat.properties; i < list.length; i += 1) {
22382 var prop = list[i];
22383 this.checkPatternExport(exports, prop);
22384 }
22385 } else if (type === "ArrayPattern") {
22386 for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
22387 var elt = list$1[i$1];
22388
22389 if (elt) {
22390 this.checkPatternExport(exports, elt);
22391 }
22392 }
22393 } else if (type === "Property") {
22394 this.checkPatternExport(exports, pat.value);
22395 } else if (type === "AssignmentPattern") {
22396 this.checkPatternExport(exports, pat.left);
22397 } else if (type === "RestElement") {
22398 this.checkPatternExport(exports, pat.argument);
22399 } else if (type === "ParenthesizedExpression") {
22400 this.checkPatternExport(exports, pat.expression);
22401 }
22402 };
22403
22404 pp$1.checkVariableExport = function (exports, decls) {
22405 if (!exports) {
22406 return;
22407 }
22408
22409 for (var i = 0, list = decls; i < list.length; i += 1) {
22410 var decl = list[i];
22411 this.checkPatternExport(exports, decl.id);
22412 }
22413 };
22414
22415 pp$1.shouldParseExportStatement = function () {
22416 return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
22417 }; // Parses a comma-separated list of module exports.
22418
22419
22420 pp$1.parseExportSpecifiers = function (exports) {
22421 var nodes = [],
22422 first = true; // export { x, y as z } [from '...']
22423
22424 this.expect(types.braceL);
22425
22426 while (!this.eat(types.braceR)) {
22427 if (!first) {
22428 this.expect(types.comma);
22429
22430 if (this.afterTrailingComma(types.braceR)) {
22431 break;
22432 }
22433 } else {
22434 first = false;
22435 }
22436
22437 var node = this.startNode();
22438 node.local = this.parseIdent(true);
22439 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
22440 this.checkExport(exports, node.exported.name, node.exported.start);
22441 nodes.push(this.finishNode(node, "ExportSpecifier"));
22442 }
22443
22444 return nodes;
22445 }; // Parses import declaration.
22446
22447
22448 pp$1.parseImport = function (node) {
22449 this.next(); // import '...'
22450
22451 if (this.type === types.string) {
22452 node.specifiers = empty;
22453 node.source = this.parseExprAtom();
22454 } else {
22455 node.specifiers = this.parseImportSpecifiers();
22456 this.expectContextual("from");
22457 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
22458 }
22459
22460 this.semicolon();
22461 return this.finishNode(node, "ImportDeclaration");
22462 }; // Parses a comma-separated list of module imports.
22463
22464
22465 pp$1.parseImportSpecifiers = function () {
22466 var nodes = [],
22467 first = true;
22468
22469 if (this.type === types.name) {
22470 // import defaultObj, { x, y as z } from '...'
22471 var node = this.startNode();
22472 node.local = this.parseIdent();
22473 this.checkLVal(node.local, BIND_LEXICAL);
22474 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
22475
22476 if (!this.eat(types.comma)) {
22477 return nodes;
22478 }
22479 }
22480
22481 if (this.type === types.star) {
22482 var node$1 = this.startNode();
22483 this.next();
22484 this.expectContextual("as");
22485 node$1.local = this.parseIdent();
22486 this.checkLVal(node$1.local, BIND_LEXICAL);
22487 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
22488 return nodes;
22489 }
22490
22491 this.expect(types.braceL);
22492
22493 while (!this.eat(types.braceR)) {
22494 if (!first) {
22495 this.expect(types.comma);
22496
22497 if (this.afterTrailingComma(types.braceR)) {
22498 break;
22499 }
22500 } else {
22501 first = false;
22502 }
22503
22504 var node$2 = this.startNode();
22505 node$2.imported = this.parseIdent(true);
22506
22507 if (this.eatContextual("as")) {
22508 node$2.local = this.parseIdent();
22509 } else {
22510 this.checkUnreserved(node$2.imported);
22511 node$2.local = node$2.imported;
22512 }
22513
22514 this.checkLVal(node$2.local, BIND_LEXICAL);
22515 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
22516 }
22517
22518 return nodes;
22519 }; // Set `ExpressionStatement#directive` property for directive prologues.
22520
22521
22522 pp$1.adaptDirectivePrologue = function (statements) {
22523 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
22524 statements[i].directive = statements[i].expression.raw.slice(1, -1);
22525 }
22526 };
22527
22528 pp$1.isDirectiveCandidate = function (statement) {
22529 return statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && ( // Reject parenthesized strings.
22530 this.input[statement.start] === "\"" || this.input[statement.start] === "'");
22531 };
22532
22533 var pp$2 = Parser.prototype; // Convert existing expression atom to assignable pattern
22534 // if possible.
22535
22536 pp$2.toAssignable = function (node, isBinding, refDestructuringErrors) {
22537 if (this.options.ecmaVersion >= 6 && node) {
22538 switch (node.type) {
22539 case "Identifier":
22540 if (this.inAsync && node.name === "await") {
22541 this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
22542 }
22543
22544 break;
22545
22546 case "ObjectPattern":
22547 case "ArrayPattern":
22548 case "RestElement":
22549 break;
22550
22551 case "ObjectExpression":
22552 node.type = "ObjectPattern";
22553
22554 if (refDestructuringErrors) {
22555 this.checkPatternErrors(refDestructuringErrors, true);
22556 }
22557
22558 for (var i = 0, list = node.properties; i < list.length; i += 1) {
22559 var prop = list[i];
22560 this.toAssignable(prop, isBinding); // Early error:
22561 // AssignmentRestProperty[Yield, Await] :
22562 // `...` DestructuringAssignmentTarget[Yield, Await]
22563 //
22564 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
22565
22566 if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
22567 this.raise(prop.argument.start, "Unexpected token");
22568 }
22569 }
22570
22571 break;
22572
22573 case "Property":
22574 // AssignmentProperty has type === "Property"
22575 if (node.kind !== "init") {
22576 this.raise(node.key.start, "Object pattern can't contain getter or setter");
22577 }
22578
22579 this.toAssignable(node.value, isBinding);
22580 break;
22581
22582 case "ArrayExpression":
22583 node.type = "ArrayPattern";
22584
22585 if (refDestructuringErrors) {
22586 this.checkPatternErrors(refDestructuringErrors, true);
22587 }
22588
22589 this.toAssignableList(node.elements, isBinding);
22590 break;
22591
22592 case "SpreadElement":
22593 node.type = "RestElement";
22594 this.toAssignable(node.argument, isBinding);
22595
22596 if (node.argument.type === "AssignmentPattern") {
22597 this.raise(node.argument.start, "Rest elements cannot have a default value");
22598 }
22599
22600 break;
22601
22602 case "AssignmentExpression":
22603 if (node.operator !== "=") {
22604 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
22605 }
22606
22607 node.type = "AssignmentPattern";
22608 delete node.operator;
22609 this.toAssignable(node.left, isBinding);
22610 // falls through to AssignmentPattern
22611
22612 case "AssignmentPattern":
22613 break;
22614
22615 case "ParenthesizedExpression":
22616 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
22617 break;
22618
22619 case "MemberExpression":
22620 if (!isBinding) {
22621 break;
22622 }
22623
22624 default:
22625 this.raise(node.start, "Assigning to rvalue");
22626 }
22627 } else if (refDestructuringErrors) {
22628 this.checkPatternErrors(refDestructuringErrors, true);
22629 }
22630
22631 return node;
22632 }; // Convert list of expression atoms to binding list.
22633
22634
22635 pp$2.toAssignableList = function (exprList, isBinding) {
22636 var end = exprList.length;
22637
22638 for (var i = 0; i < end; i++) {
22639 var elt = exprList[i];
22640
22641 if (elt) {
22642 this.toAssignable(elt, isBinding);
22643 }
22644 }
22645
22646 if (end) {
22647 var last = exprList[end - 1];
22648
22649 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
22650 this.unexpected(last.argument.start);
22651 }
22652 }
22653
22654 return exprList;
22655 }; // Parses spread element.
22656
22657
22658 pp$2.parseSpread = function (refDestructuringErrors) {
22659 var node = this.startNode();
22660 this.next();
22661 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
22662 return this.finishNode(node, "SpreadElement");
22663 };
22664
22665 pp$2.parseRestBinding = function () {
22666 var node = this.startNode();
22667 this.next(); // RestElement inside of a function parameter must be an identifier
22668
22669 if (this.options.ecmaVersion === 6 && this.type !== types.name) {
22670 this.unexpected();
22671 }
22672
22673 node.argument = this.parseBindingAtom();
22674 return this.finishNode(node, "RestElement");
22675 }; // Parses lvalue (assignable) atom.
22676
22677
22678 pp$2.parseBindingAtom = function () {
22679 if (this.options.ecmaVersion >= 6) {
22680 switch (this.type) {
22681 case types.bracketL:
22682 var node = this.startNode();
22683 this.next();
22684 node.elements = this.parseBindingList(types.bracketR, true, true);
22685 return this.finishNode(node, "ArrayPattern");
22686
22687 case types.braceL:
22688 return this.parseObj(true);
22689 }
22690 }
22691
22692 return this.parseIdent();
22693 };
22694
22695 pp$2.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
22696 var elts = [],
22697 first = true;
22698
22699 while (!this.eat(close)) {
22700 if (first) {
22701 first = false;
22702 } else {
22703 this.expect(types.comma);
22704 }
22705
22706 if (allowEmpty && this.type === types.comma) {
22707 elts.push(null);
22708 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
22709 break;
22710 } else if (this.type === types.ellipsis) {
22711 var rest = this.parseRestBinding();
22712 this.parseBindingListItem(rest);
22713 elts.push(rest);
22714
22715 if (this.type === types.comma) {
22716 this.raise(this.start, "Comma is not permitted after the rest element");
22717 }
22718
22719 this.expect(close);
22720 break;
22721 } else {
22722 var elem = this.parseMaybeDefault(this.start, this.startLoc);
22723 this.parseBindingListItem(elem);
22724 elts.push(elem);
22725 }
22726 }
22727
22728 return elts;
22729 };
22730
22731 pp$2.parseBindingListItem = function (param) {
22732 return param;
22733 }; // Parses assignment pattern around given atom if possible.
22734
22735
22736 pp$2.parseMaybeDefault = function (startPos, startLoc, left) {
22737 left = left || this.parseBindingAtom();
22738
22739 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) {
22740 return left;
22741 }
22742
22743 var node = this.startNodeAt(startPos, startLoc);
22744 node.left = left;
22745 node.right = this.parseMaybeAssign();
22746 return this.finishNode(node, "AssignmentPattern");
22747 }; // Verify that a node is an lval — something that can be assigned
22748 // to.
22749 // bindingType can be either:
22750 // 'var' indicating that the lval creates a 'var' binding
22751 // 'let' indicating that the lval creates a lexical ('let' or 'const') binding
22752 // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
22753
22754
22755 pp$2.checkLVal = function (expr, bindingType, checkClashes) {
22756 if (bindingType === void 0) bindingType = BIND_NONE;
22757
22758 switch (expr.type) {
22759 case "Identifier":
22760 if (bindingType === BIND_LEXICAL && expr.name === "let") {
22761 this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
22762 }
22763
22764 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
22765 this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
22766 }
22767
22768 if (checkClashes) {
22769 if (has(checkClashes, expr.name)) {
22770 this.raiseRecoverable(expr.start, "Argument name clash");
22771 }
22772
22773 checkClashes[expr.name] = true;
22774 }
22775
22776 if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) {
22777 this.declareName(expr.name, bindingType, expr.start);
22778 }
22779
22780 break;
22781
22782 case "MemberExpression":
22783 if (bindingType) {
22784 this.raiseRecoverable(expr.start, "Binding member expression");
22785 }
22786
22787 break;
22788
22789 case "ObjectPattern":
22790 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
22791 var prop = list[i];
22792 this.checkLVal(prop, bindingType, checkClashes);
22793 }
22794
22795 break;
22796
22797 case "Property":
22798 // AssignmentProperty has type === "Property"
22799 this.checkLVal(expr.value, bindingType, checkClashes);
22800 break;
22801
22802 case "ArrayPattern":
22803 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
22804 var elem = list$1[i$1];
22805
22806 if (elem) {
22807 this.checkLVal(elem, bindingType, checkClashes);
22808 }
22809 }
22810
22811 break;
22812
22813 case "AssignmentPattern":
22814 this.checkLVal(expr.left, bindingType, checkClashes);
22815 break;
22816
22817 case "RestElement":
22818 this.checkLVal(expr.argument, bindingType, checkClashes);
22819 break;
22820
22821 case "ParenthesizedExpression":
22822 this.checkLVal(expr.expression, bindingType, checkClashes);
22823 break;
22824
22825 default:
22826 this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
22827 }
22828 }; // A recursive descent parser operates by defining functions for all
22829
22830
22831 var pp$3 = Parser.prototype; // Check if property name clashes with already added.
22832 // Object/class getters and setters are not allowed to clash —
22833 // either with each other or with an init property — and in
22834 // strict mode, init properties are also not allowed to be repeated.
22835
22836 pp$3.checkPropClash = function (prop, propHash, refDestructuringErrors) {
22837 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
22838 return;
22839 }
22840
22841 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
22842 return;
22843 }
22844
22845 var key = prop.key;
22846 var name;
22847
22848 switch (key.type) {
22849 case "Identifier":
22850 name = key.name;
22851 break;
22852
22853 case "Literal":
22854 name = String(key.value);
22855 break;
22856
22857 default:
22858 return;
22859 }
22860
22861 var kind = prop.kind;
22862
22863 if (this.options.ecmaVersion >= 6) {
22864 if (name === "__proto__" && kind === "init") {
22865 if (propHash.proto) {
22866 if (refDestructuringErrors) {
22867 if (refDestructuringErrors.doubleProto < 0) {
22868 refDestructuringErrors.doubleProto = key.start;
22869 } // Backwards-compat kludge. Can be removed in version 6.0
22870
22871 } else {
22872 this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
22873 }
22874 }
22875
22876 propHash.proto = true;
22877 }
22878
22879 return;
22880 }
22881
22882 name = "$" + name;
22883 var other = propHash[name];
22884
22885 if (other) {
22886 var redefinition;
22887
22888 if (kind === "init") {
22889 redefinition = this.strict && other.init || other.get || other.set;
22890 } else {
22891 redefinition = other.init || other[kind];
22892 }
22893
22894 if (redefinition) {
22895 this.raiseRecoverable(key.start, "Redefinition of property");
22896 }
22897 } else {
22898 other = propHash[name] = {
22899 init: false,
22900 get: false,
22901 set: false
22902 };
22903 }
22904
22905 other[kind] = true;
22906 }; // ### Expression parsing
22907 // These nest, from the most general expression type at the top to
22908 // 'atomic', nondivisible expression types at the bottom. Most of
22909 // the functions will simply let the function(s) below them parse,
22910 // and, *if* the syntactic construct they handle is present, wrap
22911 // the AST node that the inner parser gave them in another node.
22912 // Parse a full expression. The optional arguments are used to
22913 // forbid the `in` operator (in for loops initalization expressions)
22914 // and provide reference for storing '=' operator inside shorthand
22915 // property assignment in contexts where both object expression
22916 // and object pattern might appear (so it's possible to raise
22917 // delayed syntax error at correct position).
22918
22919
22920 pp$3.parseExpression = function (noIn, refDestructuringErrors) {
22921 var startPos = this.start,
22922 startLoc = this.startLoc;
22923 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
22924
22925 if (this.type === types.comma) {
22926 var node = this.startNodeAt(startPos, startLoc);
22927 node.expressions = [expr];
22928
22929 while (this.eat(types.comma)) {
22930 node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors));
22931 }
22932
22933 return this.finishNode(node, "SequenceExpression");
22934 }
22935
22936 return expr;
22937 }; // Parse an assignment expression. This includes applications of
22938 // operators like `+=`.
22939
22940
22941 pp$3.parseMaybeAssign = function (noIn, refDestructuringErrors, afterLeftParse) {
22942 if (this.isContextual("yield")) {
22943 if (this.inGenerator) {
22944 return this.parseYield(noIn);
22945 } // The tokenizer will assume an expression is allowed after
22946 // `yield`, but this isn't that kind of yield
22947 else {
22948 this.exprAllowed = false;
22949 }
22950 }
22951
22952 var ownDestructuringErrors = false,
22953 oldParenAssign = -1,
22954 oldTrailingComma = -1;
22955
22956 if (refDestructuringErrors) {
22957 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
22958 oldTrailingComma = refDestructuringErrors.trailingComma;
22959 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
22960 } else {
22961 refDestructuringErrors = new DestructuringErrors();
22962 ownDestructuringErrors = true;
22963 }
22964
22965 var startPos = this.start,
22966 startLoc = this.startLoc;
22967
22968 if (this.type === types.parenL || this.type === types.name) {
22969 this.potentialArrowAt = this.start;
22970 }
22971
22972 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
22973
22974 if (afterLeftParse) {
22975 left = afterLeftParse.call(this, left, startPos, startLoc);
22976 }
22977
22978 if (this.type.isAssign) {
22979 var node = this.startNodeAt(startPos, startLoc);
22980 node.operator = this.value;
22981 node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
22982
22983 if (!ownDestructuringErrors) {
22984 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
22985 }
22986
22987 if (refDestructuringErrors.shorthandAssign >= node.left.start) {
22988 refDestructuringErrors.shorthandAssign = -1;
22989 } // reset because shorthand default was used correctly
22990
22991
22992 this.checkLVal(left);
22993 this.next();
22994 node.right = this.parseMaybeAssign(noIn);
22995 return this.finishNode(node, "AssignmentExpression");
22996 } else {
22997 if (ownDestructuringErrors) {
22998 this.checkExpressionErrors(refDestructuringErrors, true);
22999 }
23000 }
23001
23002 if (oldParenAssign > -1) {
23003 refDestructuringErrors.parenthesizedAssign = oldParenAssign;
23004 }
23005
23006 if (oldTrailingComma > -1) {
23007 refDestructuringErrors.trailingComma = oldTrailingComma;
23008 }
23009
23010 return left;
23011 }; // Parse a ternary conditional (`?:`) operator.
23012
23013
23014 pp$3.parseMaybeConditional = function (noIn, refDestructuringErrors) {
23015 var startPos = this.start,
23016 startLoc = this.startLoc;
23017 var expr = this.parseExprOps(noIn, refDestructuringErrors);
23018
23019 if (this.checkExpressionErrors(refDestructuringErrors)) {
23020 return expr;
23021 }
23022
23023 if (this.eat(types.question)) {
23024 var node = this.startNodeAt(startPos, startLoc);
23025 node.test = expr;
23026 node.consequent = this.parseMaybeAssign();
23027 this.expect(types.colon);
23028 node.alternate = this.parseMaybeAssign(noIn);
23029 return this.finishNode(node, "ConditionalExpression");
23030 }
23031
23032 return expr;
23033 }; // Start the precedence parser.
23034
23035
23036 pp$3.parseExprOps = function (noIn, refDestructuringErrors) {
23037 var startPos = this.start,
23038 startLoc = this.startLoc;
23039 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
23040
23041 if (this.checkExpressionErrors(refDestructuringErrors)) {
23042 return expr;
23043 }
23044
23045 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn);
23046 }; // Parse binary operators with the operator precedence parsing
23047 // algorithm. `left` is the left-hand side of the operator.
23048 // `minPrec` provides context that allows the function to stop and
23049 // defer further parser to one of its callers when it encounters an
23050 // operator that has a lower precedence than the set it is parsing.
23051
23052
23053 pp$3.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
23054 var prec = this.type.binop;
23055
23056 if (prec != null && (!noIn || this.type !== types._in)) {
23057 if (prec > minPrec) {
23058 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
56c4a2cb
DC
23059 var coalesce = this.type === types.coalesce;
23060
23061 if (coalesce) {
23062 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
23063 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
23064 prec = types.logicalAND.binop;
23065 }
23066
eb39fafa
DC
23067 var op = this.value;
23068 this.next();
23069 var startPos = this.start,
23070 startLoc = this.startLoc;
23071 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
56c4a2cb
DC
23072 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
23073
23074 if (logical && this.type === types.coalesce || coalesce && (this.type === types.logicalOR || this.type === types.logicalAND)) {
23075 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
23076 }
23077
eb39fafa
DC
23078 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
23079 }
23080 }
23081
23082 return left;
23083 };
23084
23085 pp$3.buildBinary = function (startPos, startLoc, left, right, op, logical) {
23086 var node = this.startNodeAt(startPos, startLoc);
23087 node.left = left;
23088 node.operator = op;
23089 node.right = right;
23090 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
23091 }; // Parse unary operators, both prefix and postfix.
23092
23093
23094 pp$3.parseMaybeUnary = function (refDestructuringErrors, sawUnary) {
23095 var startPos = this.start,
23096 startLoc = this.startLoc,
23097 expr;
23098
23099 if (this.isContextual("await") && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction)) {
23100 expr = this.parseAwait();
23101 sawUnary = true;
23102 } else if (this.type.prefix) {
23103 var node = this.startNode(),
23104 update = this.type === types.incDec;
23105 node.operator = this.value;
23106 node.prefix = true;
23107 this.next();
23108 node.argument = this.parseMaybeUnary(null, true);
23109 this.checkExpressionErrors(refDestructuringErrors, true);
23110
23111 if (update) {
23112 this.checkLVal(node.argument);
23113 } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") {
23114 this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
23115 } else {
23116 sawUnary = true;
23117 }
23118
23119 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
23120 } else {
23121 expr = this.parseExprSubscripts(refDestructuringErrors);
23122
23123 if (this.checkExpressionErrors(refDestructuringErrors)) {
23124 return expr;
23125 }
23126
23127 while (this.type.postfix && !this.canInsertSemicolon()) {
23128 var node$1 = this.startNodeAt(startPos, startLoc);
23129 node$1.operator = this.value;
23130 node$1.prefix = false;
23131 node$1.argument = expr;
23132 this.checkLVal(expr);
23133 this.next();
23134 expr = this.finishNode(node$1, "UpdateExpression");
23135 }
23136 }
23137
23138 if (!sawUnary && this.eat(types.starstar)) {
23139 return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false);
23140 } else {
23141 return expr;
23142 }
23143 }; // Parse call, dot, and `[]`-subscript expressions.
23144
23145
23146 pp$3.parseExprSubscripts = function (refDestructuringErrors) {
23147 var startPos = this.start,
23148 startLoc = this.startLoc;
23149 var expr = this.parseExprAtom(refDestructuringErrors);
23150
23151 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
23152 return expr;
23153 }
23154
23155 var result = this.parseSubscripts(expr, startPos, startLoc);
23156
23157 if (refDestructuringErrors && result.type === "MemberExpression") {
23158 if (refDestructuringErrors.parenthesizedAssign >= result.start) {
23159 refDestructuringErrors.parenthesizedAssign = -1;
23160 }
23161
23162 if (refDestructuringErrors.parenthesizedBind >= result.start) {
23163 refDestructuringErrors.parenthesizedBind = -1;
23164 }
23165 }
23166
23167 return result;
23168 };
23169
23170 pp$3.parseSubscripts = function (base, startPos, startLoc, noCalls) {
56c4a2cb 23171 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start;
eb39fafa
DC
23172
23173 while (true) {
23174 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow);
23175
23176 if (element === base || element.type === "ArrowFunctionExpression") {
23177 return element;
23178 }
23179
23180 base = element;
23181 }
23182 };
23183
23184 pp$3.parseSubscript = function (base, startPos, startLoc, noCalls, maybeAsyncArrow) {
23185 var computed = this.eat(types.bracketL);
23186
23187 if (computed || this.eat(types.dot)) {
23188 var node = this.startNodeAt(startPos, startLoc);
23189 node.object = base;
23190 node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
23191 node.computed = !!computed;
23192
23193 if (computed) {
23194 this.expect(types.bracketR);
23195 }
23196
23197 base = this.finishNode(node, "MemberExpression");
23198 } else if (!noCalls && this.eat(types.parenL)) {
23199 var refDestructuringErrors = new DestructuringErrors(),
23200 oldYieldPos = this.yieldPos,
23201 oldAwaitPos = this.awaitPos,
23202 oldAwaitIdentPos = this.awaitIdentPos;
23203 this.yieldPos = 0;
23204 this.awaitPos = 0;
23205 this.awaitIdentPos = 0;
23206 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
23207
23208 if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
23209 this.checkPatternErrors(refDestructuringErrors, false);
23210 this.checkYieldAwaitInDefaultParams();
23211
23212 if (this.awaitIdentPos > 0) {
23213 this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
23214 }
23215
23216 this.yieldPos = oldYieldPos;
23217 this.awaitPos = oldAwaitPos;
23218 this.awaitIdentPos = oldAwaitIdentPos;
23219 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true);
23220 }
23221
23222 this.checkExpressionErrors(refDestructuringErrors, true);
23223 this.yieldPos = oldYieldPos || this.yieldPos;
23224 this.awaitPos = oldAwaitPos || this.awaitPos;
23225 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
23226 var node$1 = this.startNodeAt(startPos, startLoc);
23227 node$1.callee = base;
23228 node$1.arguments = exprList;
23229 base = this.finishNode(node$1, "CallExpression");
23230 } else if (this.type === types.backQuote) {
23231 var node$2 = this.startNodeAt(startPos, startLoc);
23232 node$2.tag = base;
23233 node$2.quasi = this.parseTemplate({
23234 isTagged: true
23235 });
23236 base = this.finishNode(node$2, "TaggedTemplateExpression");
23237 }
23238
23239 return base;
23240 }; // Parse an atomic expression — either a single token that is an
23241 // expression, an expression started by a keyword like `function` or
23242 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
23243 // or `{}`.
23244
23245
23246 pp$3.parseExprAtom = function (refDestructuringErrors) {
23247 // If a division operator appears in an expression position, the
23248 // tokenizer got confused, and we force it to read a regexp instead.
23249 if (this.type === types.slash) {
23250 this.readRegexp();
23251 }
23252
23253 var node,
23254 canBeArrow = this.potentialArrowAt === this.start;
23255
23256 switch (this.type) {
23257 case types._super:
23258 if (!this.allowSuper) {
23259 this.raise(this.start, "'super' keyword outside a method");
23260 }
23261
23262 node = this.startNode();
23263 this.next();
23264
23265 if (this.type === types.parenL && !this.allowDirectSuper) {
23266 this.raise(node.start, "super() call outside constructor of a subclass");
23267 } // The `super` keyword can appear at below:
23268 // SuperProperty:
23269 // super [ Expression ]
23270 // super . IdentifierName
23271 // SuperCall:
23272 // super ( Arguments )
23273
23274
23275 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) {
23276 this.unexpected();
23277 }
23278
23279 return this.finishNode(node, "Super");
23280
23281 case types._this:
23282 node = this.startNode();
23283 this.next();
23284 return this.finishNode(node, "ThisExpression");
23285
23286 case types.name:
23287 var startPos = this.start,
23288 startLoc = this.startLoc,
23289 containsEsc = this.containsEsc;
23290 var id = this.parseIdent(false);
23291
23292 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) {
23293 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true);
23294 }
23295
23296 if (canBeArrow && !this.canInsertSemicolon()) {
23297 if (this.eat(types.arrow)) {
23298 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false);
23299 }
23300
23301 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
23302 id = this.parseIdent(false);
23303
23304 if (this.canInsertSemicolon() || !this.eat(types.arrow)) {
23305 this.unexpected();
23306 }
23307
23308 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true);
23309 }
23310 }
23311
23312 return id;
23313
23314 case types.regexp:
23315 var value = this.value;
23316 node = this.parseLiteral(value.value);
23317 node.regex = {
23318 pattern: value.pattern,
23319 flags: value.flags
23320 };
23321 return node;
23322
23323 case types.num:
23324 case types.string:
23325 return this.parseLiteral(this.value);
23326
23327 case types._null:
23328 case types._true:
23329 case types._false:
23330 node = this.startNode();
23331 node.value = this.type === types._null ? null : this.type === types._true;
23332 node.raw = this.type.keyword;
23333 this.next();
23334 return this.finishNode(node, "Literal");
23335
23336 case types.parenL:
23337 var start = this.start,
23338 expr = this.parseParenAndDistinguishExpression(canBeArrow);
23339
23340 if (refDestructuringErrors) {
23341 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
23342 refDestructuringErrors.parenthesizedAssign = start;
23343 }
23344
23345 if (refDestructuringErrors.parenthesizedBind < 0) {
23346 refDestructuringErrors.parenthesizedBind = start;
23347 }
23348 }
23349
23350 return expr;
23351
23352 case types.bracketL:
23353 node = this.startNode();
23354 this.next();
23355 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
23356 return this.finishNode(node, "ArrayExpression");
23357
23358 case types.braceL:
23359 return this.parseObj(false, refDestructuringErrors);
23360
23361 case types._function:
23362 node = this.startNode();
23363 this.next();
23364 return this.parseFunction(node, 0);
23365
23366 case types._class:
23367 return this.parseClass(this.startNode(), false);
23368
23369 case types._new:
23370 return this.parseNew();
23371
23372 case types.backQuote:
23373 return this.parseTemplate();
23374
23375 case types._import:
23376 if (this.options.ecmaVersion >= 11) {
23377 return this.parseExprImport();
23378 } else {
23379 return this.unexpected();
23380 }
23381
23382 default:
23383 this.unexpected();
23384 }
23385 };
23386
23387 pp$3.parseExprImport = function () {
56c4a2cb
DC
23388 var node = this.startNode(); // Consume `import` as an identifier for `import.meta`.
23389 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
23390
23391 if (this.containsEsc) {
23392 this.raiseRecoverable(this.start, "Escape sequence in keyword import");
23393 }
23394
23395 var meta = this.parseIdent(true);
eb39fafa
DC
23396
23397 switch (this.type) {
23398 case types.parenL:
23399 return this.parseDynamicImport(node);
23400
56c4a2cb
DC
23401 case types.dot:
23402 node.meta = meta;
23403 return this.parseImportMeta(node);
23404
eb39fafa
DC
23405 default:
23406 this.unexpected();
23407 }
23408 };
23409
23410 pp$3.parseDynamicImport = function (node) {
23411 this.next(); // skip `(`
23412 // Parse node.source.
23413
23414 node.source = this.parseMaybeAssign(); // Verify ending.
23415
23416 if (!this.eat(types.parenR)) {
23417 var errorPos = this.start;
23418
23419 if (this.eat(types.comma) && this.eat(types.parenR)) {
23420 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
23421 } else {
23422 this.unexpected(errorPos);
23423 }
23424 }
23425
23426 return this.finishNode(node, "ImportExpression");
23427 };
23428
56c4a2cb
DC
23429 pp$3.parseImportMeta = function (node) {
23430 this.next(); // skip `.`
23431
23432 var containsEsc = this.containsEsc;
23433 node.property = this.parseIdent(true);
23434
23435 if (node.property.name !== "meta") {
23436 this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
23437 }
23438
23439 if (containsEsc) {
23440 this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
23441 }
23442
23443 if (this.options.sourceType !== "module") {
23444 this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
23445 }
23446
23447 return this.finishNode(node, "MetaProperty");
23448 };
23449
eb39fafa
DC
23450 pp$3.parseLiteral = function (value) {
23451 var node = this.startNode();
23452 node.value = value;
23453 node.raw = this.input.slice(this.start, this.end);
23454
23455 if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
23456 node.bigint = node.raw.slice(0, -1);
23457 }
23458
23459 this.next();
23460 return this.finishNode(node, "Literal");
23461 };
23462
23463 pp$3.parseParenExpression = function () {
23464 this.expect(types.parenL);
23465 var val = this.parseExpression();
23466 this.expect(types.parenR);
23467 return val;
23468 };
23469
23470 pp$3.parseParenAndDistinguishExpression = function (canBeArrow) {
23471 var startPos = this.start,
23472 startLoc = this.startLoc,
23473 val,
23474 allowTrailingComma = this.options.ecmaVersion >= 8;
23475
23476 if (this.options.ecmaVersion >= 6) {
23477 this.next();
23478 var innerStartPos = this.start,
23479 innerStartLoc = this.startLoc;
23480 var exprList = [],
23481 first = true,
23482 lastIsComma = false;
23483 var refDestructuringErrors = new DestructuringErrors(),
23484 oldYieldPos = this.yieldPos,
23485 oldAwaitPos = this.awaitPos,
23486 spreadStart;
23487 this.yieldPos = 0;
23488 this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters
23489
23490 while (this.type !== types.parenR) {
23491 first ? first = false : this.expect(types.comma);
23492
23493 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
23494 lastIsComma = true;
23495 break;
23496 } else if (this.type === types.ellipsis) {
23497 spreadStart = this.start;
23498 exprList.push(this.parseParenItem(this.parseRestBinding()));
23499
23500 if (this.type === types.comma) {
23501 this.raise(this.start, "Comma is not permitted after the rest element");
23502 }
23503
23504 break;
23505 } else {
23506 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
23507 }
23508 }
23509
23510 var innerEndPos = this.start,
23511 innerEndLoc = this.startLoc;
23512 this.expect(types.parenR);
23513
23514 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
23515 this.checkPatternErrors(refDestructuringErrors, false);
23516 this.checkYieldAwaitInDefaultParams();
23517 this.yieldPos = oldYieldPos;
23518 this.awaitPos = oldAwaitPos;
23519 return this.parseParenArrowList(startPos, startLoc, exprList);
23520 }
23521
23522 if (!exprList.length || lastIsComma) {
23523 this.unexpected(this.lastTokStart);
23524 }
23525
23526 if (spreadStart) {
23527 this.unexpected(spreadStart);
23528 }
23529
23530 this.checkExpressionErrors(refDestructuringErrors, true);
23531 this.yieldPos = oldYieldPos || this.yieldPos;
23532 this.awaitPos = oldAwaitPos || this.awaitPos;
23533
23534 if (exprList.length > 1) {
23535 val = this.startNodeAt(innerStartPos, innerStartLoc);
23536 val.expressions = exprList;
23537 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
23538 } else {
23539 val = exprList[0];
23540 }
23541 } else {
23542 val = this.parseParenExpression();
23543 }
23544
23545 if (this.options.preserveParens) {
23546 var par = this.startNodeAt(startPos, startLoc);
23547 par.expression = val;
23548 return this.finishNode(par, "ParenthesizedExpression");
23549 } else {
23550 return val;
23551 }
23552 };
23553
23554 pp$3.parseParenItem = function (item) {
23555 return item;
23556 };
23557
23558 pp$3.parseParenArrowList = function (startPos, startLoc, exprList) {
23559 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
23560 }; // New's precedence is slightly tricky. It must allow its argument to
23561 // be a `[]` or dot subscript expression, but not a call — at least,
23562 // not without wrapping it in parentheses. Thus, it uses the noCalls
23563 // argument to parseSubscripts to prevent it from consuming the
23564 // argument list.
23565
23566
23567 var empty$1 = [];
23568
23569 pp$3.parseNew = function () {
23570 if (this.containsEsc) {
23571 this.raiseRecoverable(this.start, "Escape sequence in keyword new");
23572 }
23573
23574 var node = this.startNode();
23575 var meta = this.parseIdent(true);
23576
23577 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
23578 node.meta = meta;
23579 var containsEsc = this.containsEsc;
23580 node.property = this.parseIdent(true);
23581
56c4a2cb
DC
23582 if (node.property.name !== "target") {
23583 this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
23584 }
23585
23586 if (containsEsc) {
23587 this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
eb39fafa
DC
23588 }
23589
23590 if (!this.inNonArrowFunction()) {
56c4a2cb 23591 this.raiseRecoverable(node.start, "'new.target' can only be used in functions");
eb39fafa
DC
23592 }
23593
23594 return this.finishNode(node, "MetaProperty");
23595 }
23596
23597 var startPos = this.start,
23598 startLoc = this.startLoc,
23599 isImport = this.type === types._import;
23600 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
23601
23602 if (isImport && node.callee.type === "ImportExpression") {
23603 this.raise(startPos, "Cannot use new with import()");
23604 }
23605
23606 if (this.eat(types.parenL)) {
23607 node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false);
23608 } else {
23609 node.arguments = empty$1;
23610 }
23611
23612 return this.finishNode(node, "NewExpression");
23613 }; // Parse template expression.
23614
23615
23616 pp$3.parseTemplateElement = function (ref) {
23617 var isTagged = ref.isTagged;
23618 var elem = this.startNode();
23619
23620 if (this.type === types.invalidTemplate) {
23621 if (!isTagged) {
23622 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
23623 }
23624
23625 elem.value = {
23626 raw: this.value,
23627 cooked: null
23628 };
23629 } else {
23630 elem.value = {
23631 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
23632 cooked: this.value
23633 };
23634 }
23635
23636 this.next();
23637 elem.tail = this.type === types.backQuote;
23638 return this.finishNode(elem, "TemplateElement");
23639 };
23640
23641 pp$3.parseTemplate = function (ref) {
23642 if (ref === void 0) ref = {};
23643 var isTagged = ref.isTagged;
23644 if (isTagged === void 0) isTagged = false;
23645 var node = this.startNode();
23646 this.next();
23647 node.expressions = [];
23648 var curElt = this.parseTemplateElement({
23649 isTagged: isTagged
23650 });
23651 node.quasis = [curElt];
23652
23653 while (!curElt.tail) {
23654 if (this.type === types.eof) {
23655 this.raise(this.pos, "Unterminated template literal");
23656 }
23657
23658 this.expect(types.dollarBraceL);
23659 node.expressions.push(this.parseExpression());
23660 this.expect(types.braceR);
23661 node.quasis.push(curElt = this.parseTemplateElement({
23662 isTagged: isTagged
23663 }));
23664 }
23665
23666 this.next();
23667 return this.finishNode(node, "TemplateLiteral");
23668 };
23669
23670 pp$3.isAsyncProp = function (prop) {
23671 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
23672 }; // Parse an object literal or binding pattern.
23673
23674
23675 pp$3.parseObj = function (isPattern, refDestructuringErrors) {
23676 var node = this.startNode(),
23677 first = true,
23678 propHash = {};
23679 node.properties = [];
23680 this.next();
23681
23682 while (!this.eat(types.braceR)) {
23683 if (!first) {
23684 this.expect(types.comma);
23685
23686 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) {
23687 break;
23688 }
23689 } else {
23690 first = false;
23691 }
23692
23693 var prop = this.parseProperty(isPattern, refDestructuringErrors);
23694
23695 if (!isPattern) {
23696 this.checkPropClash(prop, propHash, refDestructuringErrors);
23697 }
23698
23699 node.properties.push(prop);
23700 }
23701
23702 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
23703 };
23704
23705 pp$3.parseProperty = function (isPattern, refDestructuringErrors) {
23706 var prop = this.startNode(),
23707 isGenerator,
23708 isAsync,
23709 startPos,
23710 startLoc;
23711
23712 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
23713 if (isPattern) {
23714 prop.argument = this.parseIdent(false);
23715
23716 if (this.type === types.comma) {
23717 this.raise(this.start, "Comma is not permitted after the rest element");
23718 }
23719
23720 return this.finishNode(prop, "RestElement");
23721 } // To disallow parenthesized identifier via `this.toAssignable()`.
23722
23723
23724 if (this.type === types.parenL && refDestructuringErrors) {
23725 if (refDestructuringErrors.parenthesizedAssign < 0) {
23726 refDestructuringErrors.parenthesizedAssign = this.start;
23727 }
23728
23729 if (refDestructuringErrors.parenthesizedBind < 0) {
23730 refDestructuringErrors.parenthesizedBind = this.start;
23731 }
23732 } // Parse argument.
23733
23734
23735 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`.
23736
23737 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
23738 refDestructuringErrors.trailingComma = this.start;
23739 } // Finish
23740
23741
23742 return this.finishNode(prop, "SpreadElement");
23743 }
23744
23745 if (this.options.ecmaVersion >= 6) {
23746 prop.method = false;
23747 prop.shorthand = false;
23748
23749 if (isPattern || refDestructuringErrors) {
23750 startPos = this.start;
23751 startLoc = this.startLoc;
23752 }
23753
23754 if (!isPattern) {
23755 isGenerator = this.eat(types.star);
23756 }
23757 }
23758
23759 var containsEsc = this.containsEsc;
23760 this.parsePropertyName(prop);
23761
23762 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
23763 isAsync = true;
23764 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
23765 this.parsePropertyName(prop, refDestructuringErrors);
23766 } else {
23767 isAsync = false;
23768 }
23769
23770 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
23771 return this.finishNode(prop, "Property");
23772 };
23773
23774 pp$3.parsePropertyValue = function (prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
23775 if ((isGenerator || isAsync) && this.type === types.colon) {
23776 this.unexpected();
23777 }
23778
23779 if (this.eat(types.colon)) {
23780 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
23781 prop.kind = "init";
23782 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
23783 if (isPattern) {
23784 this.unexpected();
23785 }
23786
23787 prop.kind = "init";
23788 prop.method = true;
23789 prop.value = this.parseMethod(isGenerator, isAsync);
23790 } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && this.type !== types.comma && this.type !== types.braceR) {
23791 if (isGenerator || isAsync) {
23792 this.unexpected();
23793 }
23794
23795 prop.kind = prop.key.name;
23796 this.parsePropertyName(prop);
23797 prop.value = this.parseMethod(false);
23798 var paramCount = prop.kind === "get" ? 0 : 1;
23799
23800 if (prop.value.params.length !== paramCount) {
23801 var start = prop.value.start;
23802
23803 if (prop.kind === "get") {
23804 this.raiseRecoverable(start, "getter should have no params");
23805 } else {
23806 this.raiseRecoverable(start, "setter should have exactly one param");
23807 }
23808 } else {
23809 if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
23810 this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
23811 }
23812 }
23813 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
23814 if (isGenerator || isAsync) {
23815 this.unexpected();
23816 }
23817
23818 this.checkUnreserved(prop.key);
23819
23820 if (prop.key.name === "await" && !this.awaitIdentPos) {
23821 this.awaitIdentPos = startPos;
23822 }
23823
23824 prop.kind = "init";
23825
23826 if (isPattern) {
23827 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
23828 } else if (this.type === types.eq && refDestructuringErrors) {
23829 if (refDestructuringErrors.shorthandAssign < 0) {
23830 refDestructuringErrors.shorthandAssign = this.start;
23831 }
23832
23833 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
23834 } else {
23835 prop.value = prop.key;
23836 }
23837
23838 prop.shorthand = true;
23839 } else {
23840 this.unexpected();
23841 }
23842 };
23843
23844 pp$3.parsePropertyName = function (prop) {
23845 if (this.options.ecmaVersion >= 6) {
23846 if (this.eat(types.bracketL)) {
23847 prop.computed = true;
23848 prop.key = this.parseMaybeAssign();
23849 this.expect(types.bracketR);
23850 return prop.key;
23851 } else {
23852 prop.computed = false;
23853 }
23854 }
23855
23856 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
23857 }; // Initialize empty function node.
23858
23859
23860 pp$3.initFunction = function (node) {
23861 node.id = null;
23862
23863 if (this.options.ecmaVersion >= 6) {
23864 node.generator = node.expression = false;
23865 }
23866
23867 if (this.options.ecmaVersion >= 8) {
23868 node.async = false;
23869 }
23870 }; // Parse object or class method.
23871
23872
23873 pp$3.parseMethod = function (isGenerator, isAsync, allowDirectSuper) {
23874 var node = this.startNode(),
23875 oldYieldPos = this.yieldPos,
23876 oldAwaitPos = this.awaitPos,
23877 oldAwaitIdentPos = this.awaitIdentPos;
23878 this.initFunction(node);
23879
23880 if (this.options.ecmaVersion >= 6) {
23881 node.generator = isGenerator;
23882 }
23883
23884 if (this.options.ecmaVersion >= 8) {
23885 node.async = !!isAsync;
23886 }
23887
23888 this.yieldPos = 0;
23889 this.awaitPos = 0;
23890 this.awaitIdentPos = 0;
23891 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
23892 this.expect(types.parenL);
23893 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
23894 this.checkYieldAwaitInDefaultParams();
23895 this.parseFunctionBody(node, false, true);
23896 this.yieldPos = oldYieldPos;
23897 this.awaitPos = oldAwaitPos;
23898 this.awaitIdentPos = oldAwaitIdentPos;
23899 return this.finishNode(node, "FunctionExpression");
23900 }; // Parse arrow function expression with given parameters.
23901
23902
23903 pp$3.parseArrowExpression = function (node, params, isAsync) {
23904 var oldYieldPos = this.yieldPos,
23905 oldAwaitPos = this.awaitPos,
23906 oldAwaitIdentPos = this.awaitIdentPos;
23907 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
23908 this.initFunction(node);
23909
23910 if (this.options.ecmaVersion >= 8) {
23911 node.async = !!isAsync;
23912 }
23913
23914 this.yieldPos = 0;
23915 this.awaitPos = 0;
23916 this.awaitIdentPos = 0;
23917 node.params = this.toAssignableList(params, true);
23918 this.parseFunctionBody(node, true, false);
23919 this.yieldPos = oldYieldPos;
23920 this.awaitPos = oldAwaitPos;
23921 this.awaitIdentPos = oldAwaitIdentPos;
23922 return this.finishNode(node, "ArrowFunctionExpression");
23923 }; // Parse function body and check parameters.
23924
23925
23926 pp$3.parseFunctionBody = function (node, isArrowFunction, isMethod) {
23927 var isExpression = isArrowFunction && this.type !== types.braceL;
23928 var oldStrict = this.strict,
23929 useStrict = false;
23930
23931 if (isExpression) {
23932 node.body = this.parseMaybeAssign();
23933 node.expression = true;
23934 this.checkParams(node, false);
23935 } else {
23936 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
23937
23938 if (!oldStrict || nonSimple) {
23939 useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names
23940 // are not repeated, and it does not try to bind the words `eval`
23941 // or `arguments`.
23942
23943 if (useStrict && nonSimple) {
23944 this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
23945 }
23946 } // Start a new scope with regard to labels and the `inFunction`
23947 // flag (restore them to their old value afterwards).
23948
23949
23950 var oldLabels = this.labels;
23951 this.labels = [];
23952
23953 if (useStrict) {
23954 this.strict = true;
23955 } // Add the params to varDeclaredNames to ensure that an error is thrown
23956 // if a let/const declaration in the function clashes with one of the params.
23957
23958
56c4a2cb
DC
23959 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
23960
23961 if (this.strict && node.id) {
23962 this.checkLVal(node.id, BIND_OUTSIDE);
23963 }
23964
23965 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
eb39fafa
DC
23966 node.expression = false;
23967 this.adaptDirectivePrologue(node.body.body);
23968 this.labels = oldLabels;
23969 }
23970
56c4a2cb 23971 this.exitScope();
eb39fafa
DC
23972 };
23973
23974 pp$3.isSimpleParamList = function (params) {
23975 for (var i = 0, list = params; i < list.length; i += 1) {
23976 var param = list[i];
23977
23978 if (param.type !== "Identifier") {
23979 return false;
23980 }
23981 }
23982
23983 return true;
23984 }; // Checks function params for various disallowed patterns such as using "eval"
23985 // or "arguments" and duplicate parameters.
23986
23987
23988 pp$3.checkParams = function (node, allowDuplicates) {
23989 var nameHash = {};
23990
23991 for (var i = 0, list = node.params; i < list.length; i += 1) {
23992 var param = list[i];
23993 this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);
23994 }
23995 }; // Parses a comma-separated list of expressions, and returns them as
23996 // an array. `close` is the token type that ends the list, and
23997 // `allowEmpty` can be turned on to allow subsequent commas with
23998 // nothing in between them to be parsed as `null` (which is needed
23999 // for array literals).
24000
24001
24002 pp$3.parseExprList = function (close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
24003 var elts = [],
24004 first = true;
24005
24006 while (!this.eat(close)) {
24007 if (!first) {
24008 this.expect(types.comma);
24009
24010 if (allowTrailingComma && this.afterTrailingComma(close)) {
24011 break;
24012 }
24013 } else {
24014 first = false;
24015 }
24016
24017 var elt = void 0;
24018
24019 if (allowEmpty && this.type === types.comma) {
24020 elt = null;
24021 } else if (this.type === types.ellipsis) {
24022 elt = this.parseSpread(refDestructuringErrors);
24023
24024 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) {
24025 refDestructuringErrors.trailingComma = this.start;
24026 }
24027 } else {
24028 elt = this.parseMaybeAssign(false, refDestructuringErrors);
24029 }
24030
24031 elts.push(elt);
24032 }
24033
24034 return elts;
24035 };
24036
24037 pp$3.checkUnreserved = function (ref) {
24038 var start = ref.start;
24039 var end = ref.end;
24040 var name = ref.name;
24041
24042 if (this.inGenerator && name === "yield") {
24043 this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
24044 }
24045
24046 if (this.inAsync && name === "await") {
24047 this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
24048 }
24049
24050 if (this.keywords.test(name)) {
24051 this.raise(start, "Unexpected keyword '" + name + "'");
24052 }
24053
24054 if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
24055 return;
24056 }
24057
24058 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
24059
24060 if (re.test(name)) {
24061 if (!this.inAsync && name === "await") {
24062 this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
24063 }
24064
24065 this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
24066 }
24067 }; // Parse the next token as an identifier. If `liberal` is true (used
24068 // when parsing properties), it will also convert keywords into
24069 // identifiers.
24070
24071
24072 pp$3.parseIdent = function (liberal, isBinding) {
24073 var node = this.startNode();
24074
24075 if (this.type === types.name) {
24076 node.name = this.value;
24077 } else if (this.type.keyword) {
24078 node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575
24079 // `class` and `function` keywords push new context into this.context.
24080 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
24081 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
24082
24083 if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
24084 this.context.pop();
24085 }
24086 } else {
24087 this.unexpected();
24088 }
24089
24090 this.next(!!liberal);
24091 this.finishNode(node, "Identifier");
24092
24093 if (!liberal) {
24094 this.checkUnreserved(node);
24095
24096 if (node.name === "await" && !this.awaitIdentPos) {
24097 this.awaitIdentPos = node.start;
24098 }
24099 }
24100
24101 return node;
24102 }; // Parses yield expression inside generator.
24103
24104
24105 pp$3.parseYield = function (noIn) {
24106 if (!this.yieldPos) {
24107 this.yieldPos = this.start;
24108 }
24109
24110 var node = this.startNode();
24111 this.next();
24112
24113 if (this.type === types.semi || this.canInsertSemicolon() || this.type !== types.star && !this.type.startsExpr) {
24114 node.delegate = false;
24115 node.argument = null;
24116 } else {
24117 node.delegate = this.eat(types.star);
24118 node.argument = this.parseMaybeAssign(noIn);
24119 }
24120
24121 return this.finishNode(node, "YieldExpression");
24122 };
24123
24124 pp$3.parseAwait = function () {
24125 if (!this.awaitPos) {
24126 this.awaitPos = this.start;
24127 }
24128
24129 var node = this.startNode();
24130 this.next();
24131 node.argument = this.parseMaybeUnary(null, false);
24132 return this.finishNode(node, "AwaitExpression");
24133 };
24134
24135 var pp$4 = Parser.prototype; // This function is used to raise exceptions on parse errors. It
24136 // takes an offset integer (into the current `input`) to indicate
24137 // the location of the error, attaches the position to the end
24138 // of the error message, and then raises a `SyntaxError` with that
24139 // message.
24140
24141 pp$4.raise = function (pos, message) {
24142 var loc = getLineInfo(this.input, pos);
24143 message += " (" + loc.line + ":" + loc.column + ")";
24144 var err = new SyntaxError(message);
24145 err.pos = pos;
24146 err.loc = loc;
24147 err.raisedAt = this.pos;
24148 throw err;
24149 };
24150
24151 pp$4.raiseRecoverable = pp$4.raise;
24152
24153 pp$4.curPosition = function () {
24154 if (this.options.locations) {
24155 return new Position(this.curLine, this.pos - this.lineStart);
24156 }
24157 };
24158
24159 var pp$5 = Parser.prototype;
24160
24161 var Scope = function Scope(flags) {
24162 this.flags = flags; // A list of var-declared names in the current lexical scope
24163
24164 this.var = []; // A list of lexically-declared names in the current lexical scope
24165
24166 this.lexical = []; // A list of lexically-declared FunctionDeclaration names in the current lexical scope
24167
24168 this.functions = [];
24169 }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
24170
24171
24172 pp$5.enterScope = function (flags) {
24173 this.scopeStack.push(new Scope(flags));
24174 };
24175
24176 pp$5.exitScope = function () {
24177 this.scopeStack.pop();
24178 }; // The spec says:
24179 // > At the top level of a function, or script, function declarations are
24180 // > treated like var declarations rather than like lexical declarations.
24181
24182
24183 pp$5.treatFunctionsAsVarInScope = function (scope) {
24184 return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
24185 };
24186
24187 pp$5.declareName = function (name, bindingType, pos) {
24188 var redeclared = false;
24189
24190 if (bindingType === BIND_LEXICAL) {
24191 var scope = this.currentScope();
24192 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
24193 scope.lexical.push(name);
24194
24195 if (this.inModule && scope.flags & SCOPE_TOP) {
24196 delete this.undefinedExports[name];
24197 }
24198 } else if (bindingType === BIND_SIMPLE_CATCH) {
24199 var scope$1 = this.currentScope();
24200 scope$1.lexical.push(name);
24201 } else if (bindingType === BIND_FUNCTION) {
24202 var scope$2 = this.currentScope();
24203
24204 if (this.treatFunctionsAsVar) {
24205 redeclared = scope$2.lexical.indexOf(name) > -1;
24206 } else {
24207 redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
24208 }
24209
24210 scope$2.functions.push(name);
24211 } else {
24212 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
24213 var scope$3 = this.scopeStack[i];
24214
24215 if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
24216 redeclared = true;
24217 break;
24218 }
24219
24220 scope$3.var.push(name);
24221
24222 if (this.inModule && scope$3.flags & SCOPE_TOP) {
24223 delete this.undefinedExports[name];
24224 }
24225
24226 if (scope$3.flags & SCOPE_VAR) {
24227 break;
24228 }
24229 }
24230 }
24231
24232 if (redeclared) {
24233 this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
24234 }
24235 };
24236
24237 pp$5.checkLocalExport = function (id) {
24238 // scope.functions must be empty as Module code is always strict.
24239 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
24240 this.undefinedExports[id.name] = id;
24241 }
24242 };
24243
24244 pp$5.currentScope = function () {
24245 return this.scopeStack[this.scopeStack.length - 1];
24246 };
24247
24248 pp$5.currentVarScope = function () {
24249 for (var i = this.scopeStack.length - 1;; i--) {
24250 var scope = this.scopeStack[i];
24251
24252 if (scope.flags & SCOPE_VAR) {
24253 return scope;
24254 }
24255 }
24256 }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
24257
24258
24259 pp$5.currentThisScope = function () {
24260 for (var i = this.scopeStack.length - 1;; i--) {
24261 var scope = this.scopeStack[i];
24262
24263 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) {
24264 return scope;
24265 }
24266 }
24267 };
24268
24269 var Node = function Node(parser, pos, loc) {
24270 this.type = "";
24271 this.start = pos;
24272 this.end = 0;
24273
24274 if (parser.options.locations) {
24275 this.loc = new SourceLocation(parser, loc);
24276 }
24277
24278 if (parser.options.directSourceFile) {
24279 this.sourceFile = parser.options.directSourceFile;
24280 }
24281
24282 if (parser.options.ranges) {
24283 this.range = [pos, 0];
24284 }
24285 }; // Start an AST node, attaching a start offset.
24286
24287
24288 var pp$6 = Parser.prototype;
24289
24290 pp$6.startNode = function () {
24291 return new Node(this, this.start, this.startLoc);
24292 };
24293
24294 pp$6.startNodeAt = function (pos, loc) {
24295 return new Node(this, pos, loc);
24296 }; // Finish an AST node, adding `type` and `end` properties.
24297
24298
24299 function finishNodeAt(node, type, pos, loc) {
24300 node.type = type;
24301 node.end = pos;
24302
24303 if (this.options.locations) {
24304 node.loc.end = loc;
24305 }
24306
24307 if (this.options.ranges) {
24308 node.range[1] = pos;
24309 }
24310
24311 return node;
24312 }
24313
24314 pp$6.finishNode = function (node, type) {
24315 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
24316 }; // Finish node at given position
24317
24318
24319 pp$6.finishNodeAt = function (node, type, pos, loc) {
24320 return finishNodeAt.call(this, node, type, pos, loc);
24321 }; // The algorithm used to determine whether a regexp can appear at a
24322
24323
24324 var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
24325 this.token = token;
24326 this.isExpr = !!isExpr;
24327 this.preserveSpace = !!preserveSpace;
24328 this.override = override;
24329 this.generator = !!generator;
24330 };
24331
24332 var types$1 = {
24333 b_stat: new TokContext("{", false),
24334 b_expr: new TokContext("{", true),
24335 b_tmpl: new TokContext("${", false),
24336 p_stat: new TokContext("(", false),
24337 p_expr: new TokContext("(", true),
24338 q_tmpl: new TokContext("`", true, true, function (p) {
24339 return p.tryReadTemplateToken();
24340 }),
24341 f_stat: new TokContext("function", false),
24342 f_expr: new TokContext("function", true),
24343 f_expr_gen: new TokContext("function", true, false, null, true),
24344 f_gen: new TokContext("function", false, false, null, true)
24345 };
24346 var pp$7 = Parser.prototype;
24347
24348 pp$7.initialContext = function () {
24349 return [types$1.b_stat];
24350 };
24351
24352 pp$7.braceIsBlock = function (prevType) {
24353 var parent = this.curContext();
24354
24355 if (parent === types$1.f_expr || parent === types$1.f_stat) {
24356 return true;
24357 }
24358
24359 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) {
24360 return !parent.isExpr;
24361 } // The check for `tt.name && exprAllowed` detects whether we are
24362 // after a `yield` or `of` construct. See the `updateContext` for
24363 // `tt.name`.
24364
24365
24366 if (prevType === types._return || prevType === types.name && this.exprAllowed) {
24367 return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
24368 }
24369
24370 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
24371 return true;
24372 }
24373
24374 if (prevType === types.braceL) {
24375 return parent === types$1.b_stat;
24376 }
24377
24378 if (prevType === types._var || prevType === types._const || prevType === types.name) {
24379 return false;
24380 }
24381
24382 return !this.exprAllowed;
24383 };
24384
24385 pp$7.inGeneratorContext = function () {
24386 for (var i = this.context.length - 1; i >= 1; i--) {
24387 var context = this.context[i];
24388
24389 if (context.token === "function") {
24390 return context.generator;
24391 }
24392 }
24393
24394 return false;
24395 };
24396
24397 pp$7.updateContext = function (prevType) {
24398 var update,
24399 type = this.type;
24400
24401 if (type.keyword && prevType === types.dot) {
24402 this.exprAllowed = false;
24403 } else if (update = type.updateContext) {
24404 update.call(this, prevType);
24405 } else {
24406 this.exprAllowed = type.beforeExpr;
24407 }
24408 }; // Token-specific context update code
24409
24410
24411 types.parenR.updateContext = types.braceR.updateContext = function () {
24412 if (this.context.length === 1) {
24413 this.exprAllowed = true;
24414 return;
24415 }
24416
24417 var out = this.context.pop();
24418
24419 if (out === types$1.b_stat && this.curContext().token === "function") {
24420 out = this.context.pop();
24421 }
24422
24423 this.exprAllowed = !out.isExpr;
24424 };
24425
24426 types.braceL.updateContext = function (prevType) {
24427 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
24428 this.exprAllowed = true;
24429 };
24430
24431 types.dollarBraceL.updateContext = function () {
24432 this.context.push(types$1.b_tmpl);
24433 this.exprAllowed = true;
24434 };
24435
24436 types.parenL.updateContext = function (prevType) {
24437 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
24438 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
24439 this.exprAllowed = true;
24440 };
24441
24442 types.incDec.updateContext = function () {// tokExprAllowed stays unchanged
24443 };
24444
24445 types._function.updateContext = types._class.updateContext = function (prevType) {
24446 if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
24447 this.context.push(types$1.f_expr);
24448 } else {
24449 this.context.push(types$1.f_stat);
24450 }
24451
24452 this.exprAllowed = false;
24453 };
24454
24455 types.backQuote.updateContext = function () {
24456 if (this.curContext() === types$1.q_tmpl) {
24457 this.context.pop();
24458 } else {
24459 this.context.push(types$1.q_tmpl);
24460 }
24461
24462 this.exprAllowed = false;
24463 };
24464
24465 types.star.updateContext = function (prevType) {
24466 if (prevType === types._function) {
24467 var index = this.context.length - 1;
24468
24469 if (this.context[index] === types$1.f_expr) {
24470 this.context[index] = types$1.f_expr_gen;
24471 } else {
24472 this.context[index] = types$1.f_gen;
24473 }
24474 }
24475
24476 this.exprAllowed = true;
24477 };
24478
24479 types.name.updateContext = function (prevType) {
24480 var allowed = false;
24481
24482 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
24483 if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
24484 allowed = true;
24485 }
24486 }
24487
24488 this.exprAllowed = allowed;
24489 }; // This file contains Unicode properties extracted from the ECMAScript
24490 // specification. The lists are extracted like so:
24491 // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
24492 // #table-binary-unicode-properties
24493
24494
24495 var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
24496 var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
24497 var ecma11BinaryProperties = ecma10BinaryProperties;
24498 var unicodeBinaryProperties = {
24499 9: ecma9BinaryProperties,
24500 10: ecma10BinaryProperties,
24501 11: ecma11BinaryProperties
24502 }; // #table-unicode-general-category-values
24503
24504 var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values
24505
24506 var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
24507 var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
24508 var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
24509 var unicodeScriptValues = {
24510 9: ecma9ScriptValues,
24511 10: ecma10ScriptValues,
24512 11: ecma11ScriptValues
24513 };
24514 var data = {};
24515
24516 function buildUnicodeData(ecmaVersion) {
24517 var d = data[ecmaVersion] = {
24518 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
24519 nonBinary: {
24520 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
24521 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
24522 }
24523 };
24524 d.nonBinary.Script_Extensions = d.nonBinary.Script;
24525 d.nonBinary.gc = d.nonBinary.General_Category;
24526 d.nonBinary.sc = d.nonBinary.Script;
24527 d.nonBinary.scx = d.nonBinary.Script_Extensions;
24528 }
24529
24530 buildUnicodeData(9);
24531 buildUnicodeData(10);
24532 buildUnicodeData(11);
24533 var pp$8 = Parser.prototype;
24534
24535 var RegExpValidationState = function RegExpValidationState(parser) {
24536 this.parser = parser;
24537 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
24538 this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion];
24539 this.source = "";
24540 this.flags = "";
24541 this.start = 0;
24542 this.switchU = false;
24543 this.switchN = false;
24544 this.pos = 0;
24545 this.lastIntValue = 0;
24546 this.lastStringValue = "";
24547 this.lastAssertionIsQuantifiable = false;
24548 this.numCapturingParens = 0;
24549 this.maxBackReference = 0;
24550 this.groupNames = [];
24551 this.backReferenceNames = [];
24552 };
24553
24554 RegExpValidationState.prototype.reset = function reset(start, pattern, flags) {
24555 var unicode = flags.indexOf("u") !== -1;
24556 this.start = start | 0;
24557 this.source = pattern + "";
24558 this.flags = flags;
24559 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
24560 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
24561 };
24562
24563 RegExpValidationState.prototype.raise = function raise(message) {
24564 this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
24565 }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
24566 // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
24567
24568
56c4a2cb
DC
24569 RegExpValidationState.prototype.at = function at(i, forceU) {
24570 if (forceU === void 0) forceU = false;
eb39fafa
DC
24571 var s = this.source;
24572 var l = s.length;
24573
24574 if (i >= l) {
24575 return -1;
24576 }
24577
24578 var c = s.charCodeAt(i);
24579
56c4a2cb 24580 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
eb39fafa
DC
24581 return c;
24582 }
24583
24584 var next = s.charCodeAt(i + 1);
24585 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c;
24586 };
24587
56c4a2cb
DC
24588 RegExpValidationState.prototype.nextIndex = function nextIndex(i, forceU) {
24589 if (forceU === void 0) forceU = false;
eb39fafa
DC
24590 var s = this.source;
24591 var l = s.length;
24592
24593 if (i >= l) {
24594 return l;
24595 }
24596
24597 var c = s.charCodeAt(i),
24598 next;
24599
56c4a2cb 24600 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
eb39fafa
DC
24601 return i + 1;
24602 }
24603
24604 return i + 2;
24605 };
24606
56c4a2cb
DC
24607 RegExpValidationState.prototype.current = function current(forceU) {
24608 if (forceU === void 0) forceU = false;
24609 return this.at(this.pos, forceU);
eb39fafa
DC
24610 };
24611
56c4a2cb
DC
24612 RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
24613 if (forceU === void 0) forceU = false;
24614 return this.at(this.nextIndex(this.pos, forceU), forceU);
eb39fafa
DC
24615 };
24616
56c4a2cb
DC
24617 RegExpValidationState.prototype.advance = function advance(forceU) {
24618 if (forceU === void 0) forceU = false;
24619 this.pos = this.nextIndex(this.pos, forceU);
eb39fafa
DC
24620 };
24621
56c4a2cb
DC
24622 RegExpValidationState.prototype.eat = function eat(ch, forceU) {
24623 if (forceU === void 0) forceU = false;
24624
24625 if (this.current(forceU) === ch) {
24626 this.advance(forceU);
eb39fafa
DC
24627 return true;
24628 }
24629
24630 return false;
24631 };
24632
24633 function codePointToString(ch) {
24634 if (ch <= 0xFFFF) {
24635 return String.fromCharCode(ch);
24636 }
24637
24638 ch -= 0x10000;
24639 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00);
24640 }
24641 /**
24642 * Validate the flags part of a given RegExpLiteral.
24643 *
24644 * @param {RegExpValidationState} state The state to validate RegExp.
24645 * @returns {void}
24646 */
24647
24648
24649 pp$8.validateRegExpFlags = function (state) {
24650 var validFlags = state.validFlags;
24651 var flags = state.flags;
24652
24653 for (var i = 0; i < flags.length; i++) {
24654 var flag = flags.charAt(i);
24655
24656 if (validFlags.indexOf(flag) === -1) {
24657 this.raise(state.start, "Invalid regular expression flag");
24658 }
24659
24660 if (flags.indexOf(flag, i + 1) > -1) {
24661 this.raise(state.start, "Duplicate regular expression flag");
24662 }
24663 }
24664 };
24665 /**
24666 * Validate the pattern part of a given RegExpLiteral.
24667 *
24668 * @param {RegExpValidationState} state The state to validate RegExp.
24669 * @returns {void}
24670 */
24671
24672
24673 pp$8.validateRegExpPattern = function (state) {
24674 this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
24675 // parsing contains a |GroupName|, reparse with the goal symbol
24676 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
24677 // exception if _P_ did not conform to the grammar, if any elements of _P_
24678 // were not matched by the parse, or if any Early Error conditions exist.
24679
24680 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
24681 state.switchN = true;
24682 this.regexp_pattern(state);
24683 }
24684 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
24685
24686
24687 pp$8.regexp_pattern = function (state) {
24688 state.pos = 0;
24689 state.lastIntValue = 0;
24690 state.lastStringValue = "";
24691 state.lastAssertionIsQuantifiable = false;
24692 state.numCapturingParens = 0;
24693 state.maxBackReference = 0;
24694 state.groupNames.length = 0;
24695 state.backReferenceNames.length = 0;
24696 this.regexp_disjunction(state);
24697
24698 if (state.pos !== state.source.length) {
24699 // Make the same messages as V8.
24700 if (state.eat(0x29
24701 /* ) */
24702 )) {
24703 state.raise("Unmatched ')'");
24704 }
24705
24706 if (state.eat(0x5D
24707 /* ] */
24708 ) || state.eat(0x7D
24709 /* } */
24710 )) {
24711 state.raise("Lone quantifier brackets");
24712 }
24713 }
24714
24715 if (state.maxBackReference > state.numCapturingParens) {
24716 state.raise("Invalid escape");
24717 }
24718
24719 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
24720 var name = list[i];
24721
24722 if (state.groupNames.indexOf(name) === -1) {
24723 state.raise("Invalid named capture referenced");
24724 }
24725 }
24726 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
24727
24728
24729 pp$8.regexp_disjunction = function (state) {
24730 this.regexp_alternative(state);
24731
24732 while (state.eat(0x7C
24733 /* | */
24734 )) {
24735 this.regexp_alternative(state);
24736 } // Make the same message as V8.
24737
24738
24739 if (this.regexp_eatQuantifier(state, true)) {
24740 state.raise("Nothing to repeat");
24741 }
24742
24743 if (state.eat(0x7B
24744 /* { */
24745 )) {
24746 state.raise("Lone quantifier brackets");
24747 }
24748 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
24749
24750
24751 pp$8.regexp_alternative = function (state) {
24752 while (state.pos < state.source.length && this.regexp_eatTerm(state)) {}
24753 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
24754
24755
24756 pp$8.regexp_eatTerm = function (state) {
24757 if (this.regexp_eatAssertion(state)) {
24758 // Handle `QuantifiableAssertion Quantifier` alternative.
24759 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
24760 // is a QuantifiableAssertion.
24761 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
24762 // Make the same message as V8.
24763 if (state.switchU) {
24764 state.raise("Invalid quantifier");
24765 }
24766 }
24767
24768 return true;
24769 }
24770
24771 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
24772 this.regexp_eatQuantifier(state);
24773 return true;
24774 }
24775
24776 return false;
24777 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
24778
24779
24780 pp$8.regexp_eatAssertion = function (state) {
24781 var start = state.pos;
24782 state.lastAssertionIsQuantifiable = false; // ^, $
24783
24784 if (state.eat(0x5E
24785 /* ^ */
24786 ) || state.eat(0x24
24787 /* $ */
24788 )) {
24789 return true;
24790 } // \b \B
24791
24792
24793 if (state.eat(0x5C
24794 /* \ */
24795 )) {
24796 if (state.eat(0x42
24797 /* B */
24798 ) || state.eat(0x62
24799 /* b */
24800 )) {
24801 return true;
24802 }
24803
24804 state.pos = start;
24805 } // Lookahead / Lookbehind
24806
24807
24808 if (state.eat(0x28
24809 /* ( */
24810 ) && state.eat(0x3F
24811 /* ? */
24812 )) {
24813 var lookbehind = false;
24814
24815 if (this.options.ecmaVersion >= 9) {
24816 lookbehind = state.eat(0x3C
24817 /* < */
24818 );
24819 }
24820
24821 if (state.eat(0x3D
24822 /* = */
24823 ) || state.eat(0x21
24824 /* ! */
24825 )) {
24826 this.regexp_disjunction(state);
24827
24828 if (!state.eat(0x29
24829 /* ) */
24830 )) {
24831 state.raise("Unterminated group");
24832 }
24833
24834 state.lastAssertionIsQuantifiable = !lookbehind;
24835 return true;
24836 }
24837 }
24838
24839 state.pos = start;
24840 return false;
24841 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
24842
24843
24844 pp$8.regexp_eatQuantifier = function (state, noError) {
24845 if (noError === void 0) noError = false;
24846
24847 if (this.regexp_eatQuantifierPrefix(state, noError)) {
24848 state.eat(0x3F
24849 /* ? */
24850 );
24851 return true;
24852 }
24853
24854 return false;
24855 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
24856
24857
24858 pp$8.regexp_eatQuantifierPrefix = function (state, noError) {
24859 return state.eat(0x2A
24860 /* * */
24861 ) || state.eat(0x2B
24862 /* + */
24863 ) || state.eat(0x3F
24864 /* ? */
24865 ) || this.regexp_eatBracedQuantifier(state, noError);
24866 };
24867
24868 pp$8.regexp_eatBracedQuantifier = function (state, noError) {
24869 var start = state.pos;
24870
24871 if (state.eat(0x7B
24872 /* { */
24873 )) {
24874 var min = 0,
24875 max = -1;
24876
24877 if (this.regexp_eatDecimalDigits(state)) {
24878 min = state.lastIntValue;
24879
24880 if (state.eat(0x2C
24881 /* , */
24882 ) && this.regexp_eatDecimalDigits(state)) {
24883 max = state.lastIntValue;
24884 }
24885
24886 if (state.eat(0x7D
24887 /* } */
24888 )) {
24889 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
24890 if (max !== -1 && max < min && !noError) {
24891 state.raise("numbers out of order in {} quantifier");
24892 }
24893
24894 return true;
24895 }
24896 }
24897
24898 if (state.switchU && !noError) {
24899 state.raise("Incomplete quantifier");
24900 }
24901
24902 state.pos = start;
24903 }
24904
24905 return false;
24906 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
24907
24908
24909 pp$8.regexp_eatAtom = function (state) {
24910 return this.regexp_eatPatternCharacters(state) || state.eat(0x2E
24911 /* . */
24912 ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
24913 };
24914
24915 pp$8.regexp_eatReverseSolidusAtomEscape = function (state) {
24916 var start = state.pos;
24917
24918 if (state.eat(0x5C
24919 /* \ */
24920 )) {
24921 if (this.regexp_eatAtomEscape(state)) {
24922 return true;
24923 }
24924
24925 state.pos = start;
24926 }
24927
24928 return false;
24929 };
24930
24931 pp$8.regexp_eatUncapturingGroup = function (state) {
24932 var start = state.pos;
24933
24934 if (state.eat(0x28
24935 /* ( */
24936 )) {
24937 if (state.eat(0x3F
24938 /* ? */
24939 ) && state.eat(0x3A
24940 /* : */
24941 )) {
24942 this.regexp_disjunction(state);
24943
24944 if (state.eat(0x29
24945 /* ) */
24946 )) {
24947 return true;
24948 }
24949
24950 state.raise("Unterminated group");
24951 }
24952
24953 state.pos = start;
24954 }
24955
24956 return false;
24957 };
24958
24959 pp$8.regexp_eatCapturingGroup = function (state) {
24960 if (state.eat(0x28
24961 /* ( */
24962 )) {
24963 if (this.options.ecmaVersion >= 9) {
24964 this.regexp_groupSpecifier(state);
24965 } else if (state.current() === 0x3F
24966 /* ? */
24967 ) {
24968 state.raise("Invalid group");
24969 }
24970
24971 this.regexp_disjunction(state);
24972
24973 if (state.eat(0x29
24974 /* ) */
24975 )) {
24976 state.numCapturingParens += 1;
24977 return true;
24978 }
24979
24980 state.raise("Unterminated group");
24981 }
24982
24983 return false;
24984 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
24985
24986
24987 pp$8.regexp_eatExtendedAtom = function (state) {
24988 return state.eat(0x2E
24989 /* . */
24990 ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
24991 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
24992
24993
24994 pp$8.regexp_eatInvalidBracedQuantifier = function (state) {
24995 if (this.regexp_eatBracedQuantifier(state, true)) {
24996 state.raise("Nothing to repeat");
24997 }
24998
24999 return false;
25000 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
25001
25002
25003 pp$8.regexp_eatSyntaxCharacter = function (state) {
25004 var ch = state.current();
25005
25006 if (isSyntaxCharacter(ch)) {
25007 state.lastIntValue = ch;
25008 state.advance();
25009 return true;
25010 }
25011
25012 return false;
25013 };
25014
25015 function isSyntaxCharacter(ch) {
25016 return ch === 0x24
25017 /* $ */
25018 || ch >= 0x28
25019 /* ( */
25020 && ch <= 0x2B
25021 /* + */
25022 || ch === 0x2E
25023 /* . */
25024 || ch === 0x3F
25025 /* ? */
25026 || ch >= 0x5B
25027 /* [ */
25028 && ch <= 0x5E
25029 /* ^ */
25030 || ch >= 0x7B
25031 /* { */
25032 && ch <= 0x7D
25033 /* } */
25034 ;
25035 } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
25036 // But eat eager.
25037
25038
25039 pp$8.regexp_eatPatternCharacters = function (state) {
25040 var start = state.pos;
25041 var ch = 0;
25042
25043 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
25044 state.advance();
25045 }
25046
25047 return state.pos !== start;
25048 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
25049
25050
25051 pp$8.regexp_eatExtendedPatternCharacter = function (state) {
25052 var ch = state.current();
25053
25054 if (ch !== -1 && ch !== 0x24
25055 /* $ */
25056 && !(ch >= 0x28
25057 /* ( */
25058 && ch <= 0x2B
25059 /* + */
25060 ) && ch !== 0x2E
25061 /* . */
25062 && ch !== 0x3F
25063 /* ? */
25064 && ch !== 0x5B
25065 /* [ */
25066 && ch !== 0x5E
25067 /* ^ */
25068 && ch !== 0x7C
25069 /* | */
25070 ) {
25071 state.advance();
25072 return true;
25073 }
25074
25075 return false;
56c4a2cb 25076 }; // GroupSpecifier ::
eb39fafa 25077 // [empty]
56c4a2cb 25078 // `?` GroupName
eb39fafa
DC
25079
25080
25081 pp$8.regexp_groupSpecifier = function (state) {
25082 if (state.eat(0x3F
25083 /* ? */
25084 )) {
25085 if (this.regexp_eatGroupName(state)) {
25086 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
25087 state.raise("Duplicate capture group name");
25088 }
25089
25090 state.groupNames.push(state.lastStringValue);
25091 return;
25092 }
25093
25094 state.raise("Invalid group");
25095 }
56c4a2cb
DC
25096 }; // GroupName ::
25097 // `<` RegExpIdentifierName `>`
eb39fafa
DC
25098 // Note: this updates `state.lastStringValue` property with the eaten name.
25099
25100
25101 pp$8.regexp_eatGroupName = function (state) {
25102 state.lastStringValue = "";
25103
25104 if (state.eat(0x3C
25105 /* < */
25106 )) {
25107 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E
25108 /* > */
25109 )) {
25110 return true;
25111 }
25112
25113 state.raise("Invalid capture group name");
25114 }
25115
25116 return false;
56c4a2cb
DC
25117 }; // RegExpIdentifierName ::
25118 // RegExpIdentifierStart
25119 // RegExpIdentifierName RegExpIdentifierPart
eb39fafa
DC
25120 // Note: this updates `state.lastStringValue` property with the eaten name.
25121
25122
25123 pp$8.regexp_eatRegExpIdentifierName = function (state) {
25124 state.lastStringValue = "";
25125
25126 if (this.regexp_eatRegExpIdentifierStart(state)) {
25127 state.lastStringValue += codePointToString(state.lastIntValue);
25128
25129 while (this.regexp_eatRegExpIdentifierPart(state)) {
25130 state.lastStringValue += codePointToString(state.lastIntValue);
25131 }
25132
25133 return true;
25134 }
25135
25136 return false;
56c4a2cb 25137 }; // RegExpIdentifierStart ::
eb39fafa
DC
25138 // UnicodeIDStart
25139 // `$`
25140 // `_`
56c4a2cb 25141 // `\` RegExpUnicodeEscapeSequence[+U]
eb39fafa
DC
25142
25143
25144 pp$8.regexp_eatRegExpIdentifierStart = function (state) {
25145 var start = state.pos;
56c4a2cb
DC
25146 var forceU = this.options.ecmaVersion >= 11;
25147 var ch = state.current(forceU);
25148 state.advance(forceU);
eb39fafa
DC
25149
25150 if (ch === 0x5C
25151 /* \ */
56c4a2cb 25152 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
eb39fafa
DC
25153 ch = state.lastIntValue;
25154 }
25155
25156 if (isRegExpIdentifierStart(ch)) {
25157 state.lastIntValue = ch;
25158 return true;
25159 }
25160
25161 state.pos = start;
25162 return false;
25163 };
25164
25165 function isRegExpIdentifierStart(ch) {
25166 return isIdentifierStart(ch, true) || ch === 0x24
25167 /* $ */
25168 || ch === 0x5F;
25169 /* _ */
56c4a2cb 25170 } // RegExpIdentifierPart ::
eb39fafa
DC
25171 // UnicodeIDContinue
25172 // `$`
25173 // `_`
56c4a2cb 25174 // `\` RegExpUnicodeEscapeSequence[+U]
eb39fafa
DC
25175 // <ZWNJ>
25176 // <ZWJ>
25177
25178
25179 pp$8.regexp_eatRegExpIdentifierPart = function (state) {
25180 var start = state.pos;
56c4a2cb
DC
25181 var forceU = this.options.ecmaVersion >= 11;
25182 var ch = state.current(forceU);
25183 state.advance(forceU);
eb39fafa
DC
25184
25185 if (ch === 0x5C
25186 /* \ */
56c4a2cb 25187 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
eb39fafa
DC
25188 ch = state.lastIntValue;
25189 }
25190
25191 if (isRegExpIdentifierPart(ch)) {
25192 state.lastIntValue = ch;
25193 return true;
25194 }
25195
25196 state.pos = start;
25197 return false;
25198 };
25199
25200 function isRegExpIdentifierPart(ch) {
25201 return isIdentifierChar(ch, true) || ch === 0x24
25202 /* $ */
25203 || ch === 0x5F
25204 /* _ */
25205 || ch === 0x200C
25206 /* <ZWNJ> */
25207 || ch === 0x200D;
25208 /* <ZWJ> */
25209 } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
25210
25211
25212 pp$8.regexp_eatAtomEscape = function (state) {
25213 if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {
25214 return true;
25215 }
25216
25217 if (state.switchU) {
25218 // Make the same message as V8.
25219 if (state.current() === 0x63
25220 /* c */
25221 ) {
25222 state.raise("Invalid unicode escape");
25223 }
25224
25225 state.raise("Invalid escape");
25226 }
25227
25228 return false;
25229 };
25230
25231 pp$8.regexp_eatBackReference = function (state) {
25232 var start = state.pos;
25233
25234 if (this.regexp_eatDecimalEscape(state)) {
25235 var n = state.lastIntValue;
25236
25237 if (state.switchU) {
25238 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
25239 if (n > state.maxBackReference) {
25240 state.maxBackReference = n;
25241 }
25242
25243 return true;
25244 }
25245
25246 if (n <= state.numCapturingParens) {
25247 return true;
25248 }
25249
25250 state.pos = start;
25251 }
25252
25253 return false;
25254 };
25255
25256 pp$8.regexp_eatKGroupName = function (state) {
25257 if (state.eat(0x6B
25258 /* k */
25259 )) {
25260 if (this.regexp_eatGroupName(state)) {
25261 state.backReferenceNames.push(state.lastStringValue);
25262 return true;
25263 }
25264
25265 state.raise("Invalid named reference");
25266 }
25267
25268 return false;
25269 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
25270
25271
25272 pp$8.regexp_eatCharacterEscape = function (state) {
56c4a2cb 25273 return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
eb39fafa
DC
25274 };
25275
25276 pp$8.regexp_eatCControlLetter = function (state) {
25277 var start = state.pos;
25278
25279 if (state.eat(0x63
25280 /* c */
25281 )) {
25282 if (this.regexp_eatControlLetter(state)) {
25283 return true;
25284 }
25285
25286 state.pos = start;
25287 }
25288
25289 return false;
25290 };
25291
25292 pp$8.regexp_eatZero = function (state) {
25293 if (state.current() === 0x30
25294 /* 0 */
25295 && !isDecimalDigit(state.lookahead())) {
25296 state.lastIntValue = 0;
25297 state.advance();
25298 return true;
25299 }
25300
25301 return false;
25302 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
25303
25304
25305 pp$8.regexp_eatControlEscape = function (state) {
25306 var ch = state.current();
25307
25308 if (ch === 0x74
25309 /* t */
25310 ) {
25311 state.lastIntValue = 0x09;
25312 /* \t */
25313
25314 state.advance();
25315 return true;
25316 }
25317
25318 if (ch === 0x6E
25319 /* n */
25320 ) {
25321 state.lastIntValue = 0x0A;
25322 /* \n */
25323
25324 state.advance();
25325 return true;
25326 }
25327
25328 if (ch === 0x76
25329 /* v */
25330 ) {
25331 state.lastIntValue = 0x0B;
25332 /* \v */
25333
25334 state.advance();
25335 return true;
25336 }
25337
25338 if (ch === 0x66
25339 /* f */
25340 ) {
25341 state.lastIntValue = 0x0C;
25342 /* \f */
25343
25344 state.advance();
25345 return true;
25346 }
25347
25348 if (ch === 0x72
25349 /* r */
25350 ) {
25351 state.lastIntValue = 0x0D;
25352 /* \r */
25353
25354 state.advance();
25355 return true;
25356 }
25357
25358 return false;
25359 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
25360
25361
25362 pp$8.regexp_eatControlLetter = function (state) {
25363 var ch = state.current();
25364
25365 if (isControlLetter(ch)) {
25366 state.lastIntValue = ch % 0x20;
25367 state.advance();
25368 return true;
25369 }
25370
25371 return false;
25372 };
25373
25374 function isControlLetter(ch) {
25375 return ch >= 0x41
25376 /* A */
25377 && ch <= 0x5A
25378 /* Z */
25379 || ch >= 0x61
25380 /* a */
25381 && ch <= 0x7A
25382 /* z */
25383 ;
25384 } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
25385
25386
56c4a2cb
DC
25387 pp$8.regexp_eatRegExpUnicodeEscapeSequence = function (state, forceU) {
25388 if (forceU === void 0) forceU = false;
eb39fafa 25389 var start = state.pos;
56c4a2cb 25390 var switchU = forceU || state.switchU;
eb39fafa
DC
25391
25392 if (state.eat(0x75
25393 /* u */
25394 )) {
25395 if (this.regexp_eatFixedHexDigits(state, 4)) {
25396 var lead = state.lastIntValue;
25397
56c4a2cb 25398 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
eb39fafa
DC
25399 var leadSurrogateEnd = state.pos;
25400
25401 if (state.eat(0x5C
25402 /* \ */
25403 ) && state.eat(0x75
25404 /* u */
25405 ) && this.regexp_eatFixedHexDigits(state, 4)) {
25406 var trail = state.lastIntValue;
25407
25408 if (trail >= 0xDC00 && trail <= 0xDFFF) {
25409 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
25410 return true;
25411 }
25412 }
25413
25414 state.pos = leadSurrogateEnd;
25415 state.lastIntValue = lead;
25416 }
25417
25418 return true;
25419 }
25420
56c4a2cb 25421 if (switchU && state.eat(0x7B
eb39fafa
DC
25422 /* { */
25423 ) && this.regexp_eatHexDigits(state) && state.eat(0x7D
25424 /* } */
25425 ) && isValidUnicode(state.lastIntValue)) {
25426 return true;
25427 }
25428
56c4a2cb 25429 if (switchU) {
eb39fafa
DC
25430 state.raise("Invalid unicode escape");
25431 }
25432
25433 state.pos = start;
25434 }
25435
25436 return false;
25437 };
25438
25439 function isValidUnicode(ch) {
25440 return ch >= 0 && ch <= 0x10FFFF;
25441 } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
25442
25443
25444 pp$8.regexp_eatIdentityEscape = function (state) {
25445 if (state.switchU) {
25446 if (this.regexp_eatSyntaxCharacter(state)) {
25447 return true;
25448 }
25449
25450 if (state.eat(0x2F
25451 /* / */
25452 )) {
25453 state.lastIntValue = 0x2F;
25454 /* / */
25455
25456 return true;
25457 }
25458
25459 return false;
25460 }
25461
25462 var ch = state.current();
25463
25464 if (ch !== 0x63
25465 /* c */
25466 && (!state.switchN || ch !== 0x6B
25467 /* k */
25468 )) {
25469 state.lastIntValue = ch;
25470 state.advance();
25471 return true;
25472 }
25473
25474 return false;
25475 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
25476
25477
25478 pp$8.regexp_eatDecimalEscape = function (state) {
25479 state.lastIntValue = 0;
25480 var ch = state.current();
25481
25482 if (ch >= 0x31
25483 /* 1 */
25484 && ch <= 0x39
25485 /* 9 */
25486 ) {
25487 do {
25488 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30
25489 /* 0 */
25490 );
25491 state.advance();
25492 } while ((ch = state.current()) >= 0x30
25493 /* 0 */
25494 && ch <= 0x39
25495 /* 9 */
25496 );
25497
25498 return true;
25499 }
25500
25501 return false;
25502 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
25503
25504
25505 pp$8.regexp_eatCharacterClassEscape = function (state) {
25506 var ch = state.current();
25507
25508 if (isCharacterClassEscape(ch)) {
25509 state.lastIntValue = -1;
25510 state.advance();
25511 return true;
25512 }
25513
25514 if (state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50
25515 /* P */
25516 || ch === 0x70
25517 /* p */
25518 )) {
25519 state.lastIntValue = -1;
25520 state.advance();
25521
25522 if (state.eat(0x7B
25523 /* { */
25524 ) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D
25525 /* } */
25526 )) {
25527 return true;
25528 }
25529
25530 state.raise("Invalid property name");
25531 }
25532
25533 return false;
25534 };
25535
25536 function isCharacterClassEscape(ch) {
25537 return ch === 0x64
25538 /* d */
25539 || ch === 0x44
25540 /* D */
25541 || ch === 0x73
25542 /* s */
25543 || ch === 0x53
25544 /* S */
25545 || ch === 0x77
25546 /* w */
25547 || ch === 0x57
25548 /* W */
25549 ;
25550 } // UnicodePropertyValueExpression ::
25551 // UnicodePropertyName `=` UnicodePropertyValue
25552 // LoneUnicodePropertyNameOrValue
25553
25554
25555 pp$8.regexp_eatUnicodePropertyValueExpression = function (state) {
25556 var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue
25557
25558 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D
25559 /* = */
25560 )) {
25561 var name = state.lastStringValue;
25562
25563 if (this.regexp_eatUnicodePropertyValue(state)) {
25564 var value = state.lastStringValue;
25565 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
25566 return true;
25567 }
25568 }
25569
25570 state.pos = start; // LoneUnicodePropertyNameOrValue
25571
25572 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
25573 var nameOrValue = state.lastStringValue;
25574 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
25575 return true;
25576 }
25577
25578 return false;
25579 };
25580
25581 pp$8.regexp_validateUnicodePropertyNameAndValue = function (state, name, value) {
25582 if (!has(state.unicodeProperties.nonBinary, name)) {
25583 state.raise("Invalid property name");
25584 }
25585
25586 if (!state.unicodeProperties.nonBinary[name].test(value)) {
25587 state.raise("Invalid property value");
25588 }
25589 };
25590
25591 pp$8.regexp_validateUnicodePropertyNameOrValue = function (state, nameOrValue) {
25592 if (!state.unicodeProperties.binary.test(nameOrValue)) {
25593 state.raise("Invalid property name");
25594 }
25595 }; // UnicodePropertyName ::
25596 // UnicodePropertyNameCharacters
25597
25598
25599 pp$8.regexp_eatUnicodePropertyName = function (state) {
25600 var ch = 0;
25601 state.lastStringValue = "";
25602
25603 while (isUnicodePropertyNameCharacter(ch = state.current())) {
25604 state.lastStringValue += codePointToString(ch);
25605 state.advance();
25606 }
25607
25608 return state.lastStringValue !== "";
25609 };
25610
25611 function isUnicodePropertyNameCharacter(ch) {
25612 return isControlLetter(ch) || ch === 0x5F;
25613 /* _ */
25614 } // UnicodePropertyValue ::
25615 // UnicodePropertyValueCharacters
25616
25617
25618 pp$8.regexp_eatUnicodePropertyValue = function (state) {
25619 var ch = 0;
25620 state.lastStringValue = "";
25621
25622 while (isUnicodePropertyValueCharacter(ch = state.current())) {
25623 state.lastStringValue += codePointToString(ch);
25624 state.advance();
25625 }
25626
25627 return state.lastStringValue !== "";
25628 };
25629
25630 function isUnicodePropertyValueCharacter(ch) {
25631 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
25632 } // LoneUnicodePropertyNameOrValue ::
25633 // UnicodePropertyValueCharacters
25634
25635
25636 pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function (state) {
25637 return this.regexp_eatUnicodePropertyValue(state);
25638 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
25639
25640
25641 pp$8.regexp_eatCharacterClass = function (state) {
25642 if (state.eat(0x5B
25643 /* [ */
25644 )) {
25645 state.eat(0x5E
25646 /* ^ */
25647 );
25648 this.regexp_classRanges(state);
25649
25650 if (state.eat(0x5D
25651 /* ] */
25652 )) {
25653 return true;
25654 } // Unreachable since it threw "unterminated regular expression" error before.
25655
25656
25657 state.raise("Unterminated character class");
25658 }
25659
25660 return false;
25661 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
25662 // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
25663 // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
25664
25665
25666 pp$8.regexp_classRanges = function (state) {
25667 while (this.regexp_eatClassAtom(state)) {
25668 var left = state.lastIntValue;
25669
25670 if (state.eat(0x2D
25671 /* - */
25672 ) && this.regexp_eatClassAtom(state)) {
25673 var right = state.lastIntValue;
25674
25675 if (state.switchU && (left === -1 || right === -1)) {
25676 state.raise("Invalid character class");
25677 }
25678
25679 if (left !== -1 && right !== -1 && left > right) {
25680 state.raise("Range out of order in character class");
25681 }
25682 }
25683 }
25684 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
25685 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
25686
25687
25688 pp$8.regexp_eatClassAtom = function (state) {
25689 var start = state.pos;
25690
25691 if (state.eat(0x5C
25692 /* \ */
25693 )) {
25694 if (this.regexp_eatClassEscape(state)) {
25695 return true;
25696 }
25697
25698 if (state.switchU) {
25699 // Make the same message as V8.
25700 var ch$1 = state.current();
25701
25702 if (ch$1 === 0x63
25703 /* c */
25704 || isOctalDigit(ch$1)) {
25705 state.raise("Invalid class escape");
25706 }
25707
25708 state.raise("Invalid escape");
25709 }
25710
25711 state.pos = start;
25712 }
25713
25714 var ch = state.current();
25715
25716 if (ch !== 0x5D
25717 /* ] */
25718 ) {
25719 state.lastIntValue = ch;
25720 state.advance();
25721 return true;
25722 }
25723
25724 return false;
25725 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
25726
25727
25728 pp$8.regexp_eatClassEscape = function (state) {
25729 var start = state.pos;
25730
25731 if (state.eat(0x62
25732 /* b */
25733 )) {
25734 state.lastIntValue = 0x08;
25735 /* <BS> */
25736
25737 return true;
25738 }
25739
25740 if (state.switchU && state.eat(0x2D
25741 /* - */
25742 )) {
25743 state.lastIntValue = 0x2D;
25744 /* - */
25745
25746 return true;
25747 }
25748
25749 if (!state.switchU && state.eat(0x63
25750 /* c */
25751 )) {
25752 if (this.regexp_eatClassControlLetter(state)) {
25753 return true;
25754 }
25755
25756 state.pos = start;
25757 }
25758
25759 return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
25760 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
25761
25762
25763 pp$8.regexp_eatClassControlLetter = function (state) {
25764 var ch = state.current();
25765
25766 if (isDecimalDigit(ch) || ch === 0x5F
25767 /* _ */
25768 ) {
25769 state.lastIntValue = ch % 0x20;
25770 state.advance();
25771 return true;
25772 }
25773
25774 return false;
25775 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
25776
25777
25778 pp$8.regexp_eatHexEscapeSequence = function (state) {
25779 var start = state.pos;
25780
25781 if (state.eat(0x78
25782 /* x */
25783 )) {
25784 if (this.regexp_eatFixedHexDigits(state, 2)) {
25785 return true;
25786 }
25787
25788 if (state.switchU) {
25789 state.raise("Invalid escape");
25790 }
25791
25792 state.pos = start;
25793 }
25794
25795 return false;
25796 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
25797
25798
25799 pp$8.regexp_eatDecimalDigits = function (state) {
25800 var start = state.pos;
25801 var ch = 0;
25802 state.lastIntValue = 0;
25803
25804 while (isDecimalDigit(ch = state.current())) {
25805 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30
25806 /* 0 */
25807 );
25808 state.advance();
25809 }
25810
25811 return state.pos !== start;
25812 };
25813
25814 function isDecimalDigit(ch) {
25815 return ch >= 0x30
25816 /* 0 */
25817 && ch <= 0x39;
25818 /* 9 */
25819 } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
25820
25821
25822 pp$8.regexp_eatHexDigits = function (state) {
25823 var start = state.pos;
25824 var ch = 0;
25825 state.lastIntValue = 0;
25826
25827 while (isHexDigit(ch = state.current())) {
25828 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
25829 state.advance();
25830 }
25831
25832 return state.pos !== start;
25833 };
25834
25835 function isHexDigit(ch) {
25836 return ch >= 0x30
25837 /* 0 */
25838 && ch <= 0x39
25839 /* 9 */
25840 || ch >= 0x41
25841 /* A */
25842 && ch <= 0x46
25843 /* F */
25844 || ch >= 0x61
25845 /* a */
25846 && ch <= 0x66
25847 /* f */
25848 ;
25849 }
25850
25851 function hexToInt(ch) {
25852 if (ch >= 0x41
25853 /* A */
25854 && ch <= 0x46
25855 /* F */
25856 ) {
25857 return 10 + (ch - 0x41
25858 /* A */
25859 );
25860 }
25861
25862 if (ch >= 0x61
25863 /* a */
25864 && ch <= 0x66
25865 /* f */
25866 ) {
25867 return 10 + (ch - 0x61
25868 /* a */
25869 );
25870 }
25871
25872 return ch - 0x30;
25873 /* 0 */
25874 } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
25875 // Allows only 0-377(octal) i.e. 0-255(decimal).
25876
25877
25878 pp$8.regexp_eatLegacyOctalEscapeSequence = function (state) {
25879 if (this.regexp_eatOctalDigit(state)) {
25880 var n1 = state.lastIntValue;
25881
25882 if (this.regexp_eatOctalDigit(state)) {
25883 var n2 = state.lastIntValue;
25884
25885 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
25886 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
25887 } else {
25888 state.lastIntValue = n1 * 8 + n2;
25889 }
25890 } else {
25891 state.lastIntValue = n1;
25892 }
25893
25894 return true;
25895 }
25896
25897 return false;
25898 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
25899
25900
25901 pp$8.regexp_eatOctalDigit = function (state) {
25902 var ch = state.current();
25903
25904 if (isOctalDigit(ch)) {
25905 state.lastIntValue = ch - 0x30;
25906 /* 0 */
25907
25908 state.advance();
25909 return true;
25910 }
25911
25912 state.lastIntValue = 0;
25913 return false;
25914 };
25915
25916 function isOctalDigit(ch) {
25917 return ch >= 0x30
25918 /* 0 */
25919 && ch <= 0x37;
25920 /* 7 */
25921 } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
25922 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
25923 // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
25924
25925
25926 pp$8.regexp_eatFixedHexDigits = function (state, length) {
25927 var start = state.pos;
25928 state.lastIntValue = 0;
25929
25930 for (var i = 0; i < length; ++i) {
25931 var ch = state.current();
25932
25933 if (!isHexDigit(ch)) {
25934 state.pos = start;
25935 return false;
25936 }
25937
25938 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
25939 state.advance();
25940 }
25941
25942 return true;
25943 }; // Object type used to represent tokens. Note that normally, tokens
25944 // simply exist as properties on the parser object. This is only
25945 // used for the onToken callback and the external tokenizer.
25946
25947
25948 var Token = function Token(p) {
25949 this.type = p.type;
25950 this.value = p.value;
25951 this.start = p.start;
25952 this.end = p.end;
25953
25954 if (p.options.locations) {
25955 this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
25956 }
25957
25958 if (p.options.ranges) {
25959 this.range = [p.start, p.end];
25960 }
25961 }; // ## Tokenizer
25962
25963
25964 var pp$9 = Parser.prototype; // Move to the next token
25965
25966 pp$9.next = function (ignoreEscapeSequenceInKeyword) {
25967 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
25968 this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
25969 }
25970
25971 if (this.options.onToken) {
25972 this.options.onToken(new Token(this));
25973 }
25974
25975 this.lastTokEnd = this.end;
25976 this.lastTokStart = this.start;
25977 this.lastTokEndLoc = this.endLoc;
25978 this.lastTokStartLoc = this.startLoc;
25979 this.nextToken();
25980 };
25981
25982 pp$9.getToken = function () {
25983 this.next();
25984 return new Token(this);
25985 }; // If we're in an ES6 environment, make parsers iterable
25986
25987
25988 if (typeof Symbol !== "undefined") {
25989 pp$9[Symbol.iterator] = function () {
25990 var this$1 = this;
25991 return {
25992 next: function next() {
25993 var token = this$1.getToken();
25994 return {
25995 done: token.type === types.eof,
25996 value: token
25997 };
25998 }
25999 };
26000 };
26001 } // Toggle strict mode. Re-reads the next number or string to please
26002 // pedantic tests (`"use strict"; 010;` should fail).
26003
26004
26005 pp$9.curContext = function () {
26006 return this.context[this.context.length - 1];
26007 }; // Read a single token, updating the parser object's token-related
26008 // properties.
26009
26010
26011 pp$9.nextToken = function () {
26012 var curContext = this.curContext();
26013
26014 if (!curContext || !curContext.preserveSpace) {
26015 this.skipSpace();
26016 }
26017
26018 this.start = this.pos;
26019
26020 if (this.options.locations) {
26021 this.startLoc = this.curPosition();
26022 }
26023
26024 if (this.pos >= this.input.length) {
26025 return this.finishToken(types.eof);
26026 }
26027
26028 if (curContext.override) {
26029 return curContext.override(this);
26030 } else {
26031 this.readToken(this.fullCharCodeAtPos());
26032 }
26033 };
26034
26035 pp$9.readToken = function (code) {
26036 // Identifier or keyword. '\uXXXX' sequences are allowed in
26037 // identifiers, so '\' also dispatches to that.
26038 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92
26039 /* '\' */
26040 ) {
26041 return this.readWord();
26042 }
26043
26044 return this.getTokenFromCode(code);
26045 };
26046
26047 pp$9.fullCharCodeAtPos = function () {
26048 var code = this.input.charCodeAt(this.pos);
26049
26050 if (code <= 0xd7ff || code >= 0xe000) {
26051 return code;
26052 }
26053
26054 var next = this.input.charCodeAt(this.pos + 1);
26055 return (code << 10) + next - 0x35fdc00;
26056 };
26057
26058 pp$9.skipBlockComment = function () {
26059 var startLoc = this.options.onComment && this.curPosition();
26060 var start = this.pos,
26061 end = this.input.indexOf("*/", this.pos += 2);
26062
26063 if (end === -1) {
26064 this.raise(this.pos - 2, "Unterminated comment");
26065 }
26066
26067 this.pos = end + 2;
26068
26069 if (this.options.locations) {
26070 lineBreakG.lastIndex = start;
26071 var match;
26072
26073 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
26074 ++this.curLine;
26075 this.lineStart = match.index + match[0].length;
26076 }
26077 }
26078
26079 if (this.options.onComment) {
26080 this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
26081 }
26082 };
26083
26084 pp$9.skipLineComment = function (startSkip) {
26085 var start = this.pos;
26086 var startLoc = this.options.onComment && this.curPosition();
26087 var ch = this.input.charCodeAt(this.pos += startSkip);
26088
26089 while (this.pos < this.input.length && !isNewLine(ch)) {
26090 ch = this.input.charCodeAt(++this.pos);
26091 }
26092
26093 if (this.options.onComment) {
26094 this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
26095 }
26096 }; // Called at the start of the parse and after every token. Skips
26097 // whitespace and comments, and.
26098
26099
26100 pp$9.skipSpace = function () {
26101 loop: while (this.pos < this.input.length) {
26102 var ch = this.input.charCodeAt(this.pos);
26103
26104 switch (ch) {
26105 case 32:
26106 case 160:
26107 // ' '
26108 ++this.pos;
26109 break;
26110
26111 case 13:
26112 if (this.input.charCodeAt(this.pos + 1) === 10) {
26113 ++this.pos;
26114 }
26115
26116 case 10:
26117 case 8232:
26118 case 8233:
26119 ++this.pos;
26120
26121 if (this.options.locations) {
26122 ++this.curLine;
26123 this.lineStart = this.pos;
26124 }
26125
26126 break;
26127
26128 case 47:
26129 // '/'
26130 switch (this.input.charCodeAt(this.pos + 1)) {
26131 case 42:
26132 // '*'
26133 this.skipBlockComment();
26134 break;
26135
26136 case 47:
26137 this.skipLineComment(2);
26138 break;
26139
26140 default:
26141 break loop;
26142 }
26143
26144 break;
26145
26146 default:
26147 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
26148 ++this.pos;
26149 } else {
26150 break loop;
26151 }
26152
26153 }
26154 }
26155 }; // Called at the end of every token. Sets `end`, `val`, and
26156 // maintains `context` and `exprAllowed`, and skips the space after
26157 // the token, so that the next one's `start` will point at the
26158 // right position.
26159
26160
26161 pp$9.finishToken = function (type, val) {
26162 this.end = this.pos;
26163
26164 if (this.options.locations) {
26165 this.endLoc = this.curPosition();
26166 }
26167
26168 var prevType = this.type;
26169 this.type = type;
26170 this.value = val;
26171 this.updateContext(prevType);
26172 }; // ### Token reading
26173 // This is the function that is called to fetch the next token. It
26174 // is somewhat obscure, because it works in character codes rather
26175 // than characters, and because operator parsing has been inlined
26176 // into it.
26177 //
26178 // All in the name of speed.
26179 //
26180
26181
26182 pp$9.readToken_dot = function () {
26183 var next = this.input.charCodeAt(this.pos + 1);
26184
26185 if (next >= 48 && next <= 57) {
26186 return this.readNumber(true);
26187 }
26188
26189 var next2 = this.input.charCodeAt(this.pos + 2);
26190
26191 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
26192 // 46 = dot '.'
26193 this.pos += 3;
26194 return this.finishToken(types.ellipsis);
26195 } else {
26196 ++this.pos;
26197 return this.finishToken(types.dot);
26198 }
26199 };
26200
26201 pp$9.readToken_slash = function () {
26202 // '/'
26203 var next = this.input.charCodeAt(this.pos + 1);
26204
26205 if (this.exprAllowed) {
26206 ++this.pos;
26207 return this.readRegexp();
26208 }
26209
26210 if (next === 61) {
26211 return this.finishOp(types.assign, 2);
26212 }
26213
26214 return this.finishOp(types.slash, 1);
26215 };
26216
26217 pp$9.readToken_mult_modulo_exp = function (code) {
26218 // '%*'
26219 var next = this.input.charCodeAt(this.pos + 1);
26220 var size = 1;
26221 var tokentype = code === 42 ? types.star : types.modulo; // exponentiation operator ** and **=
26222
26223 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
26224 ++size;
26225 tokentype = types.starstar;
26226 next = this.input.charCodeAt(this.pos + 2);
26227 }
26228
26229 if (next === 61) {
26230 return this.finishOp(types.assign, size + 1);
26231 }
26232
26233 return this.finishOp(tokentype, size);
26234 };
26235
26236 pp$9.readToken_pipe_amp = function (code) {
26237 // '|&'
26238 var next = this.input.charCodeAt(this.pos + 1);
26239
26240 if (next === code) {
26241 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
26242 }
26243
26244 if (next === 61) {
26245 return this.finishOp(types.assign, 2);
26246 }
26247
26248 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
26249 };
26250
26251 pp$9.readToken_caret = function () {
26252 // '^'
26253 var next = this.input.charCodeAt(this.pos + 1);
26254
26255 if (next === 61) {
26256 return this.finishOp(types.assign, 2);
26257 }
26258
26259 return this.finishOp(types.bitwiseXOR, 1);
26260 };
26261
26262 pp$9.readToken_plus_min = function (code) {
26263 // '+-'
26264 var next = this.input.charCodeAt(this.pos + 1);
26265
26266 if (next === code) {
26267 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
26268 // A `-->` line comment
26269 this.skipLineComment(3);
26270 this.skipSpace();
26271 return this.nextToken();
26272 }
26273
26274 return this.finishOp(types.incDec, 2);
26275 }
26276
26277 if (next === 61) {
26278 return this.finishOp(types.assign, 2);
26279 }
26280
26281 return this.finishOp(types.plusMin, 1);
26282 };
26283
26284 pp$9.readToken_lt_gt = function (code) {
26285 // '<>'
26286 var next = this.input.charCodeAt(this.pos + 1);
26287 var size = 1;
26288
26289 if (next === code) {
26290 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
26291
26292 if (this.input.charCodeAt(this.pos + size) === 61) {
26293 return this.finishOp(types.assign, size + 1);
26294 }
26295
26296 return this.finishOp(types.bitShift, size);
26297 }
26298
26299 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
26300 // `<!--`, an XML-style comment that should be interpreted as a line comment
26301 this.skipLineComment(4);
26302 this.skipSpace();
26303 return this.nextToken();
26304 }
26305
26306 if (next === 61) {
26307 size = 2;
26308 }
26309
26310 return this.finishOp(types.relational, size);
26311 };
26312
26313 pp$9.readToken_eq_excl = function (code) {
26314 // '=!'
26315 var next = this.input.charCodeAt(this.pos + 1);
26316
26317 if (next === 61) {
26318 return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
26319 }
26320
26321 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
26322 // '=>'
26323 this.pos += 2;
26324 return this.finishToken(types.arrow);
26325 }
26326
26327 return this.finishOp(code === 61 ? types.eq : types.prefix, 1);
26328 };
26329
56c4a2cb
DC
26330 pp$9.readToken_question = function () {
26331 // '?'
26332 if (this.options.ecmaVersion >= 11) {
26333 var next = this.input.charCodeAt(this.pos + 1);
26334
26335 if (next === 63) {
26336 return this.finishOp(types.coalesce, 2);
26337 }
26338 }
26339
26340 return this.finishOp(types.question, 1);
26341 };
26342
eb39fafa
DC
26343 pp$9.getTokenFromCode = function (code) {
26344 switch (code) {
26345 // The interpretation of a dot depends on whether it is followed
26346 // by a digit or another two dots.
26347 case 46:
26348 // '.'
26349 return this.readToken_dot();
26350 // Punctuation tokens.
26351
26352 case 40:
26353 ++this.pos;
26354 return this.finishToken(types.parenL);
26355
26356 case 41:
26357 ++this.pos;
26358 return this.finishToken(types.parenR);
26359
26360 case 59:
26361 ++this.pos;
26362 return this.finishToken(types.semi);
26363
26364 case 44:
26365 ++this.pos;
26366 return this.finishToken(types.comma);
26367
26368 case 91:
26369 ++this.pos;
26370 return this.finishToken(types.bracketL);
26371
26372 case 93:
26373 ++this.pos;
26374 return this.finishToken(types.bracketR);
26375
26376 case 123:
26377 ++this.pos;
26378 return this.finishToken(types.braceL);
26379
26380 case 125:
26381 ++this.pos;
26382 return this.finishToken(types.braceR);
26383
26384 case 58:
26385 ++this.pos;
26386 return this.finishToken(types.colon);
26387
eb39fafa
DC
26388 case 96:
26389 // '`'
26390 if (this.options.ecmaVersion < 6) {
26391 break;
26392 }
26393
26394 ++this.pos;
26395 return this.finishToken(types.backQuote);
26396
26397 case 48:
26398 // '0'
26399 var next = this.input.charCodeAt(this.pos + 1);
26400
26401 if (next === 120 || next === 88) {
26402 return this.readRadixNumber(16);
26403 } // '0x', '0X' - hex number
26404
26405
26406 if (this.options.ecmaVersion >= 6) {
26407 if (next === 111 || next === 79) {
26408 return this.readRadixNumber(8);
26409 } // '0o', '0O' - octal number
26410
26411
26412 if (next === 98 || next === 66) {
26413 return this.readRadixNumber(2);
26414 } // '0b', '0B' - binary number
26415
26416 }
26417
26418 // Anything else beginning with a digit is an integer, octal
26419 // number, or float.
26420
26421 case 49:
26422 case 50:
26423 case 51:
26424 case 52:
26425 case 53:
26426 case 54:
26427 case 55:
26428 case 56:
26429 case 57:
26430 // 1-9
26431 return this.readNumber(false);
26432 // Quotes produce strings.
26433
26434 case 34:
26435 case 39:
26436 // '"', "'"
26437 return this.readString(code);
26438 // Operators are parsed inline in tiny state machines. '=' (61) is
26439 // often referred to. `finishOp` simply skips the amount of
26440 // characters it is given as second argument, and returns a token
26441 // of the type given by its first argument.
26442
26443 case 47:
26444 // '/'
26445 return this.readToken_slash();
26446
26447 case 37:
26448 case 42:
26449 // '%*'
26450 return this.readToken_mult_modulo_exp(code);
26451
26452 case 124:
26453 case 38:
26454 // '|&'
26455 return this.readToken_pipe_amp(code);
26456
26457 case 94:
26458 // '^'
26459 return this.readToken_caret();
26460
26461 case 43:
26462 case 45:
26463 // '+-'
26464 return this.readToken_plus_min(code);
26465
26466 case 60:
26467 case 62:
26468 // '<>'
26469 return this.readToken_lt_gt(code);
26470
26471 case 61:
26472 case 33:
26473 // '=!'
26474 return this.readToken_eq_excl(code);
26475
56c4a2cb
DC
26476 case 63:
26477 // '?'
26478 return this.readToken_question();
26479
eb39fafa
DC
26480 case 126:
26481 // '~'
26482 return this.finishOp(types.prefix, 1);
26483 }
26484
26485 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
26486 };
26487
26488 pp$9.finishOp = function (type, size) {
26489 var str = this.input.slice(this.pos, this.pos + size);
26490 this.pos += size;
26491 return this.finishToken(type, str);
26492 };
26493
26494 pp$9.readRegexp = function () {
26495 var escaped,
26496 inClass,
26497 start = this.pos;
26498
26499 for (;;) {
26500 if (this.pos >= this.input.length) {
26501 this.raise(start, "Unterminated regular expression");
26502 }
26503
26504 var ch = this.input.charAt(this.pos);
26505
26506 if (lineBreak.test(ch)) {
26507 this.raise(start, "Unterminated regular expression");
26508 }
26509
26510 if (!escaped) {
26511 if (ch === "[") {
26512 inClass = true;
26513 } else if (ch === "]" && inClass) {
26514 inClass = false;
26515 } else if (ch === "/" && !inClass) {
26516 break;
26517 }
26518
26519 escaped = ch === "\\";
26520 } else {
26521 escaped = false;
26522 }
26523
26524 ++this.pos;
26525 }
26526
26527 var pattern = this.input.slice(start, this.pos);
26528 ++this.pos;
26529 var flagsStart = this.pos;
26530 var flags = this.readWord1();
26531
26532 if (this.containsEsc) {
26533 this.unexpected(flagsStart);
26534 } // Validate pattern
26535
26536
26537 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
26538 state.reset(start, pattern, flags);
26539 this.validateRegExpFlags(state);
26540 this.validateRegExpPattern(state); // Create Literal#value property value.
26541
26542 var value = null;
26543
26544 try {
26545 value = new RegExp(pattern, flags);
26546 } catch (e) {// ESTree requires null if it failed to instantiate RegExp object.
26547 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
26548 }
26549
26550 return this.finishToken(types.regexp, {
26551 pattern: pattern,
26552 flags: flags,
26553 value: value
26554 });
26555 }; // Read an integer in the given radix. Return null if zero digits
26556 // were read, the integer value otherwise. When `len` is given, this
26557 // will return `null` unless the integer has exactly `len` digits.
26558
26559
26560 pp$9.readInt = function (radix, len) {
26561 var start = this.pos,
26562 total = 0;
26563
26564 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
26565 var code = this.input.charCodeAt(this.pos),
26566 val = void 0;
26567
26568 if (code >= 97) {
26569 val = code - 97 + 10;
26570 } // a
26571 else if (code >= 65) {
26572 val = code - 65 + 10;
26573 } // A
26574 else if (code >= 48 && code <= 57) {
26575 val = code - 48;
26576 } // 0-9
26577 else {
26578 val = Infinity;
26579 }
26580
26581 if (val >= radix) {
26582 break;
26583 }
26584
26585 ++this.pos;
26586 total = total * radix + val;
26587 }
26588
26589 if (this.pos === start || len != null && this.pos - start !== len) {
26590 return null;
26591 }
26592
26593 return total;
26594 };
26595
26596 pp$9.readRadixNumber = function (radix) {
26597 var start = this.pos;
26598 this.pos += 2; // 0x
26599
26600 var val = this.readInt(radix);
26601
26602 if (val == null) {
26603 this.raise(this.start + 2, "Expected number in radix " + radix);
26604 }
26605
26606 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
26607 val = typeof BigInt !== "undefined" ? BigInt(this.input.slice(start, this.pos)) : null;
26608 ++this.pos;
26609 } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
26610 this.raise(this.pos, "Identifier directly after number");
26611 }
26612
26613 return this.finishToken(types.num, val);
26614 }; // Read an integer, octal integer, or floating-point number.
26615
26616
26617 pp$9.readNumber = function (startsWithDot) {
26618 var start = this.pos;
26619
26620 if (!startsWithDot && this.readInt(10) === null) {
26621 this.raise(start, "Invalid number");
26622 }
26623
26624 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
26625
26626 if (octal && this.strict) {
26627 this.raise(start, "Invalid number");
26628 }
26629
26630 var next = this.input.charCodeAt(this.pos);
26631
26632 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
26633 var str$1 = this.input.slice(start, this.pos);
26634 var val$1 = typeof BigInt !== "undefined" ? BigInt(str$1) : null;
26635 ++this.pos;
26636
26637 if (isIdentifierStart(this.fullCharCodeAtPos())) {
26638 this.raise(this.pos, "Identifier directly after number");
26639 }
26640
26641 return this.finishToken(types.num, val$1);
26642 }
26643
26644 if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
26645 octal = false;
26646 }
26647
26648 if (next === 46 && !octal) {
26649 // '.'
26650 ++this.pos;
26651 this.readInt(10);
26652 next = this.input.charCodeAt(this.pos);
26653 }
26654
26655 if ((next === 69 || next === 101) && !octal) {
26656 // 'eE'
26657 next = this.input.charCodeAt(++this.pos);
26658
26659 if (next === 43 || next === 45) {
26660 ++this.pos;
26661 } // '+-'
26662
26663
26664 if (this.readInt(10) === null) {
26665 this.raise(start, "Invalid number");
26666 }
26667 }
26668
26669 if (isIdentifierStart(this.fullCharCodeAtPos())) {
26670 this.raise(this.pos, "Identifier directly after number");
26671 }
26672
26673 var str = this.input.slice(start, this.pos);
26674 var val = octal ? parseInt(str, 8) : parseFloat(str);
26675 return this.finishToken(types.num, val);
26676 }; // Read a string value, interpreting backslash-escapes.
26677
26678
26679 pp$9.readCodePoint = function () {
26680 var ch = this.input.charCodeAt(this.pos),
26681 code;
26682
26683 if (ch === 123) {
26684 // '{'
26685 if (this.options.ecmaVersion < 6) {
26686 this.unexpected();
26687 }
26688
26689 var codePos = ++this.pos;
26690 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
26691 ++this.pos;
26692
26693 if (code > 0x10FFFF) {
26694 this.invalidStringToken(codePos, "Code point out of bounds");
26695 }
26696 } else {
26697 code = this.readHexChar(4);
26698 }
26699
26700 return code;
26701 };
26702
26703 function codePointToString$1(code) {
26704 // UTF-16 Decoding
26705 if (code <= 0xFFFF) {
26706 return String.fromCharCode(code);
26707 }
26708
26709 code -= 0x10000;
26710 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00);
26711 }
26712
26713 pp$9.readString = function (quote) {
26714 var out = "",
26715 chunkStart = ++this.pos;
26716
26717 for (;;) {
26718 if (this.pos >= this.input.length) {
26719 this.raise(this.start, "Unterminated string constant");
26720 }
26721
26722 var ch = this.input.charCodeAt(this.pos);
26723
26724 if (ch === quote) {
26725 break;
26726 }
26727
26728 if (ch === 92) {
26729 // '\'
26730 out += this.input.slice(chunkStart, this.pos);
26731 out += this.readEscapedChar(false);
26732 chunkStart = this.pos;
26733 } else {
26734 if (isNewLine(ch, this.options.ecmaVersion >= 10)) {
26735 this.raise(this.start, "Unterminated string constant");
26736 }
26737
26738 ++this.pos;
26739 }
26740 }
26741
26742 out += this.input.slice(chunkStart, this.pos++);
26743 return this.finishToken(types.string, out);
26744 }; // Reads template string tokens.
26745
26746
26747 var INVALID_TEMPLATE_ESCAPE_ERROR = {};
26748
26749 pp$9.tryReadTemplateToken = function () {
26750 this.inTemplateElement = true;
26751
26752 try {
26753 this.readTmplToken();
26754 } catch (err) {
26755 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
26756 this.readInvalidTemplateToken();
26757 } else {
26758 throw err;
26759 }
26760 }
26761
26762 this.inTemplateElement = false;
26763 };
26764
26765 pp$9.invalidStringToken = function (position, message) {
26766 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
26767 throw INVALID_TEMPLATE_ESCAPE_ERROR;
26768 } else {
26769 this.raise(position, message);
26770 }
26771 };
26772
26773 pp$9.readTmplToken = function () {
26774 var out = "",
26775 chunkStart = this.pos;
26776
26777 for (;;) {
26778 if (this.pos >= this.input.length) {
26779 this.raise(this.start, "Unterminated template");
26780 }
26781
26782 var ch = this.input.charCodeAt(this.pos);
26783
26784 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
26785 // '`', '${'
26786 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
26787 if (ch === 36) {
26788 this.pos += 2;
26789 return this.finishToken(types.dollarBraceL);
26790 } else {
26791 ++this.pos;
26792 return this.finishToken(types.backQuote);
26793 }
26794 }
26795
26796 out += this.input.slice(chunkStart, this.pos);
26797 return this.finishToken(types.template, out);
26798 }
26799
26800 if (ch === 92) {
26801 // '\'
26802 out += this.input.slice(chunkStart, this.pos);
26803 out += this.readEscapedChar(true);
26804 chunkStart = this.pos;
26805 } else if (isNewLine(ch)) {
26806 out += this.input.slice(chunkStart, this.pos);
26807 ++this.pos;
26808
26809 switch (ch) {
26810 case 13:
26811 if (this.input.charCodeAt(this.pos) === 10) {
26812 ++this.pos;
26813 }
26814
26815 case 10:
26816 out += "\n";
26817 break;
26818
26819 default:
26820 out += String.fromCharCode(ch);
26821 break;
26822 }
26823
26824 if (this.options.locations) {
26825 ++this.curLine;
26826 this.lineStart = this.pos;
26827 }
26828
26829 chunkStart = this.pos;
26830 } else {
26831 ++this.pos;
26832 }
26833 }
26834 }; // Reads a template token to search for the end, without validating any escape sequences
26835
26836
26837 pp$9.readInvalidTemplateToken = function () {
26838 for (; this.pos < this.input.length; this.pos++) {
26839 switch (this.input[this.pos]) {
26840 case "\\":
26841 ++this.pos;
26842 break;
26843
26844 case "$":
26845 if (this.input[this.pos + 1] !== "{") {
26846 break;
26847 }
26848
26849 // falls through
26850
26851 case "`":
26852 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos));
26853 // no default
26854 }
26855 }
26856
26857 this.raise(this.start, "Unterminated template");
26858 }; // Used to read escaped characters
26859
26860
26861 pp$9.readEscapedChar = function (inTemplate) {
26862 var ch = this.input.charCodeAt(++this.pos);
26863 ++this.pos;
26864
26865 switch (ch) {
26866 case 110:
26867 return "\n";
26868 // 'n' -> '\n'
26869
26870 case 114:
26871 return "\r";
26872 // 'r' -> '\r'
26873
26874 case 120:
26875 return String.fromCharCode(this.readHexChar(2));
26876 // 'x'
26877
26878 case 117:
26879 return codePointToString$1(this.readCodePoint());
26880 // 'u'
26881
26882 case 116:
26883 return "\t";
26884 // 't' -> '\t'
26885
26886 case 98:
26887 return "\b";
26888 // 'b' -> '\b'
26889
26890 case 118:
26891 return "\u000b";
26892 // 'v' -> '\u000b'
26893
26894 case 102:
26895 return "\f";
26896 // 'f' -> '\f'
26897
26898 case 13:
26899 if (this.input.charCodeAt(this.pos) === 10) {
26900 ++this.pos;
26901 }
26902
26903 // '\r\n'
26904
26905 case 10:
26906 // ' \n'
26907 if (this.options.locations) {
26908 this.lineStart = this.pos;
26909 ++this.curLine;
26910 }
26911
26912 return "";
26913
26914 case 56:
26915 case 57:
26916 if (inTemplate) {
26917 var codePos = this.pos - 1;
26918 this.invalidStringToken(codePos, "Invalid escape sequence in template string");
26919 return null;
26920 }
26921
26922 default:
26923 if (ch >= 48 && ch <= 55) {
26924 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
26925 var octal = parseInt(octalStr, 8);
26926
26927 if (octal > 255) {
26928 octalStr = octalStr.slice(0, -1);
26929 octal = parseInt(octalStr, 8);
26930 }
26931
26932 this.pos += octalStr.length - 1;
26933 ch = this.input.charCodeAt(this.pos);
26934
26935 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
26936 this.invalidStringToken(this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode");
26937 }
26938
26939 return String.fromCharCode(octal);
26940 }
26941
26942 if (isNewLine(ch)) {
26943 // Unicode new line characters after \ get removed from output in both
26944 // template literals and strings
26945 return "";
26946 }
26947
26948 return String.fromCharCode(ch);
26949 }
26950 }; // Used to read character escape sequences ('\x', '\u', '\U').
26951
26952
26953 pp$9.readHexChar = function (len) {
26954 var codePos = this.pos;
26955 var n = this.readInt(16, len);
26956
26957 if (n === null) {
26958 this.invalidStringToken(codePos, "Bad character escape sequence");
26959 }
26960
26961 return n;
26962 }; // Read an identifier, and return it as a string. Sets `this.containsEsc`
26963 // to whether the word contained a '\u' escape.
26964 //
26965 // Incrementally adds only escaped chars, adding other chunks as-is
26966 // as a micro-optimization.
26967
26968
26969 pp$9.readWord1 = function () {
26970 this.containsEsc = false;
26971 var word = "",
26972 first = true,
26973 chunkStart = this.pos;
26974 var astral = this.options.ecmaVersion >= 6;
26975
26976 while (this.pos < this.input.length) {
26977 var ch = this.fullCharCodeAtPos();
26978
26979 if (isIdentifierChar(ch, astral)) {
26980 this.pos += ch <= 0xffff ? 1 : 2;
26981 } else if (ch === 92) {
26982 // "\"
26983 this.containsEsc = true;
26984 word += this.input.slice(chunkStart, this.pos);
26985 var escStart = this.pos;
26986
26987 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
26988 {
26989 this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
26990 }
26991
26992 ++this.pos;
26993 var esc = this.readCodePoint();
26994
26995 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
26996 this.invalidStringToken(escStart, "Invalid Unicode escape");
26997 }
26998
26999 word += codePointToString$1(esc);
27000 chunkStart = this.pos;
27001 } else {
27002 break;
27003 }
27004
27005 first = false;
27006 }
27007
27008 return word + this.input.slice(chunkStart, this.pos);
27009 }; // Read an identifier or keyword token. Will check for reserved
27010 // words when necessary.
27011
27012
27013 pp$9.readWord = function () {
27014 var word = this.readWord1();
27015 var type = types.name;
27016
27017 if (this.keywords.test(word)) {
27018 type = keywords$1[word];
27019 }
27020
27021 return this.finishToken(type, word);
27022 }; // Acorn is a tiny, fast JavaScript parser written in JavaScript.
27023
27024
27025 var version = "7.1.0";
27026 Parser.acorn = {
27027 Parser: Parser,
27028 version: version,
27029 defaultOptions: defaultOptions,
27030 Position: Position,
27031 SourceLocation: SourceLocation,
27032 getLineInfo: getLineInfo,
27033 Node: Node,
27034 TokenType: TokenType,
27035 tokTypes: types,
27036 keywordTypes: keywords$1,
27037 TokContext: TokContext,
27038 tokContexts: types$1,
27039 isIdentifierChar: isIdentifierChar,
27040 isIdentifierStart: isIdentifierStart,
27041 Token: Token,
27042 isNewLine: isNewLine,
27043 lineBreak: lineBreak,
27044 lineBreakG: lineBreakG,
27045 nonASCIIwhitespace: nonASCIIwhitespace
27046 }; // The main exported interface (under `self.acorn` when in the
27047 // browser) is a `parse` function that takes a code string and
27048 // returns an abstract syntax tree as specified by [Mozilla parser
27049 // API][api].
27050 //
27051 // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
27052
27053 function parse(input, options) {
27054 return Parser.parse(input, options);
27055 } // This function tries to parse a single expression at a given
27056 // offset in a string. Useful for parsing mixed-language formats
27057 // that embed JavaScript expressions.
27058
27059
27060 function parseExpressionAt(input, pos, options) {
27061 return Parser.parseExpressionAt(input, pos, options);
27062 } // Acorn is organized as a tokenizer and a recursive-descent parser.
27063 // The `tokenizer` export provides an interface to the tokenizer.
27064
27065
27066 function tokenizer(input, options) {
27067 return Parser.tokenizer(input, options);
27068 }
27069
27070 exports.Node = Node;
27071 exports.Parser = Parser;
27072 exports.Position = Position;
27073 exports.SourceLocation = SourceLocation;
27074 exports.TokContext = TokContext;
27075 exports.Token = Token;
27076 exports.TokenType = TokenType;
27077 exports.defaultOptions = defaultOptions;
27078 exports.getLineInfo = getLineInfo;
27079 exports.isIdentifierChar = isIdentifierChar;
27080 exports.isIdentifierStart = isIdentifierStart;
27081 exports.isNewLine = isNewLine;
27082 exports.keywordTypes = keywords$1;
27083 exports.lineBreak = lineBreak;
27084 exports.lineBreakG = lineBreakG;
27085 exports.nonASCIIwhitespace = nonASCIIwhitespace;
27086 exports.parse = parse;
27087 exports.parseExpressionAt = parseExpressionAt;
27088 exports.tokContexts = types$1;
27089 exports.tokTypes = types;
27090 exports.tokenizer = tokenizer;
27091 exports.version = version;
27092 Object.defineProperty(exports, '__esModule', {
27093 value: true
27094 });
27095});
27096
27097/***/ }),
27098/* 396 */
27099/***/ (function(module, exports, __webpack_require__) {
27100
27101"use strict";
27102
27103
27104const XHTMLEntities = __webpack_require__(397);
27105
27106const hexNumber = /^[\da-fA-F]+$/;
27107const decimalNumber = /^\d+$/; // The map to `acorn-jsx` tokens from `acorn` namespace objects.
27108
27109const acornJsxMap = new WeakMap(); // Get the original tokens for the given `acorn` namespace object.
27110
27111function getJsxTokens(acorn) {
27112 acorn = acorn.Parser.acorn || acorn;
27113 let acornJsx = acornJsxMap.get(acorn);
27114
27115 if (!acornJsx) {
27116 const tt = acorn.tokTypes;
27117 const TokContext = acorn.TokContext;
27118 const TokenType = acorn.TokenType;
27119 const tc_oTag = new TokContext('<tag', false);
27120 const tc_cTag = new TokContext('</tag', false);
27121 const tc_expr = new TokContext('<tag>...</tag>', true, true);
27122 const tokContexts = {
27123 tc_oTag: tc_oTag,
27124 tc_cTag: tc_cTag,
27125 tc_expr: tc_expr
27126 };
27127 const tokTypes = {
27128 jsxName: new TokenType('jsxName'),
27129 jsxText: new TokenType('jsxText', {
27130 beforeExpr: true
27131 }),
27132 jsxTagStart: new TokenType('jsxTagStart'),
27133 jsxTagEnd: new TokenType('jsxTagEnd')
27134 };
27135
27136 tokTypes.jsxTagStart.updateContext = function () {
27137 this.context.push(tc_expr); // treat as beginning of JSX expression
27138
27139 this.context.push(tc_oTag); // start opening tag context
27140
27141 this.exprAllowed = false;
27142 };
27143
27144 tokTypes.jsxTagEnd.updateContext = function (prevType) {
27145 let out = this.context.pop();
27146
27147 if (out === tc_oTag && prevType === tt.slash || out === tc_cTag) {
27148 this.context.pop();
27149 this.exprAllowed = this.curContext() === tc_expr;
27150 } else {
27151 this.exprAllowed = true;
27152 }
27153 };
27154
27155 acornJsx = {
27156 tokContexts: tokContexts,
27157 tokTypes: tokTypes
27158 };
27159 acornJsxMap.set(acorn, acornJsx);
27160 }
27161
27162 return acornJsx;
27163} // Transforms JSX element name to string.
27164
27165
27166function getQualifiedJSXName(object) {
27167 if (!object) return object;
27168 if (object.type === 'JSXIdentifier') return object.name;
27169 if (object.type === 'JSXNamespacedName') return object.namespace.name + ':' + object.name.name;
27170 if (object.type === 'JSXMemberExpression') return getQualifiedJSXName(object.object) + '.' + getQualifiedJSXName(object.property);
27171}
27172
27173module.exports = function (options) {
27174 options = options || {};
27175 return function (Parser) {
27176 return plugin({
27177 allowNamespaces: options.allowNamespaces !== false,
27178 allowNamespacedObjects: !!options.allowNamespacedObjects
27179 }, Parser);
27180 };
27181}; // This is `tokTypes` of the peer dep.
27182// This can be different instances from the actual `tokTypes` this plugin uses.
27183
27184
27185Object.defineProperty(module.exports, "tokTypes", {
27186 get: function get_tokTypes() {
27187 return getJsxTokens(__webpack_require__(395)).tokTypes;
27188 },
27189 configurable: true,
27190 enumerable: true
27191});
27192
27193function plugin(options, Parser) {
27194 const acorn = Parser.acorn || __webpack_require__(395);
27195
27196 const acornJsx = getJsxTokens(acorn);
27197 const tt = acorn.tokTypes;
27198 const tok = acornJsx.tokTypes;
27199 const tokContexts = acorn.tokContexts;
27200 const tc_oTag = acornJsx.tokContexts.tc_oTag;
27201 const tc_cTag = acornJsx.tokContexts.tc_cTag;
27202 const tc_expr = acornJsx.tokContexts.tc_expr;
27203 const isNewLine = acorn.isNewLine;
27204 const isIdentifierStart = acorn.isIdentifierStart;
27205 const isIdentifierChar = acorn.isIdentifierChar;
27206 return class extends Parser {
27207 // Expose actual `tokTypes` and `tokContexts` to other plugins.
27208 static get acornJsx() {
27209 return acornJsx;
27210 } // Reads inline JSX contents token.
27211
27212
27213 jsx_readToken() {
27214 let out = '',
27215 chunkStart = this.pos;
27216
27217 for (;;) {
27218 if (this.pos >= this.input.length) this.raise(this.start, 'Unterminated JSX contents');
27219 let ch = this.input.charCodeAt(this.pos);
27220
27221 switch (ch) {
27222 case 60: // '<'
27223
27224 case 123:
27225 // '{'
27226 if (this.pos === this.start) {
27227 if (ch === 60 && this.exprAllowed) {
27228 ++this.pos;
27229 return this.finishToken(tok.jsxTagStart);
27230 }
27231
27232 return this.getTokenFromCode(ch);
27233 }
27234
27235 out += this.input.slice(chunkStart, this.pos);
27236 return this.finishToken(tok.jsxText, out);
27237
27238 case 38:
27239 // '&'
27240 out += this.input.slice(chunkStart, this.pos);
27241 out += this.jsx_readEntity();
27242 chunkStart = this.pos;
27243 break;
27244
27245 case 62: // '>'
27246
27247 case 125:
27248 // '}'
27249 this.raise(this.pos, "Unexpected token `" + this.input[this.pos] + "`. Did you mean `" + (ch === 62 ? "&gt;" : "&rbrace;") + "` or " + "`{\"" + this.input[this.pos] + "\"}" + "`?");
27250
27251 default:
27252 if (isNewLine(ch)) {
27253 out += this.input.slice(chunkStart, this.pos);
27254 out += this.jsx_readNewLine(true);
27255 chunkStart = this.pos;
27256 } else {
27257 ++this.pos;
27258 }
27259
27260 }
27261 }
27262 }
27263
27264 jsx_readNewLine(normalizeCRLF) {
27265 let ch = this.input.charCodeAt(this.pos);
27266 let out;
27267 ++this.pos;
27268
27269 if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
27270 ++this.pos;
27271 out = normalizeCRLF ? '\n' : '\r\n';
27272 } else {
27273 out = String.fromCharCode(ch);
27274 }
27275
27276 if (this.options.locations) {
27277 ++this.curLine;
27278 this.lineStart = this.pos;
27279 }
27280
27281 return out;
27282 }
27283
27284 jsx_readString(quote) {
27285 let out = '',
27286 chunkStart = ++this.pos;
27287
27288 for (;;) {
27289 if (this.pos >= this.input.length) this.raise(this.start, 'Unterminated string constant');
27290 let ch = this.input.charCodeAt(this.pos);
27291 if (ch === quote) break;
27292
27293 if (ch === 38) {
27294 // '&'
27295 out += this.input.slice(chunkStart, this.pos);
27296 out += this.jsx_readEntity();
27297 chunkStart = this.pos;
27298 } else if (isNewLine(ch)) {
27299 out += this.input.slice(chunkStart, this.pos);
27300 out += this.jsx_readNewLine(false);
27301 chunkStart = this.pos;
27302 } else {
27303 ++this.pos;
27304 }
27305 }
27306
27307 out += this.input.slice(chunkStart, this.pos++);
27308 return this.finishToken(tt.string, out);
27309 }
27310
27311 jsx_readEntity() {
27312 let str = '',
27313 count = 0,
27314 entity;
27315 let ch = this.input[this.pos];
27316 if (ch !== '&') this.raise(this.pos, 'Entity must start with an ampersand');
27317 let startPos = ++this.pos;
27318
27319 while (this.pos < this.input.length && count++ < 10) {
27320 ch = this.input[this.pos++];
27321
27322 if (ch === ';') {
27323 if (str[0] === '#') {
27324 if (str[1] === 'x') {
27325 str = str.substr(2);
27326 if (hexNumber.test(str)) entity = String.fromCharCode(parseInt(str, 16));
27327 } else {
27328 str = str.substr(1);
27329 if (decimalNumber.test(str)) entity = String.fromCharCode(parseInt(str, 10));
27330 }
27331 } else {
27332 entity = XHTMLEntities[str];
27333 }
27334
27335 break;
27336 }
27337
27338 str += ch;
27339 }
27340
27341 if (!entity) {
27342 this.pos = startPos;
27343 return '&';
27344 }
27345
27346 return entity;
27347 } // Read a JSX identifier (valid tag or attribute name).
27348 //
27349 // Optimized version since JSX identifiers can't contain
27350 // escape characters and so can be read as single slice.
27351 // Also assumes that first character was already checked
27352 // by isIdentifierStart in readToken.
27353
27354
27355 jsx_readWord() {
27356 let ch,
27357 start = this.pos;
27358
27359 do {
27360 ch = this.input.charCodeAt(++this.pos);
27361 } while (isIdentifierChar(ch) || ch === 45); // '-'
27362
27363
27364 return this.finishToken(tok.jsxName, this.input.slice(start, this.pos));
27365 } // Parse next token as JSX identifier
27366
27367
27368 jsx_parseIdentifier() {
27369 let node = this.startNode();
27370 if (this.type === tok.jsxName) node.name = this.value;else if (this.type.keyword) node.name = this.type.keyword;else this.unexpected();
27371 this.next();
27372 return this.finishNode(node, 'JSXIdentifier');
27373 } // Parse namespaced identifier.
27374
27375
27376 jsx_parseNamespacedName() {
27377 let startPos = this.start,
27378 startLoc = this.startLoc;
27379 let name = this.jsx_parseIdentifier();
27380 if (!options.allowNamespaces || !this.eat(tt.colon)) return name;
27381 var node = this.startNodeAt(startPos, startLoc);
27382 node.namespace = name;
27383 node.name = this.jsx_parseIdentifier();
27384 return this.finishNode(node, 'JSXNamespacedName');
27385 } // Parses element name in any form - namespaced, member
27386 // or single identifier.
27387
27388
27389 jsx_parseElementName() {
27390 if (this.type === tok.jsxTagEnd) return '';
27391 let startPos = this.start,
27392 startLoc = this.startLoc;
27393 let node = this.jsx_parseNamespacedName();
27394
27395 if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !options.allowNamespacedObjects) {
27396 this.unexpected();
27397 }
27398
27399 while (this.eat(tt.dot)) {
27400 let newNode = this.startNodeAt(startPos, startLoc);
27401 newNode.object = node;
27402 newNode.property = this.jsx_parseIdentifier();
27403 node = this.finishNode(newNode, 'JSXMemberExpression');
27404 }
27405
27406 return node;
27407 } // Parses any type of JSX attribute value.
27408
27409
27410 jsx_parseAttributeValue() {
27411 switch (this.type) {
27412 case tt.braceL:
27413 let node = this.jsx_parseExpressionContainer();
27414 if (node.expression.type === 'JSXEmptyExpression') this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression');
27415 return node;
27416
27417 case tok.jsxTagStart:
27418 case tt.string:
27419 return this.parseExprAtom();
27420
27421 default:
27422 this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text');
27423 }
27424 } // JSXEmptyExpression is unique type since it doesn't actually parse anything,
27425 // and so it should start at the end of last read token (left brace) and finish
27426 // at the beginning of the next one (right brace).
27427
27428
27429 jsx_parseEmptyExpression() {
27430 let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);
27431 return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);
27432 } // Parses JSX expression enclosed into curly brackets.
27433
27434
27435 jsx_parseExpressionContainer() {
27436 let node = this.startNode();
27437 this.next();
27438 node.expression = this.type === tt.braceR ? this.jsx_parseEmptyExpression() : this.parseExpression();
27439 this.expect(tt.braceR);
27440 return this.finishNode(node, 'JSXExpressionContainer');
27441 } // Parses following JSX attribute name-value pair.
27442
27443
27444 jsx_parseAttribute() {
27445 let node = this.startNode();
27446
27447 if (this.eat(tt.braceL)) {
27448 this.expect(tt.ellipsis);
27449 node.argument = this.parseMaybeAssign();
27450 this.expect(tt.braceR);
27451 return this.finishNode(node, 'JSXSpreadAttribute');
27452 }
27453
27454 node.name = this.jsx_parseNamespacedName();
27455 node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
27456 return this.finishNode(node, 'JSXAttribute');
27457 } // Parses JSX opening tag starting after '<'.
27458
27459
27460 jsx_parseOpeningElementAt(startPos, startLoc) {
27461 let node = this.startNodeAt(startPos, startLoc);
27462 node.attributes = [];
27463 let nodeName = this.jsx_parseElementName();
27464 if (nodeName) node.name = nodeName;
27465
27466 while (this.type !== tt.slash && this.type !== tok.jsxTagEnd) node.attributes.push(this.jsx_parseAttribute());
27467
27468 node.selfClosing = this.eat(tt.slash);
27469 this.expect(tok.jsxTagEnd);
27470 return this.finishNode(node, nodeName ? 'JSXOpeningElement' : 'JSXOpeningFragment');
27471 } // Parses JSX closing tag starting after '</'.
27472
27473
27474 jsx_parseClosingElementAt(startPos, startLoc) {
27475 let node = this.startNodeAt(startPos, startLoc);
27476 let nodeName = this.jsx_parseElementName();
27477 if (nodeName) node.name = nodeName;
27478 this.expect(tok.jsxTagEnd);
27479 return this.finishNode(node, nodeName ? 'JSXClosingElement' : 'JSXClosingFragment');
27480 } // Parses entire JSX element, including it's opening tag
27481 // (starting after '<'), attributes, contents and closing tag.
27482
27483
27484 jsx_parseElementAt(startPos, startLoc) {
27485 let node = this.startNodeAt(startPos, startLoc);
27486 let children = [];
27487 let openingElement = this.jsx_parseOpeningElementAt(startPos, startLoc);
27488 let closingElement = null;
27489
27490 if (!openingElement.selfClosing) {
27491 contents: for (;;) {
27492 switch (this.type) {
27493 case tok.jsxTagStart:
27494 startPos = this.start;
27495 startLoc = this.startLoc;
27496 this.next();
27497
27498 if (this.eat(tt.slash)) {
27499 closingElement = this.jsx_parseClosingElementAt(startPos, startLoc);
27500 break contents;
27501 }
27502
27503 children.push(this.jsx_parseElementAt(startPos, startLoc));
27504 break;
27505
27506 case tok.jsxText:
27507 children.push(this.parseExprAtom());
27508 break;
27509
27510 case tt.braceL:
27511 children.push(this.jsx_parseExpressionContainer());
27512 break;
27513
27514 default:
27515 this.unexpected();
27516 }
27517 }
27518
27519 if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
27520 this.raise(closingElement.start, 'Expected corresponding JSX closing tag for <' + getQualifiedJSXName(openingElement.name) + '>');
27521 }
27522 }
27523
27524 let fragmentOrElement = openingElement.name ? 'Element' : 'Fragment';
27525 node['opening' + fragmentOrElement] = openingElement;
27526 node['closing' + fragmentOrElement] = closingElement;
27527 node.children = children;
27528
27529 if (this.type === tt.relational && this.value === "<") {
27530 this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag");
27531 }
27532
27533 return this.finishNode(node, 'JSX' + fragmentOrElement);
27534 } // Parse JSX text
27535
27536
27537 jsx_parseText() {
27538 let node = this.parseLiteral(this.value);
27539 node.type = "JSXText";
27540 return node;
27541 } // Parses entire JSX element from current position.
27542
27543
27544 jsx_parseElement() {
27545 let startPos = this.start,
27546 startLoc = this.startLoc;
27547 this.next();
27548 return this.jsx_parseElementAt(startPos, startLoc);
27549 }
27550
27551 parseExprAtom(refShortHandDefaultPos) {
27552 if (this.type === tok.jsxText) return this.jsx_parseText();else if (this.type === tok.jsxTagStart) return this.jsx_parseElement();else return super.parseExprAtom(refShortHandDefaultPos);
27553 }
27554
27555 readToken(code) {
27556 let context = this.curContext();
27557 if (context === tc_expr) return this.jsx_readToken();
27558
27559 if (context === tc_oTag || context === tc_cTag) {
27560 if (isIdentifierStart(code)) return this.jsx_readWord();
27561
27562 if (code == 62) {
27563 ++this.pos;
27564 return this.finishToken(tok.jsxTagEnd);
27565 }
27566
27567 if ((code === 34 || code === 39) && context == tc_oTag) return this.jsx_readString(code);
27568 }
27569
27570 if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) {
27571 ++this.pos;
27572 return this.finishToken(tok.jsxTagStart);
27573 }
27574
27575 return super.readToken(code);
27576 }
27577
27578 updateContext(prevType) {
27579 if (this.type == tt.braceL) {
27580 var curContext = this.curContext();
27581 if (curContext == tc_oTag) this.context.push(tokContexts.b_expr);else if (curContext == tc_expr) this.context.push(tokContexts.b_tmpl);else super.updateContext(prevType);
27582 this.exprAllowed = true;
27583 } else if (this.type === tt.slash && prevType === tok.jsxTagStart) {
27584 this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
27585
27586 this.context.push(tc_cTag); // reconsider as closing tag context
27587
27588 this.exprAllowed = false;
27589 } else {
27590 return super.updateContext(prevType);
27591 }
27592 }
27593
27594 };
27595}
27596
27597/***/ }),
27598/* 397 */
27599/***/ (function(module, exports) {
27600
27601module.exports = {
27602 quot: '\u0022',
27603 amp: '&',
27604 apos: '\u0027',
27605 lt: '<',
27606 gt: '>',
27607 nbsp: '\u00A0',
27608 iexcl: '\u00A1',
27609 cent: '\u00A2',
27610 pound: '\u00A3',
27611 curren: '\u00A4',
27612 yen: '\u00A5',
27613 brvbar: '\u00A6',
27614 sect: '\u00A7',
27615 uml: '\u00A8',
27616 copy: '\u00A9',
27617 ordf: '\u00AA',
27618 laquo: '\u00AB',
27619 not: '\u00AC',
27620 shy: '\u00AD',
27621 reg: '\u00AE',
27622 macr: '\u00AF',
27623 deg: '\u00B0',
27624 plusmn: '\u00B1',
27625 sup2: '\u00B2',
27626 sup3: '\u00B3',
27627 acute: '\u00B4',
27628 micro: '\u00B5',
27629 para: '\u00B6',
27630 middot: '\u00B7',
27631 cedil: '\u00B8',
27632 sup1: '\u00B9',
27633 ordm: '\u00BA',
27634 raquo: '\u00BB',
27635 frac14: '\u00BC',
27636 frac12: '\u00BD',
27637 frac34: '\u00BE',
27638 iquest: '\u00BF',
27639 Agrave: '\u00C0',
27640 Aacute: '\u00C1',
27641 Acirc: '\u00C2',
27642 Atilde: '\u00C3',
27643 Auml: '\u00C4',
27644 Aring: '\u00C5',
27645 AElig: '\u00C6',
27646 Ccedil: '\u00C7',
27647 Egrave: '\u00C8',
27648 Eacute: '\u00C9',
27649 Ecirc: '\u00CA',
27650 Euml: '\u00CB',
27651 Igrave: '\u00CC',
27652 Iacute: '\u00CD',
27653 Icirc: '\u00CE',
27654 Iuml: '\u00CF',
27655 ETH: '\u00D0',
27656 Ntilde: '\u00D1',
27657 Ograve: '\u00D2',
27658 Oacute: '\u00D3',
27659 Ocirc: '\u00D4',
27660 Otilde: '\u00D5',
27661 Ouml: '\u00D6',
27662 times: '\u00D7',
27663 Oslash: '\u00D8',
27664 Ugrave: '\u00D9',
27665 Uacute: '\u00DA',
27666 Ucirc: '\u00DB',
27667 Uuml: '\u00DC',
27668 Yacute: '\u00DD',
27669 THORN: '\u00DE',
27670 szlig: '\u00DF',
27671 agrave: '\u00E0',
27672 aacute: '\u00E1',
27673 acirc: '\u00E2',
27674 atilde: '\u00E3',
27675 auml: '\u00E4',
27676 aring: '\u00E5',
27677 aelig: '\u00E6',
27678 ccedil: '\u00E7',
27679 egrave: '\u00E8',
27680 eacute: '\u00E9',
27681 ecirc: '\u00EA',
27682 euml: '\u00EB',
27683 igrave: '\u00EC',
27684 iacute: '\u00ED',
27685 icirc: '\u00EE',
27686 iuml: '\u00EF',
27687 eth: '\u00F0',
27688 ntilde: '\u00F1',
27689 ograve: '\u00F2',
27690 oacute: '\u00F3',
27691 ocirc: '\u00F4',
27692 otilde: '\u00F5',
27693 ouml: '\u00F6',
27694 divide: '\u00F7',
27695 oslash: '\u00F8',
27696 ugrave: '\u00F9',
27697 uacute: '\u00FA',
27698 ucirc: '\u00FB',
27699 uuml: '\u00FC',
27700 yacute: '\u00FD',
27701 thorn: '\u00FE',
27702 yuml: '\u00FF',
27703 OElig: '\u0152',
27704 oelig: '\u0153',
27705 Scaron: '\u0160',
27706 scaron: '\u0161',
27707 Yuml: '\u0178',
27708 fnof: '\u0192',
27709 circ: '\u02C6',
27710 tilde: '\u02DC',
27711 Alpha: '\u0391',
27712 Beta: '\u0392',
27713 Gamma: '\u0393',
27714 Delta: '\u0394',
27715 Epsilon: '\u0395',
27716 Zeta: '\u0396',
27717 Eta: '\u0397',
27718 Theta: '\u0398',
27719 Iota: '\u0399',
27720 Kappa: '\u039A',
27721 Lambda: '\u039B',
27722 Mu: '\u039C',
27723 Nu: '\u039D',
27724 Xi: '\u039E',
27725 Omicron: '\u039F',
27726 Pi: '\u03A0',
27727 Rho: '\u03A1',
27728 Sigma: '\u03A3',
27729 Tau: '\u03A4',
27730 Upsilon: '\u03A5',
27731 Phi: '\u03A6',
27732 Chi: '\u03A7',
27733 Psi: '\u03A8',
27734 Omega: '\u03A9',
27735 alpha: '\u03B1',
27736 beta: '\u03B2',
27737 gamma: '\u03B3',
27738 delta: '\u03B4',
27739 epsilon: '\u03B5',
27740 zeta: '\u03B6',
27741 eta: '\u03B7',
27742 theta: '\u03B8',
27743 iota: '\u03B9',
27744 kappa: '\u03BA',
27745 lambda: '\u03BB',
27746 mu: '\u03BC',
27747 nu: '\u03BD',
27748 xi: '\u03BE',
27749 omicron: '\u03BF',
27750 pi: '\u03C0',
27751 rho: '\u03C1',
27752 sigmaf: '\u03C2',
27753 sigma: '\u03C3',
27754 tau: '\u03C4',
27755 upsilon: '\u03C5',
27756 phi: '\u03C6',
27757 chi: '\u03C7',
27758 psi: '\u03C8',
27759 omega: '\u03C9',
27760 thetasym: '\u03D1',
27761 upsih: '\u03D2',
27762 piv: '\u03D6',
27763 ensp: '\u2002',
27764 emsp: '\u2003',
27765 thinsp: '\u2009',
27766 zwnj: '\u200C',
27767 zwj: '\u200D',
27768 lrm: '\u200E',
27769 rlm: '\u200F',
27770 ndash: '\u2013',
27771 mdash: '\u2014',
27772 lsquo: '\u2018',
27773 rsquo: '\u2019',
27774 sbquo: '\u201A',
27775 ldquo: '\u201C',
27776 rdquo: '\u201D',
27777 bdquo: '\u201E',
27778 dagger: '\u2020',
27779 Dagger: '\u2021',
27780 bull: '\u2022',
27781 hellip: '\u2026',
27782 permil: '\u2030',
27783 prime: '\u2032',
27784 Prime: '\u2033',
27785 lsaquo: '\u2039',
27786 rsaquo: '\u203A',
27787 oline: '\u203E',
27788 frasl: '\u2044',
27789 euro: '\u20AC',
27790 image: '\u2111',
27791 weierp: '\u2118',
27792 real: '\u211C',
27793 trade: '\u2122',
27794 alefsym: '\u2135',
27795 larr: '\u2190',
27796 uarr: '\u2191',
27797 rarr: '\u2192',
27798 darr: '\u2193',
27799 harr: '\u2194',
27800 crarr: '\u21B5',
27801 lArr: '\u21D0',
27802 uArr: '\u21D1',
27803 rArr: '\u21D2',
27804 dArr: '\u21D3',
27805 hArr: '\u21D4',
27806 forall: '\u2200',
27807 part: '\u2202',
27808 exist: '\u2203',
27809 empty: '\u2205',
27810 nabla: '\u2207',
27811 isin: '\u2208',
27812 notin: '\u2209',
27813 ni: '\u220B',
27814 prod: '\u220F',
27815 sum: '\u2211',
27816 minus: '\u2212',
27817 lowast: '\u2217',
27818 radic: '\u221A',
27819 prop: '\u221D',
27820 infin: '\u221E',
27821 ang: '\u2220',
27822 and: '\u2227',
27823 or: '\u2228',
27824 cap: '\u2229',
27825 cup: '\u222A',
27826 'int': '\u222B',
27827 there4: '\u2234',
27828 sim: '\u223C',
27829 cong: '\u2245',
27830 asymp: '\u2248',
27831 ne: '\u2260',
27832 equiv: '\u2261',
27833 le: '\u2264',
27834 ge: '\u2265',
27835 sub: '\u2282',
27836 sup: '\u2283',
27837 nsub: '\u2284',
27838 sube: '\u2286',
27839 supe: '\u2287',
27840 oplus: '\u2295',
27841 otimes: '\u2297',
27842 perp: '\u22A5',
27843 sdot: '\u22C5',
27844 lceil: '\u2308',
27845 rceil: '\u2309',
27846 lfloor: '\u230A',
27847 rfloor: '\u230B',
27848 lang: '\u2329',
27849 rang: '\u232A',
27850 loz: '\u25CA',
27851 spades: '\u2660',
27852 clubs: '\u2663',
27853 hearts: '\u2665',
27854 diams: '\u2666'
27855};
27856
27857/***/ }),
27858/* 398 */
27859/***/ (function(module, exports, __webpack_require__) {
27860
27861"use strict";
27862/**
27863 * @fileoverview The AST node types produced by the parser.
27864 * @author Nicholas C. Zakas
27865 */
27866 //------------------------------------------------------------------------------
27867// Requirements
27868//------------------------------------------------------------------------------
27869// None!
27870//------------------------------------------------------------------------------
27871// Public
27872//------------------------------------------------------------------------------
27873
27874module.exports = {
27875 AssignmentExpression: "AssignmentExpression",
27876 AssignmentPattern: "AssignmentPattern",
27877 ArrayExpression: "ArrayExpression",
27878 ArrayPattern: "ArrayPattern",
27879 ArrowFunctionExpression: "ArrowFunctionExpression",
27880 AwaitExpression: "AwaitExpression",
27881 BlockStatement: "BlockStatement",
27882 BinaryExpression: "BinaryExpression",
27883 BreakStatement: "BreakStatement",
27884 CallExpression: "CallExpression",
27885 CatchClause: "CatchClause",
27886 ClassBody: "ClassBody",
27887 ClassDeclaration: "ClassDeclaration",
27888 ClassExpression: "ClassExpression",
27889 ConditionalExpression: "ConditionalExpression",
27890 ContinueStatement: "ContinueStatement",
27891 DoWhileStatement: "DoWhileStatement",
27892 DebuggerStatement: "DebuggerStatement",
27893 EmptyStatement: "EmptyStatement",
27894 ExpressionStatement: "ExpressionStatement",
27895 ForStatement: "ForStatement",
27896 ForInStatement: "ForInStatement",
27897 ForOfStatement: "ForOfStatement",
27898 FunctionDeclaration: "FunctionDeclaration",
27899 FunctionExpression: "FunctionExpression",
27900 Identifier: "Identifier",
27901 IfStatement: "IfStatement",
27902 Literal: "Literal",
27903 LabeledStatement: "LabeledStatement",
27904 LogicalExpression: "LogicalExpression",
27905 MemberExpression: "MemberExpression",
27906 MetaProperty: "MetaProperty",
27907 MethodDefinition: "MethodDefinition",
27908 NewExpression: "NewExpression",
27909 ObjectExpression: "ObjectExpression",
27910 ObjectPattern: "ObjectPattern",
27911 Program: "Program",
27912 Property: "Property",
27913 RestElement: "RestElement",
27914 ReturnStatement: "ReturnStatement",
27915 SequenceExpression: "SequenceExpression",
27916 SpreadElement: "SpreadElement",
27917 Super: "Super",
27918 SwitchCase: "SwitchCase",
27919 SwitchStatement: "SwitchStatement",
27920 TaggedTemplateExpression: "TaggedTemplateExpression",
27921 TemplateElement: "TemplateElement",
27922 TemplateLiteral: "TemplateLiteral",
27923 ThisExpression: "ThisExpression",
27924 ThrowStatement: "ThrowStatement",
27925 TryStatement: "TryStatement",
27926 UnaryExpression: "UnaryExpression",
27927 UpdateExpression: "UpdateExpression",
27928 VariableDeclaration: "VariableDeclaration",
27929 VariableDeclarator: "VariableDeclarator",
27930 WhileStatement: "WhileStatement",
27931 WithStatement: "WithStatement",
27932 YieldExpression: "YieldExpression",
27933 JSXIdentifier: "JSXIdentifier",
27934 JSXNamespacedName: "JSXNamespacedName",
27935 JSXMemberExpression: "JSXMemberExpression",
27936 JSXEmptyExpression: "JSXEmptyExpression",
27937 JSXExpressionContainer: "JSXExpressionContainer",
27938 JSXElement: "JSXElement",
27939 JSXClosingElement: "JSXClosingElement",
27940 JSXOpeningElement: "JSXOpeningElement",
27941 JSXAttribute: "JSXAttribute",
27942 JSXSpreadAttribute: "JSXSpreadAttribute",
27943 JSXText: "JSXText",
27944 ExportDefaultDeclaration: "ExportDefaultDeclaration",
27945 ExportNamedDeclaration: "ExportNamedDeclaration",
27946 ExportAllDeclaration: "ExportAllDeclaration",
27947 ExportSpecifier: "ExportSpecifier",
27948 ImportDeclaration: "ImportDeclaration",
27949 ImportSpecifier: "ImportSpecifier",
27950 ImportDefaultSpecifier: "ImportDefaultSpecifier",
27951 ImportNamespaceSpecifier: "ImportNamespaceSpecifier"
27952};
27953
27954/***/ }),
27955/* 399 */
27956/***/ (function(module, exports, __webpack_require__) {
27957
27958"use strict";
27959
27960/* eslint-disable no-param-reassign*/
27961
27962const TokenTranslator = __webpack_require__(400);
27963
27964const {
27965 normalizeOptions
27966} = __webpack_require__(401);
27967
27968const STATE = Symbol("espree's internal state");
27969const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode");
27970/**
27971 * Converts an Acorn comment to a Esprima comment.
27972 * @param {boolean} block True if it's a block comment, false if not.
27973 * @param {string} text The text of the comment.
27974 * @param {int} start The index at which the comment starts.
27975 * @param {int} end The index at which the comment ends.
27976 * @param {Location} startLoc The location at which the comment starts.
27977 * @param {Location} endLoc The location at which the comment ends.
27978 * @returns {Object} The comment object.
27979 * @private
27980 */
27981
27982function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc) {
27983 const comment = {
27984 type: block ? "Block" : "Line",
27985 value: text
27986 };
27987
27988 if (typeof start === "number") {
27989 comment.start = start;
27990 comment.end = end;
27991 comment.range = [start, end];
27992 }
27993
27994 if (typeof startLoc === "object") {
27995 comment.loc = {
27996 start: startLoc,
27997 end: endLoc
27998 };
27999 }
28000
28001 return comment;
28002}
28003
28004module.exports = () => Parser => {
28005 const tokTypes = Object.assign({}, Parser.acorn.tokTypes);
28006
28007 if (Parser.acornJsx) {
28008 Object.assign(tokTypes, Parser.acornJsx.tokTypes);
28009 }
28010
28011 return class Espree extends Parser {
28012 constructor(opts, code) {
28013 if (typeof opts !== "object" || opts === null) {
28014 opts = {};
28015 }
28016
28017 if (typeof code !== "string" && !(code instanceof String)) {
28018 code = String(code);
28019 }
28020
28021 const options = normalizeOptions(opts);
28022 const ecmaFeatures = options.ecmaFeatures || {};
28023 const tokenTranslator = options.tokens === true ? new TokenTranslator(tokTypes, code) : null; // Initialize acorn parser.
28024
28025 super({
28026 // TODO: use {...options} when spread is supported(Node.js >= 8.3.0).
28027 ecmaVersion: options.ecmaVersion,
28028 sourceType: options.sourceType,
28029 ranges: options.ranges,
28030 locations: options.locations,
28031 // Truthy value is true for backward compatibility.
28032 allowReturnOutsideFunction: Boolean(ecmaFeatures.globalReturn),
28033 // Collect tokens
28034 onToken: token => {
28035 if (tokenTranslator) {
28036 // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state.
28037 tokenTranslator.onToken(token, this[STATE]);
28038 }
28039
28040 if (token.type !== tokTypes.eof) {
28041 this[STATE].lastToken = token;
28042 }
28043 },
28044 // Collect comments
28045 onComment: (block, text, start, end, startLoc, endLoc) => {
28046 if (this[STATE].comments) {
28047 const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc);
28048 this[STATE].comments.push(comment);
28049 }
28050 }
28051 }, code); // Initialize internal state.
28052
28053 this[STATE] = {
28054 tokens: tokenTranslator ? [] : null,
28055 comments: options.comment === true ? [] : null,
28056 impliedStrict: ecmaFeatures.impliedStrict === true && this.options.ecmaVersion >= 5,
28057 ecmaVersion: this.options.ecmaVersion,
28058 jsxAttrValueToken: false,
28059 lastToken: null
28060 };
28061 }
28062
28063 tokenize() {
28064 do {
28065 this.next();
28066 } while (this.type !== tokTypes.eof); // Consume the final eof token
28067
28068
28069 this.next();
28070 const extra = this[STATE];
28071 const tokens = extra.tokens;
28072
28073 if (extra.comments) {
28074 tokens.comments = extra.comments;
28075 }
28076
28077 return tokens;
28078 }
28079
28080 finishNode(...args) {
28081 const result = super.finishNode(...args);
28082 return this[ESPRIMA_FINISH_NODE](result);
28083 }
28084
28085 finishNodeAt(...args) {
28086 const result = super.finishNodeAt(...args);
28087 return this[ESPRIMA_FINISH_NODE](result);
28088 }
28089
28090 parse() {
28091 const extra = this[STATE];
28092 const program = super.parse();
28093 program.sourceType = this.options.sourceType;
28094
28095 if (extra.comments) {
28096 program.comments = extra.comments;
28097 }
28098
28099 if (extra.tokens) {
28100 program.tokens = extra.tokens;
28101 }
28102 /*
28103 * Adjust opening and closing position of program to match Esprima.
28104 * Acorn always starts programs at range 0 whereas Esprima starts at the
28105 * first AST node's start (the only real difference is when there's leading
28106 * whitespace or leading comments). Acorn also counts trailing whitespace
28107 * as part of the program whereas Esprima only counts up to the last token.
28108 */
28109
28110
28111 if (program.range) {
28112 program.range[0] = program.body.length ? program.body[0].range[0] : program.range[0];
28113 program.range[1] = extra.lastToken ? extra.lastToken.range[1] : program.range[1];
28114 }
28115
28116 if (program.loc) {
28117 program.loc.start = program.body.length ? program.body[0].loc.start : program.loc.start;
28118 program.loc.end = extra.lastToken ? extra.lastToken.loc.end : program.loc.end;
28119 }
28120
28121 return program;
28122 }
28123
28124 parseTopLevel(node) {
28125 if (this[STATE].impliedStrict) {
28126 this.strict = true;
28127 }
28128
28129 return super.parseTopLevel(node);
28130 }
28131 /**
28132 * Overwrites the default raise method to throw Esprima-style errors.
28133 * @param {int} pos The position of the error.
28134 * @param {string} message The error message.
28135 * @throws {SyntaxError} A syntax error.
28136 * @returns {void}
28137 */
28138
28139
28140 raise(pos, message) {
28141 const loc = Parser.acorn.getLineInfo(this.input, pos);
28142 const err = new SyntaxError(message);
28143 err.index = pos;
28144 err.lineNumber = loc.line;
28145 err.column = loc.column + 1; // acorn uses 0-based columns
28146
28147 throw err;
28148 }
28149 /**
28150 * Overwrites the default raise method to throw Esprima-style errors.
28151 * @param {int} pos The position of the error.
28152 * @param {string} message The error message.
28153 * @throws {SyntaxError} A syntax error.
28154 * @returns {void}
28155 */
28156
28157
28158 raiseRecoverable(pos, message) {
28159 this.raise(pos, message);
28160 }
28161 /**
28162 * Overwrites the default unexpected method to throw Esprima-style errors.
28163 * @param {int} pos The position of the error.
28164 * @throws {SyntaxError} A syntax error.
28165 * @returns {void}
28166 */
28167
28168
28169 unexpected(pos) {
28170 let message = "Unexpected token";
28171
28172 if (pos !== null && pos !== void 0) {
28173 this.pos = pos;
28174
28175 if (this.options.locations) {
28176 while (this.pos < this.lineStart) {
28177 this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
28178 --this.curLine;
28179 }
28180 }
28181
28182 this.nextToken();
28183 }
28184
28185 if (this.end > this.start) {
28186 message += " ".concat(this.input.slice(this.start, this.end));
28187 }
28188
28189 this.raise(this.start, message);
28190 }
28191 /*
28192 * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX
28193 * uses regular tt.string without any distinction between this and regular JS
28194 * strings. As such, we intercept an attempt to read a JSX string and set a flag
28195 * on extra so that when tokens are converted, the next token will be switched
28196 * to JSXText via onToken.
28197 */
28198
28199
28200 jsx_readString(quote) {
28201 // eslint-disable-line camelcase
28202 const result = super.jsx_readString(quote);
28203
28204 if (this.type === tokTypes.string) {
28205 this[STATE].jsxAttrValueToken = true;
28206 }
28207
28208 return result;
28209 }
28210 /**
28211 * Performs last-minute Esprima-specific compatibility checks and fixes.
28212 * @param {ASTNode} result The node to check.
28213 * @returns {ASTNode} The finished node.
28214 */
28215
28216
28217 [ESPRIMA_FINISH_NODE](result) {
28218 // Acorn doesn't count the opening and closing backticks as part of templates
28219 // so we have to adjust ranges/locations appropriately.
28220 if (result.type === "TemplateElement") {
28221 // additional adjustment needed if ${ is the last token
28222 const terminalDollarBraceL = this.input.slice(result.end, result.end + 2) === "${";
28223
28224 if (result.range) {
28225 result.range[0]--;
28226 result.range[1] += terminalDollarBraceL ? 2 : 1;
28227 }
28228
28229 if (result.loc) {
28230 result.loc.start.column--;
28231 result.loc.end.column += terminalDollarBraceL ? 2 : 1;
28232 }
28233 }
28234
28235 if (result.type.indexOf("Function") > -1 && !result.generator) {
28236 result.generator = false;
28237 }
28238
28239 return result;
28240 }
28241
28242 };
28243};
28244
28245/***/ }),
28246/* 400 */
28247/***/ (function(module, exports, __webpack_require__) {
28248
28249"use strict";
28250/**
28251 * @fileoverview Translates tokens between Acorn format and Esprima format.
28252 * @author Nicholas C. Zakas
28253 */
28254
28255/* eslint no-underscore-dangle: 0 */
28256 //------------------------------------------------------------------------------
28257// Requirements
28258//------------------------------------------------------------------------------
28259// none!
28260//------------------------------------------------------------------------------
28261// Private
28262//------------------------------------------------------------------------------
28263// Esprima Token Types
28264
28265const Token = {
28266 Boolean: "Boolean",
28267 EOF: "<end>",
28268 Identifier: "Identifier",
28269 Keyword: "Keyword",
28270 Null: "Null",
28271 Numeric: "Numeric",
28272 Punctuator: "Punctuator",
28273 String: "String",
28274 RegularExpression: "RegularExpression",
28275 Template: "Template",
28276 JSXIdentifier: "JSXIdentifier",
28277 JSXText: "JSXText"
28278};
28279/**
28280 * Converts part of a template into an Esprima token.
28281 * @param {AcornToken[]} tokens The Acorn tokens representing the template.
28282 * @param {string} code The source code.
28283 * @returns {EsprimaToken} The Esprima equivalent of the template token.
28284 * @private
28285 */
28286
28287function convertTemplatePart(tokens, code) {
28288 const firstToken = tokens[0],
28289 lastTemplateToken = tokens[tokens.length - 1];
28290 const token = {
28291 type: Token.Template,
28292 value: code.slice(firstToken.start, lastTemplateToken.end)
28293 };
28294
28295 if (firstToken.loc) {
28296 token.loc = {
28297 start: firstToken.loc.start,
28298 end: lastTemplateToken.loc.end
28299 };
28300 }
28301
28302 if (firstToken.range) {
28303 token.start = firstToken.range[0];
28304 token.end = lastTemplateToken.range[1];
28305 token.range = [token.start, token.end];
28306 }
28307
28308 return token;
28309}
28310/**
28311 * Contains logic to translate Acorn tokens into Esprima tokens.
28312 * @param {Object} acornTokTypes The Acorn token types.
28313 * @param {string} code The source code Acorn is parsing. This is necessary
28314 * to correct the "value" property of some tokens.
28315 * @constructor
28316 */
28317
28318
28319function TokenTranslator(acornTokTypes, code) {
28320 // token types
28321 this._acornTokTypes = acornTokTypes; // token buffer for templates
28322
28323 this._tokens = []; // track the last curly brace
28324
28325 this._curlyBrace = null; // the source code
28326
28327 this._code = code;
28328}
28329
28330TokenTranslator.prototype = {
28331 constructor: TokenTranslator,
28332
28333 /**
28334 * Translates a single Esprima token to a single Acorn token. This may be
28335 * inaccurate due to how templates are handled differently in Esprima and
28336 * Acorn, but should be accurate for all other tokens.
28337 * @param {AcornToken} token The Acorn token to translate.
28338 * @param {Object} extra Espree extra object.
28339 * @returns {EsprimaToken} The Esprima version of the token.
28340 */
28341 translate(token, extra) {
28342 const type = token.type,
28343 tt = this._acornTokTypes;
28344
28345 if (type === tt.name) {
28346 token.type = Token.Identifier; // TODO: See if this is an Acorn bug
28347
28348 if (token.value === "static") {
28349 token.type = Token.Keyword;
28350 }
28351
28352 if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) {
28353 token.type = Token.Keyword;
28354 }
28355 } else if (type === tt.semi || type === tt.comma || type === tt.parenL || type === tt.parenR || type === tt.braceL || type === tt.braceR || type === tt.dot || type === tt.bracketL || type === tt.colon || type === tt.question || type === tt.bracketR || type === tt.ellipsis || type === tt.arrow || type === tt.jsxTagStart || type === tt.incDec || type === tt.starstar || type === tt.jsxTagEnd || type === tt.prefix || type.binop && !type.keyword || type.isAssign) {
28356 token.type = Token.Punctuator;
28357 token.value = this._code.slice(token.start, token.end);
28358 } else if (type === tt.jsxName) {
28359 token.type = Token.JSXIdentifier;
28360 } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) {
28361 token.type = Token.JSXText;
28362 } else if (type.keyword) {
28363 if (type.keyword === "true" || type.keyword === "false") {
28364 token.type = Token.Boolean;
28365 } else if (type.keyword === "null") {
28366 token.type = Token.Null;
28367 } else {
28368 token.type = Token.Keyword;
28369 }
28370 } else if (type === tt.num) {
28371 token.type = Token.Numeric;
28372 token.value = this._code.slice(token.start, token.end);
28373 } else if (type === tt.string) {
28374 if (extra.jsxAttrValueToken) {
28375 extra.jsxAttrValueToken = false;
28376 token.type = Token.JSXText;
28377 } else {
28378 token.type = Token.String;
28379 }
28380
28381 token.value = this._code.slice(token.start, token.end);
28382 } else if (type === tt.regexp) {
28383 token.type = Token.RegularExpression;
28384 const value = token.value;
28385 token.regex = {
28386 flags: value.flags,
28387 pattern: value.pattern
28388 };
28389 token.value = "/".concat(value.pattern, "/").concat(value.flags);
28390 }
28391
28392 return token;
28393 },
28394
28395 /**
28396 * Function to call during Acorn's onToken handler.
28397 * @param {AcornToken} token The Acorn token.
28398 * @param {Object} extra The Espree extra object.
28399 * @returns {void}
28400 */
28401 onToken(token, extra) {
28402 const that = this,
28403 tt = this._acornTokTypes,
28404 tokens = extra.tokens,
28405 templateTokens = this._tokens;
28406 /**
28407 * Flushes the buffered template tokens and resets the template
28408 * tracking.
28409 * @returns {void}
28410 * @private
28411 */
28412
28413 function translateTemplateTokens() {
28414 tokens.push(convertTemplatePart(that._tokens, that._code));
28415 that._tokens = [];
28416 }
28417
28418 if (token.type === tt.eof) {
28419 // might be one last curlyBrace
28420 if (this._curlyBrace) {
28421 tokens.push(this.translate(this._curlyBrace, extra));
28422 }
28423
28424 return;
28425 }
28426
28427 if (token.type === tt.backQuote) {
28428 // if there's already a curly, it's not part of the template
28429 if (this._curlyBrace) {
28430 tokens.push(this.translate(this._curlyBrace, extra));
28431 this._curlyBrace = null;
28432 }
28433
28434 templateTokens.push(token); // it's the end
28435
28436 if (templateTokens.length > 1) {
28437 translateTemplateTokens();
28438 }
28439
28440 return;
28441 }
28442
28443 if (token.type === tt.dollarBraceL) {
28444 templateTokens.push(token);
28445 translateTemplateTokens();
28446 return;
28447 }
28448
28449 if (token.type === tt.braceR) {
28450 // if there's already a curly, it's not part of the template
28451 if (this._curlyBrace) {
28452 tokens.push(this.translate(this._curlyBrace, extra));
28453 } // store new curly for later
28454
28455
28456 this._curlyBrace = token;
28457 return;
28458 }
28459
28460 if (token.type === tt.template || token.type === tt.invalidTemplate) {
28461 if (this._curlyBrace) {
28462 templateTokens.push(this._curlyBrace);
28463 this._curlyBrace = null;
28464 }
28465
28466 templateTokens.push(token);
28467 return;
28468 }
28469
28470 if (this._curlyBrace) {
28471 tokens.push(this.translate(this._curlyBrace, extra));
28472 this._curlyBrace = null;
28473 }
28474
28475 tokens.push(this.translate(token, extra));
28476 }
28477
28478}; //------------------------------------------------------------------------------
28479// Public
28480//------------------------------------------------------------------------------
28481
28482module.exports = TokenTranslator;
28483
28484/***/ }),
28485/* 401 */
28486/***/ (function(module, exports, __webpack_require__) {
28487
28488"use strict";
28489/**
28490 * @fileoverview A collection of methods for processing Espree's options.
28491 * @author Kai Cataldo
28492 */
28493 //------------------------------------------------------------------------------
28494// Helpers
28495//------------------------------------------------------------------------------
28496
28497const DEFAULT_ECMA_VERSION = 5;
28498const SUPPORTED_VERSIONS = [3, 5, 6, 7, 8, 9, 10, 11];
28499/**
28500 * Normalize ECMAScript version from the initial config
28501 * @param {number} ecmaVersion ECMAScript version from the initial config
28502 * @throws {Error} throws an error if the ecmaVersion is invalid.
28503 * @returns {number} normalized ECMAScript version
28504 */
28505
28506function normalizeEcmaVersion(ecmaVersion = DEFAULT_ECMA_VERSION) {
28507 if (typeof ecmaVersion !== "number") {
28508 throw new Error("ecmaVersion must be a number. Received value of type ".concat(typeof ecmaVersion, " instead."));
28509 }
28510
28511 let version = ecmaVersion; // Calculate ECMAScript edition number from official year version starting with
28512 // ES2015, which corresponds with ES6 (or a difference of 2009).
28513
28514 if (version >= 2015) {
28515 version -= 2009;
28516 }
28517
28518 if (!SUPPORTED_VERSIONS.includes(version)) {
28519 throw new Error("Invalid ecmaVersion.");
28520 }
28521
28522 return version;
28523}
28524/**
28525 * Normalize sourceType from the initial config
28526 * @param {string} sourceType to normalize
28527 * @throws {Error} throw an error if sourceType is invalid
28528 * @returns {string} normalized sourceType
28529 */
28530
28531
28532function normalizeSourceType(sourceType = "script") {
28533 if (sourceType === "script" || sourceType === "module") {
28534 return sourceType;
28535 }
28536
28537 throw new Error("Invalid sourceType.");
28538}
28539/**
28540 * Normalize parserOptions
28541 * @param {Object} options the parser options to normalize
28542 * @throws {Error} throw an error if found invalid option.
28543 * @returns {Object} normalized options
28544 */
28545
28546
28547function normalizeOptions(options) {
28548 const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion);
28549 const sourceType = normalizeSourceType(options.sourceType);
28550 const ranges = options.range === true;
28551 const locations = options.loc === true;
28552
28553 if (sourceType === "module" && ecmaVersion < 6) {
28554 throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options.");
28555 }
28556
28557 return Object.assign({}, options, {
28558 ecmaVersion,
28559 sourceType,
28560 ranges,
28561 locations
28562 });
28563}
28564/**
28565 * Get the latest ECMAScript version supported by Espree.
28566 * @returns {number} The latest ECMAScript version.
28567 */
28568
28569
28570function getLatestEcmaVersion() {
28571 return SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.length - 1];
28572}
28573/**
28574 * Get the list of ECMAScript versions supported by Espree.
28575 * @returns {number[]} An array containing the supported ECMAScript versions.
28576 */
28577
28578
28579function getSupportedEcmaVersions() {
28580 return [...SUPPORTED_VERSIONS];
28581} //------------------------------------------------------------------------------
28582// Public
28583//------------------------------------------------------------------------------
28584
28585
28586module.exports = {
28587 normalizeOptions,
28588 getLatestEcmaVersion,
28589 getSupportedEcmaVersions
28590};
28591
28592/***/ }),
28593/* 402 */
28594/***/ (function(module) {
28595
6a5a0f88 28596module.exports = JSON.parse("{\"_from\":\"espree@^7.0.0\",\"_id\":\"espree@7.0.0\",\"_inBundle\":false,\"_integrity\":\"sha512-/r2XEx5Mw4pgKdyb7GNLQNsu++asx/dltf/CI8RFi9oGHxmQFgvLbc5Op4U6i8Oaj+kdslhJtVlEZeAqH5qOTw==\",\"_location\":\"/espree\",\"_phantomChildren\":{},\"_requested\":{\"type\":\"range\",\"registry\":true,\"raw\":\"espree@^7.0.0\",\"name\":\"espree\",\"escapedName\":\"espree\",\"rawSpec\":\"^7.0.0\",\"saveSpec\":null,\"fetchSpec\":\"^7.0.0\"},\"_requiredBy\":[\"/\",\"/eslint\"],\"_resolved\":\"https://registry.npmjs.org/espree/-/espree-7.0.0.tgz\",\"_shasum\":\"8a7a60f218e69f120a842dc24c5a88aa7748a74e\",\"_spec\":\"espree@^7.0.0\",\"_where\":\"/root/sources/pve/pve-eslint/eslint-v7.1.0\",\"author\":{\"name\":\"Nicholas C. Zakas\",\"email\":\"nicholas+npm@nczconsulting.com\"},\"bugs\":{\"url\":\"http://github.com/eslint/espree.git\"},\"bundleDependencies\":false,\"dependencies\":{\"acorn\":\"^7.1.1\",\"acorn-jsx\":\"^5.2.0\",\"eslint-visitor-keys\":\"^1.1.0\"},\"deprecated\":false,\"description\":\"An Esprima-compatible JavaScript parser built on Acorn\",\"devDependencies\":{\"browserify\":\"^16.5.0\",\"chai\":\"^4.2.0\",\"eslint\":\"^6.0.1\",\"eslint-config-eslint\":\"^5.0.1\",\"eslint-plugin-node\":\"^9.1.0\",\"eslint-release\":\"^1.0.0\",\"esprima\":\"latest\",\"esprima-fb\":\"^8001.2001.0-dev-harmony-fb\",\"json-diff\":\"^0.5.4\",\"leche\":\"^2.3.0\",\"mocha\":\"^6.2.0\",\"nyc\":\"^14.1.1\",\"regenerate\":\"^1.4.0\",\"shelljs\":\"^0.3.0\",\"shelljs-nodecli\":\"^0.1.1\",\"unicode-6.3.0\":\"^0.7.5\"},\"engines\":{\"node\":\"^10.12.0 || >=12.0.0\"},\"files\":[\"lib\",\"espree.js\"],\"homepage\":\"https://github.com/eslint/espree\",\"keywords\":[\"ast\",\"ecmascript\",\"javascript\",\"parser\",\"syntax\",\"acorn\"],\"license\":\"BSD-2-Clause\",\"main\":\"espree.js\",\"name\":\"espree\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/eslint/espree.git\"},\"scripts\":{\"browserify\":\"node Makefile.js browserify\",\"generate-alpharelease\":\"eslint-generate-prerelease alpha\",\"generate-betarelease\":\"eslint-generate-prerelease beta\",\"generate-rcrelease\":\"eslint-generate-prerelease rc\",\"generate-regex\":\"node tools/generate-identifier-regex.js\",\"generate-release\":\"eslint-generate-release\",\"lint\":\"node Makefile.js lint\",\"publish-release\":\"eslint-publish-release\",\"sync-docs\":\"node Makefile.js docs\",\"test\":\"npm run-script lint && node Makefile.js test\"},\"version\":\"7.0.0\"}");
eb39fafa
DC
28597
28598/***/ }),
28599/* 403 */
28600/***/ (function(module, exports, __webpack_require__) {
28601
28602/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/**
28603 * @license
28604 * Lodash <https://lodash.com/>
28605 * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
28606 * Released under MIT license <https://lodash.com/license>
28607 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
28608 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
28609 */
28610;(function() {
28611
28612 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
28613 var undefined;
28614
28615 /** Used as the semantic version number. */
28616 var VERSION = '4.17.15';
28617
28618 /** Used as the size to enable large array optimizations. */
28619 var LARGE_ARRAY_SIZE = 200;
28620
28621 /** Error message constants. */
28622 var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
28623 FUNC_ERROR_TEXT = 'Expected a function';
28624
28625 /** Used to stand-in for `undefined` hash values. */
28626 var HASH_UNDEFINED = '__lodash_hash_undefined__';
28627
28628 /** Used as the maximum memoize cache size. */
28629 var MAX_MEMOIZE_SIZE = 500;
28630
28631 /** Used as the internal argument placeholder. */
28632 var PLACEHOLDER = '__lodash_placeholder__';
28633
28634 /** Used to compose bitmasks for cloning. */
28635 var CLONE_DEEP_FLAG = 1,
28636 CLONE_FLAT_FLAG = 2,
28637 CLONE_SYMBOLS_FLAG = 4;
28638
28639 /** Used to compose bitmasks for value comparisons. */
28640 var COMPARE_PARTIAL_FLAG = 1,
28641 COMPARE_UNORDERED_FLAG = 2;
28642
28643 /** Used to compose bitmasks for function metadata. */
28644 var WRAP_BIND_FLAG = 1,
28645 WRAP_BIND_KEY_FLAG = 2,
28646 WRAP_CURRY_BOUND_FLAG = 4,
28647 WRAP_CURRY_FLAG = 8,
28648 WRAP_CURRY_RIGHT_FLAG = 16,
28649 WRAP_PARTIAL_FLAG = 32,
28650 WRAP_PARTIAL_RIGHT_FLAG = 64,
28651 WRAP_ARY_FLAG = 128,
28652 WRAP_REARG_FLAG = 256,
28653 WRAP_FLIP_FLAG = 512;
28654
28655 /** Used as default options for `_.truncate`. */
28656 var DEFAULT_TRUNC_LENGTH = 30,
28657 DEFAULT_TRUNC_OMISSION = '...';
28658
28659 /** Used to detect hot functions by number of calls within a span of milliseconds. */
28660 var HOT_COUNT = 800,
28661 HOT_SPAN = 16;
28662
28663 /** Used to indicate the type of lazy iteratees. */
28664 var LAZY_FILTER_FLAG = 1,
28665 LAZY_MAP_FLAG = 2,
28666 LAZY_WHILE_FLAG = 3;
28667
28668 /** Used as references for various `Number` constants. */
28669 var INFINITY = 1 / 0,
28670 MAX_SAFE_INTEGER = 9007199254740991,
28671 MAX_INTEGER = 1.7976931348623157e+308,
28672 NAN = 0 / 0;
28673
28674 /** Used as references for the maximum length and index of an array. */
28675 var MAX_ARRAY_LENGTH = 4294967295,
28676 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
28677 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
28678
28679 /** Used to associate wrap methods with their bit flags. */
28680 var wrapFlags = [
28681 ['ary', WRAP_ARY_FLAG],
28682 ['bind', WRAP_BIND_FLAG],
28683 ['bindKey', WRAP_BIND_KEY_FLAG],
28684 ['curry', WRAP_CURRY_FLAG],
28685 ['curryRight', WRAP_CURRY_RIGHT_FLAG],
28686 ['flip', WRAP_FLIP_FLAG],
28687 ['partial', WRAP_PARTIAL_FLAG],
28688 ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
28689 ['rearg', WRAP_REARG_FLAG]
28690 ];
28691
28692 /** `Object#toString` result references. */
28693 var argsTag = '[object Arguments]',
28694 arrayTag = '[object Array]',
28695 asyncTag = '[object AsyncFunction]',
28696 boolTag = '[object Boolean]',
28697 dateTag = '[object Date]',
28698 domExcTag = '[object DOMException]',
28699 errorTag = '[object Error]',
28700 funcTag = '[object Function]',
28701 genTag = '[object GeneratorFunction]',
28702 mapTag = '[object Map]',
28703 numberTag = '[object Number]',
28704 nullTag = '[object Null]',
28705 objectTag = '[object Object]',
28706 promiseTag = '[object Promise]',
28707 proxyTag = '[object Proxy]',
28708 regexpTag = '[object RegExp]',
28709 setTag = '[object Set]',
28710 stringTag = '[object String]',
28711 symbolTag = '[object Symbol]',
28712 undefinedTag = '[object Undefined]',
28713 weakMapTag = '[object WeakMap]',
28714 weakSetTag = '[object WeakSet]';
28715
28716 var arrayBufferTag = '[object ArrayBuffer]',
28717 dataViewTag = '[object DataView]',
28718 float32Tag = '[object Float32Array]',
28719 float64Tag = '[object Float64Array]',
28720 int8Tag = '[object Int8Array]',
28721 int16Tag = '[object Int16Array]',
28722 int32Tag = '[object Int32Array]',
28723 uint8Tag = '[object Uint8Array]',
28724 uint8ClampedTag = '[object Uint8ClampedArray]',
28725 uint16Tag = '[object Uint16Array]',
28726 uint32Tag = '[object Uint32Array]';
28727
28728 /** Used to match empty string literals in compiled template source. */
28729 var reEmptyStringLeading = /\b__p \+= '';/g,
28730 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
28731 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
28732
28733 /** Used to match HTML entities and HTML characters. */
28734 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
28735 reUnescapedHtml = /[&<>"']/g,
28736 reHasEscapedHtml = RegExp(reEscapedHtml.source),
28737 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
28738
28739 /** Used to match template delimiters. */
28740 var reEscape = /<%-([\s\S]+?)%>/g,
28741 reEvaluate = /<%([\s\S]+?)%>/g,
28742 reInterpolate = /<%=([\s\S]+?)%>/g;
28743
28744 /** Used to match property names within property paths. */
28745 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
28746 reIsPlainProp = /^\w*$/,
28747 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
28748
28749 /**
28750 * Used to match `RegExp`
28751 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
28752 */
28753 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
28754 reHasRegExpChar = RegExp(reRegExpChar.source);
28755
28756 /** Used to match leading and trailing whitespace. */
28757 var reTrim = /^\s+|\s+$/g,
28758 reTrimStart = /^\s+/,
28759 reTrimEnd = /\s+$/;
28760
28761 /** Used to match wrap detail comments. */
28762 var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
28763 reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
28764 reSplitDetails = /,? & /;
28765
28766 /** Used to match words composed of alphanumeric characters. */
28767 var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
28768
28769 /** Used to match backslashes in property paths. */
28770 var reEscapeChar = /\\(\\)?/g;
28771
28772 /**
28773 * Used to match
28774 * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
28775 */
28776 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
28777
28778 /** Used to match `RegExp` flags from their coerced string values. */
28779 var reFlags = /\w*$/;
28780
28781 /** Used to detect bad signed hexadecimal string values. */
28782 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
28783
28784 /** Used to detect binary string values. */
28785 var reIsBinary = /^0b[01]+$/i;
28786
28787 /** Used to detect host constructors (Safari). */
28788 var reIsHostCtor = /^\[object .+?Constructor\]$/;
28789
28790 /** Used to detect octal string values. */
28791 var reIsOctal = /^0o[0-7]+$/i;
28792
28793 /** Used to detect unsigned integer values. */
28794 var reIsUint = /^(?:0|[1-9]\d*)$/;
28795
28796 /** Used to match Latin Unicode letters (excluding mathematical operators). */
28797 var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
28798
28799 /** Used to ensure capturing order of template delimiters. */
28800 var reNoMatch = /($^)/;
28801
28802 /** Used to match unescaped characters in compiled string literals. */
28803 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
28804
28805 /** Used to compose unicode character classes. */
28806 var rsAstralRange = '\\ud800-\\udfff',
28807 rsComboMarksRange = '\\u0300-\\u036f',
28808 reComboHalfMarksRange = '\\ufe20-\\ufe2f',
28809 rsComboSymbolsRange = '\\u20d0-\\u20ff',
28810 rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
28811 rsDingbatRange = '\\u2700-\\u27bf',
28812 rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
28813 rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
28814 rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
28815 rsPunctuationRange = '\\u2000-\\u206f',
28816 rsSpaceRange = ' \\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',
28817 rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
28818 rsVarRange = '\\ufe0e\\ufe0f',
28819 rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
28820
28821 /** Used to compose unicode capture groups. */
28822 var rsApos = "['\u2019]",
28823 rsAstral = '[' + rsAstralRange + ']',
28824 rsBreak = '[' + rsBreakRange + ']',
28825 rsCombo = '[' + rsComboRange + ']',
28826 rsDigits = '\\d+',
28827 rsDingbat = '[' + rsDingbatRange + ']',
28828 rsLower = '[' + rsLowerRange + ']',
28829 rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
28830 rsFitz = '\\ud83c[\\udffb-\\udfff]',
28831 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
28832 rsNonAstral = '[^' + rsAstralRange + ']',
28833 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
28834 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
28835 rsUpper = '[' + rsUpperRange + ']',
28836 rsZWJ = '\\u200d';
28837
28838 /** Used to compose unicode regexes. */
28839 var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
28840 rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
28841 rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
28842 rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
28843 reOptMod = rsModifier + '?',
28844 rsOptVar = '[' + rsVarRange + ']?',
28845 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
28846 rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
28847 rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
28848 rsSeq = rsOptVar + reOptMod + rsOptJoin,
28849 rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
28850 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
28851
28852 /** Used to match apostrophes. */
28853 var reApos = RegExp(rsApos, 'g');
28854
28855 /**
28856 * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
28857 * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
28858 */
28859 var reComboMark = RegExp(rsCombo, 'g');
28860
28861 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
28862 var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
28863
28864 /** Used to match complex or compound words. */
28865 var reUnicodeWord = RegExp([
28866 rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
28867 rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
28868 rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
28869 rsUpper + '+' + rsOptContrUpper,
28870 rsOrdUpper,
28871 rsOrdLower,
28872 rsDigits,
28873 rsEmoji
28874 ].join('|'), 'g');
28875
28876 /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
28877 var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
28878
28879 /** Used to detect strings that need a more robust regexp to match words. */
28880 var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
28881
28882 /** Used to assign default `context` object properties. */
28883 var contextProps = [
28884 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
28885 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
28886 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
28887 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
28888 '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
28889 ];
28890
28891 /** Used to make template sourceURLs easier to identify. */
28892 var templateCounter = -1;
28893
28894 /** Used to identify `toStringTag` values of typed arrays. */
28895 var typedArrayTags = {};
28896 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
28897 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
28898 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
28899 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
28900 typedArrayTags[uint32Tag] = true;
28901 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
28902 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
28903 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
28904 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
28905 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
28906 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
28907 typedArrayTags[setTag] = typedArrayTags[stringTag] =
28908 typedArrayTags[weakMapTag] = false;
28909
28910 /** Used to identify `toStringTag` values supported by `_.clone`. */
28911 var cloneableTags = {};
28912 cloneableTags[argsTag] = cloneableTags[arrayTag] =
28913 cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
28914 cloneableTags[boolTag] = cloneableTags[dateTag] =
28915 cloneableTags[float32Tag] = cloneableTags[float64Tag] =
28916 cloneableTags[int8Tag] = cloneableTags[int16Tag] =
28917 cloneableTags[int32Tag] = cloneableTags[mapTag] =
28918 cloneableTags[numberTag] = cloneableTags[objectTag] =
28919 cloneableTags[regexpTag] = cloneableTags[setTag] =
28920 cloneableTags[stringTag] = cloneableTags[symbolTag] =
28921 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
28922 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
28923 cloneableTags[errorTag] = cloneableTags[funcTag] =
28924 cloneableTags[weakMapTag] = false;
28925
28926 /** Used to map Latin Unicode letters to basic Latin letters. */
28927 var deburredLetters = {
28928 // Latin-1 Supplement block.
28929 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
28930 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
28931 '\xc7': 'C', '\xe7': 'c',
28932 '\xd0': 'D', '\xf0': 'd',
28933 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
28934 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
28935 '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
28936 '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
28937 '\xd1': 'N', '\xf1': 'n',
28938 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
28939 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
28940 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
28941 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
28942 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
28943 '\xc6': 'Ae', '\xe6': 'ae',
28944 '\xde': 'Th', '\xfe': 'th',
28945 '\xdf': 'ss',
28946 // Latin Extended-A block.
28947 '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
28948 '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
28949 '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
28950 '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
28951 '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
28952 '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
28953 '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
28954 '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
28955 '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
28956 '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
28957 '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
28958 '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
28959 '\u0134': 'J', '\u0135': 'j',
28960 '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
28961 '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
28962 '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
28963 '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
28964 '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
28965 '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
28966 '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
28967 '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
28968 '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
28969 '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
28970 '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
28971 '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
28972 '\u0163': 't', '\u0165': 't', '\u0167': 't',
28973 '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
28974 '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
28975 '\u0174': 'W', '\u0175': 'w',
28976 '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
28977 '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
28978 '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
28979 '\u0132': 'IJ', '\u0133': 'ij',
28980 '\u0152': 'Oe', '\u0153': 'oe',
28981 '\u0149': "'n", '\u017f': 's'
28982 };
28983
28984 /** Used to map characters to HTML entities. */
28985 var htmlEscapes = {
28986 '&': '&amp;',
28987 '<': '&lt;',
28988 '>': '&gt;',
28989 '"': '&quot;',
28990 "'": '&#39;'
28991 };
28992
28993 /** Used to map HTML entities to characters. */
28994 var htmlUnescapes = {
28995 '&amp;': '&',
28996 '&lt;': '<',
28997 '&gt;': '>',
28998 '&quot;': '"',
28999 '&#39;': "'"
29000 };
29001
29002 /** Used to escape characters for inclusion in compiled string literals. */
29003 var stringEscapes = {
29004 '\\': '\\',
29005 "'": "'",
29006 '\n': 'n',
29007 '\r': 'r',
29008 '\u2028': 'u2028',
29009 '\u2029': 'u2029'
29010 };
29011
29012 /** Built-in method references without a dependency on `root`. */
29013 var freeParseFloat = parseFloat,
29014 freeParseInt = parseInt;
29015
29016 /** Detect free variable `global` from Node.js. */
29017 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
29018
29019 /** Detect free variable `self`. */
29020 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
29021
29022 /** Used as a reference to the global object. */
29023 var root = freeGlobal || freeSelf || Function('return this')();
29024
29025 /** Detect free variable `exports`. */
29026 var freeExports = true && exports && !exports.nodeType && exports;
29027
29028 /** Detect free variable `module`. */
29029 var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
29030
29031 /** Detect the popular CommonJS extension `module.exports`. */
29032 var moduleExports = freeModule && freeModule.exports === freeExports;
29033
29034 /** Detect free variable `process` from Node.js. */
29035 var freeProcess = moduleExports && freeGlobal.process;
29036
29037 /** Used to access faster Node.js helpers. */
29038 var nodeUtil = (function() {
29039 try {
29040 // Use `util.types` for Node.js 10+.
29041 var types = freeModule && freeModule.require && freeModule.require('util').types;
29042
29043 if (types) {
29044 return types;
29045 }
29046
29047 // Legacy `process.binding('util')` for Node.js < 10.
29048 return freeProcess && freeProcess.binding && freeProcess.binding('util');
29049 } catch (e) {}
29050 }());
29051
29052 /* Node.js helper references. */
29053 var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
29054 nodeIsDate = nodeUtil && nodeUtil.isDate,
29055 nodeIsMap = nodeUtil && nodeUtil.isMap,
29056 nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
29057 nodeIsSet = nodeUtil && nodeUtil.isSet,
29058 nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
29059
29060 /*--------------------------------------------------------------------------*/
29061
29062 /**
29063 * A faster alternative to `Function#apply`, this function invokes `func`
29064 * with the `this` binding of `thisArg` and the arguments of `args`.
29065 *
29066 * @private
29067 * @param {Function} func The function to invoke.
29068 * @param {*} thisArg The `this` binding of `func`.
29069 * @param {Array} args The arguments to invoke `func` with.
29070 * @returns {*} Returns the result of `func`.
29071 */
29072 function apply(func, thisArg, args) {
29073 switch (args.length) {
29074 case 0: return func.call(thisArg);
29075 case 1: return func.call(thisArg, args[0]);
29076 case 2: return func.call(thisArg, args[0], args[1]);
29077 case 3: return func.call(thisArg, args[0], args[1], args[2]);
29078 }
29079 return func.apply(thisArg, args);
29080 }
29081
29082 /**
29083 * A specialized version of `baseAggregator` for arrays.
29084 *
29085 * @private
29086 * @param {Array} [array] The array to iterate over.
29087 * @param {Function} setter The function to set `accumulator` values.
29088 * @param {Function} iteratee The iteratee to transform keys.
29089 * @param {Object} accumulator The initial aggregated object.
29090 * @returns {Function} Returns `accumulator`.
29091 */
29092 function arrayAggregator(array, setter, iteratee, accumulator) {
29093 var index = -1,
29094 length = array == null ? 0 : array.length;
29095
29096 while (++index < length) {
29097 var value = array[index];
29098 setter(accumulator, value, iteratee(value), array);
29099 }
29100 return accumulator;
29101 }
29102
29103 /**
29104 * A specialized version of `_.forEach` for arrays without support for
29105 * iteratee shorthands.
29106 *
29107 * @private
29108 * @param {Array} [array] The array to iterate over.
29109 * @param {Function} iteratee The function invoked per iteration.
29110 * @returns {Array} Returns `array`.
29111 */
29112 function arrayEach(array, iteratee) {
29113 var index = -1,
29114 length = array == null ? 0 : array.length;
29115
29116 while (++index < length) {
29117 if (iteratee(array[index], index, array) === false) {
29118 break;
29119 }
29120 }
29121 return array;
29122 }
29123
29124 /**
29125 * A specialized version of `_.forEachRight` for arrays without support for
29126 * iteratee shorthands.
29127 *
29128 * @private
29129 * @param {Array} [array] The array to iterate over.
29130 * @param {Function} iteratee The function invoked per iteration.
29131 * @returns {Array} Returns `array`.
29132 */
29133 function arrayEachRight(array, iteratee) {
29134 var length = array == null ? 0 : array.length;
29135
29136 while (length--) {
29137 if (iteratee(array[length], length, array) === false) {
29138 break;
29139 }
29140 }
29141 return array;
29142 }
29143
29144 /**
29145 * A specialized version of `_.every` for arrays without support for
29146 * iteratee shorthands.
29147 *
29148 * @private
29149 * @param {Array} [array] The array to iterate over.
29150 * @param {Function} predicate The function invoked per iteration.
29151 * @returns {boolean} Returns `true` if all elements pass the predicate check,
29152 * else `false`.
29153 */
29154 function arrayEvery(array, predicate) {
29155 var index = -1,
29156 length = array == null ? 0 : array.length;
29157
29158 while (++index < length) {
29159 if (!predicate(array[index], index, array)) {
29160 return false;
29161 }
29162 }
29163 return true;
29164 }
29165
29166 /**
29167 * A specialized version of `_.filter` for arrays without support for
29168 * iteratee shorthands.
29169 *
29170 * @private
29171 * @param {Array} [array] The array to iterate over.
29172 * @param {Function} predicate The function invoked per iteration.
29173 * @returns {Array} Returns the new filtered array.
29174 */
29175 function arrayFilter(array, predicate) {
29176 var index = -1,
29177 length = array == null ? 0 : array.length,
29178 resIndex = 0,
29179 result = [];
29180
29181 while (++index < length) {
29182 var value = array[index];
29183 if (predicate(value, index, array)) {
29184 result[resIndex++] = value;
29185 }
29186 }
29187 return result;
29188 }
29189
29190 /**
29191 * A specialized version of `_.includes` for arrays without support for
29192 * specifying an index to search from.
29193 *
29194 * @private
29195 * @param {Array} [array] The array to inspect.
29196 * @param {*} target The value to search for.
29197 * @returns {boolean} Returns `true` if `target` is found, else `false`.
29198 */
29199 function arrayIncludes(array, value) {
29200 var length = array == null ? 0 : array.length;
29201 return !!length && baseIndexOf(array, value, 0) > -1;
29202 }
29203
29204 /**
29205 * This function is like `arrayIncludes` except that it accepts a comparator.
29206 *
29207 * @private
29208 * @param {Array} [array] The array to inspect.
29209 * @param {*} target The value to search for.
29210 * @param {Function} comparator The comparator invoked per element.
29211 * @returns {boolean} Returns `true` if `target` is found, else `false`.
29212 */
29213 function arrayIncludesWith(array, value, comparator) {
29214 var index = -1,
29215 length = array == null ? 0 : array.length;
29216
29217 while (++index < length) {
29218 if (comparator(value, array[index])) {
29219 return true;
29220 }
29221 }
29222 return false;
29223 }
29224
29225 /**
29226 * A specialized version of `_.map` for arrays without support for iteratee
29227 * shorthands.
29228 *
29229 * @private
29230 * @param {Array} [array] The array to iterate over.
29231 * @param {Function} iteratee The function invoked per iteration.
29232 * @returns {Array} Returns the new mapped array.
29233 */
29234 function arrayMap(array, iteratee) {
29235 var index = -1,
29236 length = array == null ? 0 : array.length,
29237 result = Array(length);
29238
29239 while (++index < length) {
29240 result[index] = iteratee(array[index], index, array);
29241 }
29242 return result;
29243 }
29244
29245 /**
29246 * Appends the elements of `values` to `array`.
29247 *
29248 * @private
29249 * @param {Array} array The array to modify.
29250 * @param {Array} values The values to append.
29251 * @returns {Array} Returns `array`.
29252 */
29253 function arrayPush(array, values) {
29254 var index = -1,
29255 length = values.length,
29256 offset = array.length;
29257
29258 while (++index < length) {
29259 array[offset + index] = values[index];
29260 }
29261 return array;
29262 }
29263
29264 /**
29265 * A specialized version of `_.reduce` for arrays without support for
29266 * iteratee shorthands.
29267 *
29268 * @private
29269 * @param {Array} [array] The array to iterate over.
29270 * @param {Function} iteratee The function invoked per iteration.
29271 * @param {*} [accumulator] The initial value.
29272 * @param {boolean} [initAccum] Specify using the first element of `array` as
29273 * the initial value.
29274 * @returns {*} Returns the accumulated value.
29275 */
29276 function arrayReduce(array, iteratee, accumulator, initAccum) {
29277 var index = -1,
29278 length = array == null ? 0 : array.length;
29279
29280 if (initAccum && length) {
29281 accumulator = array[++index];
29282 }
29283 while (++index < length) {
29284 accumulator = iteratee(accumulator, array[index], index, array);
29285 }
29286 return accumulator;
29287 }
29288
29289 /**
29290 * A specialized version of `_.reduceRight` for arrays without support for
29291 * iteratee shorthands.
29292 *
29293 * @private
29294 * @param {Array} [array] The array to iterate over.
29295 * @param {Function} iteratee The function invoked per iteration.
29296 * @param {*} [accumulator] The initial value.
29297 * @param {boolean} [initAccum] Specify using the last element of `array` as
29298 * the initial value.
29299 * @returns {*} Returns the accumulated value.
29300 */
29301 function arrayReduceRight(array, iteratee, accumulator, initAccum) {
29302 var length = array == null ? 0 : array.length;
29303 if (initAccum && length) {
29304 accumulator = array[--length];
29305 }
29306 while (length--) {
29307 accumulator = iteratee(accumulator, array[length], length, array);
29308 }
29309 return accumulator;
29310 }
29311
29312 /**
29313 * A specialized version of `_.some` for arrays without support for iteratee
29314 * shorthands.
29315 *
29316 * @private
29317 * @param {Array} [array] The array to iterate over.
29318 * @param {Function} predicate The function invoked per iteration.
29319 * @returns {boolean} Returns `true` if any element passes the predicate check,
29320 * else `false`.
29321 */
29322 function arraySome(array, predicate) {
29323 var index = -1,
29324 length = array == null ? 0 : array.length;
29325
29326 while (++index < length) {
29327 if (predicate(array[index], index, array)) {
29328 return true;
29329 }
29330 }
29331 return false;
29332 }
29333
29334 /**
29335 * Gets the size of an ASCII `string`.
29336 *
29337 * @private
29338 * @param {string} string The string inspect.
29339 * @returns {number} Returns the string size.
29340 */
29341 var asciiSize = baseProperty('length');
29342
29343 /**
29344 * Converts an ASCII `string` to an array.
29345 *
29346 * @private
29347 * @param {string} string The string to convert.
29348 * @returns {Array} Returns the converted array.
29349 */
29350 function asciiToArray(string) {
29351 return string.split('');
29352 }
29353
29354 /**
29355 * Splits an ASCII `string` into an array of its words.
29356 *
29357 * @private
29358 * @param {string} The string to inspect.
29359 * @returns {Array} Returns the words of `string`.
29360 */
29361 function asciiWords(string) {
29362 return string.match(reAsciiWord) || [];
29363 }
29364
29365 /**
29366 * The base implementation of methods like `_.findKey` and `_.findLastKey`,
29367 * without support for iteratee shorthands, which iterates over `collection`
29368 * using `eachFunc`.
29369 *
29370 * @private
29371 * @param {Array|Object} collection The collection to inspect.
29372 * @param {Function} predicate The function invoked per iteration.
29373 * @param {Function} eachFunc The function to iterate over `collection`.
29374 * @returns {*} Returns the found element or its key, else `undefined`.
29375 */
29376 function baseFindKey(collection, predicate, eachFunc) {
29377 var result;
29378 eachFunc(collection, function(value, key, collection) {
29379 if (predicate(value, key, collection)) {
29380 result = key;
29381 return false;
29382 }
29383 });
29384 return result;
29385 }
29386
29387 /**
29388 * The base implementation of `_.findIndex` and `_.findLastIndex` without
29389 * support for iteratee shorthands.
29390 *
29391 * @private
29392 * @param {Array} array The array to inspect.
29393 * @param {Function} predicate The function invoked per iteration.
29394 * @param {number} fromIndex The index to search from.
29395 * @param {boolean} [fromRight] Specify iterating from right to left.
29396 * @returns {number} Returns the index of the matched value, else `-1`.
29397 */
29398 function baseFindIndex(array, predicate, fromIndex, fromRight) {
29399 var length = array.length,
29400 index = fromIndex + (fromRight ? 1 : -1);
29401
29402 while ((fromRight ? index-- : ++index < length)) {
29403 if (predicate(array[index], index, array)) {
29404 return index;
29405 }
29406 }
29407 return -1;
29408 }
29409
29410 /**
29411 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
29412 *
29413 * @private
29414 * @param {Array} array The array to inspect.
29415 * @param {*} value The value to search for.
29416 * @param {number} fromIndex The index to search from.
29417 * @returns {number} Returns the index of the matched value, else `-1`.
29418 */
29419 function baseIndexOf(array, value, fromIndex) {
29420 return value === value
29421 ? strictIndexOf(array, value, fromIndex)
29422 : baseFindIndex(array, baseIsNaN, fromIndex);
29423 }
29424
29425 /**
29426 * This function is like `baseIndexOf` except that it accepts a comparator.
29427 *
29428 * @private
29429 * @param {Array} array The array to inspect.
29430 * @param {*} value The value to search for.
29431 * @param {number} fromIndex The index to search from.
29432 * @param {Function} comparator The comparator invoked per element.
29433 * @returns {number} Returns the index of the matched value, else `-1`.
29434 */
29435 function baseIndexOfWith(array, value, fromIndex, comparator) {
29436 var index = fromIndex - 1,
29437 length = array.length;
29438
29439 while (++index < length) {
29440 if (comparator(array[index], value)) {
29441 return index;
29442 }
29443 }
29444 return -1;
29445 }
29446
29447 /**
29448 * The base implementation of `_.isNaN` without support for number objects.
29449 *
29450 * @private
29451 * @param {*} value The value to check.
29452 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
29453 */
29454 function baseIsNaN(value) {
29455 return value !== value;
29456 }
29457
29458 /**
29459 * The base implementation of `_.mean` and `_.meanBy` without support for
29460 * iteratee shorthands.
29461 *
29462 * @private
29463 * @param {Array} array The array to iterate over.
29464 * @param {Function} iteratee The function invoked per iteration.
29465 * @returns {number} Returns the mean.
29466 */
29467 function baseMean(array, iteratee) {
29468 var length = array == null ? 0 : array.length;
29469 return length ? (baseSum(array, iteratee) / length) : NAN;
29470 }
29471
29472 /**
29473 * The base implementation of `_.property` without support for deep paths.
29474 *
29475 * @private
29476 * @param {string} key The key of the property to get.
29477 * @returns {Function} Returns the new accessor function.
29478 */
29479 function baseProperty(key) {
29480 return function(object) {
29481 return object == null ? undefined : object[key];
29482 };
29483 }
29484
29485 /**
29486 * The base implementation of `_.propertyOf` without support for deep paths.
29487 *
29488 * @private
29489 * @param {Object} object The object to query.
29490 * @returns {Function} Returns the new accessor function.
29491 */
29492 function basePropertyOf(object) {
29493 return function(key) {
29494 return object == null ? undefined : object[key];
29495 };
29496 }
29497
29498 /**
29499 * The base implementation of `_.reduce` and `_.reduceRight`, without support
29500 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
29501 *
29502 * @private
29503 * @param {Array|Object} collection The collection to iterate over.
29504 * @param {Function} iteratee The function invoked per iteration.
29505 * @param {*} accumulator The initial value.
29506 * @param {boolean} initAccum Specify using the first or last element of
29507 * `collection` as the initial value.
29508 * @param {Function} eachFunc The function to iterate over `collection`.
29509 * @returns {*} Returns the accumulated value.
29510 */
29511 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
29512 eachFunc(collection, function(value, index, collection) {
29513 accumulator = initAccum
29514 ? (initAccum = false, value)
29515 : iteratee(accumulator, value, index, collection);
29516 });
29517 return accumulator;
29518 }
29519
29520 /**
29521 * The base implementation of `_.sortBy` which uses `comparer` to define the
29522 * sort order of `array` and replaces criteria objects with their corresponding
29523 * values.
29524 *
29525 * @private
29526 * @param {Array} array The array to sort.
29527 * @param {Function} comparer The function to define sort order.
29528 * @returns {Array} Returns `array`.
29529 */
29530 function baseSortBy(array, comparer) {
29531 var length = array.length;
29532
29533 array.sort(comparer);
29534 while (length--) {
29535 array[length] = array[length].value;
29536 }
29537 return array;
29538 }
29539
29540 /**
29541 * The base implementation of `_.sum` and `_.sumBy` without support for
29542 * iteratee shorthands.
29543 *
29544 * @private
29545 * @param {Array} array The array to iterate over.
29546 * @param {Function} iteratee The function invoked per iteration.
29547 * @returns {number} Returns the sum.
29548 */
29549 function baseSum(array, iteratee) {
29550 var result,
29551 index = -1,
29552 length = array.length;
29553
29554 while (++index < length) {
29555 var current = iteratee(array[index]);
29556 if (current !== undefined) {
29557 result = result === undefined ? current : (result + current);
29558 }
29559 }
29560 return result;
29561 }
29562
29563 /**
29564 * The base implementation of `_.times` without support for iteratee shorthands
29565 * or max array length checks.
29566 *
29567 * @private
29568 * @param {number} n The number of times to invoke `iteratee`.
29569 * @param {Function} iteratee The function invoked per iteration.
29570 * @returns {Array} Returns the array of results.
29571 */
29572 function baseTimes(n, iteratee) {
29573 var index = -1,
29574 result = Array(n);
29575
29576 while (++index < n) {
29577 result[index] = iteratee(index);
29578 }
29579 return result;
29580 }
29581
29582 /**
29583 * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
29584 * of key-value pairs for `object` corresponding to the property names of `props`.
29585 *
29586 * @private
29587 * @param {Object} object The object to query.
29588 * @param {Array} props The property names to get values for.
29589 * @returns {Object} Returns the key-value pairs.
29590 */
29591 function baseToPairs(object, props) {
29592 return arrayMap(props, function(key) {
29593 return [key, object[key]];
29594 });
29595 }
29596
29597 /**
29598 * The base implementation of `_.unary` without support for storing metadata.
29599 *
29600 * @private
29601 * @param {Function} func The function to cap arguments for.
29602 * @returns {Function} Returns the new capped function.
29603 */
29604 function baseUnary(func) {
29605 return function(value) {
29606 return func(value);
29607 };
29608 }
29609
29610 /**
29611 * The base implementation of `_.values` and `_.valuesIn` which creates an
29612 * array of `object` property values corresponding to the property names
29613 * of `props`.
29614 *
29615 * @private
29616 * @param {Object} object The object to query.
29617 * @param {Array} props The property names to get values for.
29618 * @returns {Object} Returns the array of property values.
29619 */
29620 function baseValues(object, props) {
29621 return arrayMap(props, function(key) {
29622 return object[key];
29623 });
29624 }
29625
29626 /**
29627 * Checks if a `cache` value for `key` exists.
29628 *
29629 * @private
29630 * @param {Object} cache The cache to query.
29631 * @param {string} key The key of the entry to check.
29632 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
29633 */
29634 function cacheHas(cache, key) {
29635 return cache.has(key);
29636 }
29637
29638 /**
29639 * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
29640 * that is not found in the character symbols.
29641 *
29642 * @private
29643 * @param {Array} strSymbols The string symbols to inspect.
29644 * @param {Array} chrSymbols The character symbols to find.
29645 * @returns {number} Returns the index of the first unmatched string symbol.
29646 */
29647 function charsStartIndex(strSymbols, chrSymbols) {
29648 var index = -1,
29649 length = strSymbols.length;
29650
29651 while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
29652 return index;
29653 }
29654
29655 /**
29656 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
29657 * that is not found in the character symbols.
29658 *
29659 * @private
29660 * @param {Array} strSymbols The string symbols to inspect.
29661 * @param {Array} chrSymbols The character symbols to find.
29662 * @returns {number} Returns the index of the last unmatched string symbol.
29663 */
29664 function charsEndIndex(strSymbols, chrSymbols) {
29665 var index = strSymbols.length;
29666
29667 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
29668 return index;
29669 }
29670
29671 /**
29672 * Gets the number of `placeholder` occurrences in `array`.
29673 *
29674 * @private
29675 * @param {Array} array The array to inspect.
29676 * @param {*} placeholder The placeholder to search for.
29677 * @returns {number} Returns the placeholder count.
29678 */
29679 function countHolders(array, placeholder) {
29680 var length = array.length,
29681 result = 0;
29682
29683 while (length--) {
29684 if (array[length] === placeholder) {
29685 ++result;
29686 }
29687 }
29688 return result;
29689 }
29690
29691 /**
29692 * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
29693 * letters to basic Latin letters.
29694 *
29695 * @private
29696 * @param {string} letter The matched letter to deburr.
29697 * @returns {string} Returns the deburred letter.
29698 */
29699 var deburrLetter = basePropertyOf(deburredLetters);
29700
29701 /**
29702 * Used by `_.escape` to convert characters to HTML entities.
29703 *
29704 * @private
29705 * @param {string} chr The matched character to escape.
29706 * @returns {string} Returns the escaped character.
29707 */
29708 var escapeHtmlChar = basePropertyOf(htmlEscapes);
29709
29710 /**
29711 * Used by `_.template` to escape characters for inclusion in compiled string literals.
29712 *
29713 * @private
29714 * @param {string} chr The matched character to escape.
29715 * @returns {string} Returns the escaped character.
29716 */
29717 function escapeStringChar(chr) {
29718 return '\\' + stringEscapes[chr];
29719 }
29720
29721 /**
29722 * Gets the value at `key` of `object`.
29723 *
29724 * @private
29725 * @param {Object} [object] The object to query.
29726 * @param {string} key The key of the property to get.
29727 * @returns {*} Returns the property value.
29728 */
29729 function getValue(object, key) {
29730 return object == null ? undefined : object[key];
29731 }
29732
29733 /**
29734 * Checks if `string` contains Unicode symbols.
29735 *
29736 * @private
29737 * @param {string} string The string to inspect.
29738 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
29739 */
29740 function hasUnicode(string) {
29741 return reHasUnicode.test(string);
29742 }
29743
29744 /**
29745 * Checks if `string` contains a word composed of Unicode symbols.
29746 *
29747 * @private
29748 * @param {string} string The string to inspect.
29749 * @returns {boolean} Returns `true` if a word is found, else `false`.
29750 */
29751 function hasUnicodeWord(string) {
29752 return reHasUnicodeWord.test(string);
29753 }
29754
29755 /**
29756 * Converts `iterator` to an array.
29757 *
29758 * @private
29759 * @param {Object} iterator The iterator to convert.
29760 * @returns {Array} Returns the converted array.
29761 */
29762 function iteratorToArray(iterator) {
29763 var data,
29764 result = [];
29765
29766 while (!(data = iterator.next()).done) {
29767 result.push(data.value);
29768 }
29769 return result;
29770 }
29771
29772 /**
29773 * Converts `map` to its key-value pairs.
29774 *
29775 * @private
29776 * @param {Object} map The map to convert.
29777 * @returns {Array} Returns the key-value pairs.
29778 */
29779 function mapToArray(map) {
29780 var index = -1,
29781 result = Array(map.size);
29782
29783 map.forEach(function(value, key) {
29784 result[++index] = [key, value];
29785 });
29786 return result;
29787 }
29788
29789 /**
29790 * Creates a unary function that invokes `func` with its argument transformed.
29791 *
29792 * @private
29793 * @param {Function} func The function to wrap.
29794 * @param {Function} transform The argument transform.
29795 * @returns {Function} Returns the new function.
29796 */
29797 function overArg(func, transform) {
29798 return function(arg) {
29799 return func(transform(arg));
29800 };
29801 }
29802
29803 /**
29804 * Replaces all `placeholder` elements in `array` with an internal placeholder
29805 * and returns an array of their indexes.
29806 *
29807 * @private
29808 * @param {Array} array The array to modify.
29809 * @param {*} placeholder The placeholder to replace.
29810 * @returns {Array} Returns the new array of placeholder indexes.
29811 */
29812 function replaceHolders(array, placeholder) {
29813 var index = -1,
29814 length = array.length,
29815 resIndex = 0,
29816 result = [];
29817
29818 while (++index < length) {
29819 var value = array[index];
29820 if (value === placeholder || value === PLACEHOLDER) {
29821 array[index] = PLACEHOLDER;
29822 result[resIndex++] = index;
29823 }
29824 }
29825 return result;
29826 }
29827
29828 /**
29829 * Converts `set` to an array of its values.
29830 *
29831 * @private
29832 * @param {Object} set The set to convert.
29833 * @returns {Array} Returns the values.
29834 */
29835 function setToArray(set) {
29836 var index = -1,
29837 result = Array(set.size);
29838
29839 set.forEach(function(value) {
29840 result[++index] = value;
29841 });
29842 return result;
29843 }
29844
29845 /**
29846 * Converts `set` to its value-value pairs.
29847 *
29848 * @private
29849 * @param {Object} set The set to convert.
29850 * @returns {Array} Returns the value-value pairs.
29851 */
29852 function setToPairs(set) {
29853 var index = -1,
29854 result = Array(set.size);
29855
29856 set.forEach(function(value) {
29857 result[++index] = [value, value];
29858 });
29859 return result;
29860 }
29861
29862 /**
29863 * A specialized version of `_.indexOf` which performs strict equality
29864 * comparisons of values, i.e. `===`.
29865 *
29866 * @private
29867 * @param {Array} array The array to inspect.
29868 * @param {*} value The value to search for.
29869 * @param {number} fromIndex The index to search from.
29870 * @returns {number} Returns the index of the matched value, else `-1`.
29871 */
29872 function strictIndexOf(array, value, fromIndex) {
29873 var index = fromIndex - 1,
29874 length = array.length;
29875
29876 while (++index < length) {
29877 if (array[index] === value) {
29878 return index;
29879 }
29880 }
29881 return -1;
29882 }
29883
29884 /**
29885 * A specialized version of `_.lastIndexOf` which performs strict equality
29886 * comparisons of values, i.e. `===`.
29887 *
29888 * @private
29889 * @param {Array} array The array to inspect.
29890 * @param {*} value The value to search for.
29891 * @param {number} fromIndex The index to search from.
29892 * @returns {number} Returns the index of the matched value, else `-1`.
29893 */
29894 function strictLastIndexOf(array, value, fromIndex) {
29895 var index = fromIndex + 1;
29896 while (index--) {
29897 if (array[index] === value) {
29898 return index;
29899 }
29900 }
29901 return index;
29902 }
29903
29904 /**
29905 * Gets the number of symbols in `string`.
29906 *
29907 * @private
29908 * @param {string} string The string to inspect.
29909 * @returns {number} Returns the string size.
29910 */
29911 function stringSize(string) {
29912 return hasUnicode(string)
29913 ? unicodeSize(string)
29914 : asciiSize(string);
29915 }
29916
29917 /**
29918 * Converts `string` to an array.
29919 *
29920 * @private
29921 * @param {string} string The string to convert.
29922 * @returns {Array} Returns the converted array.
29923 */
29924 function stringToArray(string) {
29925 return hasUnicode(string)
29926 ? unicodeToArray(string)
29927 : asciiToArray(string);
29928 }
29929
29930 /**
29931 * Used by `_.unescape` to convert HTML entities to characters.
29932 *
29933 * @private
29934 * @param {string} chr The matched character to unescape.
29935 * @returns {string} Returns the unescaped character.
29936 */
29937 var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
29938
29939 /**
29940 * Gets the size of a Unicode `string`.
29941 *
29942 * @private
29943 * @param {string} string The string inspect.
29944 * @returns {number} Returns the string size.
29945 */
29946 function unicodeSize(string) {
29947 var result = reUnicode.lastIndex = 0;
29948 while (reUnicode.test(string)) {
29949 ++result;
29950 }
29951 return result;
29952 }
29953
29954 /**
29955 * Converts a Unicode `string` to an array.
29956 *
29957 * @private
29958 * @param {string} string The string to convert.
29959 * @returns {Array} Returns the converted array.
29960 */
29961 function unicodeToArray(string) {
29962 return string.match(reUnicode) || [];
29963 }
29964
29965 /**
29966 * Splits a Unicode `string` into an array of its words.
29967 *
29968 * @private
29969 * @param {string} The string to inspect.
29970 * @returns {Array} Returns the words of `string`.
29971 */
29972 function unicodeWords(string) {
29973 return string.match(reUnicodeWord) || [];
29974 }
29975
29976 /*--------------------------------------------------------------------------*/
29977
29978 /**
29979 * Create a new pristine `lodash` function using the `context` object.
29980 *
29981 * @static
29982 * @memberOf _
29983 * @since 1.1.0
29984 * @category Util
29985 * @param {Object} [context=root] The context object.
29986 * @returns {Function} Returns a new `lodash` function.
29987 * @example
29988 *
29989 * _.mixin({ 'foo': _.constant('foo') });
29990 *
29991 * var lodash = _.runInContext();
29992 * lodash.mixin({ 'bar': lodash.constant('bar') });
29993 *
29994 * _.isFunction(_.foo);
29995 * // => true
29996 * _.isFunction(_.bar);
29997 * // => false
29998 *
29999 * lodash.isFunction(lodash.foo);
30000 * // => false
30001 * lodash.isFunction(lodash.bar);
30002 * // => true
30003 *
30004 * // Create a suped-up `defer` in Node.js.
30005 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
30006 */
30007 var runInContext = (function runInContext(context) {
30008 context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
30009
30010 /** Built-in constructor references. */
30011 var Array = context.Array,
30012 Date = context.Date,
30013 Error = context.Error,
30014 Function = context.Function,
30015 Math = context.Math,
30016 Object = context.Object,
30017 RegExp = context.RegExp,
30018 String = context.String,
30019 TypeError = context.TypeError;
30020
30021 /** Used for built-in method references. */
30022 var arrayProto = Array.prototype,
30023 funcProto = Function.prototype,
30024 objectProto = Object.prototype;
30025
30026 /** Used to detect overreaching core-js shims. */
30027 var coreJsData = context['__core-js_shared__'];
30028
30029 /** Used to resolve the decompiled source of functions. */
30030 var funcToString = funcProto.toString;
30031
30032 /** Used to check objects for own properties. */
30033 var hasOwnProperty = objectProto.hasOwnProperty;
30034
30035 /** Used to generate unique IDs. */
30036 var idCounter = 0;
30037
30038 /** Used to detect methods masquerading as native. */
30039 var maskSrcKey = (function() {
30040 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
30041 return uid ? ('Symbol(src)_1.' + uid) : '';
30042 }());
30043
30044 /**
30045 * Used to resolve the
30046 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
30047 * of values.
30048 */
30049 var nativeObjectToString = objectProto.toString;
30050
30051 /** Used to infer the `Object` constructor. */
30052 var objectCtorString = funcToString.call(Object);
30053
30054 /** Used to restore the original `_` reference in `_.noConflict`. */
30055 var oldDash = root._;
30056
30057 /** Used to detect if a method is native. */
30058 var reIsNative = RegExp('^' +
30059 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
30060 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
30061 );
30062
30063 /** Built-in value references. */
30064 var Buffer = moduleExports ? context.Buffer : undefined,
30065 Symbol = context.Symbol,
30066 Uint8Array = context.Uint8Array,
30067 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
30068 getPrototype = overArg(Object.getPrototypeOf, Object),
30069 objectCreate = Object.create,
30070 propertyIsEnumerable = objectProto.propertyIsEnumerable,
30071 splice = arrayProto.splice,
30072 spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
30073 symIterator = Symbol ? Symbol.iterator : undefined,
30074 symToStringTag = Symbol ? Symbol.toStringTag : undefined;
30075
30076 var defineProperty = (function() {
30077 try {
30078 var func = getNative(Object, 'defineProperty');
30079 func({}, '', {});
30080 return func;
30081 } catch (e) {}
30082 }());
30083
30084 /** Mocked built-ins. */
30085 var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
30086 ctxNow = Date && Date.now !== root.Date.now && Date.now,
30087 ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
30088
30089 /* Built-in method references for those with the same name as other `lodash` methods. */
30090 var nativeCeil = Math.ceil,
30091 nativeFloor = Math.floor,
30092 nativeGetSymbols = Object.getOwnPropertySymbols,
30093 nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
30094 nativeIsFinite = context.isFinite,
30095 nativeJoin = arrayProto.join,
30096 nativeKeys = overArg(Object.keys, Object),
30097 nativeMax = Math.max,
30098 nativeMin = Math.min,
30099 nativeNow = Date.now,
30100 nativeParseInt = context.parseInt,
30101 nativeRandom = Math.random,
30102 nativeReverse = arrayProto.reverse;
30103
30104 /* Built-in method references that are verified to be native. */
30105 var DataView = getNative(context, 'DataView'),
30106 Map = getNative(context, 'Map'),
30107 Promise = getNative(context, 'Promise'),
30108 Set = getNative(context, 'Set'),
30109 WeakMap = getNative(context, 'WeakMap'),
30110 nativeCreate = getNative(Object, 'create');
30111
30112 /** Used to store function metadata. */
30113 var metaMap = WeakMap && new WeakMap;
30114
30115 /** Used to lookup unminified function names. */
30116 var realNames = {};
30117
30118 /** Used to detect maps, sets, and weakmaps. */
30119 var dataViewCtorString = toSource(DataView),
30120 mapCtorString = toSource(Map),
30121 promiseCtorString = toSource(Promise),
30122 setCtorString = toSource(Set),
30123 weakMapCtorString = toSource(WeakMap);
30124
30125 /** Used to convert symbols to primitives and strings. */
30126 var symbolProto = Symbol ? Symbol.prototype : undefined,
30127 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
30128 symbolToString = symbolProto ? symbolProto.toString : undefined;
30129
30130 /*------------------------------------------------------------------------*/
30131
30132 /**
30133 * Creates a `lodash` object which wraps `value` to enable implicit method
30134 * chain sequences. Methods that operate on and return arrays, collections,
30135 * and functions can be chained together. Methods that retrieve a single value
30136 * or may return a primitive value will automatically end the chain sequence
30137 * and return the unwrapped value. Otherwise, the value must be unwrapped
30138 * with `_#value`.
30139 *
30140 * Explicit chain sequences, which must be unwrapped with `_#value`, may be
30141 * enabled using `_.chain`.
30142 *
30143 * The execution of chained methods is lazy, that is, it's deferred until
30144 * `_#value` is implicitly or explicitly called.
30145 *
30146 * Lazy evaluation allows several methods to support shortcut fusion.
30147 * Shortcut fusion is an optimization to merge iteratee calls; this avoids
30148 * the creation of intermediate arrays and can greatly reduce the number of
30149 * iteratee executions. Sections of a chain sequence qualify for shortcut
30150 * fusion if the section is applied to an array and iteratees accept only
30151 * one argument. The heuristic for whether a section qualifies for shortcut
30152 * fusion is subject to change.
30153 *
30154 * Chaining is supported in custom builds as long as the `_#value` method is
30155 * directly or indirectly included in the build.
30156 *
30157 * In addition to lodash methods, wrappers have `Array` and `String` methods.
30158 *
30159 * The wrapper `Array` methods are:
30160 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
30161 *
30162 * The wrapper `String` methods are:
30163 * `replace` and `split`
30164 *
30165 * The wrapper methods that support shortcut fusion are:
30166 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
30167 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
30168 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
30169 *
30170 * The chainable wrapper methods are:
30171 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
30172 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
30173 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
30174 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
30175 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
30176 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
30177 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
30178 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
30179 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
30180 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
30181 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
30182 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
30183 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
30184 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
30185 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
30186 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
30187 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
30188 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
30189 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
30190 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
30191 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
30192 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
30193 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
30194 * `zipObject`, `zipObjectDeep`, and `zipWith`
30195 *
30196 * The wrapper methods that are **not** chainable by default are:
30197 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
30198 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
30199 * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
30200 * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
30201 * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
30202 * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
30203 * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
30204 * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
30205 * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
30206 * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
30207 * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
30208 * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
30209 * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
30210 * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
30211 * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
30212 * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
30213 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
30214 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
30215 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
30216 * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
30217 * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
30218 * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
30219 * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
30220 * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
30221 * `upperFirst`, `value`, and `words`
30222 *
30223 * @name _
30224 * @constructor
30225 * @category Seq
30226 * @param {*} value The value to wrap in a `lodash` instance.
30227 * @returns {Object} Returns the new `lodash` wrapper instance.
30228 * @example
30229 *
30230 * function square(n) {
30231 * return n * n;
30232 * }
30233 *
30234 * var wrapped = _([1, 2, 3]);
30235 *
30236 * // Returns an unwrapped value.
30237 * wrapped.reduce(_.add);
30238 * // => 6
30239 *
30240 * // Returns a wrapped value.
30241 * var squares = wrapped.map(square);
30242 *
30243 * _.isArray(squares);
30244 * // => false
30245 *
30246 * _.isArray(squares.value());
30247 * // => true
30248 */
30249 function lodash(value) {
30250 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
30251 if (value instanceof LodashWrapper) {
30252 return value;
30253 }
30254 if (hasOwnProperty.call(value, '__wrapped__')) {
30255 return wrapperClone(value);
30256 }
30257 }
30258 return new LodashWrapper(value);
30259 }
30260
30261 /**
30262 * The base implementation of `_.create` without support for assigning
30263 * properties to the created object.
30264 *
30265 * @private
30266 * @param {Object} proto The object to inherit from.
30267 * @returns {Object} Returns the new object.
30268 */
30269 var baseCreate = (function() {
30270 function object() {}
30271 return function(proto) {
30272 if (!isObject(proto)) {
30273 return {};
30274 }
30275 if (objectCreate) {
30276 return objectCreate(proto);
30277 }
30278 object.prototype = proto;
30279 var result = new object;
30280 object.prototype = undefined;
30281 return result;
30282 };
30283 }());
30284
30285 /**
30286 * The function whose prototype chain sequence wrappers inherit from.
30287 *
30288 * @private
30289 */
30290 function baseLodash() {
30291 // No operation performed.
30292 }
30293
30294 /**
30295 * The base constructor for creating `lodash` wrapper objects.
30296 *
30297 * @private
30298 * @param {*} value The value to wrap.
30299 * @param {boolean} [chainAll] Enable explicit method chain sequences.
30300 */
30301 function LodashWrapper(value, chainAll) {
30302 this.__wrapped__ = value;
30303 this.__actions__ = [];
30304 this.__chain__ = !!chainAll;
30305 this.__index__ = 0;
30306 this.__values__ = undefined;
30307 }
30308
30309 /**
30310 * By default, the template delimiters used by lodash are like those in
30311 * embedded Ruby (ERB) as well as ES2015 template strings. Change the
30312 * following template settings to use alternative delimiters.
30313 *
30314 * @static
30315 * @memberOf _
30316 * @type {Object}
30317 */
30318 lodash.templateSettings = {
30319
30320 /**
30321 * Used to detect `data` property values to be HTML-escaped.
30322 *
30323 * @memberOf _.templateSettings
30324 * @type {RegExp}
30325 */
30326 'escape': reEscape,
30327
30328 /**
30329 * Used to detect code to be evaluated.
30330 *
30331 * @memberOf _.templateSettings
30332 * @type {RegExp}
30333 */
30334 'evaluate': reEvaluate,
30335
30336 /**
30337 * Used to detect `data` property values to inject.
30338 *
30339 * @memberOf _.templateSettings
30340 * @type {RegExp}
30341 */
30342 'interpolate': reInterpolate,
30343
30344 /**
30345 * Used to reference the data object in the template text.
30346 *
30347 * @memberOf _.templateSettings
30348 * @type {string}
30349 */
30350 'variable': '',
30351
30352 /**
30353 * Used to import variables into the compiled template.
30354 *
30355 * @memberOf _.templateSettings
30356 * @type {Object}
30357 */
30358 'imports': {
30359
30360 /**
30361 * A reference to the `lodash` function.
30362 *
30363 * @memberOf _.templateSettings.imports
30364 * @type {Function}
30365 */
30366 '_': lodash
30367 }
30368 };
30369
30370 // Ensure wrappers are instances of `baseLodash`.
30371 lodash.prototype = baseLodash.prototype;
30372 lodash.prototype.constructor = lodash;
30373
30374 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
30375 LodashWrapper.prototype.constructor = LodashWrapper;
30376
30377 /*------------------------------------------------------------------------*/
30378
30379 /**
30380 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
30381 *
30382 * @private
30383 * @constructor
30384 * @param {*} value The value to wrap.
30385 */
30386 function LazyWrapper(value) {
30387 this.__wrapped__ = value;
30388 this.__actions__ = [];
30389 this.__dir__ = 1;
30390 this.__filtered__ = false;
30391 this.__iteratees__ = [];
30392 this.__takeCount__ = MAX_ARRAY_LENGTH;
30393 this.__views__ = [];
30394 }
30395
30396 /**
30397 * Creates a clone of the lazy wrapper object.
30398 *
30399 * @private
30400 * @name clone
30401 * @memberOf LazyWrapper
30402 * @returns {Object} Returns the cloned `LazyWrapper` object.
30403 */
30404 function lazyClone() {
30405 var result = new LazyWrapper(this.__wrapped__);
30406 result.__actions__ = copyArray(this.__actions__);
30407 result.__dir__ = this.__dir__;
30408 result.__filtered__ = this.__filtered__;
30409 result.__iteratees__ = copyArray(this.__iteratees__);
30410 result.__takeCount__ = this.__takeCount__;
30411 result.__views__ = copyArray(this.__views__);
30412 return result;
30413 }
30414
30415 /**
30416 * Reverses the direction of lazy iteration.
30417 *
30418 * @private
30419 * @name reverse
30420 * @memberOf LazyWrapper
30421 * @returns {Object} Returns the new reversed `LazyWrapper` object.
30422 */
30423 function lazyReverse() {
30424 if (this.__filtered__) {
30425 var result = new LazyWrapper(this);
30426 result.__dir__ = -1;
30427 result.__filtered__ = true;
30428 } else {
30429 result = this.clone();
30430 result.__dir__ *= -1;
30431 }
30432 return result;
30433 }
30434
30435 /**
30436 * Extracts the unwrapped value from its lazy wrapper.
30437 *
30438 * @private
30439 * @name value
30440 * @memberOf LazyWrapper
30441 * @returns {*} Returns the unwrapped value.
30442 */
30443 function lazyValue() {
30444 var array = this.__wrapped__.value(),
30445 dir = this.__dir__,
30446 isArr = isArray(array),
30447 isRight = dir < 0,
30448 arrLength = isArr ? array.length : 0,
30449 view = getView(0, arrLength, this.__views__),
30450 start = view.start,
30451 end = view.end,
30452 length = end - start,
30453 index = isRight ? end : (start - 1),
30454 iteratees = this.__iteratees__,
30455 iterLength = iteratees.length,
30456 resIndex = 0,
30457 takeCount = nativeMin(length, this.__takeCount__);
30458
30459 if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
30460 return baseWrapperValue(array, this.__actions__);
30461 }
30462 var result = [];
30463
30464 outer:
30465 while (length-- && resIndex < takeCount) {
30466 index += dir;
30467
30468 var iterIndex = -1,
30469 value = array[index];
30470
30471 while (++iterIndex < iterLength) {
30472 var data = iteratees[iterIndex],
30473 iteratee = data.iteratee,
30474 type = data.type,
30475 computed = iteratee(value);
30476
30477 if (type == LAZY_MAP_FLAG) {
30478 value = computed;
30479 } else if (!computed) {
30480 if (type == LAZY_FILTER_FLAG) {
30481 continue outer;
30482 } else {
30483 break outer;
30484 }
30485 }
30486 }
30487 result[resIndex++] = value;
30488 }
30489 return result;
30490 }
30491
30492 // Ensure `LazyWrapper` is an instance of `baseLodash`.
30493 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
30494 LazyWrapper.prototype.constructor = LazyWrapper;
30495
30496 /*------------------------------------------------------------------------*/
30497
30498 /**
30499 * Creates a hash object.
30500 *
30501 * @private
30502 * @constructor
30503 * @param {Array} [entries] The key-value pairs to cache.
30504 */
30505 function Hash(entries) {
30506 var index = -1,
30507 length = entries == null ? 0 : entries.length;
30508
30509 this.clear();
30510 while (++index < length) {
30511 var entry = entries[index];
30512 this.set(entry[0], entry[1]);
30513 }
30514 }
30515
30516 /**
30517 * Removes all key-value entries from the hash.
30518 *
30519 * @private
30520 * @name clear
30521 * @memberOf Hash
30522 */
30523 function hashClear() {
30524 this.__data__ = nativeCreate ? nativeCreate(null) : {};
30525 this.size = 0;
30526 }
30527
30528 /**
30529 * Removes `key` and its value from the hash.
30530 *
30531 * @private
30532 * @name delete
30533 * @memberOf Hash
30534 * @param {Object} hash The hash to modify.
30535 * @param {string} key The key of the value to remove.
30536 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
30537 */
30538 function hashDelete(key) {
30539 var result = this.has(key) && delete this.__data__[key];
30540 this.size -= result ? 1 : 0;
30541 return result;
30542 }
30543
30544 /**
30545 * Gets the hash value for `key`.
30546 *
30547 * @private
30548 * @name get
30549 * @memberOf Hash
30550 * @param {string} key The key of the value to get.
30551 * @returns {*} Returns the entry value.
30552 */
30553 function hashGet(key) {
30554 var data = this.__data__;
30555 if (nativeCreate) {
30556 var result = data[key];
30557 return result === HASH_UNDEFINED ? undefined : result;
30558 }
30559 return hasOwnProperty.call(data, key) ? data[key] : undefined;
30560 }
30561
30562 /**
30563 * Checks if a hash value for `key` exists.
30564 *
30565 * @private
30566 * @name has
30567 * @memberOf Hash
30568 * @param {string} key The key of the entry to check.
30569 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
30570 */
30571 function hashHas(key) {
30572 var data = this.__data__;
30573 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
30574 }
30575
30576 /**
30577 * Sets the hash `key` to `value`.
30578 *
30579 * @private
30580 * @name set
30581 * @memberOf Hash
30582 * @param {string} key The key of the value to set.
30583 * @param {*} value The value to set.
30584 * @returns {Object} Returns the hash instance.
30585 */
30586 function hashSet(key, value) {
30587 var data = this.__data__;
30588 this.size += this.has(key) ? 0 : 1;
30589 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
30590 return this;
30591 }
30592
30593 // Add methods to `Hash`.
30594 Hash.prototype.clear = hashClear;
30595 Hash.prototype['delete'] = hashDelete;
30596 Hash.prototype.get = hashGet;
30597 Hash.prototype.has = hashHas;
30598 Hash.prototype.set = hashSet;
30599
30600 /*------------------------------------------------------------------------*/
30601
30602 /**
30603 * Creates an list cache object.
30604 *
30605 * @private
30606 * @constructor
30607 * @param {Array} [entries] The key-value pairs to cache.
30608 */
30609 function ListCache(entries) {
30610 var index = -1,
30611 length = entries == null ? 0 : entries.length;
30612
30613 this.clear();
30614 while (++index < length) {
30615 var entry = entries[index];
30616 this.set(entry[0], entry[1]);
30617 }
30618 }
30619
30620 /**
30621 * Removes all key-value entries from the list cache.
30622 *
30623 * @private
30624 * @name clear
30625 * @memberOf ListCache
30626 */
30627 function listCacheClear() {
30628 this.__data__ = [];
30629 this.size = 0;
30630 }
30631
30632 /**
30633 * Removes `key` and its value from the list cache.
30634 *
30635 * @private
30636 * @name delete
30637 * @memberOf ListCache
30638 * @param {string} key The key of the value to remove.
30639 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
30640 */
30641 function listCacheDelete(key) {
30642 var data = this.__data__,
30643 index = assocIndexOf(data, key);
30644
30645 if (index < 0) {
30646 return false;
30647 }
30648 var lastIndex = data.length - 1;
30649 if (index == lastIndex) {
30650 data.pop();
30651 } else {
30652 splice.call(data, index, 1);
30653 }
30654 --this.size;
30655 return true;
30656 }
30657
30658 /**
30659 * Gets the list cache value for `key`.
30660 *
30661 * @private
30662 * @name get
30663 * @memberOf ListCache
30664 * @param {string} key The key of the value to get.
30665 * @returns {*} Returns the entry value.
30666 */
30667 function listCacheGet(key) {
30668 var data = this.__data__,
30669 index = assocIndexOf(data, key);
30670
30671 return index < 0 ? undefined : data[index][1];
30672 }
30673
30674 /**
30675 * Checks if a list cache value for `key` exists.
30676 *
30677 * @private
30678 * @name has
30679 * @memberOf ListCache
30680 * @param {string} key The key of the entry to check.
30681 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
30682 */
30683 function listCacheHas(key) {
30684 return assocIndexOf(this.__data__, key) > -1;
30685 }
30686
30687 /**
30688 * Sets the list cache `key` to `value`.
30689 *
30690 * @private
30691 * @name set
30692 * @memberOf ListCache
30693 * @param {string} key The key of the value to set.
30694 * @param {*} value The value to set.
30695 * @returns {Object} Returns the list cache instance.
30696 */
30697 function listCacheSet(key, value) {
30698 var data = this.__data__,
30699 index = assocIndexOf(data, key);
30700
30701 if (index < 0) {
30702 ++this.size;
30703 data.push([key, value]);
30704 } else {
30705 data[index][1] = value;
30706 }
30707 return this;
30708 }
30709
30710 // Add methods to `ListCache`.
30711 ListCache.prototype.clear = listCacheClear;
30712 ListCache.prototype['delete'] = listCacheDelete;
30713 ListCache.prototype.get = listCacheGet;
30714 ListCache.prototype.has = listCacheHas;
30715 ListCache.prototype.set = listCacheSet;
30716
30717 /*------------------------------------------------------------------------*/
30718
30719 /**
30720 * Creates a map cache object to store key-value pairs.
30721 *
30722 * @private
30723 * @constructor
30724 * @param {Array} [entries] The key-value pairs to cache.
30725 */
30726 function MapCache(entries) {
30727 var index = -1,
30728 length = entries == null ? 0 : entries.length;
30729
30730 this.clear();
30731 while (++index < length) {
30732 var entry = entries[index];
30733 this.set(entry[0], entry[1]);
30734 }
30735 }
30736
30737 /**
30738 * Removes all key-value entries from the map.
30739 *
30740 * @private
30741 * @name clear
30742 * @memberOf MapCache
30743 */
30744 function mapCacheClear() {
30745 this.size = 0;
30746 this.__data__ = {
30747 'hash': new Hash,
30748 'map': new (Map || ListCache),
30749 'string': new Hash
30750 };
30751 }
30752
30753 /**
30754 * Removes `key` and its value from the map.
30755 *
30756 * @private
30757 * @name delete
30758 * @memberOf MapCache
30759 * @param {string} key The key of the value to remove.
30760 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
30761 */
30762 function mapCacheDelete(key) {
30763 var result = getMapData(this, key)['delete'](key);
30764 this.size -= result ? 1 : 0;
30765 return result;
30766 }
30767
30768 /**
30769 * Gets the map value for `key`.
30770 *
30771 * @private
30772 * @name get
30773 * @memberOf MapCache
30774 * @param {string} key The key of the value to get.
30775 * @returns {*} Returns the entry value.
30776 */
30777 function mapCacheGet(key) {
30778 return getMapData(this, key).get(key);
30779 }
30780
30781 /**
30782 * Checks if a map value for `key` exists.
30783 *
30784 * @private
30785 * @name has
30786 * @memberOf MapCache
30787 * @param {string} key The key of the entry to check.
30788 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
30789 */
30790 function mapCacheHas(key) {
30791 return getMapData(this, key).has(key);
30792 }
30793
30794 /**
30795 * Sets the map `key` to `value`.
30796 *
30797 * @private
30798 * @name set
30799 * @memberOf MapCache
30800 * @param {string} key The key of the value to set.
30801 * @param {*} value The value to set.
30802 * @returns {Object} Returns the map cache instance.
30803 */
30804 function mapCacheSet(key, value) {
30805 var data = getMapData(this, key),
30806 size = data.size;
30807
30808 data.set(key, value);
30809 this.size += data.size == size ? 0 : 1;
30810 return this;
30811 }
30812
30813 // Add methods to `MapCache`.
30814 MapCache.prototype.clear = mapCacheClear;
30815 MapCache.prototype['delete'] = mapCacheDelete;
30816 MapCache.prototype.get = mapCacheGet;
30817 MapCache.prototype.has = mapCacheHas;
30818 MapCache.prototype.set = mapCacheSet;
30819
30820 /*------------------------------------------------------------------------*/
30821
30822 /**
30823 *
30824 * Creates an array cache object to store unique values.
30825 *
30826 * @private
30827 * @constructor
30828 * @param {Array} [values] The values to cache.
30829 */
30830 function SetCache(values) {
30831 var index = -1,
30832 length = values == null ? 0 : values.length;
30833
30834 this.__data__ = new MapCache;
30835 while (++index < length) {
30836 this.add(values[index]);
30837 }
30838 }
30839
30840 /**
30841 * Adds `value` to the array cache.
30842 *
30843 * @private
30844 * @name add
30845 * @memberOf SetCache
30846 * @alias push
30847 * @param {*} value The value to cache.
30848 * @returns {Object} Returns the cache instance.
30849 */
30850 function setCacheAdd(value) {
30851 this.__data__.set(value, HASH_UNDEFINED);
30852 return this;
30853 }
30854
30855 /**
30856 * Checks if `value` is in the array cache.
30857 *
30858 * @private
30859 * @name has
30860 * @memberOf SetCache
30861 * @param {*} value The value to search for.
30862 * @returns {number} Returns `true` if `value` is found, else `false`.
30863 */
30864 function setCacheHas(value) {
30865 return this.__data__.has(value);
30866 }
30867
30868 // Add methods to `SetCache`.
30869 SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
30870 SetCache.prototype.has = setCacheHas;
30871
30872 /*------------------------------------------------------------------------*/
30873
30874 /**
30875 * Creates a stack cache object to store key-value pairs.
30876 *
30877 * @private
30878 * @constructor
30879 * @param {Array} [entries] The key-value pairs to cache.
30880 */
30881 function Stack(entries) {
30882 var data = this.__data__ = new ListCache(entries);
30883 this.size = data.size;
30884 }
30885
30886 /**
30887 * Removes all key-value entries from the stack.
30888 *
30889 * @private
30890 * @name clear
30891 * @memberOf Stack
30892 */
30893 function stackClear() {
30894 this.__data__ = new ListCache;
30895 this.size = 0;
30896 }
30897
30898 /**
30899 * Removes `key` and its value from the stack.
30900 *
30901 * @private
30902 * @name delete
30903 * @memberOf Stack
30904 * @param {string} key The key of the value to remove.
30905 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
30906 */
30907 function stackDelete(key) {
30908 var data = this.__data__,
30909 result = data['delete'](key);
30910
30911 this.size = data.size;
30912 return result;
30913 }
30914
30915 /**
30916 * Gets the stack value for `key`.
30917 *
30918 * @private
30919 * @name get
30920 * @memberOf Stack
30921 * @param {string} key The key of the value to get.
30922 * @returns {*} Returns the entry value.
30923 */
30924 function stackGet(key) {
30925 return this.__data__.get(key);
30926 }
30927
30928 /**
30929 * Checks if a stack value for `key` exists.
30930 *
30931 * @private
30932 * @name has
30933 * @memberOf Stack
30934 * @param {string} key The key of the entry to check.
30935 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
30936 */
30937 function stackHas(key) {
30938 return this.__data__.has(key);
30939 }
30940
30941 /**
30942 * Sets the stack `key` to `value`.
30943 *
30944 * @private
30945 * @name set
30946 * @memberOf Stack
30947 * @param {string} key The key of the value to set.
30948 * @param {*} value The value to set.
30949 * @returns {Object} Returns the stack cache instance.
30950 */
30951 function stackSet(key, value) {
30952 var data = this.__data__;
30953 if (data instanceof ListCache) {
30954 var pairs = data.__data__;
30955 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
30956 pairs.push([key, value]);
30957 this.size = ++data.size;
30958 return this;
30959 }
30960 data = this.__data__ = new MapCache(pairs);
30961 }
30962 data.set(key, value);
30963 this.size = data.size;
30964 return this;
30965 }
30966
30967 // Add methods to `Stack`.
30968 Stack.prototype.clear = stackClear;
30969 Stack.prototype['delete'] = stackDelete;
30970 Stack.prototype.get = stackGet;
30971 Stack.prototype.has = stackHas;
30972 Stack.prototype.set = stackSet;
30973
30974 /*------------------------------------------------------------------------*/
30975
30976 /**
30977 * Creates an array of the enumerable property names of the array-like `value`.
30978 *
30979 * @private
30980 * @param {*} value The value to query.
30981 * @param {boolean} inherited Specify returning inherited property names.
30982 * @returns {Array} Returns the array of property names.
30983 */
30984 function arrayLikeKeys(value, inherited) {
30985 var isArr = isArray(value),
30986 isArg = !isArr && isArguments(value),
30987 isBuff = !isArr && !isArg && isBuffer(value),
30988 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
30989 skipIndexes = isArr || isArg || isBuff || isType,
30990 result = skipIndexes ? baseTimes(value.length, String) : [],
30991 length = result.length;
30992
30993 for (var key in value) {
30994 if ((inherited || hasOwnProperty.call(value, key)) &&
30995 !(skipIndexes && (
30996 // Safari 9 has enumerable `arguments.length` in strict mode.
30997 key == 'length' ||
30998 // Node.js 0.10 has enumerable non-index properties on buffers.
30999 (isBuff && (key == 'offset' || key == 'parent')) ||
31000 // PhantomJS 2 has enumerable non-index properties on typed arrays.
31001 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
31002 // Skip index properties.
31003 isIndex(key, length)
31004 ))) {
31005 result.push(key);
31006 }
31007 }
31008 return result;
31009 }
31010
31011 /**
31012 * A specialized version of `_.sample` for arrays.
31013 *
31014 * @private
31015 * @param {Array} array The array to sample.
31016 * @returns {*} Returns the random element.
31017 */
31018 function arraySample(array) {
31019 var length = array.length;
31020 return length ? array[baseRandom(0, length - 1)] : undefined;
31021 }
31022
31023 /**
31024 * A specialized version of `_.sampleSize` for arrays.
31025 *
31026 * @private
31027 * @param {Array} array The array to sample.
31028 * @param {number} n The number of elements to sample.
31029 * @returns {Array} Returns the random elements.
31030 */
31031 function arraySampleSize(array, n) {
31032 return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
31033 }
31034
31035 /**
31036 * A specialized version of `_.shuffle` for arrays.
31037 *
31038 * @private
31039 * @param {Array} array The array to shuffle.
31040 * @returns {Array} Returns the new shuffled array.
31041 */
31042 function arrayShuffle(array) {
31043 return shuffleSelf(copyArray(array));
31044 }
31045
31046 /**
31047 * This function is like `assignValue` except that it doesn't assign
31048 * `undefined` values.
31049 *
31050 * @private
31051 * @param {Object} object The object to modify.
31052 * @param {string} key The key of the property to assign.
31053 * @param {*} value The value to assign.
31054 */
31055 function assignMergeValue(object, key, value) {
31056 if ((value !== undefined && !eq(object[key], value)) ||
31057 (value === undefined && !(key in object))) {
31058 baseAssignValue(object, key, value);
31059 }
31060 }
31061
31062 /**
31063 * Assigns `value` to `key` of `object` if the existing value is not equivalent
31064 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
31065 * for equality comparisons.
31066 *
31067 * @private
31068 * @param {Object} object The object to modify.
31069 * @param {string} key The key of the property to assign.
31070 * @param {*} value The value to assign.
31071 */
31072 function assignValue(object, key, value) {
31073 var objValue = object[key];
31074 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
31075 (value === undefined && !(key in object))) {
31076 baseAssignValue(object, key, value);
31077 }
31078 }
31079
31080 /**
31081 * Gets the index at which the `key` is found in `array` of key-value pairs.
31082 *
31083 * @private
31084 * @param {Array} array The array to inspect.
31085 * @param {*} key The key to search for.
31086 * @returns {number} Returns the index of the matched value, else `-1`.
31087 */
31088 function assocIndexOf(array, key) {
31089 var length = array.length;
31090 while (length--) {
31091 if (eq(array[length][0], key)) {
31092 return length;
31093 }
31094 }
31095 return -1;
31096 }
31097
31098 /**
31099 * Aggregates elements of `collection` on `accumulator` with keys transformed
31100 * by `iteratee` and values set by `setter`.
31101 *
31102 * @private
31103 * @param {Array|Object} collection The collection to iterate over.
31104 * @param {Function} setter The function to set `accumulator` values.
31105 * @param {Function} iteratee The iteratee to transform keys.
31106 * @param {Object} accumulator The initial aggregated object.
31107 * @returns {Function} Returns `accumulator`.
31108 */
31109 function baseAggregator(collection, setter, iteratee, accumulator) {
31110 baseEach(collection, function(value, key, collection) {
31111 setter(accumulator, value, iteratee(value), collection);
31112 });
31113 return accumulator;
31114 }
31115
31116 /**
31117 * The base implementation of `_.assign` without support for multiple sources
31118 * or `customizer` functions.
31119 *
31120 * @private
31121 * @param {Object} object The destination object.
31122 * @param {Object} source The source object.
31123 * @returns {Object} Returns `object`.
31124 */
31125 function baseAssign(object, source) {
31126 return object && copyObject(source, keys(source), object);
31127 }
31128
31129 /**
31130 * The base implementation of `_.assignIn` without support for multiple sources
31131 * or `customizer` functions.
31132 *
31133 * @private
31134 * @param {Object} object The destination object.
31135 * @param {Object} source The source object.
31136 * @returns {Object} Returns `object`.
31137 */
31138 function baseAssignIn(object, source) {
31139 return object && copyObject(source, keysIn(source), object);
31140 }
31141
31142 /**
31143 * The base implementation of `assignValue` and `assignMergeValue` without
31144 * value checks.
31145 *
31146 * @private
31147 * @param {Object} object The object to modify.
31148 * @param {string} key The key of the property to assign.
31149 * @param {*} value The value to assign.
31150 */
31151 function baseAssignValue(object, key, value) {
31152 if (key == '__proto__' && defineProperty) {
31153 defineProperty(object, key, {
31154 'configurable': true,
31155 'enumerable': true,
31156 'value': value,
31157 'writable': true
31158 });
31159 } else {
31160 object[key] = value;
31161 }
31162 }
31163
31164 /**
31165 * The base implementation of `_.at` without support for individual paths.
31166 *
31167 * @private
31168 * @param {Object} object The object to iterate over.
31169 * @param {string[]} paths The property paths to pick.
31170 * @returns {Array} Returns the picked elements.
31171 */
31172 function baseAt(object, paths) {
31173 var index = -1,
31174 length = paths.length,
31175 result = Array(length),
31176 skip = object == null;
31177
31178 while (++index < length) {
31179 result[index] = skip ? undefined : get(object, paths[index]);
31180 }
31181 return result;
31182 }
31183
31184 /**
31185 * The base implementation of `_.clamp` which doesn't coerce arguments.
31186 *
31187 * @private
31188 * @param {number} number The number to clamp.
31189 * @param {number} [lower] The lower bound.
31190 * @param {number} upper The upper bound.
31191 * @returns {number} Returns the clamped number.
31192 */
31193 function baseClamp(number, lower, upper) {
31194 if (number === number) {
31195 if (upper !== undefined) {
31196 number = number <= upper ? number : upper;
31197 }
31198 if (lower !== undefined) {
31199 number = number >= lower ? number : lower;
31200 }
31201 }
31202 return number;
31203 }
31204
31205 /**
31206 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
31207 * traversed objects.
31208 *
31209 * @private
31210 * @param {*} value The value to clone.
31211 * @param {boolean} bitmask The bitmask flags.
31212 * 1 - Deep clone
31213 * 2 - Flatten inherited properties
31214 * 4 - Clone symbols
31215 * @param {Function} [customizer] The function to customize cloning.
31216 * @param {string} [key] The key of `value`.
31217 * @param {Object} [object] The parent object of `value`.
31218 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
31219 * @returns {*} Returns the cloned value.
31220 */
31221 function baseClone(value, bitmask, customizer, key, object, stack) {
31222 var result,
31223 isDeep = bitmask & CLONE_DEEP_FLAG,
31224 isFlat = bitmask & CLONE_FLAT_FLAG,
31225 isFull = bitmask & CLONE_SYMBOLS_FLAG;
31226
31227 if (customizer) {
31228 result = object ? customizer(value, key, object, stack) : customizer(value);
31229 }
31230 if (result !== undefined) {
31231 return result;
31232 }
31233 if (!isObject(value)) {
31234 return value;
31235 }
31236 var isArr = isArray(value);
31237 if (isArr) {
31238 result = initCloneArray(value);
31239 if (!isDeep) {
31240 return copyArray(value, result);
31241 }
31242 } else {
31243 var tag = getTag(value),
31244 isFunc = tag == funcTag || tag == genTag;
31245
31246 if (isBuffer(value)) {
31247 return cloneBuffer(value, isDeep);
31248 }
31249 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
31250 result = (isFlat || isFunc) ? {} : initCloneObject(value);
31251 if (!isDeep) {
31252 return isFlat
31253 ? copySymbolsIn(value, baseAssignIn(result, value))
31254 : copySymbols(value, baseAssign(result, value));
31255 }
31256 } else {
31257 if (!cloneableTags[tag]) {
31258 return object ? value : {};
31259 }
31260 result = initCloneByTag(value, tag, isDeep);
31261 }
31262 }
31263 // Check for circular references and return its corresponding clone.
31264 stack || (stack = new Stack);
31265 var stacked = stack.get(value);
31266 if (stacked) {
31267 return stacked;
31268 }
31269 stack.set(value, result);
31270
31271 if (isSet(value)) {
31272 value.forEach(function(subValue) {
31273 result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
31274 });
31275 } else if (isMap(value)) {
31276 value.forEach(function(subValue, key) {
31277 result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
31278 });
31279 }
31280
31281 var keysFunc = isFull
31282 ? (isFlat ? getAllKeysIn : getAllKeys)
31283 : (isFlat ? keysIn : keys);
31284
31285 var props = isArr ? undefined : keysFunc(value);
31286 arrayEach(props || value, function(subValue, key) {
31287 if (props) {
31288 key = subValue;
31289 subValue = value[key];
31290 }
31291 // Recursively populate clone (susceptible to call stack limits).
31292 assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
31293 });
31294 return result;
31295 }
31296
31297 /**
31298 * The base implementation of `_.conforms` which doesn't clone `source`.
31299 *
31300 * @private
31301 * @param {Object} source The object of property predicates to conform to.
31302 * @returns {Function} Returns the new spec function.
31303 */
31304 function baseConforms(source) {
31305 var props = keys(source);
31306 return function(object) {
31307 return baseConformsTo(object, source, props);
31308 };
31309 }
31310
31311 /**
31312 * The base implementation of `_.conformsTo` which accepts `props` to check.
31313 *
31314 * @private
31315 * @param {Object} object The object to inspect.
31316 * @param {Object} source The object of property predicates to conform to.
31317 * @returns {boolean} Returns `true` if `object` conforms, else `false`.
31318 */
31319 function baseConformsTo(object, source, props) {
31320 var length = props.length;
31321 if (object == null) {
31322 return !length;
31323 }
31324 object = Object(object);
31325 while (length--) {
31326 var key = props[length],
31327 predicate = source[key],
31328 value = object[key];
31329
31330 if ((value === undefined && !(key in object)) || !predicate(value)) {
31331 return false;
31332 }
31333 }
31334 return true;
31335 }
31336
31337 /**
31338 * The base implementation of `_.delay` and `_.defer` which accepts `args`
31339 * to provide to `func`.
31340 *
31341 * @private
31342 * @param {Function} func The function to delay.
31343 * @param {number} wait The number of milliseconds to delay invocation.
31344 * @param {Array} args The arguments to provide to `func`.
31345 * @returns {number|Object} Returns the timer id or timeout object.
31346 */
31347 function baseDelay(func, wait, args) {
31348 if (typeof func != 'function') {
31349 throw new TypeError(FUNC_ERROR_TEXT);
31350 }
31351 return setTimeout(function() { func.apply(undefined, args); }, wait);
31352 }
31353
31354 /**
31355 * The base implementation of methods like `_.difference` without support
31356 * for excluding multiple arrays or iteratee shorthands.
31357 *
31358 * @private
31359 * @param {Array} array The array to inspect.
31360 * @param {Array} values The values to exclude.
31361 * @param {Function} [iteratee] The iteratee invoked per element.
31362 * @param {Function} [comparator] The comparator invoked per element.
31363 * @returns {Array} Returns the new array of filtered values.
31364 */
31365 function baseDifference(array, values, iteratee, comparator) {
31366 var index = -1,
31367 includes = arrayIncludes,
31368 isCommon = true,
31369 length = array.length,
31370 result = [],
31371 valuesLength = values.length;
31372
31373 if (!length) {
31374 return result;
31375 }
31376 if (iteratee) {
31377 values = arrayMap(values, baseUnary(iteratee));
31378 }
31379 if (comparator) {
31380 includes = arrayIncludesWith;
31381 isCommon = false;
31382 }
31383 else if (values.length >= LARGE_ARRAY_SIZE) {
31384 includes = cacheHas;
31385 isCommon = false;
31386 values = new SetCache(values);
31387 }
31388 outer:
31389 while (++index < length) {
31390 var value = array[index],
31391 computed = iteratee == null ? value : iteratee(value);
31392
31393 value = (comparator || value !== 0) ? value : 0;
31394 if (isCommon && computed === computed) {
31395 var valuesIndex = valuesLength;
31396 while (valuesIndex--) {
31397 if (values[valuesIndex] === computed) {
31398 continue outer;
31399 }
31400 }
31401 result.push(value);
31402 }
31403 else if (!includes(values, computed, comparator)) {
31404 result.push(value);
31405 }
31406 }
31407 return result;
31408 }
31409
31410 /**
31411 * The base implementation of `_.forEach` without support for iteratee shorthands.
31412 *
31413 * @private
31414 * @param {Array|Object} collection The collection to iterate over.
31415 * @param {Function} iteratee The function invoked per iteration.
31416 * @returns {Array|Object} Returns `collection`.
31417 */
31418 var baseEach = createBaseEach(baseForOwn);
31419
31420 /**
31421 * The base implementation of `_.forEachRight` without support for iteratee shorthands.
31422 *
31423 * @private
31424 * @param {Array|Object} collection The collection to iterate over.
31425 * @param {Function} iteratee The function invoked per iteration.
31426 * @returns {Array|Object} Returns `collection`.
31427 */
31428 var baseEachRight = createBaseEach(baseForOwnRight, true);
31429
31430 /**
31431 * The base implementation of `_.every` without support for iteratee shorthands.
31432 *
31433 * @private
31434 * @param {Array|Object} collection The collection to iterate over.
31435 * @param {Function} predicate The function invoked per iteration.
31436 * @returns {boolean} Returns `true` if all elements pass the predicate check,
31437 * else `false`
31438 */
31439 function baseEvery(collection, predicate) {
31440 var result = true;
31441 baseEach(collection, function(value, index, collection) {
31442 result = !!predicate(value, index, collection);
31443 return result;
31444 });
31445 return result;
31446 }
31447
31448 /**
31449 * The base implementation of methods like `_.max` and `_.min` which accepts a
31450 * `comparator` to determine the extremum value.
31451 *
31452 * @private
31453 * @param {Array} array The array to iterate over.
31454 * @param {Function} iteratee The iteratee invoked per iteration.
31455 * @param {Function} comparator The comparator used to compare values.
31456 * @returns {*} Returns the extremum value.
31457 */
31458 function baseExtremum(array, iteratee, comparator) {
31459 var index = -1,
31460 length = array.length;
31461
31462 while (++index < length) {
31463 var value = array[index],
31464 current = iteratee(value);
31465
31466 if (current != null && (computed === undefined
31467 ? (current === current && !isSymbol(current))
31468 : comparator(current, computed)
31469 )) {
31470 var computed = current,
31471 result = value;
31472 }
31473 }
31474 return result;
31475 }
31476
31477 /**
31478 * The base implementation of `_.fill` without an iteratee call guard.
31479 *
31480 * @private
31481 * @param {Array} array The array to fill.
31482 * @param {*} value The value to fill `array` with.
31483 * @param {number} [start=0] The start position.
31484 * @param {number} [end=array.length] The end position.
31485 * @returns {Array} Returns `array`.
31486 */
31487 function baseFill(array, value, start, end) {
31488 var length = array.length;
31489
31490 start = toInteger(start);
31491 if (start < 0) {
31492 start = -start > length ? 0 : (length + start);
31493 }
31494 end = (end === undefined || end > length) ? length : toInteger(end);
31495 if (end < 0) {
31496 end += length;
31497 }
31498 end = start > end ? 0 : toLength(end);
31499 while (start < end) {
31500 array[start++] = value;
31501 }
31502 return array;
31503 }
31504
31505 /**
31506 * The base implementation of `_.filter` without support for iteratee shorthands.
31507 *
31508 * @private
31509 * @param {Array|Object} collection The collection to iterate over.
31510 * @param {Function} predicate The function invoked per iteration.
31511 * @returns {Array} Returns the new filtered array.
31512 */
31513 function baseFilter(collection, predicate) {
31514 var result = [];
31515 baseEach(collection, function(value, index, collection) {
31516 if (predicate(value, index, collection)) {
31517 result.push(value);
31518 }
31519 });
31520 return result;
31521 }
31522
31523 /**
31524 * The base implementation of `_.flatten` with support for restricting flattening.
31525 *
31526 * @private
31527 * @param {Array} array The array to flatten.
31528 * @param {number} depth The maximum recursion depth.
31529 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
31530 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
31531 * @param {Array} [result=[]] The initial result value.
31532 * @returns {Array} Returns the new flattened array.
31533 */
31534 function baseFlatten(array, depth, predicate, isStrict, result) {
31535 var index = -1,
31536 length = array.length;
31537
31538 predicate || (predicate = isFlattenable);
31539 result || (result = []);
31540
31541 while (++index < length) {
31542 var value = array[index];
31543 if (depth > 0 && predicate(value)) {
31544 if (depth > 1) {
31545 // Recursively flatten arrays (susceptible to call stack limits).
31546 baseFlatten(value, depth - 1, predicate, isStrict, result);
31547 } else {
31548 arrayPush(result, value);
31549 }
31550 } else if (!isStrict) {
31551 result[result.length] = value;
31552 }
31553 }
31554 return result;
31555 }
31556
31557 /**
31558 * The base implementation of `baseForOwn` which iterates over `object`
31559 * properties returned by `keysFunc` and invokes `iteratee` for each property.
31560 * Iteratee functions may exit iteration early by explicitly returning `false`.
31561 *
31562 * @private
31563 * @param {Object} object The object to iterate over.
31564 * @param {Function} iteratee The function invoked per iteration.
31565 * @param {Function} keysFunc The function to get the keys of `object`.
31566 * @returns {Object} Returns `object`.
31567 */
31568 var baseFor = createBaseFor();
31569
31570 /**
31571 * This function is like `baseFor` except that it iterates over properties
31572 * in the opposite order.
31573 *
31574 * @private
31575 * @param {Object} object The object to iterate over.
31576 * @param {Function} iteratee The function invoked per iteration.
31577 * @param {Function} keysFunc The function to get the keys of `object`.
31578 * @returns {Object} Returns `object`.
31579 */
31580 var baseForRight = createBaseFor(true);
31581
31582 /**
31583 * The base implementation of `_.forOwn` without support for iteratee shorthands.
31584 *
31585 * @private
31586 * @param {Object} object The object to iterate over.
31587 * @param {Function} iteratee The function invoked per iteration.
31588 * @returns {Object} Returns `object`.
31589 */
31590 function baseForOwn(object, iteratee) {
31591 return object && baseFor(object, iteratee, keys);
31592 }
31593
31594 /**
31595 * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
31596 *
31597 * @private
31598 * @param {Object} object The object to iterate over.
31599 * @param {Function} iteratee The function invoked per iteration.
31600 * @returns {Object} Returns `object`.
31601 */
31602 function baseForOwnRight(object, iteratee) {
31603 return object && baseForRight(object, iteratee, keys);
31604 }
31605
31606 /**
31607 * The base implementation of `_.functions` which creates an array of
31608 * `object` function property names filtered from `props`.
31609 *
31610 * @private
31611 * @param {Object} object The object to inspect.
31612 * @param {Array} props The property names to filter.
31613 * @returns {Array} Returns the function names.
31614 */
31615 function baseFunctions(object, props) {
31616 return arrayFilter(props, function(key) {
31617 return isFunction(object[key]);
31618 });
31619 }
31620
31621 /**
31622 * The base implementation of `_.get` without support for default values.
31623 *
31624 * @private
31625 * @param {Object} object The object to query.
31626 * @param {Array|string} path The path of the property to get.
31627 * @returns {*} Returns the resolved value.
31628 */
31629 function baseGet(object, path) {
31630 path = castPath(path, object);
31631
31632 var index = 0,
31633 length = path.length;
31634
31635 while (object != null && index < length) {
31636 object = object[toKey(path[index++])];
31637 }
31638 return (index && index == length) ? object : undefined;
31639 }
31640
31641 /**
31642 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
31643 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
31644 * symbols of `object`.
31645 *
31646 * @private
31647 * @param {Object} object The object to query.
31648 * @param {Function} keysFunc The function to get the keys of `object`.
31649 * @param {Function} symbolsFunc The function to get the symbols of `object`.
31650 * @returns {Array} Returns the array of property names and symbols.
31651 */
31652 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
31653 var result = keysFunc(object);
31654 return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
31655 }
31656
31657 /**
31658 * The base implementation of `getTag` without fallbacks for buggy environments.
31659 *
31660 * @private
31661 * @param {*} value The value to query.
31662 * @returns {string} Returns the `toStringTag`.
31663 */
31664 function baseGetTag(value) {
31665 if (value == null) {
31666 return value === undefined ? undefinedTag : nullTag;
31667 }
31668 return (symToStringTag && symToStringTag in Object(value))
31669 ? getRawTag(value)
31670 : objectToString(value);
31671 }
31672
31673 /**
31674 * The base implementation of `_.gt` which doesn't coerce arguments.
31675 *
31676 * @private
31677 * @param {*} value The value to compare.
31678 * @param {*} other The other value to compare.
31679 * @returns {boolean} Returns `true` if `value` is greater than `other`,
31680 * else `false`.
31681 */
31682 function baseGt(value, other) {
31683 return value > other;
31684 }
31685
31686 /**
31687 * The base implementation of `_.has` without support for deep paths.
31688 *
31689 * @private
31690 * @param {Object} [object] The object to query.
31691 * @param {Array|string} key The key to check.
31692 * @returns {boolean} Returns `true` if `key` exists, else `false`.
31693 */
31694 function baseHas(object, key) {
31695 return object != null && hasOwnProperty.call(object, key);
31696 }
31697
31698 /**
31699 * The base implementation of `_.hasIn` without support for deep paths.
31700 *
31701 * @private
31702 * @param {Object} [object] The object to query.
31703 * @param {Array|string} key The key to check.
31704 * @returns {boolean} Returns `true` if `key` exists, else `false`.
31705 */
31706 function baseHasIn(object, key) {
31707 return object != null && key in Object(object);
31708 }
31709
31710 /**
31711 * The base implementation of `_.inRange` which doesn't coerce arguments.
31712 *
31713 * @private
31714 * @param {number} number The number to check.
31715 * @param {number} start The start of the range.
31716 * @param {number} end The end of the range.
31717 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
31718 */
31719 function baseInRange(number, start, end) {
31720 return number >= nativeMin(start, end) && number < nativeMax(start, end);
31721 }
31722
31723 /**
31724 * The base implementation of methods like `_.intersection`, without support
31725 * for iteratee shorthands, that accepts an array of arrays to inspect.
31726 *
31727 * @private
31728 * @param {Array} arrays The arrays to inspect.
31729 * @param {Function} [iteratee] The iteratee invoked per element.
31730 * @param {Function} [comparator] The comparator invoked per element.
31731 * @returns {Array} Returns the new array of shared values.
31732 */
31733 function baseIntersection(arrays, iteratee, comparator) {
31734 var includes = comparator ? arrayIncludesWith : arrayIncludes,
31735 length = arrays[0].length,
31736 othLength = arrays.length,
31737 othIndex = othLength,
31738 caches = Array(othLength),
31739 maxLength = Infinity,
31740 result = [];
31741
31742 while (othIndex--) {
31743 var array = arrays[othIndex];
31744 if (othIndex && iteratee) {
31745 array = arrayMap(array, baseUnary(iteratee));
31746 }
31747 maxLength = nativeMin(array.length, maxLength);
31748 caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
31749 ? new SetCache(othIndex && array)
31750 : undefined;
31751 }
31752 array = arrays[0];
31753
31754 var index = -1,
31755 seen = caches[0];
31756
31757 outer:
31758 while (++index < length && result.length < maxLength) {
31759 var value = array[index],
31760 computed = iteratee ? iteratee(value) : value;
31761
31762 value = (comparator || value !== 0) ? value : 0;
31763 if (!(seen
31764 ? cacheHas(seen, computed)
31765 : includes(result, computed, comparator)
31766 )) {
31767 othIndex = othLength;
31768 while (--othIndex) {
31769 var cache = caches[othIndex];
31770 if (!(cache
31771 ? cacheHas(cache, computed)
31772 : includes(arrays[othIndex], computed, comparator))
31773 ) {
31774 continue outer;
31775 }
31776 }
31777 if (seen) {
31778 seen.push(computed);
31779 }
31780 result.push(value);
31781 }
31782 }
31783 return result;
31784 }
31785
31786 /**
31787 * The base implementation of `_.invert` and `_.invertBy` which inverts
31788 * `object` with values transformed by `iteratee` and set by `setter`.
31789 *
31790 * @private
31791 * @param {Object} object The object to iterate over.
31792 * @param {Function} setter The function to set `accumulator` values.
31793 * @param {Function} iteratee The iteratee to transform values.
31794 * @param {Object} accumulator The initial inverted object.
31795 * @returns {Function} Returns `accumulator`.
31796 */
31797 function baseInverter(object, setter, iteratee, accumulator) {
31798 baseForOwn(object, function(value, key, object) {
31799 setter(accumulator, iteratee(value), key, object);
31800 });
31801 return accumulator;
31802 }
31803
31804 /**
31805 * The base implementation of `_.invoke` without support for individual
31806 * method arguments.
31807 *
31808 * @private
31809 * @param {Object} object The object to query.
31810 * @param {Array|string} path The path of the method to invoke.
31811 * @param {Array} args The arguments to invoke the method with.
31812 * @returns {*} Returns the result of the invoked method.
31813 */
31814 function baseInvoke(object, path, args) {
31815 path = castPath(path, object);
31816 object = parent(object, path);
31817 var func = object == null ? object : object[toKey(last(path))];
31818 return func == null ? undefined : apply(func, object, args);
31819 }
31820
31821 /**
31822 * The base implementation of `_.isArguments`.
31823 *
31824 * @private
31825 * @param {*} value The value to check.
31826 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
31827 */
31828 function baseIsArguments(value) {
31829 return isObjectLike(value) && baseGetTag(value) == argsTag;
31830 }
31831
31832 /**
31833 * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
31834 *
31835 * @private
31836 * @param {*} value The value to check.
31837 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
31838 */
31839 function baseIsArrayBuffer(value) {
31840 return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
31841 }
31842
31843 /**
31844 * The base implementation of `_.isDate` without Node.js optimizations.
31845 *
31846 * @private
31847 * @param {*} value The value to check.
31848 * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
31849 */
31850 function baseIsDate(value) {
31851 return isObjectLike(value) && baseGetTag(value) == dateTag;
31852 }
31853
31854 /**
31855 * The base implementation of `_.isEqual` which supports partial comparisons
31856 * and tracks traversed objects.
31857 *
31858 * @private
31859 * @param {*} value The value to compare.
31860 * @param {*} other The other value to compare.
31861 * @param {boolean} bitmask The bitmask flags.
31862 * 1 - Unordered comparison
31863 * 2 - Partial comparison
31864 * @param {Function} [customizer] The function to customize comparisons.
31865 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
31866 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
31867 */
31868 function baseIsEqual(value, other, bitmask, customizer, stack) {
31869 if (value === other) {
31870 return true;
31871 }
31872 if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
31873 return value !== value && other !== other;
31874 }
31875 return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
31876 }
31877
31878 /**
31879 * A specialized version of `baseIsEqual` for arrays and objects which performs
31880 * deep comparisons and tracks traversed objects enabling objects with circular
31881 * references to be compared.
31882 *
31883 * @private
31884 * @param {Object} object The object to compare.
31885 * @param {Object} other The other object to compare.
31886 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
31887 * @param {Function} customizer The function to customize comparisons.
31888 * @param {Function} equalFunc The function to determine equivalents of values.
31889 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
31890 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
31891 */
31892 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
31893 var objIsArr = isArray(object),
31894 othIsArr = isArray(other),
31895 objTag = objIsArr ? arrayTag : getTag(object),
31896 othTag = othIsArr ? arrayTag : getTag(other);
31897
31898 objTag = objTag == argsTag ? objectTag : objTag;
31899 othTag = othTag == argsTag ? objectTag : othTag;
31900
31901 var objIsObj = objTag == objectTag,
31902 othIsObj = othTag == objectTag,
31903 isSameTag = objTag == othTag;
31904
31905 if (isSameTag && isBuffer(object)) {
31906 if (!isBuffer(other)) {
31907 return false;
31908 }
31909 objIsArr = true;
31910 objIsObj = false;
31911 }
31912 if (isSameTag && !objIsObj) {
31913 stack || (stack = new Stack);
31914 return (objIsArr || isTypedArray(object))
31915 ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
31916 : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
31917 }
31918 if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
31919 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
31920 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
31921
31922 if (objIsWrapped || othIsWrapped) {
31923 var objUnwrapped = objIsWrapped ? object.value() : object,
31924 othUnwrapped = othIsWrapped ? other.value() : other;
31925
31926 stack || (stack = new Stack);
31927 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
31928 }
31929 }
31930 if (!isSameTag) {
31931 return false;
31932 }
31933 stack || (stack = new Stack);
31934 return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
31935 }
31936
31937 /**
31938 * The base implementation of `_.isMap` without Node.js optimizations.
31939 *
31940 * @private
31941 * @param {*} value The value to check.
31942 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
31943 */
31944 function baseIsMap(value) {
31945 return isObjectLike(value) && getTag(value) == mapTag;
31946 }
31947
31948 /**
31949 * The base implementation of `_.isMatch` without support for iteratee shorthands.
31950 *
31951 * @private
31952 * @param {Object} object The object to inspect.
31953 * @param {Object} source The object of property values to match.
31954 * @param {Array} matchData The property names, values, and compare flags to match.
31955 * @param {Function} [customizer] The function to customize comparisons.
31956 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
31957 */
31958 function baseIsMatch(object, source, matchData, customizer) {
31959 var index = matchData.length,
31960 length = index,
31961 noCustomizer = !customizer;
31962
31963 if (object == null) {
31964 return !length;
31965 }
31966 object = Object(object);
31967 while (index--) {
31968 var data = matchData[index];
31969 if ((noCustomizer && data[2])
31970 ? data[1] !== object[data[0]]
31971 : !(data[0] in object)
31972 ) {
31973 return false;
31974 }
31975 }
31976 while (++index < length) {
31977 data = matchData[index];
31978 var key = data[0],
31979 objValue = object[key],
31980 srcValue = data[1];
31981
31982 if (noCustomizer && data[2]) {
31983 if (objValue === undefined && !(key in object)) {
31984 return false;
31985 }
31986 } else {
31987 var stack = new Stack;
31988 if (customizer) {
31989 var result = customizer(objValue, srcValue, key, object, source, stack);
31990 }
31991 if (!(result === undefined
31992 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
31993 : result
31994 )) {
31995 return false;
31996 }
31997 }
31998 }
31999 return true;
32000 }
32001
32002 /**
32003 * The base implementation of `_.isNative` without bad shim checks.
32004 *
32005 * @private
32006 * @param {*} value The value to check.
32007 * @returns {boolean} Returns `true` if `value` is a native function,
32008 * else `false`.
32009 */
32010 function baseIsNative(value) {
32011 if (!isObject(value) || isMasked(value)) {
32012 return false;
32013 }
32014 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
32015 return pattern.test(toSource(value));
32016 }
32017
32018 /**
32019 * The base implementation of `_.isRegExp` without Node.js optimizations.
32020 *
32021 * @private
32022 * @param {*} value The value to check.
32023 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
32024 */
32025 function baseIsRegExp(value) {
32026 return isObjectLike(value) && baseGetTag(value) == regexpTag;
32027 }
32028
32029 /**
32030 * The base implementation of `_.isSet` without Node.js optimizations.
32031 *
32032 * @private
32033 * @param {*} value The value to check.
32034 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
32035 */
32036 function baseIsSet(value) {
32037 return isObjectLike(value) && getTag(value) == setTag;
32038 }
32039
32040 /**
32041 * The base implementation of `_.isTypedArray` without Node.js optimizations.
32042 *
32043 * @private
32044 * @param {*} value The value to check.
32045 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
32046 */
32047 function baseIsTypedArray(value) {
32048 return isObjectLike(value) &&
32049 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
32050 }
32051
32052 /**
32053 * The base implementation of `_.iteratee`.
32054 *
32055 * @private
32056 * @param {*} [value=_.identity] The value to convert to an iteratee.
32057 * @returns {Function} Returns the iteratee.
32058 */
32059 function baseIteratee(value) {
32060 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
32061 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
32062 if (typeof value == 'function') {
32063 return value;
32064 }
32065 if (value == null) {
32066 return identity;
32067 }
32068 if (typeof value == 'object') {
32069 return isArray(value)
32070 ? baseMatchesProperty(value[0], value[1])
32071 : baseMatches(value);
32072 }
32073 return property(value);
32074 }
32075
32076 /**
32077 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
32078 *
32079 * @private
32080 * @param {Object} object The object to query.
32081 * @returns {Array} Returns the array of property names.
32082 */
32083 function baseKeys(object) {
32084 if (!isPrototype(object)) {
32085 return nativeKeys(object);
32086 }
32087 var result = [];
32088 for (var key in Object(object)) {
32089 if (hasOwnProperty.call(object, key) && key != 'constructor') {
32090 result.push(key);
32091 }
32092 }
32093 return result;
32094 }
32095
32096 /**
32097 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
32098 *
32099 * @private
32100 * @param {Object} object The object to query.
32101 * @returns {Array} Returns the array of property names.
32102 */
32103 function baseKeysIn(object) {
32104 if (!isObject(object)) {
32105 return nativeKeysIn(object);
32106 }
32107 var isProto = isPrototype(object),
32108 result = [];
32109
32110 for (var key in object) {
32111 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
32112 result.push(key);
32113 }
32114 }
32115 return result;
32116 }
32117
32118 /**
32119 * The base implementation of `_.lt` which doesn't coerce arguments.
32120 *
32121 * @private
32122 * @param {*} value The value to compare.
32123 * @param {*} other The other value to compare.
32124 * @returns {boolean} Returns `true` if `value` is less than `other`,
32125 * else `false`.
32126 */
32127 function baseLt(value, other) {
32128 return value < other;
32129 }
32130
32131 /**
32132 * The base implementation of `_.map` without support for iteratee shorthands.
32133 *
32134 * @private
32135 * @param {Array|Object} collection The collection to iterate over.
32136 * @param {Function} iteratee The function invoked per iteration.
32137 * @returns {Array} Returns the new mapped array.
32138 */
32139 function baseMap(collection, iteratee) {
32140 var index = -1,
32141 result = isArrayLike(collection) ? Array(collection.length) : [];
32142
32143 baseEach(collection, function(value, key, collection) {
32144 result[++index] = iteratee(value, key, collection);
32145 });
32146 return result;
32147 }
32148
32149 /**
32150 * The base implementation of `_.matches` which doesn't clone `source`.
32151 *
32152 * @private
32153 * @param {Object} source The object of property values to match.
32154 * @returns {Function} Returns the new spec function.
32155 */
32156 function baseMatches(source) {
32157 var matchData = getMatchData(source);
32158 if (matchData.length == 1 && matchData[0][2]) {
32159 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
32160 }
32161 return function(object) {
32162 return object === source || baseIsMatch(object, source, matchData);
32163 };
32164 }
32165
32166 /**
32167 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
32168 *
32169 * @private
32170 * @param {string} path The path of the property to get.
32171 * @param {*} srcValue The value to match.
32172 * @returns {Function} Returns the new spec function.
32173 */
32174 function baseMatchesProperty(path, srcValue) {
32175 if (isKey(path) && isStrictComparable(srcValue)) {
32176 return matchesStrictComparable(toKey(path), srcValue);
32177 }
32178 return function(object) {
32179 var objValue = get(object, path);
32180 return (objValue === undefined && objValue === srcValue)
32181 ? hasIn(object, path)
32182 : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
32183 };
32184 }
32185
32186 /**
32187 * The base implementation of `_.merge` without support for multiple sources.
32188 *
32189 * @private
32190 * @param {Object} object The destination object.
32191 * @param {Object} source The source object.
32192 * @param {number} srcIndex The index of `source`.
32193 * @param {Function} [customizer] The function to customize merged values.
32194 * @param {Object} [stack] Tracks traversed source values and their merged
32195 * counterparts.
32196 */
32197 function baseMerge(object, source, srcIndex, customizer, stack) {
32198 if (object === source) {
32199 return;
32200 }
32201 baseFor(source, function(srcValue, key) {
32202 stack || (stack = new Stack);
32203 if (isObject(srcValue)) {
32204 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
32205 }
32206 else {
32207 var newValue = customizer
32208 ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
32209 : undefined;
32210
32211 if (newValue === undefined) {
32212 newValue = srcValue;
32213 }
32214 assignMergeValue(object, key, newValue);
32215 }
32216 }, keysIn);
32217 }
32218
32219 /**
32220 * A specialized version of `baseMerge` for arrays and objects which performs
32221 * deep merges and tracks traversed objects enabling objects with circular
32222 * references to be merged.
32223 *
32224 * @private
32225 * @param {Object} object The destination object.
32226 * @param {Object} source The source object.
32227 * @param {string} key The key of the value to merge.
32228 * @param {number} srcIndex The index of `source`.
32229 * @param {Function} mergeFunc The function to merge values.
32230 * @param {Function} [customizer] The function to customize assigned values.
32231 * @param {Object} [stack] Tracks traversed source values and their merged
32232 * counterparts.
32233 */
32234 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
32235 var objValue = safeGet(object, key),
32236 srcValue = safeGet(source, key),
32237 stacked = stack.get(srcValue);
32238
32239 if (stacked) {
32240 assignMergeValue(object, key, stacked);
32241 return;
32242 }
32243 var newValue = customizer
32244 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
32245 : undefined;
32246
32247 var isCommon = newValue === undefined;
32248
32249 if (isCommon) {
32250 var isArr = isArray(srcValue),
32251 isBuff = !isArr && isBuffer(srcValue),
32252 isTyped = !isArr && !isBuff && isTypedArray(srcValue);
32253
32254 newValue = srcValue;
32255 if (isArr || isBuff || isTyped) {
32256 if (isArray(objValue)) {
32257 newValue = objValue;
32258 }
32259 else if (isArrayLikeObject(objValue)) {
32260 newValue = copyArray(objValue);
32261 }
32262 else if (isBuff) {
32263 isCommon = false;
32264 newValue = cloneBuffer(srcValue, true);
32265 }
32266 else if (isTyped) {
32267 isCommon = false;
32268 newValue = cloneTypedArray(srcValue, true);
32269 }
32270 else {
32271 newValue = [];
32272 }
32273 }
32274 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
32275 newValue = objValue;
32276 if (isArguments(objValue)) {
32277 newValue = toPlainObject(objValue);
32278 }
32279 else if (!isObject(objValue) || isFunction(objValue)) {
32280 newValue = initCloneObject(srcValue);
32281 }
32282 }
32283 else {
32284 isCommon = false;
32285 }
32286 }
32287 if (isCommon) {
32288 // Recursively merge objects and arrays (susceptible to call stack limits).
32289 stack.set(srcValue, newValue);
32290 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
32291 stack['delete'](srcValue);
32292 }
32293 assignMergeValue(object, key, newValue);
32294 }
32295
32296 /**
32297 * The base implementation of `_.nth` which doesn't coerce arguments.
32298 *
32299 * @private
32300 * @param {Array} array The array to query.
32301 * @param {number} n The index of the element to return.
32302 * @returns {*} Returns the nth element of `array`.
32303 */
32304 function baseNth(array, n) {
32305 var length = array.length;
32306 if (!length) {
32307 return;
32308 }
32309 n += n < 0 ? length : 0;
32310 return isIndex(n, length) ? array[n] : undefined;
32311 }
32312
32313 /**
32314 * The base implementation of `_.orderBy` without param guards.
32315 *
32316 * @private
32317 * @param {Array|Object} collection The collection to iterate over.
32318 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
32319 * @param {string[]} orders The sort orders of `iteratees`.
32320 * @returns {Array} Returns the new sorted array.
32321 */
32322 function baseOrderBy(collection, iteratees, orders) {
32323 var index = -1;
32324 iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee()));
32325
32326 var result = baseMap(collection, function(value, key, collection) {
32327 var criteria = arrayMap(iteratees, function(iteratee) {
32328 return iteratee(value);
32329 });
32330 return { 'criteria': criteria, 'index': ++index, 'value': value };
32331 });
32332
32333 return baseSortBy(result, function(object, other) {
32334 return compareMultiple(object, other, orders);
32335 });
32336 }
32337
32338 /**
32339 * The base implementation of `_.pick` without support for individual
32340 * property identifiers.
32341 *
32342 * @private
32343 * @param {Object} object The source object.
32344 * @param {string[]} paths The property paths to pick.
32345 * @returns {Object} Returns the new object.
32346 */
32347 function basePick(object, paths) {
32348 return basePickBy(object, paths, function(value, path) {
32349 return hasIn(object, path);
32350 });
32351 }
32352
32353 /**
32354 * The base implementation of `_.pickBy` without support for iteratee shorthands.
32355 *
32356 * @private
32357 * @param {Object} object The source object.
32358 * @param {string[]} paths The property paths to pick.
32359 * @param {Function} predicate The function invoked per property.
32360 * @returns {Object} Returns the new object.
32361 */
32362 function basePickBy(object, paths, predicate) {
32363 var index = -1,
32364 length = paths.length,
32365 result = {};
32366
32367 while (++index < length) {
32368 var path = paths[index],
32369 value = baseGet(object, path);
32370
32371 if (predicate(value, path)) {
32372 baseSet(result, castPath(path, object), value);
32373 }
32374 }
32375 return result;
32376 }
32377
32378 /**
32379 * A specialized version of `baseProperty` which supports deep paths.
32380 *
32381 * @private
32382 * @param {Array|string} path The path of the property to get.
32383 * @returns {Function} Returns the new accessor function.
32384 */
32385 function basePropertyDeep(path) {
32386 return function(object) {
32387 return baseGet(object, path);
32388 };
32389 }
32390
32391 /**
32392 * The base implementation of `_.pullAllBy` without support for iteratee
32393 * shorthands.
32394 *
32395 * @private
32396 * @param {Array} array The array to modify.
32397 * @param {Array} values The values to remove.
32398 * @param {Function} [iteratee] The iteratee invoked per element.
32399 * @param {Function} [comparator] The comparator invoked per element.
32400 * @returns {Array} Returns `array`.
32401 */
32402 function basePullAll(array, values, iteratee, comparator) {
32403 var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
32404 index = -1,
32405 length = values.length,
32406 seen = array;
32407
32408 if (array === values) {
32409 values = copyArray(values);
32410 }
32411 if (iteratee) {
32412 seen = arrayMap(array, baseUnary(iteratee));
32413 }
32414 while (++index < length) {
32415 var fromIndex = 0,
32416 value = values[index],
32417 computed = iteratee ? iteratee(value) : value;
32418
32419 while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
32420 if (seen !== array) {
32421 splice.call(seen, fromIndex, 1);
32422 }
32423 splice.call(array, fromIndex, 1);
32424 }
32425 }
32426 return array;
32427 }
32428
32429 /**
32430 * The base implementation of `_.pullAt` without support for individual
32431 * indexes or capturing the removed elements.
32432 *
32433 * @private
32434 * @param {Array} array The array to modify.
32435 * @param {number[]} indexes The indexes of elements to remove.
32436 * @returns {Array} Returns `array`.
32437 */
32438 function basePullAt(array, indexes) {
32439 var length = array ? indexes.length : 0,
32440 lastIndex = length - 1;
32441
32442 while (length--) {
32443 var index = indexes[length];
32444 if (length == lastIndex || index !== previous) {
32445 var previous = index;
32446 if (isIndex(index)) {
32447 splice.call(array, index, 1);
32448 } else {
32449 baseUnset(array, index);
32450 }
32451 }
32452 }
32453 return array;
32454 }
32455
32456 /**
32457 * The base implementation of `_.random` without support for returning
32458 * floating-point numbers.
32459 *
32460 * @private
32461 * @param {number} lower The lower bound.
32462 * @param {number} upper The upper bound.
32463 * @returns {number} Returns the random number.
32464 */
32465 function baseRandom(lower, upper) {
32466 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
32467 }
32468
32469 /**
32470 * The base implementation of `_.range` and `_.rangeRight` which doesn't
32471 * coerce arguments.
32472 *
32473 * @private
32474 * @param {number} start The start of the range.
32475 * @param {number} end The end of the range.
32476 * @param {number} step The value to increment or decrement by.
32477 * @param {boolean} [fromRight] Specify iterating from right to left.
32478 * @returns {Array} Returns the range of numbers.
32479 */
32480 function baseRange(start, end, step, fromRight) {
32481 var index = -1,
32482 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
32483 result = Array(length);
32484
32485 while (length--) {
32486 result[fromRight ? length : ++index] = start;
32487 start += step;
32488 }
32489 return result;
32490 }
32491
32492 /**
32493 * The base implementation of `_.repeat` which doesn't coerce arguments.
32494 *
32495 * @private
32496 * @param {string} string The string to repeat.
32497 * @param {number} n The number of times to repeat the string.
32498 * @returns {string} Returns the repeated string.
32499 */
32500 function baseRepeat(string, n) {
32501 var result = '';
32502 if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
32503 return result;
32504 }
32505 // Leverage the exponentiation by squaring algorithm for a faster repeat.
32506 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
32507 do {
32508 if (n % 2) {
32509 result += string;
32510 }
32511 n = nativeFloor(n / 2);
32512 if (n) {
32513 string += string;
32514 }
32515 } while (n);
32516
32517 return result;
32518 }
32519
32520 /**
32521 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
32522 *
32523 * @private
32524 * @param {Function} func The function to apply a rest parameter to.
32525 * @param {number} [start=func.length-1] The start position of the rest parameter.
32526 * @returns {Function} Returns the new function.
32527 */
32528 function baseRest(func, start) {
32529 return setToString(overRest(func, start, identity), func + '');
32530 }
32531
32532 /**
32533 * The base implementation of `_.sample`.
32534 *
32535 * @private
32536 * @param {Array|Object} collection The collection to sample.
32537 * @returns {*} Returns the random element.
32538 */
32539 function baseSample(collection) {
32540 return arraySample(values(collection));
32541 }
32542
32543 /**
32544 * The base implementation of `_.sampleSize` without param guards.
32545 *
32546 * @private
32547 * @param {Array|Object} collection The collection to sample.
32548 * @param {number} n The number of elements to sample.
32549 * @returns {Array} Returns the random elements.
32550 */
32551 function baseSampleSize(collection, n) {
32552 var array = values(collection);
32553 return shuffleSelf(array, baseClamp(n, 0, array.length));
32554 }
32555
32556 /**
32557 * The base implementation of `_.set`.
32558 *
32559 * @private
32560 * @param {Object} object The object to modify.
32561 * @param {Array|string} path The path of the property to set.
32562 * @param {*} value The value to set.
32563 * @param {Function} [customizer] The function to customize path creation.
32564 * @returns {Object} Returns `object`.
32565 */
32566 function baseSet(object, path, value, customizer) {
32567 if (!isObject(object)) {
32568 return object;
32569 }
32570 path = castPath(path, object);
32571
32572 var index = -1,
32573 length = path.length,
32574 lastIndex = length - 1,
32575 nested = object;
32576
32577 while (nested != null && ++index < length) {
32578 var key = toKey(path[index]),
32579 newValue = value;
32580
32581 if (index != lastIndex) {
32582 var objValue = nested[key];
32583 newValue = customizer ? customizer(objValue, key, nested) : undefined;
32584 if (newValue === undefined) {
32585 newValue = isObject(objValue)
32586 ? objValue
32587 : (isIndex(path[index + 1]) ? [] : {});
32588 }
32589 }
32590 assignValue(nested, key, newValue);
32591 nested = nested[key];
32592 }
32593 return object;
32594 }
32595
32596 /**
32597 * The base implementation of `setData` without support for hot loop shorting.
32598 *
32599 * @private
32600 * @param {Function} func The function to associate metadata with.
32601 * @param {*} data The metadata.
32602 * @returns {Function} Returns `func`.
32603 */
32604 var baseSetData = !metaMap ? identity : function(func, data) {
32605 metaMap.set(func, data);
32606 return func;
32607 };
32608
32609 /**
32610 * The base implementation of `setToString` without support for hot loop shorting.
32611 *
32612 * @private
32613 * @param {Function} func The function to modify.
32614 * @param {Function} string The `toString` result.
32615 * @returns {Function} Returns `func`.
32616 */
32617 var baseSetToString = !defineProperty ? identity : function(func, string) {
32618 return defineProperty(func, 'toString', {
32619 'configurable': true,
32620 'enumerable': false,
32621 'value': constant(string),
32622 'writable': true
32623 });
32624 };
32625
32626 /**
32627 * The base implementation of `_.shuffle`.
32628 *
32629 * @private
32630 * @param {Array|Object} collection The collection to shuffle.
32631 * @returns {Array} Returns the new shuffled array.
32632 */
32633 function baseShuffle(collection) {
32634 return shuffleSelf(values(collection));
32635 }
32636
32637 /**
32638 * The base implementation of `_.slice` without an iteratee call guard.
32639 *
32640 * @private
32641 * @param {Array} array The array to slice.
32642 * @param {number} [start=0] The start position.
32643 * @param {number} [end=array.length] The end position.
32644 * @returns {Array} Returns the slice of `array`.
32645 */
32646 function baseSlice(array, start, end) {
32647 var index = -1,
32648 length = array.length;
32649
32650 if (start < 0) {
32651 start = -start > length ? 0 : (length + start);
32652 }
32653 end = end > length ? length : end;
32654 if (end < 0) {
32655 end += length;
32656 }
32657 length = start > end ? 0 : ((end - start) >>> 0);
32658 start >>>= 0;
32659
32660 var result = Array(length);
32661 while (++index < length) {
32662 result[index] = array[index + start];
32663 }
32664 return result;
32665 }
32666
32667 /**
32668 * The base implementation of `_.some` without support for iteratee shorthands.
32669 *
32670 * @private
32671 * @param {Array|Object} collection The collection to iterate over.
32672 * @param {Function} predicate The function invoked per iteration.
32673 * @returns {boolean} Returns `true` if any element passes the predicate check,
32674 * else `false`.
32675 */
32676 function baseSome(collection, predicate) {
32677 var result;
32678
32679 baseEach(collection, function(value, index, collection) {
32680 result = predicate(value, index, collection);
32681 return !result;
32682 });
32683 return !!result;
32684 }
32685
32686 /**
32687 * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
32688 * performs a binary search of `array` to determine the index at which `value`
32689 * should be inserted into `array` in order to maintain its sort order.
32690 *
32691 * @private
32692 * @param {Array} array The sorted array to inspect.
32693 * @param {*} value The value to evaluate.
32694 * @param {boolean} [retHighest] Specify returning the highest qualified index.
32695 * @returns {number} Returns the index at which `value` should be inserted
32696 * into `array`.
32697 */
32698 function baseSortedIndex(array, value, retHighest) {
32699 var low = 0,
32700 high = array == null ? low : array.length;
32701
32702 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
32703 while (low < high) {
32704 var mid = (low + high) >>> 1,
32705 computed = array[mid];
32706
32707 if (computed !== null && !isSymbol(computed) &&
32708 (retHighest ? (computed <= value) : (computed < value))) {
32709 low = mid + 1;
32710 } else {
32711 high = mid;
32712 }
32713 }
32714 return high;
32715 }
32716 return baseSortedIndexBy(array, value, identity, retHighest);
32717 }
32718
32719 /**
32720 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
32721 * which invokes `iteratee` for `value` and each element of `array` to compute
32722 * their sort ranking. The iteratee is invoked with one argument; (value).
32723 *
32724 * @private
32725 * @param {Array} array The sorted array to inspect.
32726 * @param {*} value The value to evaluate.
32727 * @param {Function} iteratee The iteratee invoked per element.
32728 * @param {boolean} [retHighest] Specify returning the highest qualified index.
32729 * @returns {number} Returns the index at which `value` should be inserted
32730 * into `array`.
32731 */
32732 function baseSortedIndexBy(array, value, iteratee, retHighest) {
32733 value = iteratee(value);
32734
32735 var low = 0,
32736 high = array == null ? 0 : array.length,
32737 valIsNaN = value !== value,
32738 valIsNull = value === null,
32739 valIsSymbol = isSymbol(value),
32740 valIsUndefined = value === undefined;
32741
32742 while (low < high) {
32743 var mid = nativeFloor((low + high) / 2),
32744 computed = iteratee(array[mid]),
32745 othIsDefined = computed !== undefined,
32746 othIsNull = computed === null,
32747 othIsReflexive = computed === computed,
32748 othIsSymbol = isSymbol(computed);
32749
32750 if (valIsNaN) {
32751 var setLow = retHighest || othIsReflexive;
32752 } else if (valIsUndefined) {
32753 setLow = othIsReflexive && (retHighest || othIsDefined);
32754 } else if (valIsNull) {
32755 setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
32756 } else if (valIsSymbol) {
32757 setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
32758 } else if (othIsNull || othIsSymbol) {
32759 setLow = false;
32760 } else {
32761 setLow = retHighest ? (computed <= value) : (computed < value);
32762 }
32763 if (setLow) {
32764 low = mid + 1;
32765 } else {
32766 high = mid;
32767 }
32768 }
32769 return nativeMin(high, MAX_ARRAY_INDEX);
32770 }
32771
32772 /**
32773 * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
32774 * support for iteratee shorthands.
32775 *
32776 * @private
32777 * @param {Array} array The array to inspect.
32778 * @param {Function} [iteratee] The iteratee invoked per element.
32779 * @returns {Array} Returns the new duplicate free array.
32780 */
32781 function baseSortedUniq(array, iteratee) {
32782 var index = -1,
32783 length = array.length,
32784 resIndex = 0,
32785 result = [];
32786
32787 while (++index < length) {
32788 var value = array[index],
32789 computed = iteratee ? iteratee(value) : value;
32790
32791 if (!index || !eq(computed, seen)) {
32792 var seen = computed;
32793 result[resIndex++] = value === 0 ? 0 : value;
32794 }
32795 }
32796 return result;
32797 }
32798
32799 /**
32800 * The base implementation of `_.toNumber` which doesn't ensure correct
32801 * conversions of binary, hexadecimal, or octal string values.
32802 *
32803 * @private
32804 * @param {*} value The value to process.
32805 * @returns {number} Returns the number.
32806 */
32807 function baseToNumber(value) {
32808 if (typeof value == 'number') {
32809 return value;
32810 }
32811 if (isSymbol(value)) {
32812 return NAN;
32813 }
32814 return +value;
32815 }
32816
32817 /**
32818 * The base implementation of `_.toString` which doesn't convert nullish
32819 * values to empty strings.
32820 *
32821 * @private
32822 * @param {*} value The value to process.
32823 * @returns {string} Returns the string.
32824 */
32825 function baseToString(value) {
32826 // Exit early for strings to avoid a performance hit in some environments.
32827 if (typeof value == 'string') {
32828 return value;
32829 }
32830 if (isArray(value)) {
32831 // Recursively convert values (susceptible to call stack limits).
32832 return arrayMap(value, baseToString) + '';
32833 }
32834 if (isSymbol(value)) {
32835 return symbolToString ? symbolToString.call(value) : '';
32836 }
32837 var result = (value + '');
32838 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
32839 }
32840
32841 /**
32842 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
32843 *
32844 * @private
32845 * @param {Array} array The array to inspect.
32846 * @param {Function} [iteratee] The iteratee invoked per element.
32847 * @param {Function} [comparator] The comparator invoked per element.
32848 * @returns {Array} Returns the new duplicate free array.
32849 */
32850 function baseUniq(array, iteratee, comparator) {
32851 var index = -1,
32852 includes = arrayIncludes,
32853 length = array.length,
32854 isCommon = true,
32855 result = [],
32856 seen = result;
32857
32858 if (comparator) {
32859 isCommon = false;
32860 includes = arrayIncludesWith;
32861 }
32862 else if (length >= LARGE_ARRAY_SIZE) {
32863 var set = iteratee ? null : createSet(array);
32864 if (set) {
32865 return setToArray(set);
32866 }
32867 isCommon = false;
32868 includes = cacheHas;
32869 seen = new SetCache;
32870 }
32871 else {
32872 seen = iteratee ? [] : result;
32873 }
32874 outer:
32875 while (++index < length) {
32876 var value = array[index],
32877 computed = iteratee ? iteratee(value) : value;
32878
32879 value = (comparator || value !== 0) ? value : 0;
32880 if (isCommon && computed === computed) {
32881 var seenIndex = seen.length;
32882 while (seenIndex--) {
32883 if (seen[seenIndex] === computed) {
32884 continue outer;
32885 }
32886 }
32887 if (iteratee) {
32888 seen.push(computed);
32889 }
32890 result.push(value);
32891 }
32892 else if (!includes(seen, computed, comparator)) {
32893 if (seen !== result) {
32894 seen.push(computed);
32895 }
32896 result.push(value);
32897 }
32898 }
32899 return result;
32900 }
32901
32902 /**
32903 * The base implementation of `_.unset`.
32904 *
32905 * @private
32906 * @param {Object} object The object to modify.
32907 * @param {Array|string} path The property path to unset.
32908 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
32909 */
32910 function baseUnset(object, path) {
32911 path = castPath(path, object);
32912 object = parent(object, path);
32913 return object == null || delete object[toKey(last(path))];
32914 }
32915
32916 /**
32917 * The base implementation of `_.update`.
32918 *
32919 * @private
32920 * @param {Object} object The object to modify.
32921 * @param {Array|string} path The path of the property to update.
32922 * @param {Function} updater The function to produce the updated value.
32923 * @param {Function} [customizer] The function to customize path creation.
32924 * @returns {Object} Returns `object`.
32925 */
32926 function baseUpdate(object, path, updater, customizer) {
32927 return baseSet(object, path, updater(baseGet(object, path)), customizer);
32928 }
32929
32930 /**
32931 * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
32932 * without support for iteratee shorthands.
32933 *
32934 * @private
32935 * @param {Array} array The array to query.
32936 * @param {Function} predicate The function invoked per iteration.
32937 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
32938 * @param {boolean} [fromRight] Specify iterating from right to left.
32939 * @returns {Array} Returns the slice of `array`.
32940 */
32941 function baseWhile(array, predicate, isDrop, fromRight) {
32942 var length = array.length,
32943 index = fromRight ? length : -1;
32944
32945 while ((fromRight ? index-- : ++index < length) &&
32946 predicate(array[index], index, array)) {}
32947
32948 return isDrop
32949 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
32950 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
32951 }
32952
32953 /**
32954 * The base implementation of `wrapperValue` which returns the result of
32955 * performing a sequence of actions on the unwrapped `value`, where each
32956 * successive action is supplied the return value of the previous.
32957 *
32958 * @private
32959 * @param {*} value The unwrapped value.
32960 * @param {Array} actions Actions to perform to resolve the unwrapped value.
32961 * @returns {*} Returns the resolved value.
32962 */
32963 function baseWrapperValue(value, actions) {
32964 var result = value;
32965 if (result instanceof LazyWrapper) {
32966 result = result.value();
32967 }
32968 return arrayReduce(actions, function(result, action) {
32969 return action.func.apply(action.thisArg, arrayPush([result], action.args));
32970 }, result);
32971 }
32972
32973 /**
32974 * The base implementation of methods like `_.xor`, without support for
32975 * iteratee shorthands, that accepts an array of arrays to inspect.
32976 *
32977 * @private
32978 * @param {Array} arrays The arrays to inspect.
32979 * @param {Function} [iteratee] The iteratee invoked per element.
32980 * @param {Function} [comparator] The comparator invoked per element.
32981 * @returns {Array} Returns the new array of values.
32982 */
32983 function baseXor(arrays, iteratee, comparator) {
32984 var length = arrays.length;
32985 if (length < 2) {
32986 return length ? baseUniq(arrays[0]) : [];
32987 }
32988 var index = -1,
32989 result = Array(length);
32990
32991 while (++index < length) {
32992 var array = arrays[index],
32993 othIndex = -1;
32994
32995 while (++othIndex < length) {
32996 if (othIndex != index) {
32997 result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
32998 }
32999 }
33000 }
33001 return baseUniq(baseFlatten(result, 1), iteratee, comparator);
33002 }
33003
33004 /**
33005 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
33006 *
33007 * @private
33008 * @param {Array} props The property identifiers.
33009 * @param {Array} values The property values.
33010 * @param {Function} assignFunc The function to assign values.
33011 * @returns {Object} Returns the new object.
33012 */
33013 function baseZipObject(props, values, assignFunc) {
33014 var index = -1,
33015 length = props.length,
33016 valsLength = values.length,
33017 result = {};
33018
33019 while (++index < length) {
33020 var value = index < valsLength ? values[index] : undefined;
33021 assignFunc(result, props[index], value);
33022 }
33023 return result;
33024 }
33025
33026 /**
33027 * Casts `value` to an empty array if it's not an array like object.
33028 *
33029 * @private
33030 * @param {*} value The value to inspect.
33031 * @returns {Array|Object} Returns the cast array-like object.
33032 */
33033 function castArrayLikeObject(value) {
33034 return isArrayLikeObject(value) ? value : [];
33035 }
33036
33037 /**
33038 * Casts `value` to `identity` if it's not a function.
33039 *
33040 * @private
33041 * @param {*} value The value to inspect.
33042 * @returns {Function} Returns cast function.
33043 */
33044 function castFunction(value) {
33045 return typeof value == 'function' ? value : identity;
33046 }
33047
33048 /**
33049 * Casts `value` to a path array if it's not one.
33050 *
33051 * @private
33052 * @param {*} value The value to inspect.
33053 * @param {Object} [object] The object to query keys on.
33054 * @returns {Array} Returns the cast property path array.
33055 */
33056 function castPath(value, object) {
33057 if (isArray(value)) {
33058 return value;
33059 }
33060 return isKey(value, object) ? [value] : stringToPath(toString(value));
33061 }
33062
33063 /**
33064 * A `baseRest` alias which can be replaced with `identity` by module
33065 * replacement plugins.
33066 *
33067 * @private
33068 * @type {Function}
33069 * @param {Function} func The function to apply a rest parameter to.
33070 * @returns {Function} Returns the new function.
33071 */
33072 var castRest = baseRest;
33073
33074 /**
33075 * Casts `array` to a slice if it's needed.
33076 *
33077 * @private
33078 * @param {Array} array The array to inspect.
33079 * @param {number} start The start position.
33080 * @param {number} [end=array.length] The end position.
33081 * @returns {Array} Returns the cast slice.
33082 */
33083 function castSlice(array, start, end) {
33084 var length = array.length;
33085 end = end === undefined ? length : end;
33086 return (!start && end >= length) ? array : baseSlice(array, start, end);
33087 }
33088
33089 /**
33090 * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
33091 *
33092 * @private
33093 * @param {number|Object} id The timer id or timeout object of the timer to clear.
33094 */
33095 var clearTimeout = ctxClearTimeout || function(id) {
33096 return root.clearTimeout(id);
33097 };
33098
33099 /**
33100 * Creates a clone of `buffer`.
33101 *
33102 * @private
33103 * @param {Buffer} buffer The buffer to clone.
33104 * @param {boolean} [isDeep] Specify a deep clone.
33105 * @returns {Buffer} Returns the cloned buffer.
33106 */
33107 function cloneBuffer(buffer, isDeep) {
33108 if (isDeep) {
33109 return buffer.slice();
33110 }
33111 var length = buffer.length,
33112 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
33113
33114 buffer.copy(result);
33115 return result;
33116 }
33117
33118 /**
33119 * Creates a clone of `arrayBuffer`.
33120 *
33121 * @private
33122 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
33123 * @returns {ArrayBuffer} Returns the cloned array buffer.
33124 */
33125 function cloneArrayBuffer(arrayBuffer) {
33126 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
33127 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
33128 return result;
33129 }
33130
33131 /**
33132 * Creates a clone of `dataView`.
33133 *
33134 * @private
33135 * @param {Object} dataView The data view to clone.
33136 * @param {boolean} [isDeep] Specify a deep clone.
33137 * @returns {Object} Returns the cloned data view.
33138 */
33139 function cloneDataView(dataView, isDeep) {
33140 var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
33141 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
33142 }
33143
33144 /**
33145 * Creates a clone of `regexp`.
33146 *
33147 * @private
33148 * @param {Object} regexp The regexp to clone.
33149 * @returns {Object} Returns the cloned regexp.
33150 */
33151 function cloneRegExp(regexp) {
33152 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
33153 result.lastIndex = regexp.lastIndex;
33154 return result;
33155 }
33156
33157 /**
33158 * Creates a clone of the `symbol` object.
33159 *
33160 * @private
33161 * @param {Object} symbol The symbol object to clone.
33162 * @returns {Object} Returns the cloned symbol object.
33163 */
33164 function cloneSymbol(symbol) {
33165 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
33166 }
33167
33168 /**
33169 * Creates a clone of `typedArray`.
33170 *
33171 * @private
33172 * @param {Object} typedArray The typed array to clone.
33173 * @param {boolean} [isDeep] Specify a deep clone.
33174 * @returns {Object} Returns the cloned typed array.
33175 */
33176 function cloneTypedArray(typedArray, isDeep) {
33177 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
33178 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
33179 }
33180
33181 /**
33182 * Compares values to sort them in ascending order.
33183 *
33184 * @private
33185 * @param {*} value The value to compare.
33186 * @param {*} other The other value to compare.
33187 * @returns {number} Returns the sort order indicator for `value`.
33188 */
33189 function compareAscending(value, other) {
33190 if (value !== other) {
33191 var valIsDefined = value !== undefined,
33192 valIsNull = value === null,
33193 valIsReflexive = value === value,
33194 valIsSymbol = isSymbol(value);
33195
33196 var othIsDefined = other !== undefined,
33197 othIsNull = other === null,
33198 othIsReflexive = other === other,
33199 othIsSymbol = isSymbol(other);
33200
33201 if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
33202 (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
33203 (valIsNull && othIsDefined && othIsReflexive) ||
33204 (!valIsDefined && othIsReflexive) ||
33205 !valIsReflexive) {
33206 return 1;
33207 }
33208 if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
33209 (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
33210 (othIsNull && valIsDefined && valIsReflexive) ||
33211 (!othIsDefined && valIsReflexive) ||
33212 !othIsReflexive) {
33213 return -1;
33214 }
33215 }
33216 return 0;
33217 }
33218
33219 /**
33220 * Used by `_.orderBy` to compare multiple properties of a value to another
33221 * and stable sort them.
33222 *
33223 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
33224 * specify an order of "desc" for descending or "asc" for ascending sort order
33225 * of corresponding values.
33226 *
33227 * @private
33228 * @param {Object} object The object to compare.
33229 * @param {Object} other The other object to compare.
33230 * @param {boolean[]|string[]} orders The order to sort by for each property.
33231 * @returns {number} Returns the sort order indicator for `object`.
33232 */
33233 function compareMultiple(object, other, orders) {
33234 var index = -1,
33235 objCriteria = object.criteria,
33236 othCriteria = other.criteria,
33237 length = objCriteria.length,
33238 ordersLength = orders.length;
33239
33240 while (++index < length) {
33241 var result = compareAscending(objCriteria[index], othCriteria[index]);
33242 if (result) {
33243 if (index >= ordersLength) {
33244 return result;
33245 }
33246 var order = orders[index];
33247 return result * (order == 'desc' ? -1 : 1);
33248 }
33249 }
33250 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
33251 // that causes it, under certain circumstances, to provide the same value for
33252 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
33253 // for more details.
33254 //
33255 // This also ensures a stable sort in V8 and other engines.
33256 // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
33257 return object.index - other.index;
33258 }
33259
33260 /**
33261 * Creates an array that is the composition of partially applied arguments,
33262 * placeholders, and provided arguments into a single array of arguments.
33263 *
33264 * @private
33265 * @param {Array} args The provided arguments.
33266 * @param {Array} partials The arguments to prepend to those provided.
33267 * @param {Array} holders The `partials` placeholder indexes.
33268 * @params {boolean} [isCurried] Specify composing for a curried function.
33269 * @returns {Array} Returns the new array of composed arguments.
33270 */
33271 function composeArgs(args, partials, holders, isCurried) {
33272 var argsIndex = -1,
33273 argsLength = args.length,
33274 holdersLength = holders.length,
33275 leftIndex = -1,
33276 leftLength = partials.length,
33277 rangeLength = nativeMax(argsLength - holdersLength, 0),
33278 result = Array(leftLength + rangeLength),
33279 isUncurried = !isCurried;
33280
33281 while (++leftIndex < leftLength) {
33282 result[leftIndex] = partials[leftIndex];
33283 }
33284 while (++argsIndex < holdersLength) {
33285 if (isUncurried || argsIndex < argsLength) {
33286 result[holders[argsIndex]] = args[argsIndex];
33287 }
33288 }
33289 while (rangeLength--) {
33290 result[leftIndex++] = args[argsIndex++];
33291 }
33292 return result;
33293 }
33294
33295 /**
33296 * This function is like `composeArgs` except that the arguments composition
33297 * is tailored for `_.partialRight`.
33298 *
33299 * @private
33300 * @param {Array} args The provided arguments.
33301 * @param {Array} partials The arguments to append to those provided.
33302 * @param {Array} holders The `partials` placeholder indexes.
33303 * @params {boolean} [isCurried] Specify composing for a curried function.
33304 * @returns {Array} Returns the new array of composed arguments.
33305 */
33306 function composeArgsRight(args, partials, holders, isCurried) {
33307 var argsIndex = -1,
33308 argsLength = args.length,
33309 holdersIndex = -1,
33310 holdersLength = holders.length,
33311 rightIndex = -1,
33312 rightLength = partials.length,
33313 rangeLength = nativeMax(argsLength - holdersLength, 0),
33314 result = Array(rangeLength + rightLength),
33315 isUncurried = !isCurried;
33316
33317 while (++argsIndex < rangeLength) {
33318 result[argsIndex] = args[argsIndex];
33319 }
33320 var offset = argsIndex;
33321 while (++rightIndex < rightLength) {
33322 result[offset + rightIndex] = partials[rightIndex];
33323 }
33324 while (++holdersIndex < holdersLength) {
33325 if (isUncurried || argsIndex < argsLength) {
33326 result[offset + holders[holdersIndex]] = args[argsIndex++];
33327 }
33328 }
33329 return result;
33330 }
33331
33332 /**
33333 * Copies the values of `source` to `array`.
33334 *
33335 * @private
33336 * @param {Array} source The array to copy values from.
33337 * @param {Array} [array=[]] The array to copy values to.
33338 * @returns {Array} Returns `array`.
33339 */
33340 function copyArray(source, array) {
33341 var index = -1,
33342 length = source.length;
33343
33344 array || (array = Array(length));
33345 while (++index < length) {
33346 array[index] = source[index];
33347 }
33348 return array;
33349 }
33350
33351 /**
33352 * Copies properties of `source` to `object`.
33353 *
33354 * @private
33355 * @param {Object} source The object to copy properties from.
33356 * @param {Array} props The property identifiers to copy.
33357 * @param {Object} [object={}] The object to copy properties to.
33358 * @param {Function} [customizer] The function to customize copied values.
33359 * @returns {Object} Returns `object`.
33360 */
33361 function copyObject(source, props, object, customizer) {
33362 var isNew = !object;
33363 object || (object = {});
33364
33365 var index = -1,
33366 length = props.length;
33367
33368 while (++index < length) {
33369 var key = props[index];
33370
33371 var newValue = customizer
33372 ? customizer(object[key], source[key], key, object, source)
33373 : undefined;
33374
33375 if (newValue === undefined) {
33376 newValue = source[key];
33377 }
33378 if (isNew) {
33379 baseAssignValue(object, key, newValue);
33380 } else {
33381 assignValue(object, key, newValue);
33382 }
33383 }
33384 return object;
33385 }
33386
33387 /**
33388 * Copies own symbols of `source` to `object`.
33389 *
33390 * @private
33391 * @param {Object} source The object to copy symbols from.
33392 * @param {Object} [object={}] The object to copy symbols to.
33393 * @returns {Object} Returns `object`.
33394 */
33395 function copySymbols(source, object) {
33396 return copyObject(source, getSymbols(source), object);
33397 }
33398
33399 /**
33400 * Copies own and inherited symbols of `source` to `object`.
33401 *
33402 * @private
33403 * @param {Object} source The object to copy symbols from.
33404 * @param {Object} [object={}] The object to copy symbols to.
33405 * @returns {Object} Returns `object`.
33406 */
33407 function copySymbolsIn(source, object) {
33408 return copyObject(source, getSymbolsIn(source), object);
33409 }
33410
33411 /**
33412 * Creates a function like `_.groupBy`.
33413 *
33414 * @private
33415 * @param {Function} setter The function to set accumulator values.
33416 * @param {Function} [initializer] The accumulator object initializer.
33417 * @returns {Function} Returns the new aggregator function.
33418 */
33419 function createAggregator(setter, initializer) {
33420 return function(collection, iteratee) {
33421 var func = isArray(collection) ? arrayAggregator : baseAggregator,
33422 accumulator = initializer ? initializer() : {};
33423
33424 return func(collection, setter, getIteratee(iteratee, 2), accumulator);
33425 };
33426 }
33427
33428 /**
33429 * Creates a function like `_.assign`.
33430 *
33431 * @private
33432 * @param {Function} assigner The function to assign values.
33433 * @returns {Function} Returns the new assigner function.
33434 */
33435 function createAssigner(assigner) {
33436 return baseRest(function(object, sources) {
33437 var index = -1,
33438 length = sources.length,
33439 customizer = length > 1 ? sources[length - 1] : undefined,
33440 guard = length > 2 ? sources[2] : undefined;
33441
33442 customizer = (assigner.length > 3 && typeof customizer == 'function')
33443 ? (length--, customizer)
33444 : undefined;
33445
33446 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
33447 customizer = length < 3 ? undefined : customizer;
33448 length = 1;
33449 }
33450 object = Object(object);
33451 while (++index < length) {
33452 var source = sources[index];
33453 if (source) {
33454 assigner(object, source, index, customizer);
33455 }
33456 }
33457 return object;
33458 });
33459 }
33460
33461 /**
33462 * Creates a `baseEach` or `baseEachRight` function.
33463 *
33464 * @private
33465 * @param {Function} eachFunc The function to iterate over a collection.
33466 * @param {boolean} [fromRight] Specify iterating from right to left.
33467 * @returns {Function} Returns the new base function.
33468 */
33469 function createBaseEach(eachFunc, fromRight) {
33470 return function(collection, iteratee) {
33471 if (collection == null) {
33472 return collection;
33473 }
33474 if (!isArrayLike(collection)) {
33475 return eachFunc(collection, iteratee);
33476 }
33477 var length = collection.length,
33478 index = fromRight ? length : -1,
33479 iterable = Object(collection);
33480
33481 while ((fromRight ? index-- : ++index < length)) {
33482 if (iteratee(iterable[index], index, iterable) === false) {
33483 break;
33484 }
33485 }
33486 return collection;
33487 };
33488 }
33489
33490 /**
33491 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
33492 *
33493 * @private
33494 * @param {boolean} [fromRight] Specify iterating from right to left.
33495 * @returns {Function} Returns the new base function.
33496 */
33497 function createBaseFor(fromRight) {
33498 return function(object, iteratee, keysFunc) {
33499 var index = -1,
33500 iterable = Object(object),
33501 props = keysFunc(object),
33502 length = props.length;
33503
33504 while (length--) {
33505 var key = props[fromRight ? length : ++index];
33506 if (iteratee(iterable[key], key, iterable) === false) {
33507 break;
33508 }
33509 }
33510 return object;
33511 };
33512 }
33513
33514 /**
33515 * Creates a function that wraps `func` to invoke it with the optional `this`
33516 * binding of `thisArg`.
33517 *
33518 * @private
33519 * @param {Function} func The function to wrap.
33520 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
33521 * @param {*} [thisArg] The `this` binding of `func`.
33522 * @returns {Function} Returns the new wrapped function.
33523 */
33524 function createBind(func, bitmask, thisArg) {
33525 var isBind = bitmask & WRAP_BIND_FLAG,
33526 Ctor = createCtor(func);
33527
33528 function wrapper() {
33529 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
33530 return fn.apply(isBind ? thisArg : this, arguments);
33531 }
33532 return wrapper;
33533 }
33534
33535 /**
33536 * Creates a function like `_.lowerFirst`.
33537 *
33538 * @private
33539 * @param {string} methodName The name of the `String` case method to use.
33540 * @returns {Function} Returns the new case function.
33541 */
33542 function createCaseFirst(methodName) {
33543 return function(string) {
33544 string = toString(string);
33545
33546 var strSymbols = hasUnicode(string)
33547 ? stringToArray(string)
33548 : undefined;
33549
33550 var chr = strSymbols
33551 ? strSymbols[0]
33552 : string.charAt(0);
33553
33554 var trailing = strSymbols
33555 ? castSlice(strSymbols, 1).join('')
33556 : string.slice(1);
33557
33558 return chr[methodName]() + trailing;
33559 };
33560 }
33561
33562 /**
33563 * Creates a function like `_.camelCase`.
33564 *
33565 * @private
33566 * @param {Function} callback The function to combine each word.
33567 * @returns {Function} Returns the new compounder function.
33568 */
33569 function createCompounder(callback) {
33570 return function(string) {
33571 return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
33572 };
33573 }
33574
33575 /**
33576 * Creates a function that produces an instance of `Ctor` regardless of
33577 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
33578 *
33579 * @private
33580 * @param {Function} Ctor The constructor to wrap.
33581 * @returns {Function} Returns the new wrapped function.
33582 */
33583 function createCtor(Ctor) {
33584 return function() {
33585 // Use a `switch` statement to work with class constructors. See
33586 // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
33587 // for more details.
33588 var args = arguments;
33589 switch (args.length) {
33590 case 0: return new Ctor;
33591 case 1: return new Ctor(args[0]);
33592 case 2: return new Ctor(args[0], args[1]);
33593 case 3: return new Ctor(args[0], args[1], args[2]);
33594 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
33595 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
33596 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
33597 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
33598 }
33599 var thisBinding = baseCreate(Ctor.prototype),
33600 result = Ctor.apply(thisBinding, args);
33601
33602 // Mimic the constructor's `return` behavior.
33603 // See https://es5.github.io/#x13.2.2 for more details.
33604 return isObject(result) ? result : thisBinding;
33605 };
33606 }
33607
33608 /**
33609 * Creates a function that wraps `func` to enable currying.
33610 *
33611 * @private
33612 * @param {Function} func The function to wrap.
33613 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
33614 * @param {number} arity The arity of `func`.
33615 * @returns {Function} Returns the new wrapped function.
33616 */
33617 function createCurry(func, bitmask, arity) {
33618 var Ctor = createCtor(func);
33619
33620 function wrapper() {
33621 var length = arguments.length,
33622 args = Array(length),
33623 index = length,
33624 placeholder = getHolder(wrapper);
33625
33626 while (index--) {
33627 args[index] = arguments[index];
33628 }
33629 var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
33630 ? []
33631 : replaceHolders(args, placeholder);
33632
33633 length -= holders.length;
33634 if (length < arity) {
33635 return createRecurry(
33636 func, bitmask, createHybrid, wrapper.placeholder, undefined,
33637 args, holders, undefined, undefined, arity - length);
33638 }
33639 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
33640 return apply(fn, this, args);
33641 }
33642 return wrapper;
33643 }
33644
33645 /**
33646 * Creates a `_.find` or `_.findLast` function.
33647 *
33648 * @private
33649 * @param {Function} findIndexFunc The function to find the collection index.
33650 * @returns {Function} Returns the new find function.
33651 */
33652 function createFind(findIndexFunc) {
33653 return function(collection, predicate, fromIndex) {
33654 var iterable = Object(collection);
33655 if (!isArrayLike(collection)) {
33656 var iteratee = getIteratee(predicate, 3);
33657 collection = keys(collection);
33658 predicate = function(key) { return iteratee(iterable[key], key, iterable); };
33659 }
33660 var index = findIndexFunc(collection, predicate, fromIndex);
33661 return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
33662 };
33663 }
33664
33665 /**
33666 * Creates a `_.flow` or `_.flowRight` function.
33667 *
33668 * @private
33669 * @param {boolean} [fromRight] Specify iterating from right to left.
33670 * @returns {Function} Returns the new flow function.
33671 */
33672 function createFlow(fromRight) {
33673 return flatRest(function(funcs) {
33674 var length = funcs.length,
33675 index = length,
33676 prereq = LodashWrapper.prototype.thru;
33677
33678 if (fromRight) {
33679 funcs.reverse();
33680 }
33681 while (index--) {
33682 var func = funcs[index];
33683 if (typeof func != 'function') {
33684 throw new TypeError(FUNC_ERROR_TEXT);
33685 }
33686 if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
33687 var wrapper = new LodashWrapper([], true);
33688 }
33689 }
33690 index = wrapper ? index : length;
33691 while (++index < length) {
33692 func = funcs[index];
33693
33694 var funcName = getFuncName(func),
33695 data = funcName == 'wrapper' ? getData(func) : undefined;
33696
33697 if (data && isLaziable(data[0]) &&
33698 data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
33699 !data[4].length && data[9] == 1
33700 ) {
33701 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
33702 } else {
33703 wrapper = (func.length == 1 && isLaziable(func))
33704 ? wrapper[funcName]()
33705 : wrapper.thru(func);
33706 }
33707 }
33708 return function() {
33709 var args = arguments,
33710 value = args[0];
33711
33712 if (wrapper && args.length == 1 && isArray(value)) {
33713 return wrapper.plant(value).value();
33714 }
33715 var index = 0,
33716 result = length ? funcs[index].apply(this, args) : value;
33717
33718 while (++index < length) {
33719 result = funcs[index].call(this, result);
33720 }
33721 return result;
33722 };
33723 });
33724 }
33725
33726 /**
33727 * Creates a function that wraps `func` to invoke it with optional `this`
33728 * binding of `thisArg`, partial application, and currying.
33729 *
33730 * @private
33731 * @param {Function|string} func The function or method name to wrap.
33732 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
33733 * @param {*} [thisArg] The `this` binding of `func`.
33734 * @param {Array} [partials] The arguments to prepend to those provided to
33735 * the new function.
33736 * @param {Array} [holders] The `partials` placeholder indexes.
33737 * @param {Array} [partialsRight] The arguments to append to those provided
33738 * to the new function.
33739 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
33740 * @param {Array} [argPos] The argument positions of the new function.
33741 * @param {number} [ary] The arity cap of `func`.
33742 * @param {number} [arity] The arity of `func`.
33743 * @returns {Function} Returns the new wrapped function.
33744 */
33745 function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
33746 var isAry = bitmask & WRAP_ARY_FLAG,
33747 isBind = bitmask & WRAP_BIND_FLAG,
33748 isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
33749 isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
33750 isFlip = bitmask & WRAP_FLIP_FLAG,
33751 Ctor = isBindKey ? undefined : createCtor(func);
33752
33753 function wrapper() {
33754 var length = arguments.length,
33755 args = Array(length),
33756 index = length;
33757
33758 while (index--) {
33759 args[index] = arguments[index];
33760 }
33761 if (isCurried) {
33762 var placeholder = getHolder(wrapper),
33763 holdersCount = countHolders(args, placeholder);
33764 }
33765 if (partials) {
33766 args = composeArgs(args, partials, holders, isCurried);
33767 }
33768 if (partialsRight) {
33769 args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
33770 }
33771 length -= holdersCount;
33772 if (isCurried && length < arity) {
33773 var newHolders = replaceHolders(args, placeholder);
33774 return createRecurry(
33775 func, bitmask, createHybrid, wrapper.placeholder, thisArg,
33776 args, newHolders, argPos, ary, arity - length
33777 );
33778 }
33779 var thisBinding = isBind ? thisArg : this,
33780 fn = isBindKey ? thisBinding[func] : func;
33781
33782 length = args.length;
33783 if (argPos) {
33784 args = reorder(args, argPos);
33785 } else if (isFlip && length > 1) {
33786 args.reverse();
33787 }
33788 if (isAry && ary < length) {
33789 args.length = ary;
33790 }
33791 if (this && this !== root && this instanceof wrapper) {
33792 fn = Ctor || createCtor(fn);
33793 }
33794 return fn.apply(thisBinding, args);
33795 }
33796 return wrapper;
33797 }
33798
33799 /**
33800 * Creates a function like `_.invertBy`.
33801 *
33802 * @private
33803 * @param {Function} setter The function to set accumulator values.
33804 * @param {Function} toIteratee The function to resolve iteratees.
33805 * @returns {Function} Returns the new inverter function.
33806 */
33807 function createInverter(setter, toIteratee) {
33808 return function(object, iteratee) {
33809 return baseInverter(object, setter, toIteratee(iteratee), {});
33810 };
33811 }
33812
33813 /**
33814 * Creates a function that performs a mathematical operation on two values.
33815 *
33816 * @private
33817 * @param {Function} operator The function to perform the operation.
33818 * @param {number} [defaultValue] The value used for `undefined` arguments.
33819 * @returns {Function} Returns the new mathematical operation function.
33820 */
33821 function createMathOperation(operator, defaultValue) {
33822 return function(value, other) {
33823 var result;
33824 if (value === undefined && other === undefined) {
33825 return defaultValue;
33826 }
33827 if (value !== undefined) {
33828 result = value;
33829 }
33830 if (other !== undefined) {
33831 if (result === undefined) {
33832 return other;
33833 }
33834 if (typeof value == 'string' || typeof other == 'string') {
33835 value = baseToString(value);
33836 other = baseToString(other);
33837 } else {
33838 value = baseToNumber(value);
33839 other = baseToNumber(other);
33840 }
33841 result = operator(value, other);
33842 }
33843 return result;
33844 };
33845 }
33846
33847 /**
33848 * Creates a function like `_.over`.
33849 *
33850 * @private
33851 * @param {Function} arrayFunc The function to iterate over iteratees.
33852 * @returns {Function} Returns the new over function.
33853 */
33854 function createOver(arrayFunc) {
33855 return flatRest(function(iteratees) {
33856 iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
33857 return baseRest(function(args) {
33858 var thisArg = this;
33859 return arrayFunc(iteratees, function(iteratee) {
33860 return apply(iteratee, thisArg, args);
33861 });
33862 });
33863 });
33864 }
33865
33866 /**
33867 * Creates the padding for `string` based on `length`. The `chars` string
33868 * is truncated if the number of characters exceeds `length`.
33869 *
33870 * @private
33871 * @param {number} length The padding length.
33872 * @param {string} [chars=' '] The string used as padding.
33873 * @returns {string} Returns the padding for `string`.
33874 */
33875 function createPadding(length, chars) {
33876 chars = chars === undefined ? ' ' : baseToString(chars);
33877
33878 var charsLength = chars.length;
33879 if (charsLength < 2) {
33880 return charsLength ? baseRepeat(chars, length) : chars;
33881 }
33882 var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
33883 return hasUnicode(chars)
33884 ? castSlice(stringToArray(result), 0, length).join('')
33885 : result.slice(0, length);
33886 }
33887
33888 /**
33889 * Creates a function that wraps `func` to invoke it with the `this` binding
33890 * of `thisArg` and `partials` prepended to the arguments it receives.
33891 *
33892 * @private
33893 * @param {Function} func The function to wrap.
33894 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
33895 * @param {*} thisArg The `this` binding of `func`.
33896 * @param {Array} partials The arguments to prepend to those provided to
33897 * the new function.
33898 * @returns {Function} Returns the new wrapped function.
33899 */
33900 function createPartial(func, bitmask, thisArg, partials) {
33901 var isBind = bitmask & WRAP_BIND_FLAG,
33902 Ctor = createCtor(func);
33903
33904 function wrapper() {
33905 var argsIndex = -1,
33906 argsLength = arguments.length,
33907 leftIndex = -1,
33908 leftLength = partials.length,
33909 args = Array(leftLength + argsLength),
33910 fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
33911
33912 while (++leftIndex < leftLength) {
33913 args[leftIndex] = partials[leftIndex];
33914 }
33915 while (argsLength--) {
33916 args[leftIndex++] = arguments[++argsIndex];
33917 }
33918 return apply(fn, isBind ? thisArg : this, args);
33919 }
33920 return wrapper;
33921 }
33922
33923 /**
33924 * Creates a `_.range` or `_.rangeRight` function.
33925 *
33926 * @private
33927 * @param {boolean} [fromRight] Specify iterating from right to left.
33928 * @returns {Function} Returns the new range function.
33929 */
33930 function createRange(fromRight) {
33931 return function(start, end, step) {
33932 if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
33933 end = step = undefined;
33934 }
33935 // Ensure the sign of `-0` is preserved.
33936 start = toFinite(start);
33937 if (end === undefined) {
33938 end = start;
33939 start = 0;
33940 } else {
33941 end = toFinite(end);
33942 }
33943 step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
33944 return baseRange(start, end, step, fromRight);
33945 };
33946 }
33947
33948 /**
33949 * Creates a function that performs a relational operation on two values.
33950 *
33951 * @private
33952 * @param {Function} operator The function to perform the operation.
33953 * @returns {Function} Returns the new relational operation function.
33954 */
33955 function createRelationalOperation(operator) {
33956 return function(value, other) {
33957 if (!(typeof value == 'string' && typeof other == 'string')) {
33958 value = toNumber(value);
33959 other = toNumber(other);
33960 }
33961 return operator(value, other);
33962 };
33963 }
33964
33965 /**
33966 * Creates a function that wraps `func` to continue currying.
33967 *
33968 * @private
33969 * @param {Function} func The function to wrap.
33970 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
33971 * @param {Function} wrapFunc The function to create the `func` wrapper.
33972 * @param {*} placeholder The placeholder value.
33973 * @param {*} [thisArg] The `this` binding of `func`.
33974 * @param {Array} [partials] The arguments to prepend to those provided to
33975 * the new function.
33976 * @param {Array} [holders] The `partials` placeholder indexes.
33977 * @param {Array} [argPos] The argument positions of the new function.
33978 * @param {number} [ary] The arity cap of `func`.
33979 * @param {number} [arity] The arity of `func`.
33980 * @returns {Function} Returns the new wrapped function.
33981 */
33982 function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
33983 var isCurry = bitmask & WRAP_CURRY_FLAG,
33984 newHolders = isCurry ? holders : undefined,
33985 newHoldersRight = isCurry ? undefined : holders,
33986 newPartials = isCurry ? partials : undefined,
33987 newPartialsRight = isCurry ? undefined : partials;
33988
33989 bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
33990 bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
33991
33992 if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
33993 bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
33994 }
33995 var newData = [
33996 func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
33997 newHoldersRight, argPos, ary, arity
33998 ];
33999
34000 var result = wrapFunc.apply(undefined, newData);
34001 if (isLaziable(func)) {
34002 setData(result, newData);
34003 }
34004 result.placeholder = placeholder;
34005 return setWrapToString(result, func, bitmask);
34006 }
34007
34008 /**
34009 * Creates a function like `_.round`.
34010 *
34011 * @private
34012 * @param {string} methodName The name of the `Math` method to use when rounding.
34013 * @returns {Function} Returns the new round function.
34014 */
34015 function createRound(methodName) {
34016 var func = Math[methodName];
34017 return function(number, precision) {
34018 number = toNumber(number);
34019 precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
34020 if (precision && nativeIsFinite(number)) {
34021 // Shift with exponential notation to avoid floating-point issues.
34022 // See [MDN](https://mdn.io/round#Examples) for more details.
34023 var pair = (toString(number) + 'e').split('e'),
34024 value = func(pair[0] + 'e' + (+pair[1] + precision));
34025
34026 pair = (toString(value) + 'e').split('e');
34027 return +(pair[0] + 'e' + (+pair[1] - precision));
34028 }
34029 return func(number);
34030 };
34031 }
34032
34033 /**
34034 * Creates a set object of `values`.
34035 *
34036 * @private
34037 * @param {Array} values The values to add to the set.
34038 * @returns {Object} Returns the new set.
34039 */
34040 var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
34041 return new Set(values);
34042 };
34043
34044 /**
34045 * Creates a `_.toPairs` or `_.toPairsIn` function.
34046 *
34047 * @private
34048 * @param {Function} keysFunc The function to get the keys of a given object.
34049 * @returns {Function} Returns the new pairs function.
34050 */
34051 function createToPairs(keysFunc) {
34052 return function(object) {
34053 var tag = getTag(object);
34054 if (tag == mapTag) {
34055 return mapToArray(object);
34056 }
34057 if (tag == setTag) {
34058 return setToPairs(object);
34059 }
34060 return baseToPairs(object, keysFunc(object));
34061 };
34062 }
34063
34064 /**
34065 * Creates a function that either curries or invokes `func` with optional
34066 * `this` binding and partially applied arguments.
34067 *
34068 * @private
34069 * @param {Function|string} func The function or method name to wrap.
34070 * @param {number} bitmask The bitmask flags.
34071 * 1 - `_.bind`
34072 * 2 - `_.bindKey`
34073 * 4 - `_.curry` or `_.curryRight` of a bound function
34074 * 8 - `_.curry`
34075 * 16 - `_.curryRight`
34076 * 32 - `_.partial`
34077 * 64 - `_.partialRight`
34078 * 128 - `_.rearg`
34079 * 256 - `_.ary`
34080 * 512 - `_.flip`
34081 * @param {*} [thisArg] The `this` binding of `func`.
34082 * @param {Array} [partials] The arguments to be partially applied.
34083 * @param {Array} [holders] The `partials` placeholder indexes.
34084 * @param {Array} [argPos] The argument positions of the new function.
34085 * @param {number} [ary] The arity cap of `func`.
34086 * @param {number} [arity] The arity of `func`.
34087 * @returns {Function} Returns the new wrapped function.
34088 */
34089 function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
34090 var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
34091 if (!isBindKey && typeof func != 'function') {
34092 throw new TypeError(FUNC_ERROR_TEXT);
34093 }
34094 var length = partials ? partials.length : 0;
34095 if (!length) {
34096 bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
34097 partials = holders = undefined;
34098 }
34099 ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
34100 arity = arity === undefined ? arity : toInteger(arity);
34101 length -= holders ? holders.length : 0;
34102
34103 if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
34104 var partialsRight = partials,
34105 holdersRight = holders;
34106
34107 partials = holders = undefined;
34108 }
34109 var data = isBindKey ? undefined : getData(func);
34110
34111 var newData = [
34112 func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
34113 argPos, ary, arity
34114 ];
34115
34116 if (data) {
34117 mergeData(newData, data);
34118 }
34119 func = newData[0];
34120 bitmask = newData[1];
34121 thisArg = newData[2];
34122 partials = newData[3];
34123 holders = newData[4];
34124 arity = newData[9] = newData[9] === undefined
34125 ? (isBindKey ? 0 : func.length)
34126 : nativeMax(newData[9] - length, 0);
34127
34128 if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
34129 bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
34130 }
34131 if (!bitmask || bitmask == WRAP_BIND_FLAG) {
34132 var result = createBind(func, bitmask, thisArg);
34133 } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
34134 result = createCurry(func, bitmask, arity);
34135 } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
34136 result = createPartial(func, bitmask, thisArg, partials);
34137 } else {
34138 result = createHybrid.apply(undefined, newData);
34139 }
34140 var setter = data ? baseSetData : setData;
34141 return setWrapToString(setter(result, newData), func, bitmask);
34142 }
34143
34144 /**
34145 * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
34146 * of source objects to the destination object for all destination properties
34147 * that resolve to `undefined`.
34148 *
34149 * @private
34150 * @param {*} objValue The destination value.
34151 * @param {*} srcValue The source value.
34152 * @param {string} key The key of the property to assign.
34153 * @param {Object} object The parent object of `objValue`.
34154 * @returns {*} Returns the value to assign.
34155 */
34156 function customDefaultsAssignIn(objValue, srcValue, key, object) {
34157 if (objValue === undefined ||
34158 (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
34159 return srcValue;
34160 }
34161 return objValue;
34162 }
34163
34164 /**
34165 * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
34166 * objects into destination objects that are passed thru.
34167 *
34168 * @private
34169 * @param {*} objValue The destination value.
34170 * @param {*} srcValue The source value.
34171 * @param {string} key The key of the property to merge.
34172 * @param {Object} object The parent object of `objValue`.
34173 * @param {Object} source The parent object of `srcValue`.
34174 * @param {Object} [stack] Tracks traversed source values and their merged
34175 * counterparts.
34176 * @returns {*} Returns the value to assign.
34177 */
34178 function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
34179 if (isObject(objValue) && isObject(srcValue)) {
34180 // Recursively merge objects and arrays (susceptible to call stack limits).
34181 stack.set(srcValue, objValue);
34182 baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
34183 stack['delete'](srcValue);
34184 }
34185 return objValue;
34186 }
34187
34188 /**
34189 * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
34190 * objects.
34191 *
34192 * @private
34193 * @param {*} value The value to inspect.
34194 * @param {string} key The key of the property to inspect.
34195 * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
34196 */
34197 function customOmitClone(value) {
34198 return isPlainObject(value) ? undefined : value;
34199 }
34200
34201 /**
34202 * A specialized version of `baseIsEqualDeep` for arrays with support for
34203 * partial deep comparisons.
34204 *
34205 * @private
34206 * @param {Array} array The array to compare.
34207 * @param {Array} other The other array to compare.
34208 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
34209 * @param {Function} customizer The function to customize comparisons.
34210 * @param {Function} equalFunc The function to determine equivalents of values.
34211 * @param {Object} stack Tracks traversed `array` and `other` objects.
34212 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
34213 */
34214 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
34215 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
34216 arrLength = array.length,
34217 othLength = other.length;
34218
34219 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
34220 return false;
34221 }
34222 // Assume cyclic values are equal.
34223 var stacked = stack.get(array);
34224 if (stacked && stack.get(other)) {
34225 return stacked == other;
34226 }
34227 var index = -1,
34228 result = true,
34229 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
34230
34231 stack.set(array, other);
34232 stack.set(other, array);
34233
34234 // Ignore non-index properties.
34235 while (++index < arrLength) {
34236 var arrValue = array[index],
34237 othValue = other[index];
34238
34239 if (customizer) {
34240 var compared = isPartial
34241 ? customizer(othValue, arrValue, index, other, array, stack)
34242 : customizer(arrValue, othValue, index, array, other, stack);
34243 }
34244 if (compared !== undefined) {
34245 if (compared) {
34246 continue;
34247 }
34248 result = false;
34249 break;
34250 }
34251 // Recursively compare arrays (susceptible to call stack limits).
34252 if (seen) {
34253 if (!arraySome(other, function(othValue, othIndex) {
34254 if (!cacheHas(seen, othIndex) &&
34255 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
34256 return seen.push(othIndex);
34257 }
34258 })) {
34259 result = false;
34260 break;
34261 }
34262 } else if (!(
34263 arrValue === othValue ||
34264 equalFunc(arrValue, othValue, bitmask, customizer, stack)
34265 )) {
34266 result = false;
34267 break;
34268 }
34269 }
34270 stack['delete'](array);
34271 stack['delete'](other);
34272 return result;
34273 }
34274
34275 /**
34276 * A specialized version of `baseIsEqualDeep` for comparing objects of
34277 * the same `toStringTag`.
34278 *
34279 * **Note:** This function only supports comparing values with tags of
34280 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
34281 *
34282 * @private
34283 * @param {Object} object The object to compare.
34284 * @param {Object} other The other object to compare.
34285 * @param {string} tag The `toStringTag` of the objects to compare.
34286 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
34287 * @param {Function} customizer The function to customize comparisons.
34288 * @param {Function} equalFunc The function to determine equivalents of values.
34289 * @param {Object} stack Tracks traversed `object` and `other` objects.
34290 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
34291 */
34292 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
34293 switch (tag) {
34294 case dataViewTag:
34295 if ((object.byteLength != other.byteLength) ||
34296 (object.byteOffset != other.byteOffset)) {
34297 return false;
34298 }
34299 object = object.buffer;
34300 other = other.buffer;
34301
34302 case arrayBufferTag:
34303 if ((object.byteLength != other.byteLength) ||
34304 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
34305 return false;
34306 }
34307 return true;
34308
34309 case boolTag:
34310 case dateTag:
34311 case numberTag:
34312 // Coerce booleans to `1` or `0` and dates to milliseconds.
34313 // Invalid dates are coerced to `NaN`.
34314 return eq(+object, +other);
34315
34316 case errorTag:
34317 return object.name == other.name && object.message == other.message;
34318
34319 case regexpTag:
34320 case stringTag:
34321 // Coerce regexes to strings and treat strings, primitives and objects,
34322 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
34323 // for more details.
34324 return object == (other + '');
34325
34326 case mapTag:
34327 var convert = mapToArray;
34328
34329 case setTag:
34330 var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
34331 convert || (convert = setToArray);
34332
34333 if (object.size != other.size && !isPartial) {
34334 return false;
34335 }
34336 // Assume cyclic values are equal.
34337 var stacked = stack.get(object);
34338 if (stacked) {
34339 return stacked == other;
34340 }
34341 bitmask |= COMPARE_UNORDERED_FLAG;
34342
34343 // Recursively compare objects (susceptible to call stack limits).
34344 stack.set(object, other);
34345 var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
34346 stack['delete'](object);
34347 return result;
34348
34349 case symbolTag:
34350 if (symbolValueOf) {
34351 return symbolValueOf.call(object) == symbolValueOf.call(other);
34352 }
34353 }
34354 return false;
34355 }
34356
34357 /**
34358 * A specialized version of `baseIsEqualDeep` for objects with support for
34359 * partial deep comparisons.
34360 *
34361 * @private
34362 * @param {Object} object The object to compare.
34363 * @param {Object} other The other object to compare.
34364 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
34365 * @param {Function} customizer The function to customize comparisons.
34366 * @param {Function} equalFunc The function to determine equivalents of values.
34367 * @param {Object} stack Tracks traversed `object` and `other` objects.
34368 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
34369 */
34370 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
34371 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
34372 objProps = getAllKeys(object),
34373 objLength = objProps.length,
34374 othProps = getAllKeys(other),
34375 othLength = othProps.length;
34376
34377 if (objLength != othLength && !isPartial) {
34378 return false;
34379 }
34380 var index = objLength;
34381 while (index--) {
34382 var key = objProps[index];
34383 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
34384 return false;
34385 }
34386 }
34387 // Assume cyclic values are equal.
34388 var stacked = stack.get(object);
34389 if (stacked && stack.get(other)) {
34390 return stacked == other;
34391 }
34392 var result = true;
34393 stack.set(object, other);
34394 stack.set(other, object);
34395
34396 var skipCtor = isPartial;
34397 while (++index < objLength) {
34398 key = objProps[index];
34399 var objValue = object[key],
34400 othValue = other[key];
34401
34402 if (customizer) {
34403 var compared = isPartial
34404 ? customizer(othValue, objValue, key, other, object, stack)
34405 : customizer(objValue, othValue, key, object, other, stack);
34406 }
34407 // Recursively compare objects (susceptible to call stack limits).
34408 if (!(compared === undefined
34409 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
34410 : compared
34411 )) {
34412 result = false;
34413 break;
34414 }
34415 skipCtor || (skipCtor = key == 'constructor');
34416 }
34417 if (result && !skipCtor) {
34418 var objCtor = object.constructor,
34419 othCtor = other.constructor;
34420
34421 // Non `Object` object instances with different constructors are not equal.
34422 if (objCtor != othCtor &&
34423 ('constructor' in object && 'constructor' in other) &&
34424 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
34425 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
34426 result = false;
34427 }
34428 }
34429 stack['delete'](object);
34430 stack['delete'](other);
34431 return result;
34432 }
34433
34434 /**
34435 * A specialized version of `baseRest` which flattens the rest array.
34436 *
34437 * @private
34438 * @param {Function} func The function to apply a rest parameter to.
34439 * @returns {Function} Returns the new function.
34440 */
34441 function flatRest(func) {
34442 return setToString(overRest(func, undefined, flatten), func + '');
34443 }
34444
34445 /**
34446 * Creates an array of own enumerable property names and symbols of `object`.
34447 *
34448 * @private
34449 * @param {Object} object The object to query.
34450 * @returns {Array} Returns the array of property names and symbols.
34451 */
34452 function getAllKeys(object) {
34453 return baseGetAllKeys(object, keys, getSymbols);
34454 }
34455
34456 /**
34457 * Creates an array of own and inherited enumerable property names and
34458 * symbols of `object`.
34459 *
34460 * @private
34461 * @param {Object} object The object to query.
34462 * @returns {Array} Returns the array of property names and symbols.
34463 */
34464 function getAllKeysIn(object) {
34465 return baseGetAllKeys(object, keysIn, getSymbolsIn);
34466 }
34467
34468 /**
34469 * Gets metadata for `func`.
34470 *
34471 * @private
34472 * @param {Function} func The function to query.
34473 * @returns {*} Returns the metadata for `func`.
34474 */
34475 var getData = !metaMap ? noop : function(func) {
34476 return metaMap.get(func);
34477 };
34478
34479 /**
34480 * Gets the name of `func`.
34481 *
34482 * @private
34483 * @param {Function} func The function to query.
34484 * @returns {string} Returns the function name.
34485 */
34486 function getFuncName(func) {
34487 var result = (func.name + ''),
34488 array = realNames[result],
34489 length = hasOwnProperty.call(realNames, result) ? array.length : 0;
34490
34491 while (length--) {
34492 var data = array[length],
34493 otherFunc = data.func;
34494 if (otherFunc == null || otherFunc == func) {
34495 return data.name;
34496 }
34497 }
34498 return result;
34499 }
34500
34501 /**
34502 * Gets the argument placeholder value for `func`.
34503 *
34504 * @private
34505 * @param {Function} func The function to inspect.
34506 * @returns {*} Returns the placeholder value.
34507 */
34508 function getHolder(func) {
34509 var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
34510 return object.placeholder;
34511 }
34512
34513 /**
34514 * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
34515 * this function returns the custom method, otherwise it returns `baseIteratee`.
34516 * If arguments are provided, the chosen function is invoked with them and
34517 * its result is returned.
34518 *
34519 * @private
34520 * @param {*} [value] The value to convert to an iteratee.
34521 * @param {number} [arity] The arity of the created iteratee.
34522 * @returns {Function} Returns the chosen function or its result.
34523 */
34524 function getIteratee() {
34525 var result = lodash.iteratee || iteratee;
34526 result = result === iteratee ? baseIteratee : result;
34527 return arguments.length ? result(arguments[0], arguments[1]) : result;
34528 }
34529
34530 /**
34531 * Gets the data for `map`.
34532 *
34533 * @private
34534 * @param {Object} map The map to query.
34535 * @param {string} key The reference key.
34536 * @returns {*} Returns the map data.
34537 */
34538 function getMapData(map, key) {
34539 var data = map.__data__;
34540 return isKeyable(key)
34541 ? data[typeof key == 'string' ? 'string' : 'hash']
34542 : data.map;
34543 }
34544
34545 /**
34546 * Gets the property names, values, and compare flags of `object`.
34547 *
34548 * @private
34549 * @param {Object} object The object to query.
34550 * @returns {Array} Returns the match data of `object`.
34551 */
34552 function getMatchData(object) {
34553 var result = keys(object),
34554 length = result.length;
34555
34556 while (length--) {
34557 var key = result[length],
34558 value = object[key];
34559
34560 result[length] = [key, value, isStrictComparable(value)];
34561 }
34562 return result;
34563 }
34564
34565 /**
34566 * Gets the native function at `key` of `object`.
34567 *
34568 * @private
34569 * @param {Object} object The object to query.
34570 * @param {string} key The key of the method to get.
34571 * @returns {*} Returns the function if it's native, else `undefined`.
34572 */
34573 function getNative(object, key) {
34574 var value = getValue(object, key);
34575 return baseIsNative(value) ? value : undefined;
34576 }
34577
34578 /**
34579 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
34580 *
34581 * @private
34582 * @param {*} value The value to query.
34583 * @returns {string} Returns the raw `toStringTag`.
34584 */
34585 function getRawTag(value) {
34586 var isOwn = hasOwnProperty.call(value, symToStringTag),
34587 tag = value[symToStringTag];
34588
34589 try {
34590 value[symToStringTag] = undefined;
34591 var unmasked = true;
34592 } catch (e) {}
34593
34594 var result = nativeObjectToString.call(value);
34595 if (unmasked) {
34596 if (isOwn) {
34597 value[symToStringTag] = tag;
34598 } else {
34599 delete value[symToStringTag];
34600 }
34601 }
34602 return result;
34603 }
34604
34605 /**
34606 * Creates an array of the own enumerable symbols of `object`.
34607 *
34608 * @private
34609 * @param {Object} object The object to query.
34610 * @returns {Array} Returns the array of symbols.
34611 */
34612 var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
34613 if (object == null) {
34614 return [];
34615 }
34616 object = Object(object);
34617 return arrayFilter(nativeGetSymbols(object), function(symbol) {
34618 return propertyIsEnumerable.call(object, symbol);
34619 });
34620 };
34621
34622 /**
34623 * Creates an array of the own and inherited enumerable symbols of `object`.
34624 *
34625 * @private
34626 * @param {Object} object The object to query.
34627 * @returns {Array} Returns the array of symbols.
34628 */
34629 var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
34630 var result = [];
34631 while (object) {
34632 arrayPush(result, getSymbols(object));
34633 object = getPrototype(object);
34634 }
34635 return result;
34636 };
34637
34638 /**
34639 * Gets the `toStringTag` of `value`.
34640 *
34641 * @private
34642 * @param {*} value The value to query.
34643 * @returns {string} Returns the `toStringTag`.
34644 */
34645 var getTag = baseGetTag;
34646
34647 // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
34648 if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
34649 (Map && getTag(new Map) != mapTag) ||
34650 (Promise && getTag(Promise.resolve()) != promiseTag) ||
34651 (Set && getTag(new Set) != setTag) ||
34652 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
34653 getTag = function(value) {
34654 var result = baseGetTag(value),
34655 Ctor = result == objectTag ? value.constructor : undefined,
34656 ctorString = Ctor ? toSource(Ctor) : '';
34657
34658 if (ctorString) {
34659 switch (ctorString) {
34660 case dataViewCtorString: return dataViewTag;
34661 case mapCtorString: return mapTag;
34662 case promiseCtorString: return promiseTag;
34663 case setCtorString: return setTag;
34664 case weakMapCtorString: return weakMapTag;
34665 }
34666 }
34667 return result;
34668 };
34669 }
34670
34671 /**
34672 * Gets the view, applying any `transforms` to the `start` and `end` positions.
34673 *
34674 * @private
34675 * @param {number} start The start of the view.
34676 * @param {number} end The end of the view.
34677 * @param {Array} transforms The transformations to apply to the view.
34678 * @returns {Object} Returns an object containing the `start` and `end`
34679 * positions of the view.
34680 */
34681 function getView(start, end, transforms) {
34682 var index = -1,
34683 length = transforms.length;
34684
34685 while (++index < length) {
34686 var data = transforms[index],
34687 size = data.size;
34688
34689 switch (data.type) {
34690 case 'drop': start += size; break;
34691 case 'dropRight': end -= size; break;
34692 case 'take': end = nativeMin(end, start + size); break;
34693 case 'takeRight': start = nativeMax(start, end - size); break;
34694 }
34695 }
34696 return { 'start': start, 'end': end };
34697 }
34698
34699 /**
34700 * Extracts wrapper details from the `source` body comment.
34701 *
34702 * @private
34703 * @param {string} source The source to inspect.
34704 * @returns {Array} Returns the wrapper details.
34705 */
34706 function getWrapDetails(source) {
34707 var match = source.match(reWrapDetails);
34708 return match ? match[1].split(reSplitDetails) : [];
34709 }
34710
34711 /**
34712 * Checks if `path` exists on `object`.
34713 *
34714 * @private
34715 * @param {Object} object The object to query.
34716 * @param {Array|string} path The path to check.
34717 * @param {Function} hasFunc The function to check properties.
34718 * @returns {boolean} Returns `true` if `path` exists, else `false`.
34719 */
34720 function hasPath(object, path, hasFunc) {
34721 path = castPath(path, object);
34722
34723 var index = -1,
34724 length = path.length,
34725 result = false;
34726
34727 while (++index < length) {
34728 var key = toKey(path[index]);
34729 if (!(result = object != null && hasFunc(object, key))) {
34730 break;
34731 }
34732 object = object[key];
34733 }
34734 if (result || ++index != length) {
34735 return result;
34736 }
34737 length = object == null ? 0 : object.length;
34738 return !!length && isLength(length) && isIndex(key, length) &&
34739 (isArray(object) || isArguments(object));
34740 }
34741
34742 /**
34743 * Initializes an array clone.
34744 *
34745 * @private
34746 * @param {Array} array The array to clone.
34747 * @returns {Array} Returns the initialized clone.
34748 */
34749 function initCloneArray(array) {
34750 var length = array.length,
34751 result = new array.constructor(length);
34752
34753 // Add properties assigned by `RegExp#exec`.
34754 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
34755 result.index = array.index;
34756 result.input = array.input;
34757 }
34758 return result;
34759 }
34760
34761 /**
34762 * Initializes an object clone.
34763 *
34764 * @private
34765 * @param {Object} object The object to clone.
34766 * @returns {Object} Returns the initialized clone.
34767 */
34768 function initCloneObject(object) {
34769 return (typeof object.constructor == 'function' && !isPrototype(object))
34770 ? baseCreate(getPrototype(object))
34771 : {};
34772 }
34773
34774 /**
34775 * Initializes an object clone based on its `toStringTag`.
34776 *
34777 * **Note:** This function only supports cloning values with tags of
34778 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
34779 *
34780 * @private
34781 * @param {Object} object The object to clone.
34782 * @param {string} tag The `toStringTag` of the object to clone.
34783 * @param {boolean} [isDeep] Specify a deep clone.
34784 * @returns {Object} Returns the initialized clone.
34785 */
34786 function initCloneByTag(object, tag, isDeep) {
34787 var Ctor = object.constructor;
34788 switch (tag) {
34789 case arrayBufferTag:
34790 return cloneArrayBuffer(object);
34791
34792 case boolTag:
34793 case dateTag:
34794 return new Ctor(+object);
34795
34796 case dataViewTag:
34797 return cloneDataView(object, isDeep);
34798
34799 case float32Tag: case float64Tag:
34800 case int8Tag: case int16Tag: case int32Tag:
34801 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
34802 return cloneTypedArray(object, isDeep);
34803
34804 case mapTag:
34805 return new Ctor;
34806
34807 case numberTag:
34808 case stringTag:
34809 return new Ctor(object);
34810
34811 case regexpTag:
34812 return cloneRegExp(object);
34813
34814 case setTag:
34815 return new Ctor;
34816
34817 case symbolTag:
34818 return cloneSymbol(object);
34819 }
34820 }
34821
34822 /**
34823 * Inserts wrapper `details` in a comment at the top of the `source` body.
34824 *
34825 * @private
34826 * @param {string} source The source to modify.
34827 * @returns {Array} details The details to insert.
34828 * @returns {string} Returns the modified source.
34829 */
34830 function insertWrapDetails(source, details) {
34831 var length = details.length;
34832 if (!length) {
34833 return source;
34834 }
34835 var lastIndex = length - 1;
34836 details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
34837 details = details.join(length > 2 ? ', ' : ' ');
34838 return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
34839 }
34840
34841 /**
34842 * Checks if `value` is a flattenable `arguments` object or array.
34843 *
34844 * @private
34845 * @param {*} value The value to check.
34846 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
34847 */
34848 function isFlattenable(value) {
34849 return isArray(value) || isArguments(value) ||
34850 !!(spreadableSymbol && value && value[spreadableSymbol]);
34851 }
34852
34853 /**
34854 * Checks if `value` is a valid array-like index.
34855 *
34856 * @private
34857 * @param {*} value The value to check.
34858 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
34859 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
34860 */
34861 function isIndex(value, length) {
34862 var type = typeof value;
34863 length = length == null ? MAX_SAFE_INTEGER : length;
34864
34865 return !!length &&
34866 (type == 'number' ||
34867 (type != 'symbol' && reIsUint.test(value))) &&
34868 (value > -1 && value % 1 == 0 && value < length);
34869 }
34870
34871 /**
34872 * Checks if the given arguments are from an iteratee call.
34873 *
34874 * @private
34875 * @param {*} value The potential iteratee value argument.
34876 * @param {*} index The potential iteratee index or key argument.
34877 * @param {*} object The potential iteratee object argument.
34878 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
34879 * else `false`.
34880 */
34881 function isIterateeCall(value, index, object) {
34882 if (!isObject(object)) {
34883 return false;
34884 }
34885 var type = typeof index;
34886 if (type == 'number'
34887 ? (isArrayLike(object) && isIndex(index, object.length))
34888 : (type == 'string' && index in object)
34889 ) {
34890 return eq(object[index], value);
34891 }
34892 return false;
34893 }
34894
34895 /**
34896 * Checks if `value` is a property name and not a property path.
34897 *
34898 * @private
34899 * @param {*} value The value to check.
34900 * @param {Object} [object] The object to query keys on.
34901 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
34902 */
34903 function isKey(value, object) {
34904 if (isArray(value)) {
34905 return false;
34906 }
34907 var type = typeof value;
34908 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
34909 value == null || isSymbol(value)) {
34910 return true;
34911 }
34912 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
34913 (object != null && value in Object(object));
34914 }
34915
34916 /**
34917 * Checks if `value` is suitable for use as unique object key.
34918 *
34919 * @private
34920 * @param {*} value The value to check.
34921 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
34922 */
34923 function isKeyable(value) {
34924 var type = typeof value;
34925 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
34926 ? (value !== '__proto__')
34927 : (value === null);
34928 }
34929
34930 /**
34931 * Checks if `func` has a lazy counterpart.
34932 *
34933 * @private
34934 * @param {Function} func The function to check.
34935 * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
34936 * else `false`.
34937 */
34938 function isLaziable(func) {
34939 var funcName = getFuncName(func),
34940 other = lodash[funcName];
34941
34942 if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
34943 return false;
34944 }
34945 if (func === other) {
34946 return true;
34947 }
34948 var data = getData(other);
34949 return !!data && func === data[0];
34950 }
34951
34952 /**
34953 * Checks if `func` has its source masked.
34954 *
34955 * @private
34956 * @param {Function} func The function to check.
34957 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
34958 */
34959 function isMasked(func) {
34960 return !!maskSrcKey && (maskSrcKey in func);
34961 }
34962
34963 /**
34964 * Checks if `func` is capable of being masked.
34965 *
34966 * @private
34967 * @param {*} value The value to check.
34968 * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
34969 */
34970 var isMaskable = coreJsData ? isFunction : stubFalse;
34971
34972 /**
34973 * Checks if `value` is likely a prototype object.
34974 *
34975 * @private
34976 * @param {*} value The value to check.
34977 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
34978 */
34979 function isPrototype(value) {
34980 var Ctor = value && value.constructor,
34981 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
34982
34983 return value === proto;
34984 }
34985
34986 /**
34987 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
34988 *
34989 * @private
34990 * @param {*} value The value to check.
34991 * @returns {boolean} Returns `true` if `value` if suitable for strict
34992 * equality comparisons, else `false`.
34993 */
34994 function isStrictComparable(value) {
34995 return value === value && !isObject(value);
34996 }
34997
34998 /**
34999 * A specialized version of `matchesProperty` for source values suitable
35000 * for strict equality comparisons, i.e. `===`.
35001 *
35002 * @private
35003 * @param {string} key The key of the property to get.
35004 * @param {*} srcValue The value to match.
35005 * @returns {Function} Returns the new spec function.
35006 */
35007 function matchesStrictComparable(key, srcValue) {
35008 return function(object) {
35009 if (object == null) {
35010 return false;
35011 }
35012 return object[key] === srcValue &&
35013 (srcValue !== undefined || (key in Object(object)));
35014 };
35015 }
35016
35017 /**
35018 * A specialized version of `_.memoize` which clears the memoized function's
35019 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
35020 *
35021 * @private
35022 * @param {Function} func The function to have its output memoized.
35023 * @returns {Function} Returns the new memoized function.
35024 */
35025 function memoizeCapped(func) {
35026 var result = memoize(func, function(key) {
35027 if (cache.size === MAX_MEMOIZE_SIZE) {
35028 cache.clear();
35029 }
35030 return key;
35031 });
35032
35033 var cache = result.cache;
35034 return result;
35035 }
35036
35037 /**
35038 * Merges the function metadata of `source` into `data`.
35039 *
35040 * Merging metadata reduces the number of wrappers used to invoke a function.
35041 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
35042 * may be applied regardless of execution order. Methods like `_.ary` and
35043 * `_.rearg` modify function arguments, making the order in which they are
35044 * executed important, preventing the merging of metadata. However, we make
35045 * an exception for a safe combined case where curried functions have `_.ary`
35046 * and or `_.rearg` applied.
35047 *
35048 * @private
35049 * @param {Array} data The destination metadata.
35050 * @param {Array} source The source metadata.
35051 * @returns {Array} Returns `data`.
35052 */
35053 function mergeData(data, source) {
35054 var bitmask = data[1],
35055 srcBitmask = source[1],
35056 newBitmask = bitmask | srcBitmask,
35057 isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
35058
35059 var isCombo =
35060 ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
35061 ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
35062 ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
35063
35064 // Exit early if metadata can't be merged.
35065 if (!(isCommon || isCombo)) {
35066 return data;
35067 }
35068 // Use source `thisArg` if available.
35069 if (srcBitmask & WRAP_BIND_FLAG) {
35070 data[2] = source[2];
35071 // Set when currying a bound function.
35072 newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
35073 }
35074 // Compose partial arguments.
35075 var value = source[3];
35076 if (value) {
35077 var partials = data[3];
35078 data[3] = partials ? composeArgs(partials, value, source[4]) : value;
35079 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
35080 }
35081 // Compose partial right arguments.
35082 value = source[5];
35083 if (value) {
35084 partials = data[5];
35085 data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
35086 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
35087 }
35088 // Use source `argPos` if available.
35089 value = source[7];
35090 if (value) {
35091 data[7] = value;
35092 }
35093 // Use source `ary` if it's smaller.
35094 if (srcBitmask & WRAP_ARY_FLAG) {
35095 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
35096 }
35097 // Use source `arity` if one is not provided.
35098 if (data[9] == null) {
35099 data[9] = source[9];
35100 }
35101 // Use source `func` and merge bitmasks.
35102 data[0] = source[0];
35103 data[1] = newBitmask;
35104
35105 return data;
35106 }
35107
35108 /**
35109 * This function is like
35110 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
35111 * except that it includes inherited enumerable properties.
35112 *
35113 * @private
35114 * @param {Object} object The object to query.
35115 * @returns {Array} Returns the array of property names.
35116 */
35117 function nativeKeysIn(object) {
35118 var result = [];
35119 if (object != null) {
35120 for (var key in Object(object)) {
35121 result.push(key);
35122 }
35123 }
35124 return result;
35125 }
35126
35127 /**
35128 * Converts `value` to a string using `Object.prototype.toString`.
35129 *
35130 * @private
35131 * @param {*} value The value to convert.
35132 * @returns {string} Returns the converted string.
35133 */
35134 function objectToString(value) {
35135 return nativeObjectToString.call(value);
35136 }
35137
35138 /**
35139 * A specialized version of `baseRest` which transforms the rest array.
35140 *
35141 * @private
35142 * @param {Function} func The function to apply a rest parameter to.
35143 * @param {number} [start=func.length-1] The start position of the rest parameter.
35144 * @param {Function} transform The rest array transform.
35145 * @returns {Function} Returns the new function.
35146 */
35147 function overRest(func, start, transform) {
35148 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
35149 return function() {
35150 var args = arguments,
35151 index = -1,
35152 length = nativeMax(args.length - start, 0),
35153 array = Array(length);
35154
35155 while (++index < length) {
35156 array[index] = args[start + index];
35157 }
35158 index = -1;
35159 var otherArgs = Array(start + 1);
35160 while (++index < start) {
35161 otherArgs[index] = args[index];
35162 }
35163 otherArgs[start] = transform(array);
35164 return apply(func, this, otherArgs);
35165 };
35166 }
35167
35168 /**
35169 * Gets the parent value at `path` of `object`.
35170 *
35171 * @private
35172 * @param {Object} object The object to query.
35173 * @param {Array} path The path to get the parent value of.
35174 * @returns {*} Returns the parent value.
35175 */
35176 function parent(object, path) {
35177 return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
35178 }
35179
35180 /**
35181 * Reorder `array` according to the specified indexes where the element at
35182 * the first index is assigned as the first element, the element at
35183 * the second index is assigned as the second element, and so on.
35184 *
35185 * @private
35186 * @param {Array} array The array to reorder.
35187 * @param {Array} indexes The arranged array indexes.
35188 * @returns {Array} Returns `array`.
35189 */
35190 function reorder(array, indexes) {
35191 var arrLength = array.length,
35192 length = nativeMin(indexes.length, arrLength),
35193 oldArray = copyArray(array);
35194
35195 while (length--) {
35196 var index = indexes[length];
35197 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
35198 }
35199 return array;
35200 }
35201
35202 /**
35203 * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
35204 *
35205 * @private
35206 * @param {Object} object The object to query.
35207 * @param {string} key The key of the property to get.
35208 * @returns {*} Returns the property value.
35209 */
35210 function safeGet(object, key) {
35211 if (key === 'constructor' && typeof object[key] === 'function') {
35212 return;
35213 }
35214
35215 if (key == '__proto__') {
35216 return;
35217 }
35218
35219 return object[key];
35220 }
35221
35222 /**
35223 * Sets metadata for `func`.
35224 *
35225 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
35226 * period of time, it will trip its breaker and transition to an identity
35227 * function to avoid garbage collection pauses in V8. See
35228 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
35229 * for more details.
35230 *
35231 * @private
35232 * @param {Function} func The function to associate metadata with.
35233 * @param {*} data The metadata.
35234 * @returns {Function} Returns `func`.
35235 */
35236 var setData = shortOut(baseSetData);
35237
35238 /**
35239 * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
35240 *
35241 * @private
35242 * @param {Function} func The function to delay.
35243 * @param {number} wait The number of milliseconds to delay invocation.
35244 * @returns {number|Object} Returns the timer id or timeout object.
35245 */
35246 var setTimeout = ctxSetTimeout || function(func, wait) {
35247 return root.setTimeout(func, wait);
35248 };
35249
35250 /**
35251 * Sets the `toString` method of `func` to return `string`.
35252 *
35253 * @private
35254 * @param {Function} func The function to modify.
35255 * @param {Function} string The `toString` result.
35256 * @returns {Function} Returns `func`.
35257 */
35258 var setToString = shortOut(baseSetToString);
35259
35260 /**
35261 * Sets the `toString` method of `wrapper` to mimic the source of `reference`
35262 * with wrapper details in a comment at the top of the source body.
35263 *
35264 * @private
35265 * @param {Function} wrapper The function to modify.
35266 * @param {Function} reference The reference function.
35267 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
35268 * @returns {Function} Returns `wrapper`.
35269 */
35270 function setWrapToString(wrapper, reference, bitmask) {
35271 var source = (reference + '');
35272 return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
35273 }
35274
35275 /**
35276 * Creates a function that'll short out and invoke `identity` instead
35277 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
35278 * milliseconds.
35279 *
35280 * @private
35281 * @param {Function} func The function to restrict.
35282 * @returns {Function} Returns the new shortable function.
35283 */
35284 function shortOut(func) {
35285 var count = 0,
35286 lastCalled = 0;
35287
35288 return function() {
35289 var stamp = nativeNow(),
35290 remaining = HOT_SPAN - (stamp - lastCalled);
35291
35292 lastCalled = stamp;
35293 if (remaining > 0) {
35294 if (++count >= HOT_COUNT) {
35295 return arguments[0];
35296 }
35297 } else {
35298 count = 0;
35299 }
35300 return func.apply(undefined, arguments);
35301 };
35302 }
35303
35304 /**
35305 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
35306 *
35307 * @private
35308 * @param {Array} array The array to shuffle.
35309 * @param {number} [size=array.length] The size of `array`.
35310 * @returns {Array} Returns `array`.
35311 */
35312 function shuffleSelf(array, size) {
35313 var index = -1,
35314 length = array.length,
35315 lastIndex = length - 1;
35316
35317 size = size === undefined ? length : size;
35318 while (++index < size) {
35319 var rand = baseRandom(index, lastIndex),
35320 value = array[rand];
35321
35322 array[rand] = array[index];
35323 array[index] = value;
35324 }
35325 array.length = size;
35326 return array;
35327 }
35328
35329 /**
35330 * Converts `string` to a property path array.
35331 *
35332 * @private
35333 * @param {string} string The string to convert.
35334 * @returns {Array} Returns the property path array.
35335 */
35336 var stringToPath = memoizeCapped(function(string) {
35337 var result = [];
35338 if (string.charCodeAt(0) === 46 /* . */) {
35339 result.push('');
35340 }
35341 string.replace(rePropName, function(match, number, quote, subString) {
35342 result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
35343 });
35344 return result;
35345 });
35346
35347 /**
35348 * Converts `value` to a string key if it's not a string or symbol.
35349 *
35350 * @private
35351 * @param {*} value The value to inspect.
35352 * @returns {string|symbol} Returns the key.
35353 */
35354 function toKey(value) {
35355 if (typeof value == 'string' || isSymbol(value)) {
35356 return value;
35357 }
35358 var result = (value + '');
35359 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
35360 }
35361
35362 /**
35363 * Converts `func` to its source code.
35364 *
35365 * @private
35366 * @param {Function} func The function to convert.
35367 * @returns {string} Returns the source code.
35368 */
35369 function toSource(func) {
35370 if (func != null) {
35371 try {
35372 return funcToString.call(func);
35373 } catch (e) {}
35374 try {
35375 return (func + '');
35376 } catch (e) {}
35377 }
35378 return '';
35379 }
35380
35381 /**
35382 * Updates wrapper `details` based on `bitmask` flags.
35383 *
35384 * @private
35385 * @returns {Array} details The details to modify.
35386 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
35387 * @returns {Array} Returns `details`.
35388 */
35389 function updateWrapDetails(details, bitmask) {
35390 arrayEach(wrapFlags, function(pair) {
35391 var value = '_.' + pair[0];
35392 if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
35393 details.push(value);
35394 }
35395 });
35396 return details.sort();
35397 }
35398
35399 /**
35400 * Creates a clone of `wrapper`.
35401 *
35402 * @private
35403 * @param {Object} wrapper The wrapper to clone.
35404 * @returns {Object} Returns the cloned wrapper.
35405 */
35406 function wrapperClone(wrapper) {
35407 if (wrapper instanceof LazyWrapper) {
35408 return wrapper.clone();
35409 }
35410 var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
35411 result.__actions__ = copyArray(wrapper.__actions__);
35412 result.__index__ = wrapper.__index__;
35413 result.__values__ = wrapper.__values__;
35414 return result;
35415 }
35416
35417 /*------------------------------------------------------------------------*/
35418
35419 /**
35420 * Creates an array of elements split into groups the length of `size`.
35421 * If `array` can't be split evenly, the final chunk will be the remaining
35422 * elements.
35423 *
35424 * @static
35425 * @memberOf _
35426 * @since 3.0.0
35427 * @category Array
35428 * @param {Array} array The array to process.
35429 * @param {number} [size=1] The length of each chunk
35430 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
35431 * @returns {Array} Returns the new array of chunks.
35432 * @example
35433 *
35434 * _.chunk(['a', 'b', 'c', 'd'], 2);
35435 * // => [['a', 'b'], ['c', 'd']]
35436 *
35437 * _.chunk(['a', 'b', 'c', 'd'], 3);
35438 * // => [['a', 'b', 'c'], ['d']]
35439 */
35440 function chunk(array, size, guard) {
35441 if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
35442 size = 1;
35443 } else {
35444 size = nativeMax(toInteger(size), 0);
35445 }
35446 var length = array == null ? 0 : array.length;
35447 if (!length || size < 1) {
35448 return [];
35449 }
35450 var index = 0,
35451 resIndex = 0,
35452 result = Array(nativeCeil(length / size));
35453
35454 while (index < length) {
35455 result[resIndex++] = baseSlice(array, index, (index += size));
35456 }
35457 return result;
35458 }
35459
35460 /**
35461 * Creates an array with all falsey values removed. The values `false`, `null`,
35462 * `0`, `""`, `undefined`, and `NaN` are falsey.
35463 *
35464 * @static
35465 * @memberOf _
35466 * @since 0.1.0
35467 * @category Array
35468 * @param {Array} array The array to compact.
35469 * @returns {Array} Returns the new array of filtered values.
35470 * @example
35471 *
35472 * _.compact([0, 1, false, 2, '', 3]);
35473 * // => [1, 2, 3]
35474 */
35475 function compact(array) {
35476 var index = -1,
35477 length = array == null ? 0 : array.length,
35478 resIndex = 0,
35479 result = [];
35480
35481 while (++index < length) {
35482 var value = array[index];
35483 if (value) {
35484 result[resIndex++] = value;
35485 }
35486 }
35487 return result;
35488 }
35489
35490 /**
35491 * Creates a new array concatenating `array` with any additional arrays
35492 * and/or values.
35493 *
35494 * @static
35495 * @memberOf _
35496 * @since 4.0.0
35497 * @category Array
35498 * @param {Array} array The array to concatenate.
35499 * @param {...*} [values] The values to concatenate.
35500 * @returns {Array} Returns the new concatenated array.
35501 * @example
35502 *
35503 * var array = [1];
35504 * var other = _.concat(array, 2, [3], [[4]]);
35505 *
35506 * console.log(other);
35507 * // => [1, 2, 3, [4]]
35508 *
35509 * console.log(array);
35510 * // => [1]
35511 */
35512 function concat() {
35513 var length = arguments.length;
35514 if (!length) {
35515 return [];
35516 }
35517 var args = Array(length - 1),
35518 array = arguments[0],
35519 index = length;
35520
35521 while (index--) {
35522 args[index - 1] = arguments[index];
35523 }
35524 return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
35525 }
35526
35527 /**
35528 * Creates an array of `array` values not included in the other given arrays
35529 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
35530 * for equality comparisons. The order and references of result values are
35531 * determined by the first array.
35532 *
35533 * **Note:** Unlike `_.pullAll`, this method returns a new array.
35534 *
35535 * @static
35536 * @memberOf _
35537 * @since 0.1.0
35538 * @category Array
35539 * @param {Array} array The array to inspect.
35540 * @param {...Array} [values] The values to exclude.
35541 * @returns {Array} Returns the new array of filtered values.
35542 * @see _.without, _.xor
35543 * @example
35544 *
35545 * _.difference([2, 1], [2, 3]);
35546 * // => [1]
35547 */
35548 var difference = baseRest(function(array, values) {
35549 return isArrayLikeObject(array)
35550 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
35551 : [];
35552 });
35553
35554 /**
35555 * This method is like `_.difference` except that it accepts `iteratee` which
35556 * is invoked for each element of `array` and `values` to generate the criterion
35557 * by which they're compared. The order and references of result values are
35558 * determined by the first array. The iteratee is invoked with one argument:
35559 * (value).
35560 *
35561 * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
35562 *
35563 * @static
35564 * @memberOf _
35565 * @since 4.0.0
35566 * @category Array
35567 * @param {Array} array The array to inspect.
35568 * @param {...Array} [values] The values to exclude.
35569 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
35570 * @returns {Array} Returns the new array of filtered values.
35571 * @example
35572 *
35573 * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
35574 * // => [1.2]
35575 *
35576 * // The `_.property` iteratee shorthand.
35577 * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
35578 * // => [{ 'x': 2 }]
35579 */
35580 var differenceBy = baseRest(function(array, values) {
35581 var iteratee = last(values);
35582 if (isArrayLikeObject(iteratee)) {
35583 iteratee = undefined;
35584 }
35585 return isArrayLikeObject(array)
35586 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
35587 : [];
35588 });
35589
35590 /**
35591 * This method is like `_.difference` except that it accepts `comparator`
35592 * which is invoked to compare elements of `array` to `values`. The order and
35593 * references of result values are determined by the first array. The comparator
35594 * is invoked with two arguments: (arrVal, othVal).
35595 *
35596 * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
35597 *
35598 * @static
35599 * @memberOf _
35600 * @since 4.0.0
35601 * @category Array
35602 * @param {Array} array The array to inspect.
35603 * @param {...Array} [values] The values to exclude.
35604 * @param {Function} [comparator] The comparator invoked per element.
35605 * @returns {Array} Returns the new array of filtered values.
35606 * @example
35607 *
35608 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
35609 *
35610 * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
35611 * // => [{ 'x': 2, 'y': 1 }]
35612 */
35613 var differenceWith = baseRest(function(array, values) {
35614 var comparator = last(values);
35615 if (isArrayLikeObject(comparator)) {
35616 comparator = undefined;
35617 }
35618 return isArrayLikeObject(array)
35619 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
35620 : [];
35621 });
35622
35623 /**
35624 * Creates a slice of `array` with `n` elements dropped from the beginning.
35625 *
35626 * @static
35627 * @memberOf _
35628 * @since 0.5.0
35629 * @category Array
35630 * @param {Array} array The array to query.
35631 * @param {number} [n=1] The number of elements to drop.
35632 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
35633 * @returns {Array} Returns the slice of `array`.
35634 * @example
35635 *
35636 * _.drop([1, 2, 3]);
35637 * // => [2, 3]
35638 *
35639 * _.drop([1, 2, 3], 2);
35640 * // => [3]
35641 *
35642 * _.drop([1, 2, 3], 5);
35643 * // => []
35644 *
35645 * _.drop([1, 2, 3], 0);
35646 * // => [1, 2, 3]
35647 */
35648 function drop(array, n, guard) {
35649 var length = array == null ? 0 : array.length;
35650 if (!length) {
35651 return [];
35652 }
35653 n = (guard || n === undefined) ? 1 : toInteger(n);
35654 return baseSlice(array, n < 0 ? 0 : n, length);
35655 }
35656
35657 /**
35658 * Creates a slice of `array` with `n` elements dropped from the end.
35659 *
35660 * @static
35661 * @memberOf _
35662 * @since 3.0.0
35663 * @category Array
35664 * @param {Array} array The array to query.
35665 * @param {number} [n=1] The number of elements to drop.
35666 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
35667 * @returns {Array} Returns the slice of `array`.
35668 * @example
35669 *
35670 * _.dropRight([1, 2, 3]);
35671 * // => [1, 2]
35672 *
35673 * _.dropRight([1, 2, 3], 2);
35674 * // => [1]
35675 *
35676 * _.dropRight([1, 2, 3], 5);
35677 * // => []
35678 *
35679 * _.dropRight([1, 2, 3], 0);
35680 * // => [1, 2, 3]
35681 */
35682 function dropRight(array, n, guard) {
35683 var length = array == null ? 0 : array.length;
35684 if (!length) {
35685 return [];
35686 }
35687 n = (guard || n === undefined) ? 1 : toInteger(n);
35688 n = length - n;
35689 return baseSlice(array, 0, n < 0 ? 0 : n);
35690 }
35691
35692 /**
35693 * Creates a slice of `array` excluding elements dropped from the end.
35694 * Elements are dropped until `predicate` returns falsey. The predicate is
35695 * invoked with three arguments: (value, index, array).
35696 *
35697 * @static
35698 * @memberOf _
35699 * @since 3.0.0
35700 * @category Array
35701 * @param {Array} array The array to query.
35702 * @param {Function} [predicate=_.identity] The function invoked per iteration.
35703 * @returns {Array} Returns the slice of `array`.
35704 * @example
35705 *
35706 * var users = [
35707 * { 'user': 'barney', 'active': true },
35708 * { 'user': 'fred', 'active': false },
35709 * { 'user': 'pebbles', 'active': false }
35710 * ];
35711 *
35712 * _.dropRightWhile(users, function(o) { return !o.active; });
35713 * // => objects for ['barney']
35714 *
35715 * // The `_.matches` iteratee shorthand.
35716 * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
35717 * // => objects for ['barney', 'fred']
35718 *
35719 * // The `_.matchesProperty` iteratee shorthand.
35720 * _.dropRightWhile(users, ['active', false]);
35721 * // => objects for ['barney']
35722 *
35723 * // The `_.property` iteratee shorthand.
35724 * _.dropRightWhile(users, 'active');
35725 * // => objects for ['barney', 'fred', 'pebbles']
35726 */
35727 function dropRightWhile(array, predicate) {
35728 return (array && array.length)
35729 ? baseWhile(array, getIteratee(predicate, 3), true, true)
35730 : [];
35731 }
35732
35733 /**
35734 * Creates a slice of `array` excluding elements dropped from the beginning.
35735 * Elements are dropped until `predicate` returns falsey. The predicate is
35736 * invoked with three arguments: (value, index, array).
35737 *
35738 * @static
35739 * @memberOf _
35740 * @since 3.0.0
35741 * @category Array
35742 * @param {Array} array The array to query.
35743 * @param {Function} [predicate=_.identity] The function invoked per iteration.
35744 * @returns {Array} Returns the slice of `array`.
35745 * @example
35746 *
35747 * var users = [
35748 * { 'user': 'barney', 'active': false },
35749 * { 'user': 'fred', 'active': false },
35750 * { 'user': 'pebbles', 'active': true }
35751 * ];
35752 *
35753 * _.dropWhile(users, function(o) { return !o.active; });
35754 * // => objects for ['pebbles']
35755 *
35756 * // The `_.matches` iteratee shorthand.
35757 * _.dropWhile(users, { 'user': 'barney', 'active': false });
35758 * // => objects for ['fred', 'pebbles']
35759 *
35760 * // The `_.matchesProperty` iteratee shorthand.
35761 * _.dropWhile(users, ['active', false]);
35762 * // => objects for ['pebbles']
35763 *
35764 * // The `_.property` iteratee shorthand.
35765 * _.dropWhile(users, 'active');
35766 * // => objects for ['barney', 'fred', 'pebbles']
35767 */
35768 function dropWhile(array, predicate) {
35769 return (array && array.length)
35770 ? baseWhile(array, getIteratee(predicate, 3), true)
35771 : [];
35772 }
35773
35774 /**
35775 * Fills elements of `array` with `value` from `start` up to, but not
35776 * including, `end`.
35777 *
35778 * **Note:** This method mutates `array`.
35779 *
35780 * @static
35781 * @memberOf _
35782 * @since 3.2.0
35783 * @category Array
35784 * @param {Array} array The array to fill.
35785 * @param {*} value The value to fill `array` with.
35786 * @param {number} [start=0] The start position.
35787 * @param {number} [end=array.length] The end position.
35788 * @returns {Array} Returns `array`.
35789 * @example
35790 *
35791 * var array = [1, 2, 3];
35792 *
35793 * _.fill(array, 'a');
35794 * console.log(array);
35795 * // => ['a', 'a', 'a']
35796 *
35797 * _.fill(Array(3), 2);
35798 * // => [2, 2, 2]
35799 *
35800 * _.fill([4, 6, 8, 10], '*', 1, 3);
35801 * // => [4, '*', '*', 10]
35802 */
35803 function fill(array, value, start, end) {
35804 var length = array == null ? 0 : array.length;
35805 if (!length) {
35806 return [];
35807 }
35808 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
35809 start = 0;
35810 end = length;
35811 }
35812 return baseFill(array, value, start, end);
35813 }
35814
35815 /**
35816 * This method is like `_.find` except that it returns the index of the first
35817 * element `predicate` returns truthy for instead of the element itself.
35818 *
35819 * @static
35820 * @memberOf _
35821 * @since 1.1.0
35822 * @category Array
35823 * @param {Array} array The array to inspect.
35824 * @param {Function} [predicate=_.identity] The function invoked per iteration.
35825 * @param {number} [fromIndex=0] The index to search from.
35826 * @returns {number} Returns the index of the found element, else `-1`.
35827 * @example
35828 *
35829 * var users = [
35830 * { 'user': 'barney', 'active': false },
35831 * { 'user': 'fred', 'active': false },
35832 * { 'user': 'pebbles', 'active': true }
35833 * ];
35834 *
35835 * _.findIndex(users, function(o) { return o.user == 'barney'; });
35836 * // => 0
35837 *
35838 * // The `_.matches` iteratee shorthand.
35839 * _.findIndex(users, { 'user': 'fred', 'active': false });
35840 * // => 1
35841 *
35842 * // The `_.matchesProperty` iteratee shorthand.
35843 * _.findIndex(users, ['active', false]);
35844 * // => 0
35845 *
35846 * // The `_.property` iteratee shorthand.
35847 * _.findIndex(users, 'active');
35848 * // => 2
35849 */
35850 function findIndex(array, predicate, fromIndex) {
35851 var length = array == null ? 0 : array.length;
35852 if (!length) {
35853 return -1;
35854 }
35855 var index = fromIndex == null ? 0 : toInteger(fromIndex);
35856 if (index < 0) {
35857 index = nativeMax(length + index, 0);
35858 }
35859 return baseFindIndex(array, getIteratee(predicate, 3), index);
35860 }
35861
35862 /**
35863 * This method is like `_.findIndex` except that it iterates over elements
35864 * of `collection` from right to left.
35865 *
35866 * @static
35867 * @memberOf _
35868 * @since 2.0.0
35869 * @category Array
35870 * @param {Array} array The array to inspect.
35871 * @param {Function} [predicate=_.identity] The function invoked per iteration.
35872 * @param {number} [fromIndex=array.length-1] The index to search from.
35873 * @returns {number} Returns the index of the found element, else `-1`.
35874 * @example
35875 *
35876 * var users = [
35877 * { 'user': 'barney', 'active': true },
35878 * { 'user': 'fred', 'active': false },
35879 * { 'user': 'pebbles', 'active': false }
35880 * ];
35881 *
35882 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
35883 * // => 2
35884 *
35885 * // The `_.matches` iteratee shorthand.
35886 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
35887 * // => 0
35888 *
35889 * // The `_.matchesProperty` iteratee shorthand.
35890 * _.findLastIndex(users, ['active', false]);
35891 * // => 2
35892 *
35893 * // The `_.property` iteratee shorthand.
35894 * _.findLastIndex(users, 'active');
35895 * // => 0
35896 */
35897 function findLastIndex(array, predicate, fromIndex) {
35898 var length = array == null ? 0 : array.length;
35899 if (!length) {
35900 return -1;
35901 }
35902 var index = length - 1;
35903 if (fromIndex !== undefined) {
35904 index = toInteger(fromIndex);
35905 index = fromIndex < 0
35906 ? nativeMax(length + index, 0)
35907 : nativeMin(index, length - 1);
35908 }
35909 return baseFindIndex(array, getIteratee(predicate, 3), index, true);
35910 }
35911
35912 /**
35913 * Flattens `array` a single level deep.
35914 *
35915 * @static
35916 * @memberOf _
35917 * @since 0.1.0
35918 * @category Array
35919 * @param {Array} array The array to flatten.
35920 * @returns {Array} Returns the new flattened array.
35921 * @example
35922 *
35923 * _.flatten([1, [2, [3, [4]], 5]]);
35924 * // => [1, 2, [3, [4]], 5]
35925 */
35926 function flatten(array) {
35927 var length = array == null ? 0 : array.length;
35928 return length ? baseFlatten(array, 1) : [];
35929 }
35930
35931 /**
35932 * Recursively flattens `array`.
35933 *
35934 * @static
35935 * @memberOf _
35936 * @since 3.0.0
35937 * @category Array
35938 * @param {Array} array The array to flatten.
35939 * @returns {Array} Returns the new flattened array.
35940 * @example
35941 *
35942 * _.flattenDeep([1, [2, [3, [4]], 5]]);
35943 * // => [1, 2, 3, 4, 5]
35944 */
35945 function flattenDeep(array) {
35946 var length = array == null ? 0 : array.length;
35947 return length ? baseFlatten(array, INFINITY) : [];
35948 }
35949
35950 /**
35951 * Recursively flatten `array` up to `depth` times.
35952 *
35953 * @static
35954 * @memberOf _
35955 * @since 4.4.0
35956 * @category Array
35957 * @param {Array} array The array to flatten.
35958 * @param {number} [depth=1] The maximum recursion depth.
35959 * @returns {Array} Returns the new flattened array.
35960 * @example
35961 *
35962 * var array = [1, [2, [3, [4]], 5]];
35963 *
35964 * _.flattenDepth(array, 1);
35965 * // => [1, 2, [3, [4]], 5]
35966 *
35967 * _.flattenDepth(array, 2);
35968 * // => [1, 2, 3, [4], 5]
35969 */
35970 function flattenDepth(array, depth) {
35971 var length = array == null ? 0 : array.length;
35972 if (!length) {
35973 return [];
35974 }
35975 depth = depth === undefined ? 1 : toInteger(depth);
35976 return baseFlatten(array, depth);
35977 }
35978
35979 /**
35980 * The inverse of `_.toPairs`; this method returns an object composed
35981 * from key-value `pairs`.
35982 *
35983 * @static
35984 * @memberOf _
35985 * @since 4.0.0
35986 * @category Array
35987 * @param {Array} pairs The key-value pairs.
35988 * @returns {Object} Returns the new object.
35989 * @example
35990 *
35991 * _.fromPairs([['a', 1], ['b', 2]]);
35992 * // => { 'a': 1, 'b': 2 }
35993 */
35994 function fromPairs(pairs) {
35995 var index = -1,
35996 length = pairs == null ? 0 : pairs.length,
35997 result = {};
35998
35999 while (++index < length) {
36000 var pair = pairs[index];
36001 result[pair[0]] = pair[1];
36002 }
36003 return result;
36004 }
36005
36006 /**
36007 * Gets the first element of `array`.
36008 *
36009 * @static
36010 * @memberOf _
36011 * @since 0.1.0
36012 * @alias first
36013 * @category Array
36014 * @param {Array} array The array to query.
36015 * @returns {*} Returns the first element of `array`.
36016 * @example
36017 *
36018 * _.head([1, 2, 3]);
36019 * // => 1
36020 *
36021 * _.head([]);
36022 * // => undefined
36023 */
36024 function head(array) {
36025 return (array && array.length) ? array[0] : undefined;
36026 }
36027
36028 /**
36029 * Gets the index at which the first occurrence of `value` is found in `array`
36030 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
36031 * for equality comparisons. If `fromIndex` is negative, it's used as the
36032 * offset from the end of `array`.
36033 *
36034 * @static
36035 * @memberOf _
36036 * @since 0.1.0
36037 * @category Array
36038 * @param {Array} array The array to inspect.
36039 * @param {*} value The value to search for.
36040 * @param {number} [fromIndex=0] The index to search from.
36041 * @returns {number} Returns the index of the matched value, else `-1`.
36042 * @example
36043 *
36044 * _.indexOf([1, 2, 1, 2], 2);
36045 * // => 1
36046 *
36047 * // Search from the `fromIndex`.
36048 * _.indexOf([1, 2, 1, 2], 2, 2);
36049 * // => 3
36050 */
36051 function indexOf(array, value, fromIndex) {
36052 var length = array == null ? 0 : array.length;
36053 if (!length) {
36054 return -1;
36055 }
36056 var index = fromIndex == null ? 0 : toInteger(fromIndex);
36057 if (index < 0) {
36058 index = nativeMax(length + index, 0);
36059 }
36060 return baseIndexOf(array, value, index);
36061 }
36062
36063 /**
36064 * Gets all but the last element of `array`.
36065 *
36066 * @static
36067 * @memberOf _
36068 * @since 0.1.0
36069 * @category Array
36070 * @param {Array} array The array to query.
36071 * @returns {Array} Returns the slice of `array`.
36072 * @example
36073 *
36074 * _.initial([1, 2, 3]);
36075 * // => [1, 2]
36076 */
36077 function initial(array) {
36078 var length = array == null ? 0 : array.length;
36079 return length ? baseSlice(array, 0, -1) : [];
36080 }
36081
36082 /**
36083 * Creates an array of unique values that are included in all given arrays
36084 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
36085 * for equality comparisons. The order and references of result values are
36086 * determined by the first array.
36087 *
36088 * @static
36089 * @memberOf _
36090 * @since 0.1.0
36091 * @category Array
36092 * @param {...Array} [arrays] The arrays to inspect.
36093 * @returns {Array} Returns the new array of intersecting values.
36094 * @example
36095 *
36096 * _.intersection([2, 1], [2, 3]);
36097 * // => [2]
36098 */
36099 var intersection = baseRest(function(arrays) {
36100 var mapped = arrayMap(arrays, castArrayLikeObject);
36101 return (mapped.length && mapped[0] === arrays[0])
36102 ? baseIntersection(mapped)
36103 : [];
36104 });
36105
36106 /**
36107 * This method is like `_.intersection` except that it accepts `iteratee`
36108 * which is invoked for each element of each `arrays` to generate the criterion
36109 * by which they're compared. The order and references of result values are
36110 * determined by the first array. The iteratee is invoked with one argument:
36111 * (value).
36112 *
36113 * @static
36114 * @memberOf _
36115 * @since 4.0.0
36116 * @category Array
36117 * @param {...Array} [arrays] The arrays to inspect.
36118 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
36119 * @returns {Array} Returns the new array of intersecting values.
36120 * @example
36121 *
36122 * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
36123 * // => [2.1]
36124 *
36125 * // The `_.property` iteratee shorthand.
36126 * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
36127 * // => [{ 'x': 1 }]
36128 */
36129 var intersectionBy = baseRest(function(arrays) {
36130 var iteratee = last(arrays),
36131 mapped = arrayMap(arrays, castArrayLikeObject);
36132
36133 if (iteratee === last(mapped)) {
36134 iteratee = undefined;
36135 } else {
36136 mapped.pop();
36137 }
36138 return (mapped.length && mapped[0] === arrays[0])
36139 ? baseIntersection(mapped, getIteratee(iteratee, 2))
36140 : [];
36141 });
36142
36143 /**
36144 * This method is like `_.intersection` except that it accepts `comparator`
36145 * which is invoked to compare elements of `arrays`. The order and references
36146 * of result values are determined by the first array. The comparator is
36147 * invoked with two arguments: (arrVal, othVal).
36148 *
36149 * @static
36150 * @memberOf _
36151 * @since 4.0.0
36152 * @category Array
36153 * @param {...Array} [arrays] The arrays to inspect.
36154 * @param {Function} [comparator] The comparator invoked per element.
36155 * @returns {Array} Returns the new array of intersecting values.
36156 * @example
36157 *
36158 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
36159 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
36160 *
36161 * _.intersectionWith(objects, others, _.isEqual);
36162 * // => [{ 'x': 1, 'y': 2 }]
36163 */
36164 var intersectionWith = baseRest(function(arrays) {
36165 var comparator = last(arrays),
36166 mapped = arrayMap(arrays, castArrayLikeObject);
36167
36168 comparator = typeof comparator == 'function' ? comparator : undefined;
36169 if (comparator) {
36170 mapped.pop();
36171 }
36172 return (mapped.length && mapped[0] === arrays[0])
36173 ? baseIntersection(mapped, undefined, comparator)
36174 : [];
36175 });
36176
36177 /**
36178 * Converts all elements in `array` into a string separated by `separator`.
36179 *
36180 * @static
36181 * @memberOf _
36182 * @since 4.0.0
36183 * @category Array
36184 * @param {Array} array The array to convert.
36185 * @param {string} [separator=','] The element separator.
36186 * @returns {string} Returns the joined string.
36187 * @example
36188 *
36189 * _.join(['a', 'b', 'c'], '~');
36190 * // => 'a~b~c'
36191 */
36192 function join(array, separator) {
36193 return array == null ? '' : nativeJoin.call(array, separator);
36194 }
36195
36196 /**
36197 * Gets the last element of `array`.
36198 *
36199 * @static
36200 * @memberOf _
36201 * @since 0.1.0
36202 * @category Array
36203 * @param {Array} array The array to query.
36204 * @returns {*} Returns the last element of `array`.
36205 * @example
36206 *
36207 * _.last([1, 2, 3]);
36208 * // => 3
36209 */
36210 function last(array) {
36211 var length = array == null ? 0 : array.length;
36212 return length ? array[length - 1] : undefined;
36213 }
36214
36215 /**
36216 * This method is like `_.indexOf` except that it iterates over elements of
36217 * `array` from right to left.
36218 *
36219 * @static
36220 * @memberOf _
36221 * @since 0.1.0
36222 * @category Array
36223 * @param {Array} array The array to inspect.
36224 * @param {*} value The value to search for.
36225 * @param {number} [fromIndex=array.length-1] The index to search from.
36226 * @returns {number} Returns the index of the matched value, else `-1`.
36227 * @example
36228 *
36229 * _.lastIndexOf([1, 2, 1, 2], 2);
36230 * // => 3
36231 *
36232 * // Search from the `fromIndex`.
36233 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
36234 * // => 1
36235 */
36236 function lastIndexOf(array, value, fromIndex) {
36237 var length = array == null ? 0 : array.length;
36238 if (!length) {
36239 return -1;
36240 }
36241 var index = length;
36242 if (fromIndex !== undefined) {
36243 index = toInteger(fromIndex);
36244 index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
36245 }
36246 return value === value
36247 ? strictLastIndexOf(array, value, index)
36248 : baseFindIndex(array, baseIsNaN, index, true);
36249 }
36250
36251 /**
36252 * Gets the element at index `n` of `array`. If `n` is negative, the nth
36253 * element from the end is returned.
36254 *
36255 * @static
36256 * @memberOf _
36257 * @since 4.11.0
36258 * @category Array
36259 * @param {Array} array The array to query.
36260 * @param {number} [n=0] The index of the element to return.
36261 * @returns {*} Returns the nth element of `array`.
36262 * @example
36263 *
36264 * var array = ['a', 'b', 'c', 'd'];
36265 *
36266 * _.nth(array, 1);
36267 * // => 'b'
36268 *
36269 * _.nth(array, -2);
36270 * // => 'c';
36271 */
36272 function nth(array, n) {
36273 return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
36274 }
36275
36276 /**
36277 * Removes all given values from `array` using
36278 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
36279 * for equality comparisons.
36280 *
36281 * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
36282 * to remove elements from an array by predicate.
36283 *
36284 * @static
36285 * @memberOf _
36286 * @since 2.0.0
36287 * @category Array
36288 * @param {Array} array The array to modify.
36289 * @param {...*} [values] The values to remove.
36290 * @returns {Array} Returns `array`.
36291 * @example
36292 *
36293 * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
36294 *
36295 * _.pull(array, 'a', 'c');
36296 * console.log(array);
36297 * // => ['b', 'b']
36298 */
36299 var pull = baseRest(pullAll);
36300
36301 /**
36302 * This method is like `_.pull` except that it accepts an array of values to remove.
36303 *
36304 * **Note:** Unlike `_.difference`, this method mutates `array`.
36305 *
36306 * @static
36307 * @memberOf _
36308 * @since 4.0.0
36309 * @category Array
36310 * @param {Array} array The array to modify.
36311 * @param {Array} values The values to remove.
36312 * @returns {Array} Returns `array`.
36313 * @example
36314 *
36315 * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
36316 *
36317 * _.pullAll(array, ['a', 'c']);
36318 * console.log(array);
36319 * // => ['b', 'b']
36320 */
36321 function pullAll(array, values) {
36322 return (array && array.length && values && values.length)
36323 ? basePullAll(array, values)
36324 : array;
36325 }
36326
36327 /**
36328 * This method is like `_.pullAll` except that it accepts `iteratee` which is
36329 * invoked for each element of `array` and `values` to generate the criterion
36330 * by which they're compared. The iteratee is invoked with one argument: (value).
36331 *
36332 * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
36333 *
36334 * @static
36335 * @memberOf _
36336 * @since 4.0.0
36337 * @category Array
36338 * @param {Array} array The array to modify.
36339 * @param {Array} values The values to remove.
36340 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
36341 * @returns {Array} Returns `array`.
36342 * @example
36343 *
36344 * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
36345 *
36346 * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
36347 * console.log(array);
36348 * // => [{ 'x': 2 }]
36349 */
36350 function pullAllBy(array, values, iteratee) {
36351 return (array && array.length && values && values.length)
36352 ? basePullAll(array, values, getIteratee(iteratee, 2))
36353 : array;
36354 }
36355
36356 /**
36357 * This method is like `_.pullAll` except that it accepts `comparator` which
36358 * is invoked to compare elements of `array` to `values`. The comparator is
36359 * invoked with two arguments: (arrVal, othVal).
36360 *
36361 * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
36362 *
36363 * @static
36364 * @memberOf _
36365 * @since 4.6.0
36366 * @category Array
36367 * @param {Array} array The array to modify.
36368 * @param {Array} values The values to remove.
36369 * @param {Function} [comparator] The comparator invoked per element.
36370 * @returns {Array} Returns `array`.
36371 * @example
36372 *
36373 * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
36374 *
36375 * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
36376 * console.log(array);
36377 * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
36378 */
36379 function pullAllWith(array, values, comparator) {
36380 return (array && array.length && values && values.length)
36381 ? basePullAll(array, values, undefined, comparator)
36382 : array;
36383 }
36384
36385 /**
36386 * Removes elements from `array` corresponding to `indexes` and returns an
36387 * array of removed elements.
36388 *
36389 * **Note:** Unlike `_.at`, this method mutates `array`.
36390 *
36391 * @static
36392 * @memberOf _
36393 * @since 3.0.0
36394 * @category Array
36395 * @param {Array} array The array to modify.
36396 * @param {...(number|number[])} [indexes] The indexes of elements to remove.
36397 * @returns {Array} Returns the new array of removed elements.
36398 * @example
36399 *
36400 * var array = ['a', 'b', 'c', 'd'];
36401 * var pulled = _.pullAt(array, [1, 3]);
36402 *
36403 * console.log(array);
36404 * // => ['a', 'c']
36405 *
36406 * console.log(pulled);
36407 * // => ['b', 'd']
36408 */
36409 var pullAt = flatRest(function(array, indexes) {
36410 var length = array == null ? 0 : array.length,
36411 result = baseAt(array, indexes);
36412
36413 basePullAt(array, arrayMap(indexes, function(index) {
36414 return isIndex(index, length) ? +index : index;
36415 }).sort(compareAscending));
36416
36417 return result;
36418 });
36419
36420 /**
36421 * Removes all elements from `array` that `predicate` returns truthy for
36422 * and returns an array of the removed elements. The predicate is invoked
36423 * with three arguments: (value, index, array).
36424 *
36425 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
36426 * to pull elements from an array by value.
36427 *
36428 * @static
36429 * @memberOf _
36430 * @since 2.0.0
36431 * @category Array
36432 * @param {Array} array The array to modify.
36433 * @param {Function} [predicate=_.identity] The function invoked per iteration.
36434 * @returns {Array} Returns the new array of removed elements.
36435 * @example
36436 *
36437 * var array = [1, 2, 3, 4];
36438 * var evens = _.remove(array, function(n) {
36439 * return n % 2 == 0;
36440 * });
36441 *
36442 * console.log(array);
36443 * // => [1, 3]
36444 *
36445 * console.log(evens);
36446 * // => [2, 4]
36447 */
36448 function remove(array, predicate) {
36449 var result = [];
36450 if (!(array && array.length)) {
36451 return result;
36452 }
36453 var index = -1,
36454 indexes = [],
36455 length = array.length;
36456
36457 predicate = getIteratee(predicate, 3);
36458 while (++index < length) {
36459 var value = array[index];
36460 if (predicate(value, index, array)) {
36461 result.push(value);
36462 indexes.push(index);
36463 }
36464 }
36465 basePullAt(array, indexes);
36466 return result;
36467 }
36468
36469 /**
36470 * Reverses `array` so that the first element becomes the last, the second
36471 * element becomes the second to last, and so on.
36472 *
36473 * **Note:** This method mutates `array` and is based on
36474 * [`Array#reverse`](https://mdn.io/Array/reverse).
36475 *
36476 * @static
36477 * @memberOf _
36478 * @since 4.0.0
36479 * @category Array
36480 * @param {Array} array The array to modify.
36481 * @returns {Array} Returns `array`.
36482 * @example
36483 *
36484 * var array = [1, 2, 3];
36485 *
36486 * _.reverse(array);
36487 * // => [3, 2, 1]
36488 *
36489 * console.log(array);
36490 * // => [3, 2, 1]
36491 */
36492 function reverse(array) {
36493 return array == null ? array : nativeReverse.call(array);
36494 }
36495
36496 /**
36497 * Creates a slice of `array` from `start` up to, but not including, `end`.
36498 *
36499 * **Note:** This method is used instead of
36500 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
36501 * returned.
36502 *
36503 * @static
36504 * @memberOf _
36505 * @since 3.0.0
36506 * @category Array
36507 * @param {Array} array The array to slice.
36508 * @param {number} [start=0] The start position.
36509 * @param {number} [end=array.length] The end position.
36510 * @returns {Array} Returns the slice of `array`.
36511 */
36512 function slice(array, start, end) {
36513 var length = array == null ? 0 : array.length;
36514 if (!length) {
36515 return [];
36516 }
36517 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
36518 start = 0;
36519 end = length;
36520 }
36521 else {
36522 start = start == null ? 0 : toInteger(start);
36523 end = end === undefined ? length : toInteger(end);
36524 }
36525 return baseSlice(array, start, end);
36526 }
36527
36528 /**
36529 * Uses a binary search to determine the lowest index at which `value`
36530 * should be inserted into `array` in order to maintain its sort order.
36531 *
36532 * @static
36533 * @memberOf _
36534 * @since 0.1.0
36535 * @category Array
36536 * @param {Array} array The sorted array to inspect.
36537 * @param {*} value The value to evaluate.
36538 * @returns {number} Returns the index at which `value` should be inserted
36539 * into `array`.
36540 * @example
36541 *
36542 * _.sortedIndex([30, 50], 40);
36543 * // => 1
36544 */
36545 function sortedIndex(array, value) {
36546 return baseSortedIndex(array, value);
36547 }
36548
36549 /**
36550 * This method is like `_.sortedIndex` except that it accepts `iteratee`
36551 * which is invoked for `value` and each element of `array` to compute their
36552 * sort ranking. The iteratee is invoked with one argument: (value).
36553 *
36554 * @static
36555 * @memberOf _
36556 * @since 4.0.0
36557 * @category Array
36558 * @param {Array} array The sorted array to inspect.
36559 * @param {*} value The value to evaluate.
36560 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
36561 * @returns {number} Returns the index at which `value` should be inserted
36562 * into `array`.
36563 * @example
36564 *
36565 * var objects = [{ 'x': 4 }, { 'x': 5 }];
36566 *
36567 * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
36568 * // => 0
36569 *
36570 * // The `_.property` iteratee shorthand.
36571 * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
36572 * // => 0
36573 */
36574 function sortedIndexBy(array, value, iteratee) {
36575 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
36576 }
36577
36578 /**
36579 * This method is like `_.indexOf` except that it performs a binary
36580 * search on a sorted `array`.
36581 *
36582 * @static
36583 * @memberOf _
36584 * @since 4.0.0
36585 * @category Array
36586 * @param {Array} array The array to inspect.
36587 * @param {*} value The value to search for.
36588 * @returns {number} Returns the index of the matched value, else `-1`.
36589 * @example
36590 *
36591 * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
36592 * // => 1
36593 */
36594 function sortedIndexOf(array, value) {
36595 var length = array == null ? 0 : array.length;
36596 if (length) {
36597 var index = baseSortedIndex(array, value);
36598 if (index < length && eq(array[index], value)) {
36599 return index;
36600 }
36601 }
36602 return -1;
36603 }
36604
36605 /**
36606 * This method is like `_.sortedIndex` except that it returns the highest
36607 * index at which `value` should be inserted into `array` in order to
36608 * maintain its sort order.
36609 *
36610 * @static
36611 * @memberOf _
36612 * @since 3.0.0
36613 * @category Array
36614 * @param {Array} array The sorted array to inspect.
36615 * @param {*} value The value to evaluate.
36616 * @returns {number} Returns the index at which `value` should be inserted
36617 * into `array`.
36618 * @example
36619 *
36620 * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
36621 * // => 4
36622 */
36623 function sortedLastIndex(array, value) {
36624 return baseSortedIndex(array, value, true);
36625 }
36626
36627 /**
36628 * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
36629 * which is invoked for `value` and each element of `array` to compute their
36630 * sort ranking. The iteratee is invoked with one argument: (value).
36631 *
36632 * @static
36633 * @memberOf _
36634 * @since 4.0.0
36635 * @category Array
36636 * @param {Array} array The sorted array to inspect.
36637 * @param {*} value The value to evaluate.
36638 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
36639 * @returns {number} Returns the index at which `value` should be inserted
36640 * into `array`.
36641 * @example
36642 *
36643 * var objects = [{ 'x': 4 }, { 'x': 5 }];
36644 *
36645 * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
36646 * // => 1
36647 *
36648 * // The `_.property` iteratee shorthand.
36649 * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
36650 * // => 1
36651 */
36652 function sortedLastIndexBy(array, value, iteratee) {
36653 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
36654 }
36655
36656 /**
36657 * This method is like `_.lastIndexOf` except that it performs a binary
36658 * search on a sorted `array`.
36659 *
36660 * @static
36661 * @memberOf _
36662 * @since 4.0.0
36663 * @category Array
36664 * @param {Array} array The array to inspect.
36665 * @param {*} value The value to search for.
36666 * @returns {number} Returns the index of the matched value, else `-1`.
36667 * @example
36668 *
36669 * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
36670 * // => 3
36671 */
36672 function sortedLastIndexOf(array, value) {
36673 var length = array == null ? 0 : array.length;
36674 if (length) {
36675 var index = baseSortedIndex(array, value, true) - 1;
36676 if (eq(array[index], value)) {
36677 return index;
36678 }
36679 }
36680 return -1;
36681 }
36682
36683 /**
36684 * This method is like `_.uniq` except that it's designed and optimized
36685 * for sorted arrays.
36686 *
36687 * @static
36688 * @memberOf _
36689 * @since 4.0.0
36690 * @category Array
36691 * @param {Array} array The array to inspect.
36692 * @returns {Array} Returns the new duplicate free array.
36693 * @example
36694 *
36695 * _.sortedUniq([1, 1, 2]);
36696 * // => [1, 2]
36697 */
36698 function sortedUniq(array) {
36699 return (array && array.length)
36700 ? baseSortedUniq(array)
36701 : [];
36702 }
36703
36704 /**
36705 * This method is like `_.uniqBy` except that it's designed and optimized
36706 * for sorted arrays.
36707 *
36708 * @static
36709 * @memberOf _
36710 * @since 4.0.0
36711 * @category Array
36712 * @param {Array} array The array to inspect.
36713 * @param {Function} [iteratee] The iteratee invoked per element.
36714 * @returns {Array} Returns the new duplicate free array.
36715 * @example
36716 *
36717 * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
36718 * // => [1.1, 2.3]
36719 */
36720 function sortedUniqBy(array, iteratee) {
36721 return (array && array.length)
36722 ? baseSortedUniq(array, getIteratee(iteratee, 2))
36723 : [];
36724 }
36725
36726 /**
36727 * Gets all but the first element of `array`.
36728 *
36729 * @static
36730 * @memberOf _
36731 * @since 4.0.0
36732 * @category Array
36733 * @param {Array} array The array to query.
36734 * @returns {Array} Returns the slice of `array`.
36735 * @example
36736 *
36737 * _.tail([1, 2, 3]);
36738 * // => [2, 3]
36739 */
36740 function tail(array) {
36741 var length = array == null ? 0 : array.length;
36742 return length ? baseSlice(array, 1, length) : [];
36743 }
36744
36745 /**
36746 * Creates a slice of `array` with `n` elements taken from the beginning.
36747 *
36748 * @static
36749 * @memberOf _
36750 * @since 0.1.0
36751 * @category Array
36752 * @param {Array} array The array to query.
36753 * @param {number} [n=1] The number of elements to take.
36754 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
36755 * @returns {Array} Returns the slice of `array`.
36756 * @example
36757 *
36758 * _.take([1, 2, 3]);
36759 * // => [1]
36760 *
36761 * _.take([1, 2, 3], 2);
36762 * // => [1, 2]
36763 *
36764 * _.take([1, 2, 3], 5);
36765 * // => [1, 2, 3]
36766 *
36767 * _.take([1, 2, 3], 0);
36768 * // => []
36769 */
36770 function take(array, n, guard) {
36771 if (!(array && array.length)) {
36772 return [];
36773 }
36774 n = (guard || n === undefined) ? 1 : toInteger(n);
36775 return baseSlice(array, 0, n < 0 ? 0 : n);
36776 }
36777
36778 /**
36779 * Creates a slice of `array` with `n` elements taken from the end.
36780 *
36781 * @static
36782 * @memberOf _
36783 * @since 3.0.0
36784 * @category Array
36785 * @param {Array} array The array to query.
36786 * @param {number} [n=1] The number of elements to take.
36787 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
36788 * @returns {Array} Returns the slice of `array`.
36789 * @example
36790 *
36791 * _.takeRight([1, 2, 3]);
36792 * // => [3]
36793 *
36794 * _.takeRight([1, 2, 3], 2);
36795 * // => [2, 3]
36796 *
36797 * _.takeRight([1, 2, 3], 5);
36798 * // => [1, 2, 3]
36799 *
36800 * _.takeRight([1, 2, 3], 0);
36801 * // => []
36802 */
36803 function takeRight(array, n, guard) {
36804 var length = array == null ? 0 : array.length;
36805 if (!length) {
36806 return [];
36807 }
36808 n = (guard || n === undefined) ? 1 : toInteger(n);
36809 n = length - n;
36810 return baseSlice(array, n < 0 ? 0 : n, length);
36811 }
36812
36813 /**
36814 * Creates a slice of `array` with elements taken from the end. Elements are
36815 * taken until `predicate` returns falsey. The predicate is invoked with
36816 * three arguments: (value, index, array).
36817 *
36818 * @static
36819 * @memberOf _
36820 * @since 3.0.0
36821 * @category Array
36822 * @param {Array} array The array to query.
36823 * @param {Function} [predicate=_.identity] The function invoked per iteration.
36824 * @returns {Array} Returns the slice of `array`.
36825 * @example
36826 *
36827 * var users = [
36828 * { 'user': 'barney', 'active': true },
36829 * { 'user': 'fred', 'active': false },
36830 * { 'user': 'pebbles', 'active': false }
36831 * ];
36832 *
36833 * _.takeRightWhile(users, function(o) { return !o.active; });
36834 * // => objects for ['fred', 'pebbles']
36835 *
36836 * // The `_.matches` iteratee shorthand.
36837 * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
36838 * // => objects for ['pebbles']
36839 *
36840 * // The `_.matchesProperty` iteratee shorthand.
36841 * _.takeRightWhile(users, ['active', false]);
36842 * // => objects for ['fred', 'pebbles']
36843 *
36844 * // The `_.property` iteratee shorthand.
36845 * _.takeRightWhile(users, 'active');
36846 * // => []
36847 */
36848 function takeRightWhile(array, predicate) {
36849 return (array && array.length)
36850 ? baseWhile(array, getIteratee(predicate, 3), false, true)
36851 : [];
36852 }
36853
36854 /**
36855 * Creates a slice of `array` with elements taken from the beginning. Elements
36856 * are taken until `predicate` returns falsey. The predicate is invoked with
36857 * three arguments: (value, index, array).
36858 *
36859 * @static
36860 * @memberOf _
36861 * @since 3.0.0
36862 * @category Array
36863 * @param {Array} array The array to query.
36864 * @param {Function} [predicate=_.identity] The function invoked per iteration.
36865 * @returns {Array} Returns the slice of `array`.
36866 * @example
36867 *
36868 * var users = [
36869 * { 'user': 'barney', 'active': false },
36870 * { 'user': 'fred', 'active': false },
36871 * { 'user': 'pebbles', 'active': true }
36872 * ];
36873 *
36874 * _.takeWhile(users, function(o) { return !o.active; });
36875 * // => objects for ['barney', 'fred']
36876 *
36877 * // The `_.matches` iteratee shorthand.
36878 * _.takeWhile(users, { 'user': 'barney', 'active': false });
36879 * // => objects for ['barney']
36880 *
36881 * // The `_.matchesProperty` iteratee shorthand.
36882 * _.takeWhile(users, ['active', false]);
36883 * // => objects for ['barney', 'fred']
36884 *
36885 * // The `_.property` iteratee shorthand.
36886 * _.takeWhile(users, 'active');
36887 * // => []
36888 */
36889 function takeWhile(array, predicate) {
36890 return (array && array.length)
36891 ? baseWhile(array, getIteratee(predicate, 3))
36892 : [];
36893 }
36894
36895 /**
36896 * Creates an array of unique values, in order, from all given arrays using
36897 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
36898 * for equality comparisons.
36899 *
36900 * @static
36901 * @memberOf _
36902 * @since 0.1.0
36903 * @category Array
36904 * @param {...Array} [arrays] The arrays to inspect.
36905 * @returns {Array} Returns the new array of combined values.
36906 * @example
36907 *
36908 * _.union([2], [1, 2]);
36909 * // => [2, 1]
36910 */
36911 var union = baseRest(function(arrays) {
36912 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
36913 });
36914
36915 /**
36916 * This method is like `_.union` except that it accepts `iteratee` which is
36917 * invoked for each element of each `arrays` to generate the criterion by
36918 * which uniqueness is computed. Result values are chosen from the first
36919 * array in which the value occurs. The iteratee is invoked with one argument:
36920 * (value).
36921 *
36922 * @static
36923 * @memberOf _
36924 * @since 4.0.0
36925 * @category Array
36926 * @param {...Array} [arrays] The arrays to inspect.
36927 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
36928 * @returns {Array} Returns the new array of combined values.
36929 * @example
36930 *
36931 * _.unionBy([2.1], [1.2, 2.3], Math.floor);
36932 * // => [2.1, 1.2]
36933 *
36934 * // The `_.property` iteratee shorthand.
36935 * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
36936 * // => [{ 'x': 1 }, { 'x': 2 }]
36937 */
36938 var unionBy = baseRest(function(arrays) {
36939 var iteratee = last(arrays);
36940 if (isArrayLikeObject(iteratee)) {
36941 iteratee = undefined;
36942 }
36943 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
36944 });
36945
36946 /**
36947 * This method is like `_.union` except that it accepts `comparator` which
36948 * is invoked to compare elements of `arrays`. Result values are chosen from
36949 * the first array in which the value occurs. The comparator is invoked
36950 * with two arguments: (arrVal, othVal).
36951 *
36952 * @static
36953 * @memberOf _
36954 * @since 4.0.0
36955 * @category Array
36956 * @param {...Array} [arrays] The arrays to inspect.
36957 * @param {Function} [comparator] The comparator invoked per element.
36958 * @returns {Array} Returns the new array of combined values.
36959 * @example
36960 *
36961 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
36962 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
36963 *
36964 * _.unionWith(objects, others, _.isEqual);
36965 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
36966 */
36967 var unionWith = baseRest(function(arrays) {
36968 var comparator = last(arrays);
36969 comparator = typeof comparator == 'function' ? comparator : undefined;
36970 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
36971 });
36972
36973 /**
36974 * Creates a duplicate-free version of an array, using
36975 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
36976 * for equality comparisons, in which only the first occurrence of each element
36977 * is kept. The order of result values is determined by the order they occur
36978 * in the array.
36979 *
36980 * @static
36981 * @memberOf _
36982 * @since 0.1.0
36983 * @category Array
36984 * @param {Array} array The array to inspect.
36985 * @returns {Array} Returns the new duplicate free array.
36986 * @example
36987 *
36988 * _.uniq([2, 1, 2]);
36989 * // => [2, 1]
36990 */
36991 function uniq(array) {
36992 return (array && array.length) ? baseUniq(array) : [];
36993 }
36994
36995 /**
36996 * This method is like `_.uniq` except that it accepts `iteratee` which is
36997 * invoked for each element in `array` to generate the criterion by which
36998 * uniqueness is computed. The order of result values is determined by the
36999 * order they occur in the array. The iteratee is invoked with one argument:
37000 * (value).
37001 *
37002 * @static
37003 * @memberOf _
37004 * @since 4.0.0
37005 * @category Array
37006 * @param {Array} array The array to inspect.
37007 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
37008 * @returns {Array} Returns the new duplicate free array.
37009 * @example
37010 *
37011 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
37012 * // => [2.1, 1.2]
37013 *
37014 * // The `_.property` iteratee shorthand.
37015 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
37016 * // => [{ 'x': 1 }, { 'x': 2 }]
37017 */
37018 function uniqBy(array, iteratee) {
37019 return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
37020 }
37021
37022 /**
37023 * This method is like `_.uniq` except that it accepts `comparator` which
37024 * is invoked to compare elements of `array`. The order of result values is
37025 * determined by the order they occur in the array.The comparator is invoked
37026 * with two arguments: (arrVal, othVal).
37027 *
37028 * @static
37029 * @memberOf _
37030 * @since 4.0.0
37031 * @category Array
37032 * @param {Array} array The array to inspect.
37033 * @param {Function} [comparator] The comparator invoked per element.
37034 * @returns {Array} Returns the new duplicate free array.
37035 * @example
37036 *
37037 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
37038 *
37039 * _.uniqWith(objects, _.isEqual);
37040 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
37041 */
37042 function uniqWith(array, comparator) {
37043 comparator = typeof comparator == 'function' ? comparator : undefined;
37044 return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
37045 }
37046
37047 /**
37048 * This method is like `_.zip` except that it accepts an array of grouped
37049 * elements and creates an array regrouping the elements to their pre-zip
37050 * configuration.
37051 *
37052 * @static
37053 * @memberOf _
37054 * @since 1.2.0
37055 * @category Array
37056 * @param {Array} array The array of grouped elements to process.
37057 * @returns {Array} Returns the new array of regrouped elements.
37058 * @example
37059 *
37060 * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
37061 * // => [['a', 1, true], ['b', 2, false]]
37062 *
37063 * _.unzip(zipped);
37064 * // => [['a', 'b'], [1, 2], [true, false]]
37065 */
37066 function unzip(array) {
37067 if (!(array && array.length)) {
37068 return [];
37069 }
37070 var length = 0;
37071 array = arrayFilter(array, function(group) {
37072 if (isArrayLikeObject(group)) {
37073 length = nativeMax(group.length, length);
37074 return true;
37075 }
37076 });
37077 return baseTimes(length, function(index) {
37078 return arrayMap(array, baseProperty(index));
37079 });
37080 }
37081
37082 /**
37083 * This method is like `_.unzip` except that it accepts `iteratee` to specify
37084 * how regrouped values should be combined. The iteratee is invoked with the
37085 * elements of each group: (...group).
37086 *
37087 * @static
37088 * @memberOf _
37089 * @since 3.8.0
37090 * @category Array
37091 * @param {Array} array The array of grouped elements to process.
37092 * @param {Function} [iteratee=_.identity] The function to combine
37093 * regrouped values.
37094 * @returns {Array} Returns the new array of regrouped elements.
37095 * @example
37096 *
37097 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
37098 * // => [[1, 10, 100], [2, 20, 200]]
37099 *
37100 * _.unzipWith(zipped, _.add);
37101 * // => [3, 30, 300]
37102 */
37103 function unzipWith(array, iteratee) {
37104 if (!(array && array.length)) {
37105 return [];
37106 }
37107 var result = unzip(array);
37108 if (iteratee == null) {
37109 return result;
37110 }
37111 return arrayMap(result, function(group) {
37112 return apply(iteratee, undefined, group);
37113 });
37114 }
37115
37116 /**
37117 * Creates an array excluding all given values using
37118 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
37119 * for equality comparisons.
37120 *
37121 * **Note:** Unlike `_.pull`, this method returns a new array.
37122 *
37123 * @static
37124 * @memberOf _
37125 * @since 0.1.0
37126 * @category Array
37127 * @param {Array} array The array to inspect.
37128 * @param {...*} [values] The values to exclude.
37129 * @returns {Array} Returns the new array of filtered values.
37130 * @see _.difference, _.xor
37131 * @example
37132 *
37133 * _.without([2, 1, 2, 3], 1, 2);
37134 * // => [3]
37135 */
37136 var without = baseRest(function(array, values) {
37137 return isArrayLikeObject(array)
37138 ? baseDifference(array, values)
37139 : [];
37140 });
37141
37142 /**
37143 * Creates an array of unique values that is the
37144 * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
37145 * of the given arrays. The order of result values is determined by the order
37146 * they occur in the arrays.
37147 *
37148 * @static
37149 * @memberOf _
37150 * @since 2.4.0
37151 * @category Array
37152 * @param {...Array} [arrays] The arrays to inspect.
37153 * @returns {Array} Returns the new array of filtered values.
37154 * @see _.difference, _.without
37155 * @example
37156 *
37157 * _.xor([2, 1], [2, 3]);
37158 * // => [1, 3]
37159 */
37160 var xor = baseRest(function(arrays) {
37161 return baseXor(arrayFilter(arrays, isArrayLikeObject));
37162 });
37163
37164 /**
37165 * This method is like `_.xor` except that it accepts `iteratee` which is
37166 * invoked for each element of each `arrays` to generate the criterion by
37167 * which by which they're compared. The order of result values is determined
37168 * by the order they occur in the arrays. The iteratee is invoked with one
37169 * argument: (value).
37170 *
37171 * @static
37172 * @memberOf _
37173 * @since 4.0.0
37174 * @category Array
37175 * @param {...Array} [arrays] The arrays to inspect.
37176 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
37177 * @returns {Array} Returns the new array of filtered values.
37178 * @example
37179 *
37180 * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
37181 * // => [1.2, 3.4]
37182 *
37183 * // The `_.property` iteratee shorthand.
37184 * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
37185 * // => [{ 'x': 2 }]
37186 */
37187 var xorBy = baseRest(function(arrays) {
37188 var iteratee = last(arrays);
37189 if (isArrayLikeObject(iteratee)) {
37190 iteratee = undefined;
37191 }
37192 return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
37193 });
37194
37195 /**
37196 * This method is like `_.xor` except that it accepts `comparator` which is
37197 * invoked to compare elements of `arrays`. The order of result values is
37198 * determined by the order they occur in the arrays. The comparator is invoked
37199 * with two arguments: (arrVal, othVal).
37200 *
37201 * @static
37202 * @memberOf _
37203 * @since 4.0.0
37204 * @category Array
37205 * @param {...Array} [arrays] The arrays to inspect.
37206 * @param {Function} [comparator] The comparator invoked per element.
37207 * @returns {Array} Returns the new array of filtered values.
37208 * @example
37209 *
37210 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
37211 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
37212 *
37213 * _.xorWith(objects, others, _.isEqual);
37214 * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
37215 */
37216 var xorWith = baseRest(function(arrays) {
37217 var comparator = last(arrays);
37218 comparator = typeof comparator == 'function' ? comparator : undefined;
37219 return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
37220 });
37221
37222 /**
37223 * Creates an array of grouped elements, the first of which contains the
37224 * first elements of the given arrays, the second of which contains the
37225 * second elements of the given arrays, and so on.
37226 *
37227 * @static
37228 * @memberOf _
37229 * @since 0.1.0
37230 * @category Array
37231 * @param {...Array} [arrays] The arrays to process.
37232 * @returns {Array} Returns the new array of grouped elements.
37233 * @example
37234 *
37235 * _.zip(['a', 'b'], [1, 2], [true, false]);
37236 * // => [['a', 1, true], ['b', 2, false]]
37237 */
37238 var zip = baseRest(unzip);
37239
37240 /**
37241 * This method is like `_.fromPairs` except that it accepts two arrays,
37242 * one of property identifiers and one of corresponding values.
37243 *
37244 * @static
37245 * @memberOf _
37246 * @since 0.4.0
37247 * @category Array
37248 * @param {Array} [props=[]] The property identifiers.
37249 * @param {Array} [values=[]] The property values.
37250 * @returns {Object} Returns the new object.
37251 * @example
37252 *
37253 * _.zipObject(['a', 'b'], [1, 2]);
37254 * // => { 'a': 1, 'b': 2 }
37255 */
37256 function zipObject(props, values) {
37257 return baseZipObject(props || [], values || [], assignValue);
37258 }
37259
37260 /**
37261 * This method is like `_.zipObject` except that it supports property paths.
37262 *
37263 * @static
37264 * @memberOf _
37265 * @since 4.1.0
37266 * @category Array
37267 * @param {Array} [props=[]] The property identifiers.
37268 * @param {Array} [values=[]] The property values.
37269 * @returns {Object} Returns the new object.
37270 * @example
37271 *
37272 * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
37273 * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
37274 */
37275 function zipObjectDeep(props, values) {
37276 return baseZipObject(props || [], values || [], baseSet);
37277 }
37278
37279 /**
37280 * This method is like `_.zip` except that it accepts `iteratee` to specify
37281 * how grouped values should be combined. The iteratee is invoked with the
37282 * elements of each group: (...group).
37283 *
37284 * @static
37285 * @memberOf _
37286 * @since 3.8.0
37287 * @category Array
37288 * @param {...Array} [arrays] The arrays to process.
37289 * @param {Function} [iteratee=_.identity] The function to combine
37290 * grouped values.
37291 * @returns {Array} Returns the new array of grouped elements.
37292 * @example
37293 *
37294 * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
37295 * return a + b + c;
37296 * });
37297 * // => [111, 222]
37298 */
37299 var zipWith = baseRest(function(arrays) {
37300 var length = arrays.length,
37301 iteratee = length > 1 ? arrays[length - 1] : undefined;
37302
37303 iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
37304 return unzipWith(arrays, iteratee);
37305 });
37306
37307 /*------------------------------------------------------------------------*/
37308
37309 /**
37310 * Creates a `lodash` wrapper instance that wraps `value` with explicit method
37311 * chain sequences enabled. The result of such sequences must be unwrapped
37312 * with `_#value`.
37313 *
37314 * @static
37315 * @memberOf _
37316 * @since 1.3.0
37317 * @category Seq
37318 * @param {*} value The value to wrap.
37319 * @returns {Object} Returns the new `lodash` wrapper instance.
37320 * @example
37321 *
37322 * var users = [
37323 * { 'user': 'barney', 'age': 36 },
37324 * { 'user': 'fred', 'age': 40 },
37325 * { 'user': 'pebbles', 'age': 1 }
37326 * ];
37327 *
37328 * var youngest = _
37329 * .chain(users)
37330 * .sortBy('age')
37331 * .map(function(o) {
37332 * return o.user + ' is ' + o.age;
37333 * })
37334 * .head()
37335 * .value();
37336 * // => 'pebbles is 1'
37337 */
37338 function chain(value) {
37339 var result = lodash(value);
37340 result.__chain__ = true;
37341 return result;
37342 }
37343
37344 /**
37345 * This method invokes `interceptor` and returns `value`. The interceptor
37346 * is invoked with one argument; (value). The purpose of this method is to
37347 * "tap into" a method chain sequence in order to modify intermediate results.
37348 *
37349 * @static
37350 * @memberOf _
37351 * @since 0.1.0
37352 * @category Seq
37353 * @param {*} value The value to provide to `interceptor`.
37354 * @param {Function} interceptor The function to invoke.
37355 * @returns {*} Returns `value`.
37356 * @example
37357 *
37358 * _([1, 2, 3])
37359 * .tap(function(array) {
37360 * // Mutate input array.
37361 * array.pop();
37362 * })
37363 * .reverse()
37364 * .value();
37365 * // => [2, 1]
37366 */
37367 function tap(value, interceptor) {
37368 interceptor(value);
37369 return value;
37370 }
37371
37372 /**
37373 * This method is like `_.tap` except that it returns the result of `interceptor`.
37374 * The purpose of this method is to "pass thru" values replacing intermediate
37375 * results in a method chain sequence.
37376 *
37377 * @static
37378 * @memberOf _
37379 * @since 3.0.0
37380 * @category Seq
37381 * @param {*} value The value to provide to `interceptor`.
37382 * @param {Function} interceptor The function to invoke.
37383 * @returns {*} Returns the result of `interceptor`.
37384 * @example
37385 *
37386 * _(' abc ')
37387 * .chain()
37388 * .trim()
37389 * .thru(function(value) {
37390 * return [value];
37391 * })
37392 * .value();
37393 * // => ['abc']
37394 */
37395 function thru(value, interceptor) {
37396 return interceptor(value);
37397 }
37398
37399 /**
37400 * This method is the wrapper version of `_.at`.
37401 *
37402 * @name at
37403 * @memberOf _
37404 * @since 1.0.0
37405 * @category Seq
37406 * @param {...(string|string[])} [paths] The property paths to pick.
37407 * @returns {Object} Returns the new `lodash` wrapper instance.
37408 * @example
37409 *
37410 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
37411 *
37412 * _(object).at(['a[0].b.c', 'a[1]']).value();
37413 * // => [3, 4]
37414 */
37415 var wrapperAt = flatRest(function(paths) {
37416 var length = paths.length,
37417 start = length ? paths[0] : 0,
37418 value = this.__wrapped__,
37419 interceptor = function(object) { return baseAt(object, paths); };
37420
37421 if (length > 1 || this.__actions__.length ||
37422 !(value instanceof LazyWrapper) || !isIndex(start)) {
37423 return this.thru(interceptor);
37424 }
37425 value = value.slice(start, +start + (length ? 1 : 0));
37426 value.__actions__.push({
37427 'func': thru,
37428 'args': [interceptor],
37429 'thisArg': undefined
37430 });
37431 return new LodashWrapper(value, this.__chain__).thru(function(array) {
37432 if (length && !array.length) {
37433 array.push(undefined);
37434 }
37435 return array;
37436 });
37437 });
37438
37439 /**
37440 * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
37441 *
37442 * @name chain
37443 * @memberOf _
37444 * @since 0.1.0
37445 * @category Seq
37446 * @returns {Object} Returns the new `lodash` wrapper instance.
37447 * @example
37448 *
37449 * var users = [
37450 * { 'user': 'barney', 'age': 36 },
37451 * { 'user': 'fred', 'age': 40 }
37452 * ];
37453 *
37454 * // A sequence without explicit chaining.
37455 * _(users).head();
37456 * // => { 'user': 'barney', 'age': 36 }
37457 *
37458 * // A sequence with explicit chaining.
37459 * _(users)
37460 * .chain()
37461 * .head()
37462 * .pick('user')
37463 * .value();
37464 * // => { 'user': 'barney' }
37465 */
37466 function wrapperChain() {
37467 return chain(this);
37468 }
37469
37470 /**
37471 * Executes the chain sequence and returns the wrapped result.
37472 *
37473 * @name commit
37474 * @memberOf _
37475 * @since 3.2.0
37476 * @category Seq
37477 * @returns {Object} Returns the new `lodash` wrapper instance.
37478 * @example
37479 *
37480 * var array = [1, 2];
37481 * var wrapped = _(array).push(3);
37482 *
37483 * console.log(array);
37484 * // => [1, 2]
37485 *
37486 * wrapped = wrapped.commit();
37487 * console.log(array);
37488 * // => [1, 2, 3]
37489 *
37490 * wrapped.last();
37491 * // => 3
37492 *
37493 * console.log(array);
37494 * // => [1, 2, 3]
37495 */
37496 function wrapperCommit() {
37497 return new LodashWrapper(this.value(), this.__chain__);
37498 }
37499
37500 /**
37501 * Gets the next value on a wrapped object following the
37502 * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
37503 *
37504 * @name next
37505 * @memberOf _
37506 * @since 4.0.0
37507 * @category Seq
37508 * @returns {Object} Returns the next iterator value.
37509 * @example
37510 *
37511 * var wrapped = _([1, 2]);
37512 *
37513 * wrapped.next();
37514 * // => { 'done': false, 'value': 1 }
37515 *
37516 * wrapped.next();
37517 * // => { 'done': false, 'value': 2 }
37518 *
37519 * wrapped.next();
37520 * // => { 'done': true, 'value': undefined }
37521 */
37522 function wrapperNext() {
37523 if (this.__values__ === undefined) {
37524 this.__values__ = toArray(this.value());
37525 }
37526 var done = this.__index__ >= this.__values__.length,
37527 value = done ? undefined : this.__values__[this.__index__++];
37528
37529 return { 'done': done, 'value': value };
37530 }
37531
37532 /**
37533 * Enables the wrapper to be iterable.
37534 *
37535 * @name Symbol.iterator
37536 * @memberOf _
37537 * @since 4.0.0
37538 * @category Seq
37539 * @returns {Object} Returns the wrapper object.
37540 * @example
37541 *
37542 * var wrapped = _([1, 2]);
37543 *
37544 * wrapped[Symbol.iterator]() === wrapped;
37545 * // => true
37546 *
37547 * Array.from(wrapped);
37548 * // => [1, 2]
37549 */
37550 function wrapperToIterator() {
37551 return this;
37552 }
37553
37554 /**
37555 * Creates a clone of the chain sequence planting `value` as the wrapped value.
37556 *
37557 * @name plant
37558 * @memberOf _
37559 * @since 3.2.0
37560 * @category Seq
37561 * @param {*} value The value to plant.
37562 * @returns {Object} Returns the new `lodash` wrapper instance.
37563 * @example
37564 *
37565 * function square(n) {
37566 * return n * n;
37567 * }
37568 *
37569 * var wrapped = _([1, 2]).map(square);
37570 * var other = wrapped.plant([3, 4]);
37571 *
37572 * other.value();
37573 * // => [9, 16]
37574 *
37575 * wrapped.value();
37576 * // => [1, 4]
37577 */
37578 function wrapperPlant(value) {
37579 var result,
37580 parent = this;
37581
37582 while (parent instanceof baseLodash) {
37583 var clone = wrapperClone(parent);
37584 clone.__index__ = 0;
37585 clone.__values__ = undefined;
37586 if (result) {
37587 previous.__wrapped__ = clone;
37588 } else {
37589 result = clone;
37590 }
37591 var previous = clone;
37592 parent = parent.__wrapped__;
37593 }
37594 previous.__wrapped__ = value;
37595 return result;
37596 }
37597
37598 /**
37599 * This method is the wrapper version of `_.reverse`.
37600 *
37601 * **Note:** This method mutates the wrapped array.
37602 *
37603 * @name reverse
37604 * @memberOf _
37605 * @since 0.1.0
37606 * @category Seq
37607 * @returns {Object} Returns the new `lodash` wrapper instance.
37608 * @example
37609 *
37610 * var array = [1, 2, 3];
37611 *
37612 * _(array).reverse().value()
37613 * // => [3, 2, 1]
37614 *
37615 * console.log(array);
37616 * // => [3, 2, 1]
37617 */
37618 function wrapperReverse() {
37619 var value = this.__wrapped__;
37620 if (value instanceof LazyWrapper) {
37621 var wrapped = value;
37622 if (this.__actions__.length) {
37623 wrapped = new LazyWrapper(this);
37624 }
37625 wrapped = wrapped.reverse();
37626 wrapped.__actions__.push({
37627 'func': thru,
37628 'args': [reverse],
37629 'thisArg': undefined
37630 });
37631 return new LodashWrapper(wrapped, this.__chain__);
37632 }
37633 return this.thru(reverse);
37634 }
37635
37636 /**
37637 * Executes the chain sequence to resolve the unwrapped value.
37638 *
37639 * @name value
37640 * @memberOf _
37641 * @since 0.1.0
37642 * @alias toJSON, valueOf
37643 * @category Seq
37644 * @returns {*} Returns the resolved unwrapped value.
37645 * @example
37646 *
37647 * _([1, 2, 3]).value();
37648 * // => [1, 2, 3]
37649 */
37650 function wrapperValue() {
37651 return baseWrapperValue(this.__wrapped__, this.__actions__);
37652 }
37653
37654 /*------------------------------------------------------------------------*/
37655
37656 /**
37657 * Creates an object composed of keys generated from the results of running
37658 * each element of `collection` thru `iteratee`. The corresponding value of
37659 * each key is the number of times the key was returned by `iteratee`. The
37660 * iteratee is invoked with one argument: (value).
37661 *
37662 * @static
37663 * @memberOf _
37664 * @since 0.5.0
37665 * @category Collection
37666 * @param {Array|Object} collection The collection to iterate over.
37667 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
37668 * @returns {Object} Returns the composed aggregate object.
37669 * @example
37670 *
37671 * _.countBy([6.1, 4.2, 6.3], Math.floor);
37672 * // => { '4': 1, '6': 2 }
37673 *
37674 * // The `_.property` iteratee shorthand.
37675 * _.countBy(['one', 'two', 'three'], 'length');
37676 * // => { '3': 2, '5': 1 }
37677 */
37678 var countBy = createAggregator(function(result, value, key) {
37679 if (hasOwnProperty.call(result, key)) {
37680 ++result[key];
37681 } else {
37682 baseAssignValue(result, key, 1);
37683 }
37684 });
37685
37686 /**
37687 * Checks if `predicate` returns truthy for **all** elements of `collection`.
37688 * Iteration is stopped once `predicate` returns falsey. The predicate is
37689 * invoked with three arguments: (value, index|key, collection).
37690 *
37691 * **Note:** This method returns `true` for
37692 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
37693 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
37694 * elements of empty collections.
37695 *
37696 * @static
37697 * @memberOf _
37698 * @since 0.1.0
37699 * @category Collection
37700 * @param {Array|Object} collection The collection to iterate over.
37701 * @param {Function} [predicate=_.identity] The function invoked per iteration.
37702 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
37703 * @returns {boolean} Returns `true` if all elements pass the predicate check,
37704 * else `false`.
37705 * @example
37706 *
37707 * _.every([true, 1, null, 'yes'], Boolean);
37708 * // => false
37709 *
37710 * var users = [
37711 * { 'user': 'barney', 'age': 36, 'active': false },
37712 * { 'user': 'fred', 'age': 40, 'active': false }
37713 * ];
37714 *
37715 * // The `_.matches` iteratee shorthand.
37716 * _.every(users, { 'user': 'barney', 'active': false });
37717 * // => false
37718 *
37719 * // The `_.matchesProperty` iteratee shorthand.
37720 * _.every(users, ['active', false]);
37721 * // => true
37722 *
37723 * // The `_.property` iteratee shorthand.
37724 * _.every(users, 'active');
37725 * // => false
37726 */
37727 function every(collection, predicate, guard) {
37728 var func = isArray(collection) ? arrayEvery : baseEvery;
37729 if (guard && isIterateeCall(collection, predicate, guard)) {
37730 predicate = undefined;
37731 }
37732 return func(collection, getIteratee(predicate, 3));
37733 }
37734
37735 /**
37736 * Iterates over elements of `collection`, returning an array of all elements
37737 * `predicate` returns truthy for. The predicate is invoked with three
37738 * arguments: (value, index|key, collection).
37739 *
37740 * **Note:** Unlike `_.remove`, this method returns a new array.
37741 *
37742 * @static
37743 * @memberOf _
37744 * @since 0.1.0
37745 * @category Collection
37746 * @param {Array|Object} collection The collection to iterate over.
37747 * @param {Function} [predicate=_.identity] The function invoked per iteration.
37748 * @returns {Array} Returns the new filtered array.
37749 * @see _.reject
37750 * @example
37751 *
37752 * var users = [
37753 * { 'user': 'barney', 'age': 36, 'active': true },
37754 * { 'user': 'fred', 'age': 40, 'active': false }
37755 * ];
37756 *
37757 * _.filter(users, function(o) { return !o.active; });
37758 * // => objects for ['fred']
37759 *
37760 * // The `_.matches` iteratee shorthand.
37761 * _.filter(users, { 'age': 36, 'active': true });
37762 * // => objects for ['barney']
37763 *
37764 * // The `_.matchesProperty` iteratee shorthand.
37765 * _.filter(users, ['active', false]);
37766 * // => objects for ['fred']
37767 *
37768 * // The `_.property` iteratee shorthand.
37769 * _.filter(users, 'active');
37770 * // => objects for ['barney']
37771 */
37772 function filter(collection, predicate) {
37773 var func = isArray(collection) ? arrayFilter : baseFilter;
37774 return func(collection, getIteratee(predicate, 3));
37775 }
37776
37777 /**
37778 * Iterates over elements of `collection`, returning the first element
37779 * `predicate` returns truthy for. The predicate is invoked with three
37780 * arguments: (value, index|key, collection).
37781 *
37782 * @static
37783 * @memberOf _
37784 * @since 0.1.0
37785 * @category Collection
37786 * @param {Array|Object} collection The collection to inspect.
37787 * @param {Function} [predicate=_.identity] The function invoked per iteration.
37788 * @param {number} [fromIndex=0] The index to search from.
37789 * @returns {*} Returns the matched element, else `undefined`.
37790 * @example
37791 *
37792 * var users = [
37793 * { 'user': 'barney', 'age': 36, 'active': true },
37794 * { 'user': 'fred', 'age': 40, 'active': false },
37795 * { 'user': 'pebbles', 'age': 1, 'active': true }
37796 * ];
37797 *
37798 * _.find(users, function(o) { return o.age < 40; });
37799 * // => object for 'barney'
37800 *
37801 * // The `_.matches` iteratee shorthand.
37802 * _.find(users, { 'age': 1, 'active': true });
37803 * // => object for 'pebbles'
37804 *
37805 * // The `_.matchesProperty` iteratee shorthand.
37806 * _.find(users, ['active', false]);
37807 * // => object for 'fred'
37808 *
37809 * // The `_.property` iteratee shorthand.
37810 * _.find(users, 'active');
37811 * // => object for 'barney'
37812 */
37813 var find = createFind(findIndex);
37814
37815 /**
37816 * This method is like `_.find` except that it iterates over elements of
37817 * `collection` from right to left.
37818 *
37819 * @static
37820 * @memberOf _
37821 * @since 2.0.0
37822 * @category Collection
37823 * @param {Array|Object} collection The collection to inspect.
37824 * @param {Function} [predicate=_.identity] The function invoked per iteration.
37825 * @param {number} [fromIndex=collection.length-1] The index to search from.
37826 * @returns {*} Returns the matched element, else `undefined`.
37827 * @example
37828 *
37829 * _.findLast([1, 2, 3, 4], function(n) {
37830 * return n % 2 == 1;
37831 * });
37832 * // => 3
37833 */
37834 var findLast = createFind(findLastIndex);
37835
37836 /**
37837 * Creates a flattened array of values by running each element in `collection`
37838 * thru `iteratee` and flattening the mapped results. The iteratee is invoked
37839 * with three arguments: (value, index|key, collection).
37840 *
37841 * @static
37842 * @memberOf _
37843 * @since 4.0.0
37844 * @category Collection
37845 * @param {Array|Object} collection The collection to iterate over.
37846 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37847 * @returns {Array} Returns the new flattened array.
37848 * @example
37849 *
37850 * function duplicate(n) {
37851 * return [n, n];
37852 * }
37853 *
37854 * _.flatMap([1, 2], duplicate);
37855 * // => [1, 1, 2, 2]
37856 */
37857 function flatMap(collection, iteratee) {
37858 return baseFlatten(map(collection, iteratee), 1);
37859 }
37860
37861 /**
37862 * This method is like `_.flatMap` except that it recursively flattens the
37863 * mapped results.
37864 *
37865 * @static
37866 * @memberOf _
37867 * @since 4.7.0
37868 * @category Collection
37869 * @param {Array|Object} collection The collection to iterate over.
37870 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37871 * @returns {Array} Returns the new flattened array.
37872 * @example
37873 *
37874 * function duplicate(n) {
37875 * return [[[n, n]]];
37876 * }
37877 *
37878 * _.flatMapDeep([1, 2], duplicate);
37879 * // => [1, 1, 2, 2]
37880 */
37881 function flatMapDeep(collection, iteratee) {
37882 return baseFlatten(map(collection, iteratee), INFINITY);
37883 }
37884
37885 /**
37886 * This method is like `_.flatMap` except that it recursively flattens the
37887 * mapped results up to `depth` times.
37888 *
37889 * @static
37890 * @memberOf _
37891 * @since 4.7.0
37892 * @category Collection
37893 * @param {Array|Object} collection The collection to iterate over.
37894 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37895 * @param {number} [depth=1] The maximum recursion depth.
37896 * @returns {Array} Returns the new flattened array.
37897 * @example
37898 *
37899 * function duplicate(n) {
37900 * return [[[n, n]]];
37901 * }
37902 *
37903 * _.flatMapDepth([1, 2], duplicate, 2);
37904 * // => [[1, 1], [2, 2]]
37905 */
37906 function flatMapDepth(collection, iteratee, depth) {
37907 depth = depth === undefined ? 1 : toInteger(depth);
37908 return baseFlatten(map(collection, iteratee), depth);
37909 }
37910
37911 /**
37912 * Iterates over elements of `collection` and invokes `iteratee` for each element.
37913 * The iteratee is invoked with three arguments: (value, index|key, collection).
37914 * Iteratee functions may exit iteration early by explicitly returning `false`.
37915 *
37916 * **Note:** As with other "Collections" methods, objects with a "length"
37917 * property are iterated like arrays. To avoid this behavior use `_.forIn`
37918 * or `_.forOwn` for object iteration.
37919 *
37920 * @static
37921 * @memberOf _
37922 * @since 0.1.0
37923 * @alias each
37924 * @category Collection
37925 * @param {Array|Object} collection The collection to iterate over.
37926 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37927 * @returns {Array|Object} Returns `collection`.
37928 * @see _.forEachRight
37929 * @example
37930 *
37931 * _.forEach([1, 2], function(value) {
37932 * console.log(value);
37933 * });
37934 * // => Logs `1` then `2`.
37935 *
37936 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
37937 * console.log(key);
37938 * });
37939 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
37940 */
37941 function forEach(collection, iteratee) {
37942 var func = isArray(collection) ? arrayEach : baseEach;
37943 return func(collection, getIteratee(iteratee, 3));
37944 }
37945
37946 /**
37947 * This method is like `_.forEach` except that it iterates over elements of
37948 * `collection` from right to left.
37949 *
37950 * @static
37951 * @memberOf _
37952 * @since 2.0.0
37953 * @alias eachRight
37954 * @category Collection
37955 * @param {Array|Object} collection The collection to iterate over.
37956 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37957 * @returns {Array|Object} Returns `collection`.
37958 * @see _.forEach
37959 * @example
37960 *
37961 * _.forEachRight([1, 2], function(value) {
37962 * console.log(value);
37963 * });
37964 * // => Logs `2` then `1`.
37965 */
37966 function forEachRight(collection, iteratee) {
37967 var func = isArray(collection) ? arrayEachRight : baseEachRight;
37968 return func(collection, getIteratee(iteratee, 3));
37969 }
37970
37971 /**
37972 * Creates an object composed of keys generated from the results of running
37973 * each element of `collection` thru `iteratee`. The order of grouped values
37974 * is determined by the order they occur in `collection`. The corresponding
37975 * value of each key is an array of elements responsible for generating the
37976 * key. The iteratee is invoked with one argument: (value).
37977 *
37978 * @static
37979 * @memberOf _
37980 * @since 0.1.0
37981 * @category Collection
37982 * @param {Array|Object} collection The collection to iterate over.
37983 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
37984 * @returns {Object} Returns the composed aggregate object.
37985 * @example
37986 *
37987 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
37988 * // => { '4': [4.2], '6': [6.1, 6.3] }
37989 *
37990 * // The `_.property` iteratee shorthand.
37991 * _.groupBy(['one', 'two', 'three'], 'length');
37992 * // => { '3': ['one', 'two'], '5': ['three'] }
37993 */
37994 var groupBy = createAggregator(function(result, value, key) {
37995 if (hasOwnProperty.call(result, key)) {
37996 result[key].push(value);
37997 } else {
37998 baseAssignValue(result, key, [value]);
37999 }
38000 });
38001
38002 /**
38003 * Checks if `value` is in `collection`. If `collection` is a string, it's
38004 * checked for a substring of `value`, otherwise
38005 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
38006 * is used for equality comparisons. If `fromIndex` is negative, it's used as
38007 * the offset from the end of `collection`.
38008 *
38009 * @static
38010 * @memberOf _
38011 * @since 0.1.0
38012 * @category Collection
38013 * @param {Array|Object|string} collection The collection to inspect.
38014 * @param {*} value The value to search for.
38015 * @param {number} [fromIndex=0] The index to search from.
38016 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
38017 * @returns {boolean} Returns `true` if `value` is found, else `false`.
38018 * @example
38019 *
38020 * _.includes([1, 2, 3], 1);
38021 * // => true
38022 *
38023 * _.includes([1, 2, 3], 1, 2);
38024 * // => false
38025 *
38026 * _.includes({ 'a': 1, 'b': 2 }, 1);
38027 * // => true
38028 *
38029 * _.includes('abcd', 'bc');
38030 * // => true
38031 */
38032 function includes(collection, value, fromIndex, guard) {
38033 collection = isArrayLike(collection) ? collection : values(collection);
38034 fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
38035
38036 var length = collection.length;
38037 if (fromIndex < 0) {
38038 fromIndex = nativeMax(length + fromIndex, 0);
38039 }
38040 return isString(collection)
38041 ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
38042 : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
38043 }
38044
38045 /**
38046 * Invokes the method at `path` of each element in `collection`, returning
38047 * an array of the results of each invoked method. Any additional arguments
38048 * are provided to each invoked method. If `path` is a function, it's invoked
38049 * for, and `this` bound to, each element in `collection`.
38050 *
38051 * @static
38052 * @memberOf _
38053 * @since 4.0.0
38054 * @category Collection
38055 * @param {Array|Object} collection The collection to iterate over.
38056 * @param {Array|Function|string} path The path of the method to invoke or
38057 * the function invoked per iteration.
38058 * @param {...*} [args] The arguments to invoke each method with.
38059 * @returns {Array} Returns the array of results.
38060 * @example
38061 *
38062 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
38063 * // => [[1, 5, 7], [1, 2, 3]]
38064 *
38065 * _.invokeMap([123, 456], String.prototype.split, '');
38066 * // => [['1', '2', '3'], ['4', '5', '6']]
38067 */
38068 var invokeMap = baseRest(function(collection, path, args) {
38069 var index = -1,
38070 isFunc = typeof path == 'function',
38071 result = isArrayLike(collection) ? Array(collection.length) : [];
38072
38073 baseEach(collection, function(value) {
38074 result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
38075 });
38076 return result;
38077 });
38078
38079 /**
38080 * Creates an object composed of keys generated from the results of running
38081 * each element of `collection` thru `iteratee`. The corresponding value of
38082 * each key is the last element responsible for generating the key. The
38083 * iteratee is invoked with one argument: (value).
38084 *
38085 * @static
38086 * @memberOf _
38087 * @since 4.0.0
38088 * @category Collection
38089 * @param {Array|Object} collection The collection to iterate over.
38090 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
38091 * @returns {Object} Returns the composed aggregate object.
38092 * @example
38093 *
38094 * var array = [
38095 * { 'dir': 'left', 'code': 97 },
38096 * { 'dir': 'right', 'code': 100 }
38097 * ];
38098 *
38099 * _.keyBy(array, function(o) {
38100 * return String.fromCharCode(o.code);
38101 * });
38102 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
38103 *
38104 * _.keyBy(array, 'dir');
38105 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
38106 */
38107 var keyBy = createAggregator(function(result, value, key) {
38108 baseAssignValue(result, key, value);
38109 });
38110
38111 /**
38112 * Creates an array of values by running each element in `collection` thru
38113 * `iteratee`. The iteratee is invoked with three arguments:
38114 * (value, index|key, collection).
38115 *
38116 * Many lodash methods are guarded to work as iteratees for methods like
38117 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
38118 *
38119 * The guarded methods are:
38120 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
38121 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
38122 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
38123 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
38124 *
38125 * @static
38126 * @memberOf _
38127 * @since 0.1.0
38128 * @category Collection
38129 * @param {Array|Object} collection The collection to iterate over.
38130 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
38131 * @returns {Array} Returns the new mapped array.
38132 * @example
38133 *
38134 * function square(n) {
38135 * return n * n;
38136 * }
38137 *
38138 * _.map([4, 8], square);
38139 * // => [16, 64]
38140 *
38141 * _.map({ 'a': 4, 'b': 8 }, square);
38142 * // => [16, 64] (iteration order is not guaranteed)
38143 *
38144 * var users = [
38145 * { 'user': 'barney' },
38146 * { 'user': 'fred' }
38147 * ];
38148 *
38149 * // The `_.property` iteratee shorthand.
38150 * _.map(users, 'user');
38151 * // => ['barney', 'fred']
38152 */
38153 function map(collection, iteratee) {
38154 var func = isArray(collection) ? arrayMap : baseMap;
38155 return func(collection, getIteratee(iteratee, 3));
38156 }
38157
38158 /**
38159 * This method is like `_.sortBy` except that it allows specifying the sort
38160 * orders of the iteratees to sort by. If `orders` is unspecified, all values
38161 * are sorted in ascending order. Otherwise, specify an order of "desc" for
38162 * descending or "asc" for ascending sort order of corresponding values.
38163 *
38164 * @static
38165 * @memberOf _
38166 * @since 4.0.0
38167 * @category Collection
38168 * @param {Array|Object} collection The collection to iterate over.
38169 * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
38170 * The iteratees to sort by.
38171 * @param {string[]} [orders] The sort orders of `iteratees`.
38172 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
38173 * @returns {Array} Returns the new sorted array.
38174 * @example
38175 *
38176 * var users = [
38177 * { 'user': 'fred', 'age': 48 },
38178 * { 'user': 'barney', 'age': 34 },
38179 * { 'user': 'fred', 'age': 40 },
38180 * { 'user': 'barney', 'age': 36 }
38181 * ];
38182 *
38183 * // Sort by `user` in ascending order and by `age` in descending order.
38184 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
38185 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
38186 */
38187 function orderBy(collection, iteratees, orders, guard) {
38188 if (collection == null) {
38189 return [];
38190 }
38191 if (!isArray(iteratees)) {
38192 iteratees = iteratees == null ? [] : [iteratees];
38193 }
38194 orders = guard ? undefined : orders;
38195 if (!isArray(orders)) {
38196 orders = orders == null ? [] : [orders];
38197 }
38198 return baseOrderBy(collection, iteratees, orders);
38199 }
38200
38201 /**
38202 * Creates an array of elements split into two groups, the first of which
38203 * contains elements `predicate` returns truthy for, the second of which
38204 * contains elements `predicate` returns falsey for. The predicate is
38205 * invoked with one argument: (value).
38206 *
38207 * @static
38208 * @memberOf _
38209 * @since 3.0.0
38210 * @category Collection
38211 * @param {Array|Object} collection The collection to iterate over.
38212 * @param {Function} [predicate=_.identity] The function invoked per iteration.
38213 * @returns {Array} Returns the array of grouped elements.
38214 * @example
38215 *
38216 * var users = [
38217 * { 'user': 'barney', 'age': 36, 'active': false },
38218 * { 'user': 'fred', 'age': 40, 'active': true },
38219 * { 'user': 'pebbles', 'age': 1, 'active': false }
38220 * ];
38221 *
38222 * _.partition(users, function(o) { return o.active; });
38223 * // => objects for [['fred'], ['barney', 'pebbles']]
38224 *
38225 * // The `_.matches` iteratee shorthand.
38226 * _.partition(users, { 'age': 1, 'active': false });
38227 * // => objects for [['pebbles'], ['barney', 'fred']]
38228 *
38229 * // The `_.matchesProperty` iteratee shorthand.
38230 * _.partition(users, ['active', false]);
38231 * // => objects for [['barney', 'pebbles'], ['fred']]
38232 *
38233 * // The `_.property` iteratee shorthand.
38234 * _.partition(users, 'active');
38235 * // => objects for [['fred'], ['barney', 'pebbles']]
38236 */
38237 var partition = createAggregator(function(result, value, key) {
38238 result[key ? 0 : 1].push(value);
38239 }, function() { return [[], []]; });
38240
38241 /**
38242 * Reduces `collection` to a value which is the accumulated result of running
38243 * each element in `collection` thru `iteratee`, where each successive
38244 * invocation is supplied the return value of the previous. If `accumulator`
38245 * is not given, the first element of `collection` is used as the initial
38246 * value. The iteratee is invoked with four arguments:
38247 * (accumulator, value, index|key, collection).
38248 *
38249 * Many lodash methods are guarded to work as iteratees for methods like
38250 * `_.reduce`, `_.reduceRight`, and `_.transform`.
38251 *
38252 * The guarded methods are:
38253 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
38254 * and `sortBy`
38255 *
38256 * @static
38257 * @memberOf _
38258 * @since 0.1.0
38259 * @category Collection
38260 * @param {Array|Object} collection The collection to iterate over.
38261 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
38262 * @param {*} [accumulator] The initial value.
38263 * @returns {*} Returns the accumulated value.
38264 * @see _.reduceRight
38265 * @example
38266 *
38267 * _.reduce([1, 2], function(sum, n) {
38268 * return sum + n;
38269 * }, 0);
38270 * // => 3
38271 *
38272 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
38273 * (result[value] || (result[value] = [])).push(key);
38274 * return result;
38275 * }, {});
38276 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
38277 */
38278 function reduce(collection, iteratee, accumulator) {
38279 var func = isArray(collection) ? arrayReduce : baseReduce,
38280 initAccum = arguments.length < 3;
38281
38282 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
38283 }
38284
38285 /**
38286 * This method is like `_.reduce` except that it iterates over elements of
38287 * `collection` from right to left.
38288 *
38289 * @static
38290 * @memberOf _
38291 * @since 0.1.0
38292 * @category Collection
38293 * @param {Array|Object} collection The collection to iterate over.
38294 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
38295 * @param {*} [accumulator] The initial value.
38296 * @returns {*} Returns the accumulated value.
38297 * @see _.reduce
38298 * @example
38299 *
38300 * var array = [[0, 1], [2, 3], [4, 5]];
38301 *
38302 * _.reduceRight(array, function(flattened, other) {
38303 * return flattened.concat(other);
38304 * }, []);
38305 * // => [4, 5, 2, 3, 0, 1]
38306 */
38307 function reduceRight(collection, iteratee, accumulator) {
38308 var func = isArray(collection) ? arrayReduceRight : baseReduce,
38309 initAccum = arguments.length < 3;
38310
38311 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
38312 }
38313
38314 /**
38315 * The opposite of `_.filter`; this method returns the elements of `collection`
38316 * that `predicate` does **not** return truthy for.
38317 *
38318 * @static
38319 * @memberOf _
38320 * @since 0.1.0
38321 * @category Collection
38322 * @param {Array|Object} collection The collection to iterate over.
38323 * @param {Function} [predicate=_.identity] The function invoked per iteration.
38324 * @returns {Array} Returns the new filtered array.
38325 * @see _.filter
38326 * @example
38327 *
38328 * var users = [
38329 * { 'user': 'barney', 'age': 36, 'active': false },
38330 * { 'user': 'fred', 'age': 40, 'active': true }
38331 * ];
38332 *
38333 * _.reject(users, function(o) { return !o.active; });
38334 * // => objects for ['fred']
38335 *
38336 * // The `_.matches` iteratee shorthand.
38337 * _.reject(users, { 'age': 40, 'active': true });
38338 * // => objects for ['barney']
38339 *
38340 * // The `_.matchesProperty` iteratee shorthand.
38341 * _.reject(users, ['active', false]);
38342 * // => objects for ['fred']
38343 *
38344 * // The `_.property` iteratee shorthand.
38345 * _.reject(users, 'active');
38346 * // => objects for ['barney']
38347 */
38348 function reject(collection, predicate) {
38349 var func = isArray(collection) ? arrayFilter : baseFilter;
38350 return func(collection, negate(getIteratee(predicate, 3)));
38351 }
38352
38353 /**
38354 * Gets a random element from `collection`.
38355 *
38356 * @static
38357 * @memberOf _
38358 * @since 2.0.0
38359 * @category Collection
38360 * @param {Array|Object} collection The collection to sample.
38361 * @returns {*} Returns the random element.
38362 * @example
38363 *
38364 * _.sample([1, 2, 3, 4]);
38365 * // => 2
38366 */
38367 function sample(collection) {
38368 var func = isArray(collection) ? arraySample : baseSample;
38369 return func(collection);
38370 }
38371
38372 /**
38373 * Gets `n` random elements at unique keys from `collection` up to the
38374 * size of `collection`.
38375 *
38376 * @static
38377 * @memberOf _
38378 * @since 4.0.0
38379 * @category Collection
38380 * @param {Array|Object} collection The collection to sample.
38381 * @param {number} [n=1] The number of elements to sample.
38382 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38383 * @returns {Array} Returns the random elements.
38384 * @example
38385 *
38386 * _.sampleSize([1, 2, 3], 2);
38387 * // => [3, 1]
38388 *
38389 * _.sampleSize([1, 2, 3], 4);
38390 * // => [2, 3, 1]
38391 */
38392 function sampleSize(collection, n, guard) {
38393 if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
38394 n = 1;
38395 } else {
38396 n = toInteger(n);
38397 }
38398 var func = isArray(collection) ? arraySampleSize : baseSampleSize;
38399 return func(collection, n);
38400 }
38401
38402 /**
38403 * Creates an array of shuffled values, using a version of the
38404 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
38405 *
38406 * @static
38407 * @memberOf _
38408 * @since 0.1.0
38409 * @category Collection
38410 * @param {Array|Object} collection The collection to shuffle.
38411 * @returns {Array} Returns the new shuffled array.
38412 * @example
38413 *
38414 * _.shuffle([1, 2, 3, 4]);
38415 * // => [4, 1, 3, 2]
38416 */
38417 function shuffle(collection) {
38418 var func = isArray(collection) ? arrayShuffle : baseShuffle;
38419 return func(collection);
38420 }
38421
38422 /**
38423 * Gets the size of `collection` by returning its length for array-like
38424 * values or the number of own enumerable string keyed properties for objects.
38425 *
38426 * @static
38427 * @memberOf _
38428 * @since 0.1.0
38429 * @category Collection
38430 * @param {Array|Object|string} collection The collection to inspect.
38431 * @returns {number} Returns the collection size.
38432 * @example
38433 *
38434 * _.size([1, 2, 3]);
38435 * // => 3
38436 *
38437 * _.size({ 'a': 1, 'b': 2 });
38438 * // => 2
38439 *
38440 * _.size('pebbles');
38441 * // => 7
38442 */
38443 function size(collection) {
38444 if (collection == null) {
38445 return 0;
38446 }
38447 if (isArrayLike(collection)) {
38448 return isString(collection) ? stringSize(collection) : collection.length;
38449 }
38450 var tag = getTag(collection);
38451 if (tag == mapTag || tag == setTag) {
38452 return collection.size;
38453 }
38454 return baseKeys(collection).length;
38455 }
38456
38457 /**
38458 * Checks if `predicate` returns truthy for **any** element of `collection`.
38459 * Iteration is stopped once `predicate` returns truthy. The predicate is
38460 * invoked with three arguments: (value, index|key, collection).
38461 *
38462 * @static
38463 * @memberOf _
38464 * @since 0.1.0
38465 * @category Collection
38466 * @param {Array|Object} collection The collection to iterate over.
38467 * @param {Function} [predicate=_.identity] The function invoked per iteration.
38468 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38469 * @returns {boolean} Returns `true` if any element passes the predicate check,
38470 * else `false`.
38471 * @example
38472 *
38473 * _.some([null, 0, 'yes', false], Boolean);
38474 * // => true
38475 *
38476 * var users = [
38477 * { 'user': 'barney', 'active': true },
38478 * { 'user': 'fred', 'active': false }
38479 * ];
38480 *
38481 * // The `_.matches` iteratee shorthand.
38482 * _.some(users, { 'user': 'barney', 'active': false });
38483 * // => false
38484 *
38485 * // The `_.matchesProperty` iteratee shorthand.
38486 * _.some(users, ['active', false]);
38487 * // => true
38488 *
38489 * // The `_.property` iteratee shorthand.
38490 * _.some(users, 'active');
38491 * // => true
38492 */
38493 function some(collection, predicate, guard) {
38494 var func = isArray(collection) ? arraySome : baseSome;
38495 if (guard && isIterateeCall(collection, predicate, guard)) {
38496 predicate = undefined;
38497 }
38498 return func(collection, getIteratee(predicate, 3));
38499 }
38500
38501 /**
38502 * Creates an array of elements, sorted in ascending order by the results of
38503 * running each element in a collection thru each iteratee. This method
38504 * performs a stable sort, that is, it preserves the original sort order of
38505 * equal elements. The iteratees are invoked with one argument: (value).
38506 *
38507 * @static
38508 * @memberOf _
38509 * @since 0.1.0
38510 * @category Collection
38511 * @param {Array|Object} collection The collection to iterate over.
38512 * @param {...(Function|Function[])} [iteratees=[_.identity]]
38513 * The iteratees to sort by.
38514 * @returns {Array} Returns the new sorted array.
38515 * @example
38516 *
38517 * var users = [
38518 * { 'user': 'fred', 'age': 48 },
38519 * { 'user': 'barney', 'age': 36 },
38520 * { 'user': 'fred', 'age': 40 },
38521 * { 'user': 'barney', 'age': 34 }
38522 * ];
38523 *
38524 * _.sortBy(users, [function(o) { return o.user; }]);
38525 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
38526 *
38527 * _.sortBy(users, ['user', 'age']);
38528 * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
38529 */
38530 var sortBy = baseRest(function(collection, iteratees) {
38531 if (collection == null) {
38532 return [];
38533 }
38534 var length = iteratees.length;
38535 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
38536 iteratees = [];
38537 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
38538 iteratees = [iteratees[0]];
38539 }
38540 return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
38541 });
38542
38543 /*------------------------------------------------------------------------*/
38544
38545 /**
38546 * Gets the timestamp of the number of milliseconds that have elapsed since
38547 * the Unix epoch (1 January 1970 00:00:00 UTC).
38548 *
38549 * @static
38550 * @memberOf _
38551 * @since 2.4.0
38552 * @category Date
38553 * @returns {number} Returns the timestamp.
38554 * @example
38555 *
38556 * _.defer(function(stamp) {
38557 * console.log(_.now() - stamp);
38558 * }, _.now());
38559 * // => Logs the number of milliseconds it took for the deferred invocation.
38560 */
38561 var now = ctxNow || function() {
38562 return root.Date.now();
38563 };
38564
38565 /*------------------------------------------------------------------------*/
38566
38567 /**
38568 * The opposite of `_.before`; this method creates a function that invokes
38569 * `func` once it's called `n` or more times.
38570 *
38571 * @static
38572 * @memberOf _
38573 * @since 0.1.0
38574 * @category Function
38575 * @param {number} n The number of calls before `func` is invoked.
38576 * @param {Function} func The function to restrict.
38577 * @returns {Function} Returns the new restricted function.
38578 * @example
38579 *
38580 * var saves = ['profile', 'settings'];
38581 *
38582 * var done = _.after(saves.length, function() {
38583 * console.log('done saving!');
38584 * });
38585 *
38586 * _.forEach(saves, function(type) {
38587 * asyncSave({ 'type': type, 'complete': done });
38588 * });
38589 * // => Logs 'done saving!' after the two async saves have completed.
38590 */
38591 function after(n, func) {
38592 if (typeof func != 'function') {
38593 throw new TypeError(FUNC_ERROR_TEXT);
38594 }
38595 n = toInteger(n);
38596 return function() {
38597 if (--n < 1) {
38598 return func.apply(this, arguments);
38599 }
38600 };
38601 }
38602
38603 /**
38604 * Creates a function that invokes `func`, with up to `n` arguments,
38605 * ignoring any additional arguments.
38606 *
38607 * @static
38608 * @memberOf _
38609 * @since 3.0.0
38610 * @category Function
38611 * @param {Function} func The function to cap arguments for.
38612 * @param {number} [n=func.length] The arity cap.
38613 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38614 * @returns {Function} Returns the new capped function.
38615 * @example
38616 *
38617 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
38618 * // => [6, 8, 10]
38619 */
38620 function ary(func, n, guard) {
38621 n = guard ? undefined : n;
38622 n = (func && n == null) ? func.length : n;
38623 return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
38624 }
38625
38626 /**
38627 * Creates a function that invokes `func`, with the `this` binding and arguments
38628 * of the created function, while it's called less than `n` times. Subsequent
38629 * calls to the created function return the result of the last `func` invocation.
38630 *
38631 * @static
38632 * @memberOf _
38633 * @since 3.0.0
38634 * @category Function
38635 * @param {number} n The number of calls at which `func` is no longer invoked.
38636 * @param {Function} func The function to restrict.
38637 * @returns {Function} Returns the new restricted function.
38638 * @example
38639 *
38640 * jQuery(element).on('click', _.before(5, addContactToList));
38641 * // => Allows adding up to 4 contacts to the list.
38642 */
38643 function before(n, func) {
38644 var result;
38645 if (typeof func != 'function') {
38646 throw new TypeError(FUNC_ERROR_TEXT);
38647 }
38648 n = toInteger(n);
38649 return function() {
38650 if (--n > 0) {
38651 result = func.apply(this, arguments);
38652 }
38653 if (n <= 1) {
38654 func = undefined;
38655 }
38656 return result;
38657 };
38658 }
38659
38660 /**
38661 * Creates a function that invokes `func` with the `this` binding of `thisArg`
38662 * and `partials` prepended to the arguments it receives.
38663 *
38664 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
38665 * may be used as a placeholder for partially applied arguments.
38666 *
38667 * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
38668 * property of bound functions.
38669 *
38670 * @static
38671 * @memberOf _
38672 * @since 0.1.0
38673 * @category Function
38674 * @param {Function} func The function to bind.
38675 * @param {*} thisArg The `this` binding of `func`.
38676 * @param {...*} [partials] The arguments to be partially applied.
38677 * @returns {Function} Returns the new bound function.
38678 * @example
38679 *
38680 * function greet(greeting, punctuation) {
38681 * return greeting + ' ' + this.user + punctuation;
38682 * }
38683 *
38684 * var object = { 'user': 'fred' };
38685 *
38686 * var bound = _.bind(greet, object, 'hi');
38687 * bound('!');
38688 * // => 'hi fred!'
38689 *
38690 * // Bound with placeholders.
38691 * var bound = _.bind(greet, object, _, '!');
38692 * bound('hi');
38693 * // => 'hi fred!'
38694 */
38695 var bind = baseRest(function(func, thisArg, partials) {
38696 var bitmask = WRAP_BIND_FLAG;
38697 if (partials.length) {
38698 var holders = replaceHolders(partials, getHolder(bind));
38699 bitmask |= WRAP_PARTIAL_FLAG;
38700 }
38701 return createWrap(func, bitmask, thisArg, partials, holders);
38702 });
38703
38704 /**
38705 * Creates a function that invokes the method at `object[key]` with `partials`
38706 * prepended to the arguments it receives.
38707 *
38708 * This method differs from `_.bind` by allowing bound functions to reference
38709 * methods that may be redefined or don't yet exist. See
38710 * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
38711 * for more details.
38712 *
38713 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
38714 * builds, may be used as a placeholder for partially applied arguments.
38715 *
38716 * @static
38717 * @memberOf _
38718 * @since 0.10.0
38719 * @category Function
38720 * @param {Object} object The object to invoke the method on.
38721 * @param {string} key The key of the method.
38722 * @param {...*} [partials] The arguments to be partially applied.
38723 * @returns {Function} Returns the new bound function.
38724 * @example
38725 *
38726 * var object = {
38727 * 'user': 'fred',
38728 * 'greet': function(greeting, punctuation) {
38729 * return greeting + ' ' + this.user + punctuation;
38730 * }
38731 * };
38732 *
38733 * var bound = _.bindKey(object, 'greet', 'hi');
38734 * bound('!');
38735 * // => 'hi fred!'
38736 *
38737 * object.greet = function(greeting, punctuation) {
38738 * return greeting + 'ya ' + this.user + punctuation;
38739 * };
38740 *
38741 * bound('!');
38742 * // => 'hiya fred!'
38743 *
38744 * // Bound with placeholders.
38745 * var bound = _.bindKey(object, 'greet', _, '!');
38746 * bound('hi');
38747 * // => 'hiya fred!'
38748 */
38749 var bindKey = baseRest(function(object, key, partials) {
38750 var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
38751 if (partials.length) {
38752 var holders = replaceHolders(partials, getHolder(bindKey));
38753 bitmask |= WRAP_PARTIAL_FLAG;
38754 }
38755 return createWrap(key, bitmask, object, partials, holders);
38756 });
38757
38758 /**
38759 * Creates a function that accepts arguments of `func` and either invokes
38760 * `func` returning its result, if at least `arity` number of arguments have
38761 * been provided, or returns a function that accepts the remaining `func`
38762 * arguments, and so on. The arity of `func` may be specified if `func.length`
38763 * is not sufficient.
38764 *
38765 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
38766 * may be used as a placeholder for provided arguments.
38767 *
38768 * **Note:** This method doesn't set the "length" property of curried functions.
38769 *
38770 * @static
38771 * @memberOf _
38772 * @since 2.0.0
38773 * @category Function
38774 * @param {Function} func The function to curry.
38775 * @param {number} [arity=func.length] The arity of `func`.
38776 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38777 * @returns {Function} Returns the new curried function.
38778 * @example
38779 *
38780 * var abc = function(a, b, c) {
38781 * return [a, b, c];
38782 * };
38783 *
38784 * var curried = _.curry(abc);
38785 *
38786 * curried(1)(2)(3);
38787 * // => [1, 2, 3]
38788 *
38789 * curried(1, 2)(3);
38790 * // => [1, 2, 3]
38791 *
38792 * curried(1, 2, 3);
38793 * // => [1, 2, 3]
38794 *
38795 * // Curried with placeholders.
38796 * curried(1)(_, 3)(2);
38797 * // => [1, 2, 3]
38798 */
38799 function curry(func, arity, guard) {
38800 arity = guard ? undefined : arity;
38801 var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
38802 result.placeholder = curry.placeholder;
38803 return result;
38804 }
38805
38806 /**
38807 * This method is like `_.curry` except that arguments are applied to `func`
38808 * in the manner of `_.partialRight` instead of `_.partial`.
38809 *
38810 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
38811 * builds, may be used as a placeholder for provided arguments.
38812 *
38813 * **Note:** This method doesn't set the "length" property of curried functions.
38814 *
38815 * @static
38816 * @memberOf _
38817 * @since 3.0.0
38818 * @category Function
38819 * @param {Function} func The function to curry.
38820 * @param {number} [arity=func.length] The arity of `func`.
38821 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38822 * @returns {Function} Returns the new curried function.
38823 * @example
38824 *
38825 * var abc = function(a, b, c) {
38826 * return [a, b, c];
38827 * };
38828 *
38829 * var curried = _.curryRight(abc);
38830 *
38831 * curried(3)(2)(1);
38832 * // => [1, 2, 3]
38833 *
38834 * curried(2, 3)(1);
38835 * // => [1, 2, 3]
38836 *
38837 * curried(1, 2, 3);
38838 * // => [1, 2, 3]
38839 *
38840 * // Curried with placeholders.
38841 * curried(3)(1, _)(2);
38842 * // => [1, 2, 3]
38843 */
38844 function curryRight(func, arity, guard) {
38845 arity = guard ? undefined : arity;
38846 var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
38847 result.placeholder = curryRight.placeholder;
38848 return result;
38849 }
38850
38851 /**
38852 * Creates a debounced function that delays invoking `func` until after `wait`
38853 * milliseconds have elapsed since the last time the debounced function was
38854 * invoked. The debounced function comes with a `cancel` method to cancel
38855 * delayed `func` invocations and a `flush` method to immediately invoke them.
38856 * Provide `options` to indicate whether `func` should be invoked on the
38857 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
38858 * with the last arguments provided to the debounced function. Subsequent
38859 * calls to the debounced function return the result of the last `func`
38860 * invocation.
38861 *
38862 * **Note:** If `leading` and `trailing` options are `true`, `func` is
38863 * invoked on the trailing edge of the timeout only if the debounced function
38864 * is invoked more than once during the `wait` timeout.
38865 *
38866 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
38867 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
38868 *
38869 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
38870 * for details over the differences between `_.debounce` and `_.throttle`.
38871 *
38872 * @static
38873 * @memberOf _
38874 * @since 0.1.0
38875 * @category Function
38876 * @param {Function} func The function to debounce.
38877 * @param {number} [wait=0] The number of milliseconds to delay.
38878 * @param {Object} [options={}] The options object.
38879 * @param {boolean} [options.leading=false]
38880 * Specify invoking on the leading edge of the timeout.
38881 * @param {number} [options.maxWait]
38882 * The maximum time `func` is allowed to be delayed before it's invoked.
38883 * @param {boolean} [options.trailing=true]
38884 * Specify invoking on the trailing edge of the timeout.
38885 * @returns {Function} Returns the new debounced function.
38886 * @example
38887 *
38888 * // Avoid costly calculations while the window size is in flux.
38889 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
38890 *
38891 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
38892 * jQuery(element).on('click', _.debounce(sendMail, 300, {
38893 * 'leading': true,
38894 * 'trailing': false
38895 * }));
38896 *
38897 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
38898 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
38899 * var source = new EventSource('/stream');
38900 * jQuery(source).on('message', debounced);
38901 *
38902 * // Cancel the trailing debounced invocation.
38903 * jQuery(window).on('popstate', debounced.cancel);
38904 */
38905 function debounce(func, wait, options) {
38906 var lastArgs,
38907 lastThis,
38908 maxWait,
38909 result,
38910 timerId,
38911 lastCallTime,
38912 lastInvokeTime = 0,
38913 leading = false,
38914 maxing = false,
38915 trailing = true;
38916
38917 if (typeof func != 'function') {
38918 throw new TypeError(FUNC_ERROR_TEXT);
38919 }
38920 wait = toNumber(wait) || 0;
38921 if (isObject(options)) {
38922 leading = !!options.leading;
38923 maxing = 'maxWait' in options;
38924 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
38925 trailing = 'trailing' in options ? !!options.trailing : trailing;
38926 }
38927
38928 function invokeFunc(time) {
38929 var args = lastArgs,
38930 thisArg = lastThis;
38931
38932 lastArgs = lastThis = undefined;
38933 lastInvokeTime = time;
38934 result = func.apply(thisArg, args);
38935 return result;
38936 }
38937
38938 function leadingEdge(time) {
38939 // Reset any `maxWait` timer.
38940 lastInvokeTime = time;
38941 // Start the timer for the trailing edge.
38942 timerId = setTimeout(timerExpired, wait);
38943 // Invoke the leading edge.
38944 return leading ? invokeFunc(time) : result;
38945 }
38946
38947 function remainingWait(time) {
38948 var timeSinceLastCall = time - lastCallTime,
38949 timeSinceLastInvoke = time - lastInvokeTime,
38950 timeWaiting = wait - timeSinceLastCall;
38951
38952 return maxing
38953 ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
38954 : timeWaiting;
38955 }
38956
38957 function shouldInvoke(time) {
38958 var timeSinceLastCall = time - lastCallTime,
38959 timeSinceLastInvoke = time - lastInvokeTime;
38960
38961 // Either this is the first call, activity has stopped and we're at the
38962 // trailing edge, the system time has gone backwards and we're treating
38963 // it as the trailing edge, or we've hit the `maxWait` limit.
38964 return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
38965 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
38966 }
38967
38968 function timerExpired() {
38969 var time = now();
38970 if (shouldInvoke(time)) {
38971 return trailingEdge(time);
38972 }
38973 // Restart the timer.
38974 timerId = setTimeout(timerExpired, remainingWait(time));
38975 }
38976
38977 function trailingEdge(time) {
38978 timerId = undefined;
38979
38980 // Only invoke if we have `lastArgs` which means `func` has been
38981 // debounced at least once.
38982 if (trailing && lastArgs) {
38983 return invokeFunc(time);
38984 }
38985 lastArgs = lastThis = undefined;
38986 return result;
38987 }
38988
38989 function cancel() {
38990 if (timerId !== undefined) {
38991 clearTimeout(timerId);
38992 }
38993 lastInvokeTime = 0;
38994 lastArgs = lastCallTime = lastThis = timerId = undefined;
38995 }
38996
38997 function flush() {
38998 return timerId === undefined ? result : trailingEdge(now());
38999 }
39000
39001 function debounced() {
39002 var time = now(),
39003 isInvoking = shouldInvoke(time);
39004
39005 lastArgs = arguments;
39006 lastThis = this;
39007 lastCallTime = time;
39008
39009 if (isInvoking) {
39010 if (timerId === undefined) {
39011 return leadingEdge(lastCallTime);
39012 }
39013 if (maxing) {
39014 // Handle invocations in a tight loop.
39015 clearTimeout(timerId);
39016 timerId = setTimeout(timerExpired, wait);
39017 return invokeFunc(lastCallTime);
39018 }
39019 }
39020 if (timerId === undefined) {
39021 timerId = setTimeout(timerExpired, wait);
39022 }
39023 return result;
39024 }
39025 debounced.cancel = cancel;
39026 debounced.flush = flush;
39027 return debounced;
39028 }
39029
39030 /**
39031 * Defers invoking the `func` until the current call stack has cleared. Any
39032 * additional arguments are provided to `func` when it's invoked.
39033 *
39034 * @static
39035 * @memberOf _
39036 * @since 0.1.0
39037 * @category Function
39038 * @param {Function} func The function to defer.
39039 * @param {...*} [args] The arguments to invoke `func` with.
39040 * @returns {number} Returns the timer id.
39041 * @example
39042 *
39043 * _.defer(function(text) {
39044 * console.log(text);
39045 * }, 'deferred');
39046 * // => Logs 'deferred' after one millisecond.
39047 */
39048 var defer = baseRest(function(func, args) {
39049 return baseDelay(func, 1, args);
39050 });
39051
39052 /**
39053 * Invokes `func` after `wait` milliseconds. Any additional arguments are
39054 * provided to `func` when it's invoked.
39055 *
39056 * @static
39057 * @memberOf _
39058 * @since 0.1.0
39059 * @category Function
39060 * @param {Function} func The function to delay.
39061 * @param {number} wait The number of milliseconds to delay invocation.
39062 * @param {...*} [args] The arguments to invoke `func` with.
39063 * @returns {number} Returns the timer id.
39064 * @example
39065 *
39066 * _.delay(function(text) {
39067 * console.log(text);
39068 * }, 1000, 'later');
39069 * // => Logs 'later' after one second.
39070 */
39071 var delay = baseRest(function(func, wait, args) {
39072 return baseDelay(func, toNumber(wait) || 0, args);
39073 });
39074
39075 /**
39076 * Creates a function that invokes `func` with arguments reversed.
39077 *
39078 * @static
39079 * @memberOf _
39080 * @since 4.0.0
39081 * @category Function
39082 * @param {Function} func The function to flip arguments for.
39083 * @returns {Function} Returns the new flipped function.
39084 * @example
39085 *
39086 * var flipped = _.flip(function() {
39087 * return _.toArray(arguments);
39088 * });
39089 *
39090 * flipped('a', 'b', 'c', 'd');
39091 * // => ['d', 'c', 'b', 'a']
39092 */
39093 function flip(func) {
39094 return createWrap(func, WRAP_FLIP_FLAG);
39095 }
39096
39097 /**
39098 * Creates a function that memoizes the result of `func`. If `resolver` is
39099 * provided, it determines the cache key for storing the result based on the
39100 * arguments provided to the memoized function. By default, the first argument
39101 * provided to the memoized function is used as the map cache key. The `func`
39102 * is invoked with the `this` binding of the memoized function.
39103 *
39104 * **Note:** The cache is exposed as the `cache` property on the memoized
39105 * function. Its creation may be customized by replacing the `_.memoize.Cache`
39106 * constructor with one whose instances implement the
39107 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
39108 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
39109 *
39110 * @static
39111 * @memberOf _
39112 * @since 0.1.0
39113 * @category Function
39114 * @param {Function} func The function to have its output memoized.
39115 * @param {Function} [resolver] The function to resolve the cache key.
39116 * @returns {Function} Returns the new memoized function.
39117 * @example
39118 *
39119 * var object = { 'a': 1, 'b': 2 };
39120 * var other = { 'c': 3, 'd': 4 };
39121 *
39122 * var values = _.memoize(_.values);
39123 * values(object);
39124 * // => [1, 2]
39125 *
39126 * values(other);
39127 * // => [3, 4]
39128 *
39129 * object.a = 2;
39130 * values(object);
39131 * // => [1, 2]
39132 *
39133 * // Modify the result cache.
39134 * values.cache.set(object, ['a', 'b']);
39135 * values(object);
39136 * // => ['a', 'b']
39137 *
39138 * // Replace `_.memoize.Cache`.
39139 * _.memoize.Cache = WeakMap;
39140 */
39141 function memoize(func, resolver) {
39142 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
39143 throw new TypeError(FUNC_ERROR_TEXT);
39144 }
39145 var memoized = function() {
39146 var args = arguments,
39147 key = resolver ? resolver.apply(this, args) : args[0],
39148 cache = memoized.cache;
39149
39150 if (cache.has(key)) {
39151 return cache.get(key);
39152 }
39153 var result = func.apply(this, args);
39154 memoized.cache = cache.set(key, result) || cache;
39155 return result;
39156 };
39157 memoized.cache = new (memoize.Cache || MapCache);
39158 return memoized;
39159 }
39160
39161 // Expose `MapCache`.
39162 memoize.Cache = MapCache;
39163
39164 /**
39165 * Creates a function that negates the result of the predicate `func`. The
39166 * `func` predicate is invoked with the `this` binding and arguments of the
39167 * created function.
39168 *
39169 * @static
39170 * @memberOf _
39171 * @since 3.0.0
39172 * @category Function
39173 * @param {Function} predicate The predicate to negate.
39174 * @returns {Function} Returns the new negated function.
39175 * @example
39176 *
39177 * function isEven(n) {
39178 * return n % 2 == 0;
39179 * }
39180 *
39181 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
39182 * // => [1, 3, 5]
39183 */
39184 function negate(predicate) {
39185 if (typeof predicate != 'function') {
39186 throw new TypeError(FUNC_ERROR_TEXT);
39187 }
39188 return function() {
39189 var args = arguments;
39190 switch (args.length) {
39191 case 0: return !predicate.call(this);
39192 case 1: return !predicate.call(this, args[0]);
39193 case 2: return !predicate.call(this, args[0], args[1]);
39194 case 3: return !predicate.call(this, args[0], args[1], args[2]);
39195 }
39196 return !predicate.apply(this, args);
39197 };
39198 }
39199
39200 /**
39201 * Creates a function that is restricted to invoking `func` once. Repeat calls
39202 * to the function return the value of the first invocation. The `func` is
39203 * invoked with the `this` binding and arguments of the created function.
39204 *
39205 * @static
39206 * @memberOf _
39207 * @since 0.1.0
39208 * @category Function
39209 * @param {Function} func The function to restrict.
39210 * @returns {Function} Returns the new restricted function.
39211 * @example
39212 *
39213 * var initialize = _.once(createApplication);
39214 * initialize();
39215 * initialize();
39216 * // => `createApplication` is invoked once
39217 */
39218 function once(func) {
39219 return before(2, func);
39220 }
39221
39222 /**
39223 * Creates a function that invokes `func` with its arguments transformed.
39224 *
39225 * @static
39226 * @since 4.0.0
39227 * @memberOf _
39228 * @category Function
39229 * @param {Function} func The function to wrap.
39230 * @param {...(Function|Function[])} [transforms=[_.identity]]
39231 * The argument transforms.
39232 * @returns {Function} Returns the new function.
39233 * @example
39234 *
39235 * function doubled(n) {
39236 * return n * 2;
39237 * }
39238 *
39239 * function square(n) {
39240 * return n * n;
39241 * }
39242 *
39243 * var func = _.overArgs(function(x, y) {
39244 * return [x, y];
39245 * }, [square, doubled]);
39246 *
39247 * func(9, 3);
39248 * // => [81, 6]
39249 *
39250 * func(10, 5);
39251 * // => [100, 10]
39252 */
39253 var overArgs = castRest(function(func, transforms) {
39254 transforms = (transforms.length == 1 && isArray(transforms[0]))
39255 ? arrayMap(transforms[0], baseUnary(getIteratee()))
39256 : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
39257
39258 var funcsLength = transforms.length;
39259 return baseRest(function(args) {
39260 var index = -1,
39261 length = nativeMin(args.length, funcsLength);
39262
39263 while (++index < length) {
39264 args[index] = transforms[index].call(this, args[index]);
39265 }
39266 return apply(func, this, args);
39267 });
39268 });
39269
39270 /**
39271 * Creates a function that invokes `func` with `partials` prepended to the
39272 * arguments it receives. This method is like `_.bind` except it does **not**
39273 * alter the `this` binding.
39274 *
39275 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
39276 * builds, may be used as a placeholder for partially applied arguments.
39277 *
39278 * **Note:** This method doesn't set the "length" property of partially
39279 * applied functions.
39280 *
39281 * @static
39282 * @memberOf _
39283 * @since 0.2.0
39284 * @category Function
39285 * @param {Function} func The function to partially apply arguments to.
39286 * @param {...*} [partials] The arguments to be partially applied.
39287 * @returns {Function} Returns the new partially applied function.
39288 * @example
39289 *
39290 * function greet(greeting, name) {
39291 * return greeting + ' ' + name;
39292 * }
39293 *
39294 * var sayHelloTo = _.partial(greet, 'hello');
39295 * sayHelloTo('fred');
39296 * // => 'hello fred'
39297 *
39298 * // Partially applied with placeholders.
39299 * var greetFred = _.partial(greet, _, 'fred');
39300 * greetFred('hi');
39301 * // => 'hi fred'
39302 */
39303 var partial = baseRest(function(func, partials) {
39304 var holders = replaceHolders(partials, getHolder(partial));
39305 return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
39306 });
39307
39308 /**
39309 * This method is like `_.partial` except that partially applied arguments
39310 * are appended to the arguments it receives.
39311 *
39312 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
39313 * builds, may be used as a placeholder for partially applied arguments.
39314 *
39315 * **Note:** This method doesn't set the "length" property of partially
39316 * applied functions.
39317 *
39318 * @static
39319 * @memberOf _
39320 * @since 1.0.0
39321 * @category Function
39322 * @param {Function} func The function to partially apply arguments to.
39323 * @param {...*} [partials] The arguments to be partially applied.
39324 * @returns {Function} Returns the new partially applied function.
39325 * @example
39326 *
39327 * function greet(greeting, name) {
39328 * return greeting + ' ' + name;
39329 * }
39330 *
39331 * var greetFred = _.partialRight(greet, 'fred');
39332 * greetFred('hi');
39333 * // => 'hi fred'
39334 *
39335 * // Partially applied with placeholders.
39336 * var sayHelloTo = _.partialRight(greet, 'hello', _);
39337 * sayHelloTo('fred');
39338 * // => 'hello fred'
39339 */
39340 var partialRight = baseRest(function(func, partials) {
39341 var holders = replaceHolders(partials, getHolder(partialRight));
39342 return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
39343 });
39344
39345 /**
39346 * Creates a function that invokes `func` with arguments arranged according
39347 * to the specified `indexes` where the argument value at the first index is
39348 * provided as the first argument, the argument value at the second index is
39349 * provided as the second argument, and so on.
39350 *
39351 * @static
39352 * @memberOf _
39353 * @since 3.0.0
39354 * @category Function
39355 * @param {Function} func The function to rearrange arguments for.
39356 * @param {...(number|number[])} indexes The arranged argument indexes.
39357 * @returns {Function} Returns the new function.
39358 * @example
39359 *
39360 * var rearged = _.rearg(function(a, b, c) {
39361 * return [a, b, c];
39362 * }, [2, 0, 1]);
39363 *
39364 * rearged('b', 'c', 'a')
39365 * // => ['a', 'b', 'c']
39366 */
39367 var rearg = flatRest(function(func, indexes) {
39368 return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
39369 });
39370
39371 /**
39372 * Creates a function that invokes `func` with the `this` binding of the
39373 * created function and arguments from `start` and beyond provided as
39374 * an array.
39375 *
39376 * **Note:** This method is based on the
39377 * [rest parameter](https://mdn.io/rest_parameters).
39378 *
39379 * @static
39380 * @memberOf _
39381 * @since 4.0.0
39382 * @category Function
39383 * @param {Function} func The function to apply a rest parameter to.
39384 * @param {number} [start=func.length-1] The start position of the rest parameter.
39385 * @returns {Function} Returns the new function.
39386 * @example
39387 *
39388 * var say = _.rest(function(what, names) {
39389 * return what + ' ' + _.initial(names).join(', ') +
39390 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
39391 * });
39392 *
39393 * say('hello', 'fred', 'barney', 'pebbles');
39394 * // => 'hello fred, barney, & pebbles'
39395 */
39396 function rest(func, start) {
39397 if (typeof func != 'function') {
39398 throw new TypeError(FUNC_ERROR_TEXT);
39399 }
39400 start = start === undefined ? start : toInteger(start);
39401 return baseRest(func, start);
39402 }
39403
39404 /**
39405 * Creates a function that invokes `func` with the `this` binding of the
39406 * create function and an array of arguments much like
39407 * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
39408 *
39409 * **Note:** This method is based on the
39410 * [spread operator](https://mdn.io/spread_operator).
39411 *
39412 * @static
39413 * @memberOf _
39414 * @since 3.2.0
39415 * @category Function
39416 * @param {Function} func The function to spread arguments over.
39417 * @param {number} [start=0] The start position of the spread.
39418 * @returns {Function} Returns the new function.
39419 * @example
39420 *
39421 * var say = _.spread(function(who, what) {
39422 * return who + ' says ' + what;
39423 * });
39424 *
39425 * say(['fred', 'hello']);
39426 * // => 'fred says hello'
39427 *
39428 * var numbers = Promise.all([
39429 * Promise.resolve(40),
39430 * Promise.resolve(36)
39431 * ]);
39432 *
39433 * numbers.then(_.spread(function(x, y) {
39434 * return x + y;
39435 * }));
39436 * // => a Promise of 76
39437 */
39438 function spread(func, start) {
39439 if (typeof func != 'function') {
39440 throw new TypeError(FUNC_ERROR_TEXT);
39441 }
39442 start = start == null ? 0 : nativeMax(toInteger(start), 0);
39443 return baseRest(function(args) {
39444 var array = args[start],
39445 otherArgs = castSlice(args, 0, start);
39446
39447 if (array) {
39448 arrayPush(otherArgs, array);
39449 }
39450 return apply(func, this, otherArgs);
39451 });
39452 }
39453
39454 /**
39455 * Creates a throttled function that only invokes `func` at most once per
39456 * every `wait` milliseconds. The throttled function comes with a `cancel`
39457 * method to cancel delayed `func` invocations and a `flush` method to
39458 * immediately invoke them. Provide `options` to indicate whether `func`
39459 * should be invoked on the leading and/or trailing edge of the `wait`
39460 * timeout. The `func` is invoked with the last arguments provided to the
39461 * throttled function. Subsequent calls to the throttled function return the
39462 * result of the last `func` invocation.
39463 *
39464 * **Note:** If `leading` and `trailing` options are `true`, `func` is
39465 * invoked on the trailing edge of the timeout only if the throttled function
39466 * is invoked more than once during the `wait` timeout.
39467 *
39468 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
39469 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
39470 *
39471 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
39472 * for details over the differences between `_.throttle` and `_.debounce`.
39473 *
39474 * @static
39475 * @memberOf _
39476 * @since 0.1.0
39477 * @category Function
39478 * @param {Function} func The function to throttle.
39479 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
39480 * @param {Object} [options={}] The options object.
39481 * @param {boolean} [options.leading=true]
39482 * Specify invoking on the leading edge of the timeout.
39483 * @param {boolean} [options.trailing=true]
39484 * Specify invoking on the trailing edge of the timeout.
39485 * @returns {Function} Returns the new throttled function.
39486 * @example
39487 *
39488 * // Avoid excessively updating the position while scrolling.
39489 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
39490 *
39491 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
39492 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
39493 * jQuery(element).on('click', throttled);
39494 *
39495 * // Cancel the trailing throttled invocation.
39496 * jQuery(window).on('popstate', throttled.cancel);
39497 */
39498 function throttle(func, wait, options) {
39499 var leading = true,
39500 trailing = true;
39501
39502 if (typeof func != 'function') {
39503 throw new TypeError(FUNC_ERROR_TEXT);
39504 }
39505 if (isObject(options)) {
39506 leading = 'leading' in options ? !!options.leading : leading;
39507 trailing = 'trailing' in options ? !!options.trailing : trailing;
39508 }
39509 return debounce(func, wait, {
39510 'leading': leading,
39511 'maxWait': wait,
39512 'trailing': trailing
39513 });
39514 }
39515
39516 /**
39517 * Creates a function that accepts up to one argument, ignoring any
39518 * additional arguments.
39519 *
39520 * @static
39521 * @memberOf _
39522 * @since 4.0.0
39523 * @category Function
39524 * @param {Function} func The function to cap arguments for.
39525 * @returns {Function} Returns the new capped function.
39526 * @example
39527 *
39528 * _.map(['6', '8', '10'], _.unary(parseInt));
39529 * // => [6, 8, 10]
39530 */
39531 function unary(func) {
39532 return ary(func, 1);
39533 }
39534
39535 /**
39536 * Creates a function that provides `value` to `wrapper` as its first
39537 * argument. Any additional arguments provided to the function are appended
39538 * to those provided to the `wrapper`. The wrapper is invoked with the `this`
39539 * binding of the created function.
39540 *
39541 * @static
39542 * @memberOf _
39543 * @since 0.1.0
39544 * @category Function
39545 * @param {*} value The value to wrap.
39546 * @param {Function} [wrapper=identity] The wrapper function.
39547 * @returns {Function} Returns the new function.
39548 * @example
39549 *
39550 * var p = _.wrap(_.escape, function(func, text) {
39551 * return '<p>' + func(text) + '</p>';
39552 * });
39553 *
39554 * p('fred, barney, & pebbles');
39555 * // => '<p>fred, barney, &amp; pebbles</p>'
39556 */
39557 function wrap(value, wrapper) {
39558 return partial(castFunction(wrapper), value);
39559 }
39560
39561 /*------------------------------------------------------------------------*/
39562
39563 /**
39564 * Casts `value` as an array if it's not one.
39565 *
39566 * @static
39567 * @memberOf _
39568 * @since 4.4.0
39569 * @category Lang
39570 * @param {*} value The value to inspect.
39571 * @returns {Array} Returns the cast array.
39572 * @example
39573 *
39574 * _.castArray(1);
39575 * // => [1]
39576 *
39577 * _.castArray({ 'a': 1 });
39578 * // => [{ 'a': 1 }]
39579 *
39580 * _.castArray('abc');
39581 * // => ['abc']
39582 *
39583 * _.castArray(null);
39584 * // => [null]
39585 *
39586 * _.castArray(undefined);
39587 * // => [undefined]
39588 *
39589 * _.castArray();
39590 * // => []
39591 *
39592 * var array = [1, 2, 3];
39593 * console.log(_.castArray(array) === array);
39594 * // => true
39595 */
39596 function castArray() {
39597 if (!arguments.length) {
39598 return [];
39599 }
39600 var value = arguments[0];
39601 return isArray(value) ? value : [value];
39602 }
39603
39604 /**
39605 * Creates a shallow clone of `value`.
39606 *
39607 * **Note:** This method is loosely based on the
39608 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
39609 * and supports cloning arrays, array buffers, booleans, date objects, maps,
39610 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
39611 * arrays. The own enumerable properties of `arguments` objects are cloned
39612 * as plain objects. An empty object is returned for uncloneable values such
39613 * as error objects, functions, DOM nodes, and WeakMaps.
39614 *
39615 * @static
39616 * @memberOf _
39617 * @since 0.1.0
39618 * @category Lang
39619 * @param {*} value The value to clone.
39620 * @returns {*} Returns the cloned value.
39621 * @see _.cloneDeep
39622 * @example
39623 *
39624 * var objects = [{ 'a': 1 }, { 'b': 2 }];
39625 *
39626 * var shallow = _.clone(objects);
39627 * console.log(shallow[0] === objects[0]);
39628 * // => true
39629 */
39630 function clone(value) {
39631 return baseClone(value, CLONE_SYMBOLS_FLAG);
39632 }
39633
39634 /**
39635 * This method is like `_.clone` except that it accepts `customizer` which
39636 * is invoked to produce the cloned value. If `customizer` returns `undefined`,
39637 * cloning is handled by the method instead. The `customizer` is invoked with
39638 * up to four arguments; (value [, index|key, object, stack]).
39639 *
39640 * @static
39641 * @memberOf _
39642 * @since 4.0.0
39643 * @category Lang
39644 * @param {*} value The value to clone.
39645 * @param {Function} [customizer] The function to customize cloning.
39646 * @returns {*} Returns the cloned value.
39647 * @see _.cloneDeepWith
39648 * @example
39649 *
39650 * function customizer(value) {
39651 * if (_.isElement(value)) {
39652 * return value.cloneNode(false);
39653 * }
39654 * }
39655 *
39656 * var el = _.cloneWith(document.body, customizer);
39657 *
39658 * console.log(el === document.body);
39659 * // => false
39660 * console.log(el.nodeName);
39661 * // => 'BODY'
39662 * console.log(el.childNodes.length);
39663 * // => 0
39664 */
39665 function cloneWith(value, customizer) {
39666 customizer = typeof customizer == 'function' ? customizer : undefined;
39667 return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
39668 }
39669
39670 /**
39671 * This method is like `_.clone` except that it recursively clones `value`.
39672 *
39673 * @static
39674 * @memberOf _
39675 * @since 1.0.0
39676 * @category Lang
39677 * @param {*} value The value to recursively clone.
39678 * @returns {*} Returns the deep cloned value.
39679 * @see _.clone
39680 * @example
39681 *
39682 * var objects = [{ 'a': 1 }, { 'b': 2 }];
39683 *
39684 * var deep = _.cloneDeep(objects);
39685 * console.log(deep[0] === objects[0]);
39686 * // => false
39687 */
39688 function cloneDeep(value) {
39689 return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
39690 }
39691
39692 /**
39693 * This method is like `_.cloneWith` except that it recursively clones `value`.
39694 *
39695 * @static
39696 * @memberOf _
39697 * @since 4.0.0
39698 * @category Lang
39699 * @param {*} value The value to recursively clone.
39700 * @param {Function} [customizer] The function to customize cloning.
39701 * @returns {*} Returns the deep cloned value.
39702 * @see _.cloneWith
39703 * @example
39704 *
39705 * function customizer(value) {
39706 * if (_.isElement(value)) {
39707 * return value.cloneNode(true);
39708 * }
39709 * }
39710 *
39711 * var el = _.cloneDeepWith(document.body, customizer);
39712 *
39713 * console.log(el === document.body);
39714 * // => false
39715 * console.log(el.nodeName);
39716 * // => 'BODY'
39717 * console.log(el.childNodes.length);
39718 * // => 20
39719 */
39720 function cloneDeepWith(value, customizer) {
39721 customizer = typeof customizer == 'function' ? customizer : undefined;
39722 return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
39723 }
39724
39725 /**
39726 * Checks if `object` conforms to `source` by invoking the predicate
39727 * properties of `source` with the corresponding property values of `object`.
39728 *
39729 * **Note:** This method is equivalent to `_.conforms` when `source` is
39730 * partially applied.
39731 *
39732 * @static
39733 * @memberOf _
39734 * @since 4.14.0
39735 * @category Lang
39736 * @param {Object} object The object to inspect.
39737 * @param {Object} source The object of property predicates to conform to.
39738 * @returns {boolean} Returns `true` if `object` conforms, else `false`.
39739 * @example
39740 *
39741 * var object = { 'a': 1, 'b': 2 };
39742 *
39743 * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
39744 * // => true
39745 *
39746 * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
39747 * // => false
39748 */
39749 function conformsTo(object, source) {
39750 return source == null || baseConformsTo(object, source, keys(source));
39751 }
39752
39753 /**
39754 * Performs a
39755 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
39756 * comparison between two values to determine if they are equivalent.
39757 *
39758 * @static
39759 * @memberOf _
39760 * @since 4.0.0
39761 * @category Lang
39762 * @param {*} value The value to compare.
39763 * @param {*} other The other value to compare.
39764 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
39765 * @example
39766 *
39767 * var object = { 'a': 1 };
39768 * var other = { 'a': 1 };
39769 *
39770 * _.eq(object, object);
39771 * // => true
39772 *
39773 * _.eq(object, other);
39774 * // => false
39775 *
39776 * _.eq('a', 'a');
39777 * // => true
39778 *
39779 * _.eq('a', Object('a'));
39780 * // => false
39781 *
39782 * _.eq(NaN, NaN);
39783 * // => true
39784 */
39785 function eq(value, other) {
39786 return value === other || (value !== value && other !== other);
39787 }
39788
39789 /**
39790 * Checks if `value` is greater than `other`.
39791 *
39792 * @static
39793 * @memberOf _
39794 * @since 3.9.0
39795 * @category Lang
39796 * @param {*} value The value to compare.
39797 * @param {*} other The other value to compare.
39798 * @returns {boolean} Returns `true` if `value` is greater than `other`,
39799 * else `false`.
39800 * @see _.lt
39801 * @example
39802 *
39803 * _.gt(3, 1);
39804 * // => true
39805 *
39806 * _.gt(3, 3);
39807 * // => false
39808 *
39809 * _.gt(1, 3);
39810 * // => false
39811 */
39812 var gt = createRelationalOperation(baseGt);
39813
39814 /**
39815 * Checks if `value` is greater than or equal to `other`.
39816 *
39817 * @static
39818 * @memberOf _
39819 * @since 3.9.0
39820 * @category Lang
39821 * @param {*} value The value to compare.
39822 * @param {*} other The other value to compare.
39823 * @returns {boolean} Returns `true` if `value` is greater than or equal to
39824 * `other`, else `false`.
39825 * @see _.lte
39826 * @example
39827 *
39828 * _.gte(3, 1);
39829 * // => true
39830 *
39831 * _.gte(3, 3);
39832 * // => true
39833 *
39834 * _.gte(1, 3);
39835 * // => false
39836 */
39837 var gte = createRelationalOperation(function(value, other) {
39838 return value >= other;
39839 });
39840
39841 /**
39842 * Checks if `value` is likely an `arguments` object.
39843 *
39844 * @static
39845 * @memberOf _
39846 * @since 0.1.0
39847 * @category Lang
39848 * @param {*} value The value to check.
39849 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
39850 * else `false`.
39851 * @example
39852 *
39853 * _.isArguments(function() { return arguments; }());
39854 * // => true
39855 *
39856 * _.isArguments([1, 2, 3]);
39857 * // => false
39858 */
39859 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
39860 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
39861 !propertyIsEnumerable.call(value, 'callee');
39862 };
39863
39864 /**
39865 * Checks if `value` is classified as an `Array` object.
39866 *
39867 * @static
39868 * @memberOf _
39869 * @since 0.1.0
39870 * @category Lang
39871 * @param {*} value The value to check.
39872 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
39873 * @example
39874 *
39875 * _.isArray([1, 2, 3]);
39876 * // => true
39877 *
39878 * _.isArray(document.body.children);
39879 * // => false
39880 *
39881 * _.isArray('abc');
39882 * // => false
39883 *
39884 * _.isArray(_.noop);
39885 * // => false
39886 */
39887 var isArray = Array.isArray;
39888
39889 /**
39890 * Checks if `value` is classified as an `ArrayBuffer` object.
39891 *
39892 * @static
39893 * @memberOf _
39894 * @since 4.3.0
39895 * @category Lang
39896 * @param {*} value The value to check.
39897 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
39898 * @example
39899 *
39900 * _.isArrayBuffer(new ArrayBuffer(2));
39901 * // => true
39902 *
39903 * _.isArrayBuffer(new Array(2));
39904 * // => false
39905 */
39906 var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
39907
39908 /**
39909 * Checks if `value` is array-like. A value is considered array-like if it's
39910 * not a function and has a `value.length` that's an integer greater than or
39911 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
39912 *
39913 * @static
39914 * @memberOf _
39915 * @since 4.0.0
39916 * @category Lang
39917 * @param {*} value The value to check.
39918 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
39919 * @example
39920 *
39921 * _.isArrayLike([1, 2, 3]);
39922 * // => true
39923 *
39924 * _.isArrayLike(document.body.children);
39925 * // => true
39926 *
39927 * _.isArrayLike('abc');
39928 * // => true
39929 *
39930 * _.isArrayLike(_.noop);
39931 * // => false
39932 */
39933 function isArrayLike(value) {
39934 return value != null && isLength(value.length) && !isFunction(value);
39935 }
39936
39937 /**
39938 * This method is like `_.isArrayLike` except that it also checks if `value`
39939 * is an object.
39940 *
39941 * @static
39942 * @memberOf _
39943 * @since 4.0.0
39944 * @category Lang
39945 * @param {*} value The value to check.
39946 * @returns {boolean} Returns `true` if `value` is an array-like object,
39947 * else `false`.
39948 * @example
39949 *
39950 * _.isArrayLikeObject([1, 2, 3]);
39951 * // => true
39952 *
39953 * _.isArrayLikeObject(document.body.children);
39954 * // => true
39955 *
39956 * _.isArrayLikeObject('abc');
39957 * // => false
39958 *
39959 * _.isArrayLikeObject(_.noop);
39960 * // => false
39961 */
39962 function isArrayLikeObject(value) {
39963 return isObjectLike(value) && isArrayLike(value);
39964 }
39965
39966 /**
39967 * Checks if `value` is classified as a boolean primitive or object.
39968 *
39969 * @static
39970 * @memberOf _
39971 * @since 0.1.0
39972 * @category Lang
39973 * @param {*} value The value to check.
39974 * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
39975 * @example
39976 *
39977 * _.isBoolean(false);
39978 * // => true
39979 *
39980 * _.isBoolean(null);
39981 * // => false
39982 */
39983 function isBoolean(value) {
39984 return value === true || value === false ||
39985 (isObjectLike(value) && baseGetTag(value) == boolTag);
39986 }
39987
39988 /**
39989 * Checks if `value` is a buffer.
39990 *
39991 * @static
39992 * @memberOf _
39993 * @since 4.3.0
39994 * @category Lang
39995 * @param {*} value The value to check.
39996 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
39997 * @example
39998 *
39999 * _.isBuffer(new Buffer(2));
40000 * // => true
40001 *
40002 * _.isBuffer(new Uint8Array(2));
40003 * // => false
40004 */
40005 var isBuffer = nativeIsBuffer || stubFalse;
40006
40007 /**
40008 * Checks if `value` is classified as a `Date` object.
40009 *
40010 * @static
40011 * @memberOf _
40012 * @since 0.1.0
40013 * @category Lang
40014 * @param {*} value The value to check.
40015 * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
40016 * @example
40017 *
40018 * _.isDate(new Date);
40019 * // => true
40020 *
40021 * _.isDate('Mon April 23 2012');
40022 * // => false
40023 */
40024 var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
40025
40026 /**
40027 * Checks if `value` is likely a DOM element.
40028 *
40029 * @static
40030 * @memberOf _
40031 * @since 0.1.0
40032 * @category Lang
40033 * @param {*} value The value to check.
40034 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
40035 * @example
40036 *
40037 * _.isElement(document.body);
40038 * // => true
40039 *
40040 * _.isElement('<body>');
40041 * // => false
40042 */
40043 function isElement(value) {
40044 return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
40045 }
40046
40047 /**
40048 * Checks if `value` is an empty object, collection, map, or set.
40049 *
40050 * Objects are considered empty if they have no own enumerable string keyed
40051 * properties.
40052 *
40053 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
40054 * jQuery-like collections are considered empty if they have a `length` of `0`.
40055 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
40056 *
40057 * @static
40058 * @memberOf _
40059 * @since 0.1.0
40060 * @category Lang
40061 * @param {*} value The value to check.
40062 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
40063 * @example
40064 *
40065 * _.isEmpty(null);
40066 * // => true
40067 *
40068 * _.isEmpty(true);
40069 * // => true
40070 *
40071 * _.isEmpty(1);
40072 * // => true
40073 *
40074 * _.isEmpty([1, 2, 3]);
40075 * // => false
40076 *
40077 * _.isEmpty({ 'a': 1 });
40078 * // => false
40079 */
40080 function isEmpty(value) {
40081 if (value == null) {
40082 return true;
40083 }
40084 if (isArrayLike(value) &&
40085 (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
40086 isBuffer(value) || isTypedArray(value) || isArguments(value))) {
40087 return !value.length;
40088 }
40089 var tag = getTag(value);
40090 if (tag == mapTag || tag == setTag) {
40091 return !value.size;
40092 }
40093 if (isPrototype(value)) {
40094 return !baseKeys(value).length;
40095 }
40096 for (var key in value) {
40097 if (hasOwnProperty.call(value, key)) {
40098 return false;
40099 }
40100 }
40101 return true;
40102 }
40103
40104 /**
40105 * Performs a deep comparison between two values to determine if they are
40106 * equivalent.
40107 *
40108 * **Note:** This method supports comparing arrays, array buffers, booleans,
40109 * date objects, error objects, maps, numbers, `Object` objects, regexes,
40110 * sets, strings, symbols, and typed arrays. `Object` objects are compared
40111 * by their own, not inherited, enumerable properties. Functions and DOM
40112 * nodes are compared by strict equality, i.e. `===`.
40113 *
40114 * @static
40115 * @memberOf _
40116 * @since 0.1.0
40117 * @category Lang
40118 * @param {*} value The value to compare.
40119 * @param {*} other The other value to compare.
40120 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
40121 * @example
40122 *
40123 * var object = { 'a': 1 };
40124 * var other = { 'a': 1 };
40125 *
40126 * _.isEqual(object, other);
40127 * // => true
40128 *
40129 * object === other;
40130 * // => false
40131 */
40132 function isEqual(value, other) {
40133 return baseIsEqual(value, other);
40134 }
40135
40136 /**
40137 * This method is like `_.isEqual` except that it accepts `customizer` which
40138 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
40139 * are handled by the method instead. The `customizer` is invoked with up to
40140 * six arguments: (objValue, othValue [, index|key, object, other, stack]).
40141 *
40142 * @static
40143 * @memberOf _
40144 * @since 4.0.0
40145 * @category Lang
40146 * @param {*} value The value to compare.
40147 * @param {*} other The other value to compare.
40148 * @param {Function} [customizer] The function to customize comparisons.
40149 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
40150 * @example
40151 *
40152 * function isGreeting(value) {
40153 * return /^h(?:i|ello)$/.test(value);
40154 * }
40155 *
40156 * function customizer(objValue, othValue) {
40157 * if (isGreeting(objValue) && isGreeting(othValue)) {
40158 * return true;
40159 * }
40160 * }
40161 *
40162 * var array = ['hello', 'goodbye'];
40163 * var other = ['hi', 'goodbye'];
40164 *
40165 * _.isEqualWith(array, other, customizer);
40166 * // => true
40167 */
40168 function isEqualWith(value, other, customizer) {
40169 customizer = typeof customizer == 'function' ? customizer : undefined;
40170 var result = customizer ? customizer(value, other) : undefined;
40171 return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
40172 }
40173
40174 /**
40175 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
40176 * `SyntaxError`, `TypeError`, or `URIError` object.
40177 *
40178 * @static
40179 * @memberOf _
40180 * @since 3.0.0
40181 * @category Lang
40182 * @param {*} value The value to check.
40183 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
40184 * @example
40185 *
40186 * _.isError(new Error);
40187 * // => true
40188 *
40189 * _.isError(Error);
40190 * // => false
40191 */
40192 function isError(value) {
40193 if (!isObjectLike(value)) {
40194 return false;
40195 }
40196 var tag = baseGetTag(value);
40197 return tag == errorTag || tag == domExcTag ||
40198 (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
40199 }
40200
40201 /**
40202 * Checks if `value` is a finite primitive number.
40203 *
40204 * **Note:** This method is based on
40205 * [`Number.isFinite`](https://mdn.io/Number/isFinite).
40206 *
40207 * @static
40208 * @memberOf _
40209 * @since 0.1.0
40210 * @category Lang
40211 * @param {*} value The value to check.
40212 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
40213 * @example
40214 *
40215 * _.isFinite(3);
40216 * // => true
40217 *
40218 * _.isFinite(Number.MIN_VALUE);
40219 * // => true
40220 *
40221 * _.isFinite(Infinity);
40222 * // => false
40223 *
40224 * _.isFinite('3');
40225 * // => false
40226 */
40227 function isFinite(value) {
40228 return typeof value == 'number' && nativeIsFinite(value);
40229 }
40230
40231 /**
40232 * Checks if `value` is classified as a `Function` object.
40233 *
40234 * @static
40235 * @memberOf _
40236 * @since 0.1.0
40237 * @category Lang
40238 * @param {*} value The value to check.
40239 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
40240 * @example
40241 *
40242 * _.isFunction(_);
40243 * // => true
40244 *
40245 * _.isFunction(/abc/);
40246 * // => false
40247 */
40248 function isFunction(value) {
40249 if (!isObject(value)) {
40250 return false;
40251 }
40252 // The use of `Object#toString` avoids issues with the `typeof` operator
40253 // in Safari 9 which returns 'object' for typed arrays and other constructors.
40254 var tag = baseGetTag(value);
40255 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
40256 }
40257
40258 /**
40259 * Checks if `value` is an integer.
40260 *
40261 * **Note:** This method is based on
40262 * [`Number.isInteger`](https://mdn.io/Number/isInteger).
40263 *
40264 * @static
40265 * @memberOf _
40266 * @since 4.0.0
40267 * @category Lang
40268 * @param {*} value The value to check.
40269 * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
40270 * @example
40271 *
40272 * _.isInteger(3);
40273 * // => true
40274 *
40275 * _.isInteger(Number.MIN_VALUE);
40276 * // => false
40277 *
40278 * _.isInteger(Infinity);
40279 * // => false
40280 *
40281 * _.isInteger('3');
40282 * // => false
40283 */
40284 function isInteger(value) {
40285 return typeof value == 'number' && value == toInteger(value);
40286 }
40287
40288 /**
40289 * Checks if `value` is a valid array-like length.
40290 *
40291 * **Note:** This method is loosely based on
40292 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
40293 *
40294 * @static
40295 * @memberOf _
40296 * @since 4.0.0
40297 * @category Lang
40298 * @param {*} value The value to check.
40299 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
40300 * @example
40301 *
40302 * _.isLength(3);
40303 * // => true
40304 *
40305 * _.isLength(Number.MIN_VALUE);
40306 * // => false
40307 *
40308 * _.isLength(Infinity);
40309 * // => false
40310 *
40311 * _.isLength('3');
40312 * // => false
40313 */
40314 function isLength(value) {
40315 return typeof value == 'number' &&
40316 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
40317 }
40318
40319 /**
40320 * Checks if `value` is the
40321 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
40322 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
40323 *
40324 * @static
40325 * @memberOf _
40326 * @since 0.1.0
40327 * @category Lang
40328 * @param {*} value The value to check.
40329 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
40330 * @example
40331 *
40332 * _.isObject({});
40333 * // => true
40334 *
40335 * _.isObject([1, 2, 3]);
40336 * // => true
40337 *
40338 * _.isObject(_.noop);
40339 * // => true
40340 *
40341 * _.isObject(null);
40342 * // => false
40343 */
40344 function isObject(value) {
40345 var type = typeof value;
40346 return value != null && (type == 'object' || type == 'function');
40347 }
40348
40349 /**
40350 * Checks if `value` is object-like. A value is object-like if it's not `null`
40351 * and has a `typeof` result of "object".
40352 *
40353 * @static
40354 * @memberOf _
40355 * @since 4.0.0
40356 * @category Lang
40357 * @param {*} value The value to check.
40358 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
40359 * @example
40360 *
40361 * _.isObjectLike({});
40362 * // => true
40363 *
40364 * _.isObjectLike([1, 2, 3]);
40365 * // => true
40366 *
40367 * _.isObjectLike(_.noop);
40368 * // => false
40369 *
40370 * _.isObjectLike(null);
40371 * // => false
40372 */
40373 function isObjectLike(value) {
40374 return value != null && typeof value == 'object';
40375 }
40376
40377 /**
40378 * Checks if `value` is classified as a `Map` object.
40379 *
40380 * @static
40381 * @memberOf _
40382 * @since 4.3.0
40383 * @category Lang
40384 * @param {*} value The value to check.
40385 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
40386 * @example
40387 *
40388 * _.isMap(new Map);
40389 * // => true
40390 *
40391 * _.isMap(new WeakMap);
40392 * // => false
40393 */
40394 var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
40395
40396 /**
40397 * Performs a partial deep comparison between `object` and `source` to
40398 * determine if `object` contains equivalent property values.
40399 *
40400 * **Note:** This method is equivalent to `_.matches` when `source` is
40401 * partially applied.
40402 *
40403 * Partial comparisons will match empty array and empty object `source`
40404 * values against any array or object value, respectively. See `_.isEqual`
40405 * for a list of supported value comparisons.
40406 *
40407 * @static
40408 * @memberOf _
40409 * @since 3.0.0
40410 * @category Lang
40411 * @param {Object} object The object to inspect.
40412 * @param {Object} source The object of property values to match.
40413 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
40414 * @example
40415 *
40416 * var object = { 'a': 1, 'b': 2 };
40417 *
40418 * _.isMatch(object, { 'b': 2 });
40419 * // => true
40420 *
40421 * _.isMatch(object, { 'b': 1 });
40422 * // => false
40423 */
40424 function isMatch(object, source) {
40425 return object === source || baseIsMatch(object, source, getMatchData(source));
40426 }
40427
40428 /**
40429 * This method is like `_.isMatch` except that it accepts `customizer` which
40430 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
40431 * are handled by the method instead. The `customizer` is invoked with five
40432 * arguments: (objValue, srcValue, index|key, object, source).
40433 *
40434 * @static
40435 * @memberOf _
40436 * @since 4.0.0
40437 * @category Lang
40438 * @param {Object} object The object to inspect.
40439 * @param {Object} source The object of property values to match.
40440 * @param {Function} [customizer] The function to customize comparisons.
40441 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
40442 * @example
40443 *
40444 * function isGreeting(value) {
40445 * return /^h(?:i|ello)$/.test(value);
40446 * }
40447 *
40448 * function customizer(objValue, srcValue) {
40449 * if (isGreeting(objValue) && isGreeting(srcValue)) {
40450 * return true;
40451 * }
40452 * }
40453 *
40454 * var object = { 'greeting': 'hello' };
40455 * var source = { 'greeting': 'hi' };
40456 *
40457 * _.isMatchWith(object, source, customizer);
40458 * // => true
40459 */
40460 function isMatchWith(object, source, customizer) {
40461 customizer = typeof customizer == 'function' ? customizer : undefined;
40462 return baseIsMatch(object, source, getMatchData(source), customizer);
40463 }
40464
40465 /**
40466 * Checks if `value` is `NaN`.
40467 *
40468 * **Note:** This method is based on
40469 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
40470 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
40471 * `undefined` and other non-number values.
40472 *
40473 * @static
40474 * @memberOf _
40475 * @since 0.1.0
40476 * @category Lang
40477 * @param {*} value The value to check.
40478 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
40479 * @example
40480 *
40481 * _.isNaN(NaN);
40482 * // => true
40483 *
40484 * _.isNaN(new Number(NaN));
40485 * // => true
40486 *
40487 * isNaN(undefined);
40488 * // => true
40489 *
40490 * _.isNaN(undefined);
40491 * // => false
40492 */
40493 function isNaN(value) {
40494 // An `NaN` primitive is the only value that is not equal to itself.
40495 // Perform the `toStringTag` check first to avoid errors with some
40496 // ActiveX objects in IE.
40497 return isNumber(value) && value != +value;
40498 }
40499
40500 /**
40501 * Checks if `value` is a pristine native function.
40502 *
40503 * **Note:** This method can't reliably detect native functions in the presence
40504 * of the core-js package because core-js circumvents this kind of detection.
40505 * Despite multiple requests, the core-js maintainer has made it clear: any
40506 * attempt to fix the detection will be obstructed. As a result, we're left
40507 * with little choice but to throw an error. Unfortunately, this also affects
40508 * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
40509 * which rely on core-js.
40510 *
40511 * @static
40512 * @memberOf _
40513 * @since 3.0.0
40514 * @category Lang
40515 * @param {*} value The value to check.
40516 * @returns {boolean} Returns `true` if `value` is a native function,
40517 * else `false`.
40518 * @example
40519 *
40520 * _.isNative(Array.prototype.push);
40521 * // => true
40522 *
40523 * _.isNative(_);
40524 * // => false
40525 */
40526 function isNative(value) {
40527 if (isMaskable(value)) {
40528 throw new Error(CORE_ERROR_TEXT);
40529 }
40530 return baseIsNative(value);
40531 }
40532
40533 /**
40534 * Checks if `value` is `null`.
40535 *
40536 * @static
40537 * @memberOf _
40538 * @since 0.1.0
40539 * @category Lang
40540 * @param {*} value The value to check.
40541 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
40542 * @example
40543 *
40544 * _.isNull(null);
40545 * // => true
40546 *
40547 * _.isNull(void 0);
40548 * // => false
40549 */
40550 function isNull(value) {
40551 return value === null;
40552 }
40553
40554 /**
40555 * Checks if `value` is `null` or `undefined`.
40556 *
40557 * @static
40558 * @memberOf _
40559 * @since 4.0.0
40560 * @category Lang
40561 * @param {*} value The value to check.
40562 * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
40563 * @example
40564 *
40565 * _.isNil(null);
40566 * // => true
40567 *
40568 * _.isNil(void 0);
40569 * // => true
40570 *
40571 * _.isNil(NaN);
40572 * // => false
40573 */
40574 function isNil(value) {
40575 return value == null;
40576 }
40577
40578 /**
40579 * Checks if `value` is classified as a `Number` primitive or object.
40580 *
40581 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
40582 * classified as numbers, use the `_.isFinite` method.
40583 *
40584 * @static
40585 * @memberOf _
40586 * @since 0.1.0
40587 * @category Lang
40588 * @param {*} value The value to check.
40589 * @returns {boolean} Returns `true` if `value` is a number, else `false`.
40590 * @example
40591 *
40592 * _.isNumber(3);
40593 * // => true
40594 *
40595 * _.isNumber(Number.MIN_VALUE);
40596 * // => true
40597 *
40598 * _.isNumber(Infinity);
40599 * // => true
40600 *
40601 * _.isNumber('3');
40602 * // => false
40603 */
40604 function isNumber(value) {
40605 return typeof value == 'number' ||
40606 (isObjectLike(value) && baseGetTag(value) == numberTag);
40607 }
40608
40609 /**
40610 * Checks if `value` is a plain object, that is, an object created by the
40611 * `Object` constructor or one with a `[[Prototype]]` of `null`.
40612 *
40613 * @static
40614 * @memberOf _
40615 * @since 0.8.0
40616 * @category Lang
40617 * @param {*} value The value to check.
40618 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
40619 * @example
40620 *
40621 * function Foo() {
40622 * this.a = 1;
40623 * }
40624 *
40625 * _.isPlainObject(new Foo);
40626 * // => false
40627 *
40628 * _.isPlainObject([1, 2, 3]);
40629 * // => false
40630 *
40631 * _.isPlainObject({ 'x': 0, 'y': 0 });
40632 * // => true
40633 *
40634 * _.isPlainObject(Object.create(null));
40635 * // => true
40636 */
40637 function isPlainObject(value) {
40638 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
40639 return false;
40640 }
40641 var proto = getPrototype(value);
40642 if (proto === null) {
40643 return true;
40644 }
40645 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
40646 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
40647 funcToString.call(Ctor) == objectCtorString;
40648 }
40649
40650 /**
40651 * Checks if `value` is classified as a `RegExp` object.
40652 *
40653 * @static
40654 * @memberOf _
40655 * @since 0.1.0
40656 * @category Lang
40657 * @param {*} value The value to check.
40658 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
40659 * @example
40660 *
40661 * _.isRegExp(/abc/);
40662 * // => true
40663 *
40664 * _.isRegExp('/abc/');
40665 * // => false
40666 */
40667 var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
40668
40669 /**
40670 * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
40671 * double precision number which isn't the result of a rounded unsafe integer.
40672 *
40673 * **Note:** This method is based on
40674 * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
40675 *
40676 * @static
40677 * @memberOf _
40678 * @since 4.0.0
40679 * @category Lang
40680 * @param {*} value The value to check.
40681 * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
40682 * @example
40683 *
40684 * _.isSafeInteger(3);
40685 * // => true
40686 *
40687 * _.isSafeInteger(Number.MIN_VALUE);
40688 * // => false
40689 *
40690 * _.isSafeInteger(Infinity);
40691 * // => false
40692 *
40693 * _.isSafeInteger('3');
40694 * // => false
40695 */
40696 function isSafeInteger(value) {
40697 return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
40698 }
40699
40700 /**
40701 * Checks if `value` is classified as a `Set` object.
40702 *
40703 * @static
40704 * @memberOf _
40705 * @since 4.3.0
40706 * @category Lang
40707 * @param {*} value The value to check.
40708 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
40709 * @example
40710 *
40711 * _.isSet(new Set);
40712 * // => true
40713 *
40714 * _.isSet(new WeakSet);
40715 * // => false
40716 */
40717 var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
40718
40719 /**
40720 * Checks if `value` is classified as a `String` primitive or object.
40721 *
40722 * @static
40723 * @since 0.1.0
40724 * @memberOf _
40725 * @category Lang
40726 * @param {*} value The value to check.
40727 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
40728 * @example
40729 *
40730 * _.isString('abc');
40731 * // => true
40732 *
40733 * _.isString(1);
40734 * // => false
40735 */
40736 function isString(value) {
40737 return typeof value == 'string' ||
40738 (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
40739 }
40740
40741 /**
40742 * Checks if `value` is classified as a `Symbol` primitive or object.
40743 *
40744 * @static
40745 * @memberOf _
40746 * @since 4.0.0
40747 * @category Lang
40748 * @param {*} value The value to check.
40749 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
40750 * @example
40751 *
40752 * _.isSymbol(Symbol.iterator);
40753 * // => true
40754 *
40755 * _.isSymbol('abc');
40756 * // => false
40757 */
40758 function isSymbol(value) {
40759 return typeof value == 'symbol' ||
40760 (isObjectLike(value) && baseGetTag(value) == symbolTag);
40761 }
40762
40763 /**
40764 * Checks if `value` is classified as a typed array.
40765 *
40766 * @static
40767 * @memberOf _
40768 * @since 3.0.0
40769 * @category Lang
40770 * @param {*} value The value to check.
40771 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
40772 * @example
40773 *
40774 * _.isTypedArray(new Uint8Array);
40775 * // => true
40776 *
40777 * _.isTypedArray([]);
40778 * // => false
40779 */
40780 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
40781
40782 /**
40783 * Checks if `value` is `undefined`.
40784 *
40785 * @static
40786 * @since 0.1.0
40787 * @memberOf _
40788 * @category Lang
40789 * @param {*} value The value to check.
40790 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
40791 * @example
40792 *
40793 * _.isUndefined(void 0);
40794 * // => true
40795 *
40796 * _.isUndefined(null);
40797 * // => false
40798 */
40799 function isUndefined(value) {
40800 return value === undefined;
40801 }
40802
40803 /**
40804 * Checks if `value` is classified as a `WeakMap` object.
40805 *
40806 * @static
40807 * @memberOf _
40808 * @since 4.3.0
40809 * @category Lang
40810 * @param {*} value The value to check.
40811 * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
40812 * @example
40813 *
40814 * _.isWeakMap(new WeakMap);
40815 * // => true
40816 *
40817 * _.isWeakMap(new Map);
40818 * // => false
40819 */
40820 function isWeakMap(value) {
40821 return isObjectLike(value) && getTag(value) == weakMapTag;
40822 }
40823
40824 /**
40825 * Checks if `value` is classified as a `WeakSet` object.
40826 *
40827 * @static
40828 * @memberOf _
40829 * @since 4.3.0
40830 * @category Lang
40831 * @param {*} value The value to check.
40832 * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
40833 * @example
40834 *
40835 * _.isWeakSet(new WeakSet);
40836 * // => true
40837 *
40838 * _.isWeakSet(new Set);
40839 * // => false
40840 */
40841 function isWeakSet(value) {
40842 return isObjectLike(value) && baseGetTag(value) == weakSetTag;
40843 }
40844
40845 /**
40846 * Checks if `value` is less than `other`.
40847 *
40848 * @static
40849 * @memberOf _
40850 * @since 3.9.0
40851 * @category Lang
40852 * @param {*} value The value to compare.
40853 * @param {*} other The other value to compare.
40854 * @returns {boolean} Returns `true` if `value` is less than `other`,
40855 * else `false`.
40856 * @see _.gt
40857 * @example
40858 *
40859 * _.lt(1, 3);
40860 * // => true
40861 *
40862 * _.lt(3, 3);
40863 * // => false
40864 *
40865 * _.lt(3, 1);
40866 * // => false
40867 */
40868 var lt = createRelationalOperation(baseLt);
40869
40870 /**
40871 * Checks if `value` is less than or equal to `other`.
40872 *
40873 * @static
40874 * @memberOf _
40875 * @since 3.9.0
40876 * @category Lang
40877 * @param {*} value The value to compare.
40878 * @param {*} other The other value to compare.
40879 * @returns {boolean} Returns `true` if `value` is less than or equal to
40880 * `other`, else `false`.
40881 * @see _.gte
40882 * @example
40883 *
40884 * _.lte(1, 3);
40885 * // => true
40886 *
40887 * _.lte(3, 3);
40888 * // => true
40889 *
40890 * _.lte(3, 1);
40891 * // => false
40892 */
40893 var lte = createRelationalOperation(function(value, other) {
40894 return value <= other;
40895 });
40896
40897 /**
40898 * Converts `value` to an array.
40899 *
40900 * @static
40901 * @since 0.1.0
40902 * @memberOf _
40903 * @category Lang
40904 * @param {*} value The value to convert.
40905 * @returns {Array} Returns the converted array.
40906 * @example
40907 *
40908 * _.toArray({ 'a': 1, 'b': 2 });
40909 * // => [1, 2]
40910 *
40911 * _.toArray('abc');
40912 * // => ['a', 'b', 'c']
40913 *
40914 * _.toArray(1);
40915 * // => []
40916 *
40917 * _.toArray(null);
40918 * // => []
40919 */
40920 function toArray(value) {
40921 if (!value) {
40922 return [];
40923 }
40924 if (isArrayLike(value)) {
40925 return isString(value) ? stringToArray(value) : copyArray(value);
40926 }
40927 if (symIterator && value[symIterator]) {
40928 return iteratorToArray(value[symIterator]());
40929 }
40930 var tag = getTag(value),
40931 func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
40932
40933 return func(value);
40934 }
40935
40936 /**
40937 * Converts `value` to a finite number.
40938 *
40939 * @static
40940 * @memberOf _
40941 * @since 4.12.0
40942 * @category Lang
40943 * @param {*} value The value to convert.
40944 * @returns {number} Returns the converted number.
40945 * @example
40946 *
40947 * _.toFinite(3.2);
40948 * // => 3.2
40949 *
40950 * _.toFinite(Number.MIN_VALUE);
40951 * // => 5e-324
40952 *
40953 * _.toFinite(Infinity);
40954 * // => 1.7976931348623157e+308
40955 *
40956 * _.toFinite('3.2');
40957 * // => 3.2
40958 */
40959 function toFinite(value) {
40960 if (!value) {
40961 return value === 0 ? value : 0;
40962 }
40963 value = toNumber(value);
40964 if (value === INFINITY || value === -INFINITY) {
40965 var sign = (value < 0 ? -1 : 1);
40966 return sign * MAX_INTEGER;
40967 }
40968 return value === value ? value : 0;
40969 }
40970
40971 /**
40972 * Converts `value` to an integer.
40973 *
40974 * **Note:** This method is loosely based on
40975 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
40976 *
40977 * @static
40978 * @memberOf _
40979 * @since 4.0.0
40980 * @category Lang
40981 * @param {*} value The value to convert.
40982 * @returns {number} Returns the converted integer.
40983 * @example
40984 *
40985 * _.toInteger(3.2);
40986 * // => 3
40987 *
40988 * _.toInteger(Number.MIN_VALUE);
40989 * // => 0
40990 *
40991 * _.toInteger(Infinity);
40992 * // => 1.7976931348623157e+308
40993 *
40994 * _.toInteger('3.2');
40995 * // => 3
40996 */
40997 function toInteger(value) {
40998 var result = toFinite(value),
40999 remainder = result % 1;
41000
41001 return result === result ? (remainder ? result - remainder : result) : 0;
41002 }
41003
41004 /**
41005 * Converts `value` to an integer suitable for use as the length of an
41006 * array-like object.
41007 *
41008 * **Note:** This method is based on
41009 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
41010 *
41011 * @static
41012 * @memberOf _
41013 * @since 4.0.0
41014 * @category Lang
41015 * @param {*} value The value to convert.
41016 * @returns {number} Returns the converted integer.
41017 * @example
41018 *
41019 * _.toLength(3.2);
41020 * // => 3
41021 *
41022 * _.toLength(Number.MIN_VALUE);
41023 * // => 0
41024 *
41025 * _.toLength(Infinity);
41026 * // => 4294967295
41027 *
41028 * _.toLength('3.2');
41029 * // => 3
41030 */
41031 function toLength(value) {
41032 return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
41033 }
41034
41035 /**
41036 * Converts `value` to a number.
41037 *
41038 * @static
41039 * @memberOf _
41040 * @since 4.0.0
41041 * @category Lang
41042 * @param {*} value The value to process.
41043 * @returns {number} Returns the number.
41044 * @example
41045 *
41046 * _.toNumber(3.2);
41047 * // => 3.2
41048 *
41049 * _.toNumber(Number.MIN_VALUE);
41050 * // => 5e-324
41051 *
41052 * _.toNumber(Infinity);
41053 * // => Infinity
41054 *
41055 * _.toNumber('3.2');
41056 * // => 3.2
41057 */
41058 function toNumber(value) {
41059 if (typeof value == 'number') {
41060 return value;
41061 }
41062 if (isSymbol(value)) {
41063 return NAN;
41064 }
41065 if (isObject(value)) {
41066 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
41067 value = isObject(other) ? (other + '') : other;
41068 }
41069 if (typeof value != 'string') {
41070 return value === 0 ? value : +value;
41071 }
41072 value = value.replace(reTrim, '');
41073 var isBinary = reIsBinary.test(value);
41074 return (isBinary || reIsOctal.test(value))
41075 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
41076 : (reIsBadHex.test(value) ? NAN : +value);
41077 }
41078
41079 /**
41080 * Converts `value` to a plain object flattening inherited enumerable string
41081 * keyed properties of `value` to own properties of the plain object.
41082 *
41083 * @static
41084 * @memberOf _
41085 * @since 3.0.0
41086 * @category Lang
41087 * @param {*} value The value to convert.
41088 * @returns {Object} Returns the converted plain object.
41089 * @example
41090 *
41091 * function Foo() {
41092 * this.b = 2;
41093 * }
41094 *
41095 * Foo.prototype.c = 3;
41096 *
41097 * _.assign({ 'a': 1 }, new Foo);
41098 * // => { 'a': 1, 'b': 2 }
41099 *
41100 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
41101 * // => { 'a': 1, 'b': 2, 'c': 3 }
41102 */
41103 function toPlainObject(value) {
41104 return copyObject(value, keysIn(value));
41105 }
41106
41107 /**
41108 * Converts `value` to a safe integer. A safe integer can be compared and
41109 * represented correctly.
41110 *
41111 * @static
41112 * @memberOf _
41113 * @since 4.0.0
41114 * @category Lang
41115 * @param {*} value The value to convert.
41116 * @returns {number} Returns the converted integer.
41117 * @example
41118 *
41119 * _.toSafeInteger(3.2);
41120 * // => 3
41121 *
41122 * _.toSafeInteger(Number.MIN_VALUE);
41123 * // => 0
41124 *
41125 * _.toSafeInteger(Infinity);
41126 * // => 9007199254740991
41127 *
41128 * _.toSafeInteger('3.2');
41129 * // => 3
41130 */
41131 function toSafeInteger(value) {
41132 return value
41133 ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
41134 : (value === 0 ? value : 0);
41135 }
41136
41137 /**
41138 * Converts `value` to a string. An empty string is returned for `null`
41139 * and `undefined` values. The sign of `-0` is preserved.
41140 *
41141 * @static
41142 * @memberOf _
41143 * @since 4.0.0
41144 * @category Lang
41145 * @param {*} value The value to convert.
41146 * @returns {string} Returns the converted string.
41147 * @example
41148 *
41149 * _.toString(null);
41150 * // => ''
41151 *
41152 * _.toString(-0);
41153 * // => '-0'
41154 *
41155 * _.toString([1, 2, 3]);
41156 * // => '1,2,3'
41157 */
41158 function toString(value) {
41159 return value == null ? '' : baseToString(value);
41160 }
41161
41162 /*------------------------------------------------------------------------*/
41163
41164 /**
41165 * Assigns own enumerable string keyed properties of source objects to the
41166 * destination object. Source objects are applied from left to right.
41167 * Subsequent sources overwrite property assignments of previous sources.
41168 *
41169 * **Note:** This method mutates `object` and is loosely based on
41170 * [`Object.assign`](https://mdn.io/Object/assign).
41171 *
41172 * @static
41173 * @memberOf _
41174 * @since 0.10.0
41175 * @category Object
41176 * @param {Object} object The destination object.
41177 * @param {...Object} [sources] The source objects.
41178 * @returns {Object} Returns `object`.
41179 * @see _.assignIn
41180 * @example
41181 *
41182 * function Foo() {
41183 * this.a = 1;
41184 * }
41185 *
41186 * function Bar() {
41187 * this.c = 3;
41188 * }
41189 *
41190 * Foo.prototype.b = 2;
41191 * Bar.prototype.d = 4;
41192 *
41193 * _.assign({ 'a': 0 }, new Foo, new Bar);
41194 * // => { 'a': 1, 'c': 3 }
41195 */
41196 var assign = createAssigner(function(object, source) {
41197 if (isPrototype(source) || isArrayLike(source)) {
41198 copyObject(source, keys(source), object);
41199 return;
41200 }
41201 for (var key in source) {
41202 if (hasOwnProperty.call(source, key)) {
41203 assignValue(object, key, source[key]);
41204 }
41205 }
41206 });
41207
41208 /**
41209 * This method is like `_.assign` except that it iterates over own and
41210 * inherited source properties.
41211 *
41212 * **Note:** This method mutates `object`.
41213 *
41214 * @static
41215 * @memberOf _
41216 * @since 4.0.0
41217 * @alias extend
41218 * @category Object
41219 * @param {Object} object The destination object.
41220 * @param {...Object} [sources] The source objects.
41221 * @returns {Object} Returns `object`.
41222 * @see _.assign
41223 * @example
41224 *
41225 * function Foo() {
41226 * this.a = 1;
41227 * }
41228 *
41229 * function Bar() {
41230 * this.c = 3;
41231 * }
41232 *
41233 * Foo.prototype.b = 2;
41234 * Bar.prototype.d = 4;
41235 *
41236 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
41237 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
41238 */
41239 var assignIn = createAssigner(function(object, source) {
41240 copyObject(source, keysIn(source), object);
41241 });
41242
41243 /**
41244 * This method is like `_.assignIn` except that it accepts `customizer`
41245 * which is invoked to produce the assigned values. If `customizer` returns
41246 * `undefined`, assignment is handled by the method instead. The `customizer`
41247 * is invoked with five arguments: (objValue, srcValue, key, object, source).
41248 *
41249 * **Note:** This method mutates `object`.
41250 *
41251 * @static
41252 * @memberOf _
41253 * @since 4.0.0
41254 * @alias extendWith
41255 * @category Object
41256 * @param {Object} object The destination object.
41257 * @param {...Object} sources The source objects.
41258 * @param {Function} [customizer] The function to customize assigned values.
41259 * @returns {Object} Returns `object`.
41260 * @see _.assignWith
41261 * @example
41262 *
41263 * function customizer(objValue, srcValue) {
41264 * return _.isUndefined(objValue) ? srcValue : objValue;
41265 * }
41266 *
41267 * var defaults = _.partialRight(_.assignInWith, customizer);
41268 *
41269 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
41270 * // => { 'a': 1, 'b': 2 }
41271 */
41272 var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
41273 copyObject(source, keysIn(source), object, customizer);
41274 });
41275
41276 /**
41277 * This method is like `_.assign` except that it accepts `customizer`
41278 * which is invoked to produce the assigned values. If `customizer` returns
41279 * `undefined`, assignment is handled by the method instead. The `customizer`
41280 * is invoked with five arguments: (objValue, srcValue, key, object, source).
41281 *
41282 * **Note:** This method mutates `object`.
41283 *
41284 * @static
41285 * @memberOf _
41286 * @since 4.0.0
41287 * @category Object
41288 * @param {Object} object The destination object.
41289 * @param {...Object} sources The source objects.
41290 * @param {Function} [customizer] The function to customize assigned values.
41291 * @returns {Object} Returns `object`.
41292 * @see _.assignInWith
41293 * @example
41294 *
41295 * function customizer(objValue, srcValue) {
41296 * return _.isUndefined(objValue) ? srcValue : objValue;
41297 * }
41298 *
41299 * var defaults = _.partialRight(_.assignWith, customizer);
41300 *
41301 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
41302 * // => { 'a': 1, 'b': 2 }
41303 */
41304 var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
41305 copyObject(source, keys(source), object, customizer);
41306 });
41307
41308 /**
41309 * Creates an array of values corresponding to `paths` of `object`.
41310 *
41311 * @static
41312 * @memberOf _
41313 * @since 1.0.0
41314 * @category Object
41315 * @param {Object} object The object to iterate over.
41316 * @param {...(string|string[])} [paths] The property paths to pick.
41317 * @returns {Array} Returns the picked values.
41318 * @example
41319 *
41320 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
41321 *
41322 * _.at(object, ['a[0].b.c', 'a[1]']);
41323 * // => [3, 4]
41324 */
41325 var at = flatRest(baseAt);
41326
41327 /**
41328 * Creates an object that inherits from the `prototype` object. If a
41329 * `properties` object is given, its own enumerable string keyed properties
41330 * are assigned to the created object.
41331 *
41332 * @static
41333 * @memberOf _
41334 * @since 2.3.0
41335 * @category Object
41336 * @param {Object} prototype The object to inherit from.
41337 * @param {Object} [properties] The properties to assign to the object.
41338 * @returns {Object} Returns the new object.
41339 * @example
41340 *
41341 * function Shape() {
41342 * this.x = 0;
41343 * this.y = 0;
41344 * }
41345 *
41346 * function Circle() {
41347 * Shape.call(this);
41348 * }
41349 *
41350 * Circle.prototype = _.create(Shape.prototype, {
41351 * 'constructor': Circle
41352 * });
41353 *
41354 * var circle = new Circle;
41355 * circle instanceof Circle;
41356 * // => true
41357 *
41358 * circle instanceof Shape;
41359 * // => true
41360 */
41361 function create(prototype, properties) {
41362 var result = baseCreate(prototype);
41363 return properties == null ? result : baseAssign(result, properties);
41364 }
41365
41366 /**
41367 * Assigns own and inherited enumerable string keyed properties of source
41368 * objects to the destination object for all destination properties that
41369 * resolve to `undefined`. Source objects are applied from left to right.
41370 * Once a property is set, additional values of the same property are ignored.
41371 *
41372 * **Note:** This method mutates `object`.
41373 *
41374 * @static
41375 * @since 0.1.0
41376 * @memberOf _
41377 * @category Object
41378 * @param {Object} object The destination object.
41379 * @param {...Object} [sources] The source objects.
41380 * @returns {Object} Returns `object`.
41381 * @see _.defaultsDeep
41382 * @example
41383 *
41384 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
41385 * // => { 'a': 1, 'b': 2 }
41386 */
41387 var defaults = baseRest(function(object, sources) {
41388 object = Object(object);
41389
41390 var index = -1;
41391 var length = sources.length;
41392 var guard = length > 2 ? sources[2] : undefined;
41393
41394 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
41395 length = 1;
41396 }
41397
41398 while (++index < length) {
41399 var source = sources[index];
41400 var props = keysIn(source);
41401 var propsIndex = -1;
41402 var propsLength = props.length;
41403
41404 while (++propsIndex < propsLength) {
41405 var key = props[propsIndex];
41406 var value = object[key];
41407
41408 if (value === undefined ||
41409 (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
41410 object[key] = source[key];
41411 }
41412 }
41413 }
41414
41415 return object;
41416 });
41417
41418 /**
41419 * This method is like `_.defaults` except that it recursively assigns
41420 * default properties.
41421 *
41422 * **Note:** This method mutates `object`.
41423 *
41424 * @static
41425 * @memberOf _
41426 * @since 3.10.0
41427 * @category Object
41428 * @param {Object} object The destination object.
41429 * @param {...Object} [sources] The source objects.
41430 * @returns {Object} Returns `object`.
41431 * @see _.defaults
41432 * @example
41433 *
41434 * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
41435 * // => { 'a': { 'b': 2, 'c': 3 } }
41436 */
41437 var defaultsDeep = baseRest(function(args) {
41438 args.push(undefined, customDefaultsMerge);
41439 return apply(mergeWith, undefined, args);
41440 });
41441
41442 /**
41443 * This method is like `_.find` except that it returns the key of the first
41444 * element `predicate` returns truthy for instead of the element itself.
41445 *
41446 * @static
41447 * @memberOf _
41448 * @since 1.1.0
41449 * @category Object
41450 * @param {Object} object The object to inspect.
41451 * @param {Function} [predicate=_.identity] The function invoked per iteration.
41452 * @returns {string|undefined} Returns the key of the matched element,
41453 * else `undefined`.
41454 * @example
41455 *
41456 * var users = {
41457 * 'barney': { 'age': 36, 'active': true },
41458 * 'fred': { 'age': 40, 'active': false },
41459 * 'pebbles': { 'age': 1, 'active': true }
41460 * };
41461 *
41462 * _.findKey(users, function(o) { return o.age < 40; });
41463 * // => 'barney' (iteration order is not guaranteed)
41464 *
41465 * // The `_.matches` iteratee shorthand.
41466 * _.findKey(users, { 'age': 1, 'active': true });
41467 * // => 'pebbles'
41468 *
41469 * // The `_.matchesProperty` iteratee shorthand.
41470 * _.findKey(users, ['active', false]);
41471 * // => 'fred'
41472 *
41473 * // The `_.property` iteratee shorthand.
41474 * _.findKey(users, 'active');
41475 * // => 'barney'
41476 */
41477 function findKey(object, predicate) {
41478 return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
41479 }
41480
41481 /**
41482 * This method is like `_.findKey` except that it iterates over elements of
41483 * a collection in the opposite order.
41484 *
41485 * @static
41486 * @memberOf _
41487 * @since 2.0.0
41488 * @category Object
41489 * @param {Object} object The object to inspect.
41490 * @param {Function} [predicate=_.identity] The function invoked per iteration.
41491 * @returns {string|undefined} Returns the key of the matched element,
41492 * else `undefined`.
41493 * @example
41494 *
41495 * var users = {
41496 * 'barney': { 'age': 36, 'active': true },
41497 * 'fred': { 'age': 40, 'active': false },
41498 * 'pebbles': { 'age': 1, 'active': true }
41499 * };
41500 *
41501 * _.findLastKey(users, function(o) { return o.age < 40; });
41502 * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
41503 *
41504 * // The `_.matches` iteratee shorthand.
41505 * _.findLastKey(users, { 'age': 36, 'active': true });
41506 * // => 'barney'
41507 *
41508 * // The `_.matchesProperty` iteratee shorthand.
41509 * _.findLastKey(users, ['active', false]);
41510 * // => 'fred'
41511 *
41512 * // The `_.property` iteratee shorthand.
41513 * _.findLastKey(users, 'active');
41514 * // => 'pebbles'
41515 */
41516 function findLastKey(object, predicate) {
41517 return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
41518 }
41519
41520 /**
41521 * Iterates over own and inherited enumerable string keyed properties of an
41522 * object and invokes `iteratee` for each property. The iteratee is invoked
41523 * with three arguments: (value, key, object). Iteratee functions may exit
41524 * iteration early by explicitly returning `false`.
41525 *
41526 * @static
41527 * @memberOf _
41528 * @since 0.3.0
41529 * @category Object
41530 * @param {Object} object The object to iterate over.
41531 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
41532 * @returns {Object} Returns `object`.
41533 * @see _.forInRight
41534 * @example
41535 *
41536 * function Foo() {
41537 * this.a = 1;
41538 * this.b = 2;
41539 * }
41540 *
41541 * Foo.prototype.c = 3;
41542 *
41543 * _.forIn(new Foo, function(value, key) {
41544 * console.log(key);
41545 * });
41546 * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
41547 */
41548 function forIn(object, iteratee) {
41549 return object == null
41550 ? object
41551 : baseFor(object, getIteratee(iteratee, 3), keysIn);
41552 }
41553
41554 /**
41555 * This method is like `_.forIn` except that it iterates over properties of
41556 * `object` in the opposite order.
41557 *
41558 * @static
41559 * @memberOf _
41560 * @since 2.0.0
41561 * @category Object
41562 * @param {Object} object The object to iterate over.
41563 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
41564 * @returns {Object} Returns `object`.
41565 * @see _.forIn
41566 * @example
41567 *
41568 * function Foo() {
41569 * this.a = 1;
41570 * this.b = 2;
41571 * }
41572 *
41573 * Foo.prototype.c = 3;
41574 *
41575 * _.forInRight(new Foo, function(value, key) {
41576 * console.log(key);
41577 * });
41578 * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
41579 */
41580 function forInRight(object, iteratee) {
41581 return object == null
41582 ? object
41583 : baseForRight(object, getIteratee(iteratee, 3), keysIn);
41584 }
41585
41586 /**
41587 * Iterates over own enumerable string keyed properties of an object and
41588 * invokes `iteratee` for each property. The iteratee is invoked with three
41589 * arguments: (value, key, object). Iteratee functions may exit iteration
41590 * early by explicitly returning `false`.
41591 *
41592 * @static
41593 * @memberOf _
41594 * @since 0.3.0
41595 * @category Object
41596 * @param {Object} object The object to iterate over.
41597 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
41598 * @returns {Object} Returns `object`.
41599 * @see _.forOwnRight
41600 * @example
41601 *
41602 * function Foo() {
41603 * this.a = 1;
41604 * this.b = 2;
41605 * }
41606 *
41607 * Foo.prototype.c = 3;
41608 *
41609 * _.forOwn(new Foo, function(value, key) {
41610 * console.log(key);
41611 * });
41612 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
41613 */
41614 function forOwn(object, iteratee) {
41615 return object && baseForOwn(object, getIteratee(iteratee, 3));
41616 }
41617
41618 /**
41619 * This method is like `_.forOwn` except that it iterates over properties of
41620 * `object` in the opposite order.
41621 *
41622 * @static
41623 * @memberOf _
41624 * @since 2.0.0
41625 * @category Object
41626 * @param {Object} object The object to iterate over.
41627 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
41628 * @returns {Object} Returns `object`.
41629 * @see _.forOwn
41630 * @example
41631 *
41632 * function Foo() {
41633 * this.a = 1;
41634 * this.b = 2;
41635 * }
41636 *
41637 * Foo.prototype.c = 3;
41638 *
41639 * _.forOwnRight(new Foo, function(value, key) {
41640 * console.log(key);
41641 * });
41642 * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
41643 */
41644 function forOwnRight(object, iteratee) {
41645 return object && baseForOwnRight(object, getIteratee(iteratee, 3));
41646 }
41647
41648 /**
41649 * Creates an array of function property names from own enumerable properties
41650 * of `object`.
41651 *
41652 * @static
41653 * @since 0.1.0
41654 * @memberOf _
41655 * @category Object
41656 * @param {Object} object The object to inspect.
41657 * @returns {Array} Returns the function names.
41658 * @see _.functionsIn
41659 * @example
41660 *
41661 * function Foo() {
41662 * this.a = _.constant('a');
41663 * this.b = _.constant('b');
41664 * }
41665 *
41666 * Foo.prototype.c = _.constant('c');
41667 *
41668 * _.functions(new Foo);
41669 * // => ['a', 'b']
41670 */
41671 function functions(object) {
41672 return object == null ? [] : baseFunctions(object, keys(object));
41673 }
41674
41675 /**
41676 * Creates an array of function property names from own and inherited
41677 * enumerable properties of `object`.
41678 *
41679 * @static
41680 * @memberOf _
41681 * @since 4.0.0
41682 * @category Object
41683 * @param {Object} object The object to inspect.
41684 * @returns {Array} Returns the function names.
41685 * @see _.functions
41686 * @example
41687 *
41688 * function Foo() {
41689 * this.a = _.constant('a');
41690 * this.b = _.constant('b');
41691 * }
41692 *
41693 * Foo.prototype.c = _.constant('c');
41694 *
41695 * _.functionsIn(new Foo);
41696 * // => ['a', 'b', 'c']
41697 */
41698 function functionsIn(object) {
41699 return object == null ? [] : baseFunctions(object, keysIn(object));
41700 }
41701
41702 /**
41703 * Gets the value at `path` of `object`. If the resolved value is
41704 * `undefined`, the `defaultValue` is returned in its place.
41705 *
41706 * @static
41707 * @memberOf _
41708 * @since 3.7.0
41709 * @category Object
41710 * @param {Object} object The object to query.
41711 * @param {Array|string} path The path of the property to get.
41712 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
41713 * @returns {*} Returns the resolved value.
41714 * @example
41715 *
41716 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
41717 *
41718 * _.get(object, 'a[0].b.c');
41719 * // => 3
41720 *
41721 * _.get(object, ['a', '0', 'b', 'c']);
41722 * // => 3
41723 *
41724 * _.get(object, 'a.b.c', 'default');
41725 * // => 'default'
41726 */
41727 function get(object, path, defaultValue) {
41728 var result = object == null ? undefined : baseGet(object, path);
41729 return result === undefined ? defaultValue : result;
41730 }
41731
41732 /**
41733 * Checks if `path` is a direct property of `object`.
41734 *
41735 * @static
41736 * @since 0.1.0
41737 * @memberOf _
41738 * @category Object
41739 * @param {Object} object The object to query.
41740 * @param {Array|string} path The path to check.
41741 * @returns {boolean} Returns `true` if `path` exists, else `false`.
41742 * @example
41743 *
41744 * var object = { 'a': { 'b': 2 } };
41745 * var other = _.create({ 'a': _.create({ 'b': 2 }) });
41746 *
41747 * _.has(object, 'a');
41748 * // => true
41749 *
41750 * _.has(object, 'a.b');
41751 * // => true
41752 *
41753 * _.has(object, ['a', 'b']);
41754 * // => true
41755 *
41756 * _.has(other, 'a');
41757 * // => false
41758 */
41759 function has(object, path) {
41760 return object != null && hasPath(object, path, baseHas);
41761 }
41762
41763 /**
41764 * Checks if `path` is a direct or inherited property of `object`.
41765 *
41766 * @static
41767 * @memberOf _
41768 * @since 4.0.0
41769 * @category Object
41770 * @param {Object} object The object to query.
41771 * @param {Array|string} path The path to check.
41772 * @returns {boolean} Returns `true` if `path` exists, else `false`.
41773 * @example
41774 *
41775 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
41776 *
41777 * _.hasIn(object, 'a');
41778 * // => true
41779 *
41780 * _.hasIn(object, 'a.b');
41781 * // => true
41782 *
41783 * _.hasIn(object, ['a', 'b']);
41784 * // => true
41785 *
41786 * _.hasIn(object, 'b');
41787 * // => false
41788 */
41789 function hasIn(object, path) {
41790 return object != null && hasPath(object, path, baseHasIn);
41791 }
41792
41793 /**
41794 * Creates an object composed of the inverted keys and values of `object`.
41795 * If `object` contains duplicate values, subsequent values overwrite
41796 * property assignments of previous values.
41797 *
41798 * @static
41799 * @memberOf _
41800 * @since 0.7.0
41801 * @category Object
41802 * @param {Object} object The object to invert.
41803 * @returns {Object} Returns the new inverted object.
41804 * @example
41805 *
41806 * var object = { 'a': 1, 'b': 2, 'c': 1 };
41807 *
41808 * _.invert(object);
41809 * // => { '1': 'c', '2': 'b' }
41810 */
41811 var invert = createInverter(function(result, value, key) {
41812 if (value != null &&
41813 typeof value.toString != 'function') {
41814 value = nativeObjectToString.call(value);
41815 }
41816
41817 result[value] = key;
41818 }, constant(identity));
41819
41820 /**
41821 * This method is like `_.invert` except that the inverted object is generated
41822 * from the results of running each element of `object` thru `iteratee`. The
41823 * corresponding inverted value of each inverted key is an array of keys
41824 * responsible for generating the inverted value. The iteratee is invoked
41825 * with one argument: (value).
41826 *
41827 * @static
41828 * @memberOf _
41829 * @since 4.1.0
41830 * @category Object
41831 * @param {Object} object The object to invert.
41832 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
41833 * @returns {Object} Returns the new inverted object.
41834 * @example
41835 *
41836 * var object = { 'a': 1, 'b': 2, 'c': 1 };
41837 *
41838 * _.invertBy(object);
41839 * // => { '1': ['a', 'c'], '2': ['b'] }
41840 *
41841 * _.invertBy(object, function(value) {
41842 * return 'group' + value;
41843 * });
41844 * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
41845 */
41846 var invertBy = createInverter(function(result, value, key) {
41847 if (value != null &&
41848 typeof value.toString != 'function') {
41849 value = nativeObjectToString.call(value);
41850 }
41851
41852 if (hasOwnProperty.call(result, value)) {
41853 result[value].push(key);
41854 } else {
41855 result[value] = [key];
41856 }
41857 }, getIteratee);
41858
41859 /**
41860 * Invokes the method at `path` of `object`.
41861 *
41862 * @static
41863 * @memberOf _
41864 * @since 4.0.0
41865 * @category Object
41866 * @param {Object} object The object to query.
41867 * @param {Array|string} path The path of the method to invoke.
41868 * @param {...*} [args] The arguments to invoke the method with.
41869 * @returns {*} Returns the result of the invoked method.
41870 * @example
41871 *
41872 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
41873 *
41874 * _.invoke(object, 'a[0].b.c.slice', 1, 3);
41875 * // => [2, 3]
41876 */
41877 var invoke = baseRest(baseInvoke);
41878
41879 /**
41880 * Creates an array of the own enumerable property names of `object`.
41881 *
41882 * **Note:** Non-object values are coerced to objects. See the
41883 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
41884 * for more details.
41885 *
41886 * @static
41887 * @since 0.1.0
41888 * @memberOf _
41889 * @category Object
41890 * @param {Object} object The object to query.
41891 * @returns {Array} Returns the array of property names.
41892 * @example
41893 *
41894 * function Foo() {
41895 * this.a = 1;
41896 * this.b = 2;
41897 * }
41898 *
41899 * Foo.prototype.c = 3;
41900 *
41901 * _.keys(new Foo);
41902 * // => ['a', 'b'] (iteration order is not guaranteed)
41903 *
41904 * _.keys('hi');
41905 * // => ['0', '1']
41906 */
41907 function keys(object) {
41908 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
41909 }
41910
41911 /**
41912 * Creates an array of the own and inherited enumerable property names of `object`.
41913 *
41914 * **Note:** Non-object values are coerced to objects.
41915 *
41916 * @static
41917 * @memberOf _
41918 * @since 3.0.0
41919 * @category Object
41920 * @param {Object} object The object to query.
41921 * @returns {Array} Returns the array of property names.
41922 * @example
41923 *
41924 * function Foo() {
41925 * this.a = 1;
41926 * this.b = 2;
41927 * }
41928 *
41929 * Foo.prototype.c = 3;
41930 *
41931 * _.keysIn(new Foo);
41932 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
41933 */
41934 function keysIn(object) {
41935 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
41936 }
41937
41938 /**
41939 * The opposite of `_.mapValues`; this method creates an object with the
41940 * same values as `object` and keys generated by running each own enumerable
41941 * string keyed property of `object` thru `iteratee`. The iteratee is invoked
41942 * with three arguments: (value, key, object).
41943 *
41944 * @static
41945 * @memberOf _
41946 * @since 3.8.0
41947 * @category Object
41948 * @param {Object} object The object to iterate over.
41949 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
41950 * @returns {Object} Returns the new mapped object.
41951 * @see _.mapValues
41952 * @example
41953 *
41954 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
41955 * return key + value;
41956 * });
41957 * // => { 'a1': 1, 'b2': 2 }
41958 */
41959 function mapKeys(object, iteratee) {
41960 var result = {};
41961 iteratee = getIteratee(iteratee, 3);
41962
41963 baseForOwn(object, function(value, key, object) {
41964 baseAssignValue(result, iteratee(value, key, object), value);
41965 });
41966 return result;
41967 }
41968
41969 /**
41970 * Creates an object with the same keys as `object` and values generated
41971 * by running each own enumerable string keyed property of `object` thru
41972 * `iteratee`. The iteratee is invoked with three arguments:
41973 * (value, key, object).
41974 *
41975 * @static
41976 * @memberOf _
41977 * @since 2.4.0
41978 * @category Object
41979 * @param {Object} object The object to iterate over.
41980 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
41981 * @returns {Object} Returns the new mapped object.
41982 * @see _.mapKeys
41983 * @example
41984 *
41985 * var users = {
41986 * 'fred': { 'user': 'fred', 'age': 40 },
41987 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
41988 * };
41989 *
41990 * _.mapValues(users, function(o) { return o.age; });
41991 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
41992 *
41993 * // The `_.property` iteratee shorthand.
41994 * _.mapValues(users, 'age');
41995 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
41996 */
41997 function mapValues(object, iteratee) {
41998 var result = {};
41999 iteratee = getIteratee(iteratee, 3);
42000
42001 baseForOwn(object, function(value, key, object) {
42002 baseAssignValue(result, key, iteratee(value, key, object));
42003 });
42004 return result;
42005 }
42006
42007 /**
42008 * This method is like `_.assign` except that it recursively merges own and
42009 * inherited enumerable string keyed properties of source objects into the
42010 * destination object. Source properties that resolve to `undefined` are
42011 * skipped if a destination value exists. Array and plain object properties
42012 * are merged recursively. Other objects and value types are overridden by
42013 * assignment. Source objects are applied from left to right. Subsequent
42014 * sources overwrite property assignments of previous sources.
42015 *
42016 * **Note:** This method mutates `object`.
42017 *
42018 * @static
42019 * @memberOf _
42020 * @since 0.5.0
42021 * @category Object
42022 * @param {Object} object The destination object.
42023 * @param {...Object} [sources] The source objects.
42024 * @returns {Object} Returns `object`.
42025 * @example
42026 *
42027 * var object = {
42028 * 'a': [{ 'b': 2 }, { 'd': 4 }]
42029 * };
42030 *
42031 * var other = {
42032 * 'a': [{ 'c': 3 }, { 'e': 5 }]
42033 * };
42034 *
42035 * _.merge(object, other);
42036 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
42037 */
42038 var merge = createAssigner(function(object, source, srcIndex) {
42039 baseMerge(object, source, srcIndex);
42040 });
42041
42042 /**
42043 * This method is like `_.merge` except that it accepts `customizer` which
42044 * is invoked to produce the merged values of the destination and source
42045 * properties. If `customizer` returns `undefined`, merging is handled by the
42046 * method instead. The `customizer` is invoked with six arguments:
42047 * (objValue, srcValue, key, object, source, stack).
42048 *
42049 * **Note:** This method mutates `object`.
42050 *
42051 * @static
42052 * @memberOf _
42053 * @since 4.0.0
42054 * @category Object
42055 * @param {Object} object The destination object.
42056 * @param {...Object} sources The source objects.
42057 * @param {Function} customizer The function to customize assigned values.
42058 * @returns {Object} Returns `object`.
42059 * @example
42060 *
42061 * function customizer(objValue, srcValue) {
42062 * if (_.isArray(objValue)) {
42063 * return objValue.concat(srcValue);
42064 * }
42065 * }
42066 *
42067 * var object = { 'a': [1], 'b': [2] };
42068 * var other = { 'a': [3], 'b': [4] };
42069 *
42070 * _.mergeWith(object, other, customizer);
42071 * // => { 'a': [1, 3], 'b': [2, 4] }
42072 */
42073 var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
42074 baseMerge(object, source, srcIndex, customizer);
42075 });
42076
42077 /**
42078 * The opposite of `_.pick`; this method creates an object composed of the
42079 * own and inherited enumerable property paths of `object` that are not omitted.
42080 *
42081 * **Note:** This method is considerably slower than `_.pick`.
42082 *
42083 * @static
42084 * @since 0.1.0
42085 * @memberOf _
42086 * @category Object
42087 * @param {Object} object The source object.
42088 * @param {...(string|string[])} [paths] The property paths to omit.
42089 * @returns {Object} Returns the new object.
42090 * @example
42091 *
42092 * var object = { 'a': 1, 'b': '2', 'c': 3 };
42093 *
42094 * _.omit(object, ['a', 'c']);
42095 * // => { 'b': '2' }
42096 */
42097 var omit = flatRest(function(object, paths) {
42098 var result = {};
42099 if (object == null) {
42100 return result;
42101 }
42102 var isDeep = false;
42103 paths = arrayMap(paths, function(path) {
42104 path = castPath(path, object);
42105 isDeep || (isDeep = path.length > 1);
42106 return path;
42107 });
42108 copyObject(object, getAllKeysIn(object), result);
42109 if (isDeep) {
42110 result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
42111 }
42112 var length = paths.length;
42113 while (length--) {
42114 baseUnset(result, paths[length]);
42115 }
42116 return result;
42117 });
42118
42119 /**
42120 * The opposite of `_.pickBy`; this method creates an object composed of
42121 * the own and inherited enumerable string keyed properties of `object` that
42122 * `predicate` doesn't return truthy for. The predicate is invoked with two
42123 * arguments: (value, key).
42124 *
42125 * @static
42126 * @memberOf _
42127 * @since 4.0.0
42128 * @category Object
42129 * @param {Object} object The source object.
42130 * @param {Function} [predicate=_.identity] The function invoked per property.
42131 * @returns {Object} Returns the new object.
42132 * @example
42133 *
42134 * var object = { 'a': 1, 'b': '2', 'c': 3 };
42135 *
42136 * _.omitBy(object, _.isNumber);
42137 * // => { 'b': '2' }
42138 */
42139 function omitBy(object, predicate) {
42140 return pickBy(object, negate(getIteratee(predicate)));
42141 }
42142
42143 /**
42144 * Creates an object composed of the picked `object` properties.
42145 *
42146 * @static
42147 * @since 0.1.0
42148 * @memberOf _
42149 * @category Object
42150 * @param {Object} object The source object.
42151 * @param {...(string|string[])} [paths] The property paths to pick.
42152 * @returns {Object} Returns the new object.
42153 * @example
42154 *
42155 * var object = { 'a': 1, 'b': '2', 'c': 3 };
42156 *
42157 * _.pick(object, ['a', 'c']);
42158 * // => { 'a': 1, 'c': 3 }
42159 */
42160 var pick = flatRest(function(object, paths) {
42161 return object == null ? {} : basePick(object, paths);
42162 });
42163
42164 /**
42165 * Creates an object composed of the `object` properties `predicate` returns
42166 * truthy for. The predicate is invoked with two arguments: (value, key).
42167 *
42168 * @static
42169 * @memberOf _
42170 * @since 4.0.0
42171 * @category Object
42172 * @param {Object} object The source object.
42173 * @param {Function} [predicate=_.identity] The function invoked per property.
42174 * @returns {Object} Returns the new object.
42175 * @example
42176 *
42177 * var object = { 'a': 1, 'b': '2', 'c': 3 };
42178 *
42179 * _.pickBy(object, _.isNumber);
42180 * // => { 'a': 1, 'c': 3 }
42181 */
42182 function pickBy(object, predicate) {
42183 if (object == null) {
42184 return {};
42185 }
42186 var props = arrayMap(getAllKeysIn(object), function(prop) {
42187 return [prop];
42188 });
42189 predicate = getIteratee(predicate);
42190 return basePickBy(object, props, function(value, path) {
42191 return predicate(value, path[0]);
42192 });
42193 }
42194
42195 /**
42196 * This method is like `_.get` except that if the resolved value is a
42197 * function it's invoked with the `this` binding of its parent object and
42198 * its result is returned.
42199 *
42200 * @static
42201 * @since 0.1.0
42202 * @memberOf _
42203 * @category Object
42204 * @param {Object} object The object to query.
42205 * @param {Array|string} path The path of the property to resolve.
42206 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
42207 * @returns {*} Returns the resolved value.
42208 * @example
42209 *
42210 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
42211 *
42212 * _.result(object, 'a[0].b.c1');
42213 * // => 3
42214 *
42215 * _.result(object, 'a[0].b.c2');
42216 * // => 4
42217 *
42218 * _.result(object, 'a[0].b.c3', 'default');
42219 * // => 'default'
42220 *
42221 * _.result(object, 'a[0].b.c3', _.constant('default'));
42222 * // => 'default'
42223 */
42224 function result(object, path, defaultValue) {
42225 path = castPath(path, object);
42226
42227 var index = -1,
42228 length = path.length;
42229
42230 // Ensure the loop is entered when path is empty.
42231 if (!length) {
42232 length = 1;
42233 object = undefined;
42234 }
42235 while (++index < length) {
42236 var value = object == null ? undefined : object[toKey(path[index])];
42237 if (value === undefined) {
42238 index = length;
42239 value = defaultValue;
42240 }
42241 object = isFunction(value) ? value.call(object) : value;
42242 }
42243 return object;
42244 }
42245
42246 /**
42247 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
42248 * it's created. Arrays are created for missing index properties while objects
42249 * are created for all other missing properties. Use `_.setWith` to customize
42250 * `path` creation.
42251 *
42252 * **Note:** This method mutates `object`.
42253 *
42254 * @static
42255 * @memberOf _
42256 * @since 3.7.0
42257 * @category Object
42258 * @param {Object} object The object to modify.
42259 * @param {Array|string} path The path of the property to set.
42260 * @param {*} value The value to set.
42261 * @returns {Object} Returns `object`.
42262 * @example
42263 *
42264 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
42265 *
42266 * _.set(object, 'a[0].b.c', 4);
42267 * console.log(object.a[0].b.c);
42268 * // => 4
42269 *
42270 * _.set(object, ['x', '0', 'y', 'z'], 5);
42271 * console.log(object.x[0].y.z);
42272 * // => 5
42273 */
42274 function set(object, path, value) {
42275 return object == null ? object : baseSet(object, path, value);
42276 }
42277
42278 /**
42279 * This method is like `_.set` except that it accepts `customizer` which is
42280 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
42281 * path creation is handled by the method instead. The `customizer` is invoked
42282 * with three arguments: (nsValue, key, nsObject).
42283 *
42284 * **Note:** This method mutates `object`.
42285 *
42286 * @static
42287 * @memberOf _
42288 * @since 4.0.0
42289 * @category Object
42290 * @param {Object} object The object to modify.
42291 * @param {Array|string} path The path of the property to set.
42292 * @param {*} value The value to set.
42293 * @param {Function} [customizer] The function to customize assigned values.
42294 * @returns {Object} Returns `object`.
42295 * @example
42296 *
42297 * var object = {};
42298 *
42299 * _.setWith(object, '[0][1]', 'a', Object);
42300 * // => { '0': { '1': 'a' } }
42301 */
42302 function setWith(object, path, value, customizer) {
42303 customizer = typeof customizer == 'function' ? customizer : undefined;
42304 return object == null ? object : baseSet(object, path, value, customizer);
42305 }
42306
42307 /**
42308 * Creates an array of own enumerable string keyed-value pairs for `object`
42309 * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
42310 * entries are returned.
42311 *
42312 * @static
42313 * @memberOf _
42314 * @since 4.0.0
42315 * @alias entries
42316 * @category Object
42317 * @param {Object} object The object to query.
42318 * @returns {Array} Returns the key-value pairs.
42319 * @example
42320 *
42321 * function Foo() {
42322 * this.a = 1;
42323 * this.b = 2;
42324 * }
42325 *
42326 * Foo.prototype.c = 3;
42327 *
42328 * _.toPairs(new Foo);
42329 * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
42330 */
42331 var toPairs = createToPairs(keys);
42332
42333 /**
42334 * Creates an array of own and inherited enumerable string keyed-value pairs
42335 * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
42336 * or set, its entries are returned.
42337 *
42338 * @static
42339 * @memberOf _
42340 * @since 4.0.0
42341 * @alias entriesIn
42342 * @category Object
42343 * @param {Object} object The object to query.
42344 * @returns {Array} Returns the key-value pairs.
42345 * @example
42346 *
42347 * function Foo() {
42348 * this.a = 1;
42349 * this.b = 2;
42350 * }
42351 *
42352 * Foo.prototype.c = 3;
42353 *
42354 * _.toPairsIn(new Foo);
42355 * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
42356 */
42357 var toPairsIn = createToPairs(keysIn);
42358
42359 /**
42360 * An alternative to `_.reduce`; this method transforms `object` to a new
42361 * `accumulator` object which is the result of running each of its own
42362 * enumerable string keyed properties thru `iteratee`, with each invocation
42363 * potentially mutating the `accumulator` object. If `accumulator` is not
42364 * provided, a new object with the same `[[Prototype]]` will be used. The
42365 * iteratee is invoked with four arguments: (accumulator, value, key, object).
42366 * Iteratee functions may exit iteration early by explicitly returning `false`.
42367 *
42368 * @static
42369 * @memberOf _
42370 * @since 1.3.0
42371 * @category Object
42372 * @param {Object} object The object to iterate over.
42373 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
42374 * @param {*} [accumulator] The custom accumulator value.
42375 * @returns {*} Returns the accumulated value.
42376 * @example
42377 *
42378 * _.transform([2, 3, 4], function(result, n) {
42379 * result.push(n *= n);
42380 * return n % 2 == 0;
42381 * }, []);
42382 * // => [4, 9]
42383 *
42384 * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
42385 * (result[value] || (result[value] = [])).push(key);
42386 * }, {});
42387 * // => { '1': ['a', 'c'], '2': ['b'] }
42388 */
42389 function transform(object, iteratee, accumulator) {
42390 var isArr = isArray(object),
42391 isArrLike = isArr || isBuffer(object) || isTypedArray(object);
42392
42393 iteratee = getIteratee(iteratee, 4);
42394 if (accumulator == null) {
42395 var Ctor = object && object.constructor;
42396 if (isArrLike) {
42397 accumulator = isArr ? new Ctor : [];
42398 }
42399 else if (isObject(object)) {
42400 accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
42401 }
42402 else {
42403 accumulator = {};
42404 }
42405 }
42406 (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
42407 return iteratee(accumulator, value, index, object);
42408 });
42409 return accumulator;
42410 }
42411
42412 /**
42413 * Removes the property at `path` of `object`.
42414 *
42415 * **Note:** This method mutates `object`.
42416 *
42417 * @static
42418 * @memberOf _
42419 * @since 4.0.0
42420 * @category Object
42421 * @param {Object} object The object to modify.
42422 * @param {Array|string} path The path of the property to unset.
42423 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
42424 * @example
42425 *
42426 * var object = { 'a': [{ 'b': { 'c': 7 } }] };
42427 * _.unset(object, 'a[0].b.c');
42428 * // => true
42429 *
42430 * console.log(object);
42431 * // => { 'a': [{ 'b': {} }] };
42432 *
42433 * _.unset(object, ['a', '0', 'b', 'c']);
42434 * // => true
42435 *
42436 * console.log(object);
42437 * // => { 'a': [{ 'b': {} }] };
42438 */
42439 function unset(object, path) {
42440 return object == null ? true : baseUnset(object, path);
42441 }
42442
42443 /**
42444 * This method is like `_.set` except that accepts `updater` to produce the
42445 * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
42446 * is invoked with one argument: (value).
42447 *
42448 * **Note:** This method mutates `object`.
42449 *
42450 * @static
42451 * @memberOf _
42452 * @since 4.6.0
42453 * @category Object
42454 * @param {Object} object The object to modify.
42455 * @param {Array|string} path The path of the property to set.
42456 * @param {Function} updater The function to produce the updated value.
42457 * @returns {Object} Returns `object`.
42458 * @example
42459 *
42460 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
42461 *
42462 * _.update(object, 'a[0].b.c', function(n) { return n * n; });
42463 * console.log(object.a[0].b.c);
42464 * // => 9
42465 *
42466 * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
42467 * console.log(object.x[0].y.z);
42468 * // => 0
42469 */
42470 function update(object, path, updater) {
42471 return object == null ? object : baseUpdate(object, path, castFunction(updater));
42472 }
42473
42474 /**
42475 * This method is like `_.update` except that it accepts `customizer` which is
42476 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
42477 * path creation is handled by the method instead. The `customizer` is invoked
42478 * with three arguments: (nsValue, key, nsObject).
42479 *
42480 * **Note:** This method mutates `object`.
42481 *
42482 * @static
42483 * @memberOf _
42484 * @since 4.6.0
42485 * @category Object
42486 * @param {Object} object The object to modify.
42487 * @param {Array|string} path The path of the property to set.
42488 * @param {Function} updater The function to produce the updated value.
42489 * @param {Function} [customizer] The function to customize assigned values.
42490 * @returns {Object} Returns `object`.
42491 * @example
42492 *
42493 * var object = {};
42494 *
42495 * _.updateWith(object, '[0][1]', _.constant('a'), Object);
42496 * // => { '0': { '1': 'a' } }
42497 */
42498 function updateWith(object, path, updater, customizer) {
42499 customizer = typeof customizer == 'function' ? customizer : undefined;
42500 return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
42501 }
42502
42503 /**
42504 * Creates an array of the own enumerable string keyed property values of `object`.
42505 *
42506 * **Note:** Non-object values are coerced to objects.
42507 *
42508 * @static
42509 * @since 0.1.0
42510 * @memberOf _
42511 * @category Object
42512 * @param {Object} object The object to query.
42513 * @returns {Array} Returns the array of property values.
42514 * @example
42515 *
42516 * function Foo() {
42517 * this.a = 1;
42518 * this.b = 2;
42519 * }
42520 *
42521 * Foo.prototype.c = 3;
42522 *
42523 * _.values(new Foo);
42524 * // => [1, 2] (iteration order is not guaranteed)
42525 *
42526 * _.values('hi');
42527 * // => ['h', 'i']
42528 */
42529 function values(object) {
42530 return object == null ? [] : baseValues(object, keys(object));
42531 }
42532
42533 /**
42534 * Creates an array of the own and inherited enumerable string keyed property
42535 * values of `object`.
42536 *
42537 * **Note:** Non-object values are coerced to objects.
42538 *
42539 * @static
42540 * @memberOf _
42541 * @since 3.0.0
42542 * @category Object
42543 * @param {Object} object The object to query.
42544 * @returns {Array} Returns the array of property values.
42545 * @example
42546 *
42547 * function Foo() {
42548 * this.a = 1;
42549 * this.b = 2;
42550 * }
42551 *
42552 * Foo.prototype.c = 3;
42553 *
42554 * _.valuesIn(new Foo);
42555 * // => [1, 2, 3] (iteration order is not guaranteed)
42556 */
42557 function valuesIn(object) {
42558 return object == null ? [] : baseValues(object, keysIn(object));
42559 }
42560
42561 /*------------------------------------------------------------------------*/
42562
42563 /**
42564 * Clamps `number` within the inclusive `lower` and `upper` bounds.
42565 *
42566 * @static
42567 * @memberOf _
42568 * @since 4.0.0
42569 * @category Number
42570 * @param {number} number The number to clamp.
42571 * @param {number} [lower] The lower bound.
42572 * @param {number} upper The upper bound.
42573 * @returns {number} Returns the clamped number.
42574 * @example
42575 *
42576 * _.clamp(-10, -5, 5);
42577 * // => -5
42578 *
42579 * _.clamp(10, -5, 5);
42580 * // => 5
42581 */
42582 function clamp(number, lower, upper) {
42583 if (upper === undefined) {
42584 upper = lower;
42585 lower = undefined;
42586 }
42587 if (upper !== undefined) {
42588 upper = toNumber(upper);
42589 upper = upper === upper ? upper : 0;
42590 }
42591 if (lower !== undefined) {
42592 lower = toNumber(lower);
42593 lower = lower === lower ? lower : 0;
42594 }
42595 return baseClamp(toNumber(number), lower, upper);
42596 }
42597
42598 /**
42599 * Checks if `n` is between `start` and up to, but not including, `end`. If
42600 * `end` is not specified, it's set to `start` with `start` then set to `0`.
42601 * If `start` is greater than `end` the params are swapped to support
42602 * negative ranges.
42603 *
42604 * @static
42605 * @memberOf _
42606 * @since 3.3.0
42607 * @category Number
42608 * @param {number} number The number to check.
42609 * @param {number} [start=0] The start of the range.
42610 * @param {number} end The end of the range.
42611 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
42612 * @see _.range, _.rangeRight
42613 * @example
42614 *
42615 * _.inRange(3, 2, 4);
42616 * // => true
42617 *
42618 * _.inRange(4, 8);
42619 * // => true
42620 *
42621 * _.inRange(4, 2);
42622 * // => false
42623 *
42624 * _.inRange(2, 2);
42625 * // => false
42626 *
42627 * _.inRange(1.2, 2);
42628 * // => true
42629 *
42630 * _.inRange(5.2, 4);
42631 * // => false
42632 *
42633 * _.inRange(-3, -2, -6);
42634 * // => true
42635 */
42636 function inRange(number, start, end) {
42637 start = toFinite(start);
42638 if (end === undefined) {
42639 end = start;
42640 start = 0;
42641 } else {
42642 end = toFinite(end);
42643 }
42644 number = toNumber(number);
42645 return baseInRange(number, start, end);
42646 }
42647
42648 /**
42649 * Produces a random number between the inclusive `lower` and `upper` bounds.
42650 * If only one argument is provided a number between `0` and the given number
42651 * is returned. If `floating` is `true`, or either `lower` or `upper` are
42652 * floats, a floating-point number is returned instead of an integer.
42653 *
42654 * **Note:** JavaScript follows the IEEE-754 standard for resolving
42655 * floating-point values which can produce unexpected results.
42656 *
42657 * @static
42658 * @memberOf _
42659 * @since 0.7.0
42660 * @category Number
42661 * @param {number} [lower=0] The lower bound.
42662 * @param {number} [upper=1] The upper bound.
42663 * @param {boolean} [floating] Specify returning a floating-point number.
42664 * @returns {number} Returns the random number.
42665 * @example
42666 *
42667 * _.random(0, 5);
42668 * // => an integer between 0 and 5
42669 *
42670 * _.random(5);
42671 * // => also an integer between 0 and 5
42672 *
42673 * _.random(5, true);
42674 * // => a floating-point number between 0 and 5
42675 *
42676 * _.random(1.2, 5.2);
42677 * // => a floating-point number between 1.2 and 5.2
42678 */
42679 function random(lower, upper, floating) {
42680 if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
42681 upper = floating = undefined;
42682 }
42683 if (floating === undefined) {
42684 if (typeof upper == 'boolean') {
42685 floating = upper;
42686 upper = undefined;
42687 }
42688 else if (typeof lower == 'boolean') {
42689 floating = lower;
42690 lower = undefined;
42691 }
42692 }
42693 if (lower === undefined && upper === undefined) {
42694 lower = 0;
42695 upper = 1;
42696 }
42697 else {
42698 lower = toFinite(lower);
42699 if (upper === undefined) {
42700 upper = lower;
42701 lower = 0;
42702 } else {
42703 upper = toFinite(upper);
42704 }
42705 }
42706 if (lower > upper) {
42707 var temp = lower;
42708 lower = upper;
42709 upper = temp;
42710 }
42711 if (floating || lower % 1 || upper % 1) {
42712 var rand = nativeRandom();
42713 return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
42714 }
42715 return baseRandom(lower, upper);
42716 }
42717
42718 /*------------------------------------------------------------------------*/
42719
42720 /**
42721 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
42722 *
42723 * @static
42724 * @memberOf _
42725 * @since 3.0.0
42726 * @category String
42727 * @param {string} [string=''] The string to convert.
42728 * @returns {string} Returns the camel cased string.
42729 * @example
42730 *
42731 * _.camelCase('Foo Bar');
42732 * // => 'fooBar'
42733 *
42734 * _.camelCase('--foo-bar--');
42735 * // => 'fooBar'
42736 *
42737 * _.camelCase('__FOO_BAR__');
42738 * // => 'fooBar'
42739 */
42740 var camelCase = createCompounder(function(result, word, index) {
42741 word = word.toLowerCase();
42742 return result + (index ? capitalize(word) : word);
42743 });
42744
42745 /**
42746 * Converts the first character of `string` to upper case and the remaining
42747 * to lower case.
42748 *
42749 * @static
42750 * @memberOf _
42751 * @since 3.0.0
42752 * @category String
42753 * @param {string} [string=''] The string to capitalize.
42754 * @returns {string} Returns the capitalized string.
42755 * @example
42756 *
42757 * _.capitalize('FRED');
42758 * // => 'Fred'
42759 */
42760 function capitalize(string) {
42761 return upperFirst(toString(string).toLowerCase());
42762 }
42763
42764 /**
42765 * Deburrs `string` by converting
42766 * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
42767 * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
42768 * letters to basic Latin letters and removing
42769 * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
42770 *
42771 * @static
42772 * @memberOf _
42773 * @since 3.0.0
42774 * @category String
42775 * @param {string} [string=''] The string to deburr.
42776 * @returns {string} Returns the deburred string.
42777 * @example
42778 *
42779 * _.deburr('déjà vu');
42780 * // => 'deja vu'
42781 */
42782 function deburr(string) {
42783 string = toString(string);
42784 return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
42785 }
42786
42787 /**
42788 * Checks if `string` ends with the given target string.
42789 *
42790 * @static
42791 * @memberOf _
42792 * @since 3.0.0
42793 * @category String
42794 * @param {string} [string=''] The string to inspect.
42795 * @param {string} [target] The string to search for.
42796 * @param {number} [position=string.length] The position to search up to.
42797 * @returns {boolean} Returns `true` if `string` ends with `target`,
42798 * else `false`.
42799 * @example
42800 *
42801 * _.endsWith('abc', 'c');
42802 * // => true
42803 *
42804 * _.endsWith('abc', 'b');
42805 * // => false
42806 *
42807 * _.endsWith('abc', 'b', 2);
42808 * // => true
42809 */
42810 function endsWith(string, target, position) {
42811 string = toString(string);
42812 target = baseToString(target);
42813
42814 var length = string.length;
42815 position = position === undefined
42816 ? length
42817 : baseClamp(toInteger(position), 0, length);
42818
42819 var end = position;
42820 position -= target.length;
42821 return position >= 0 && string.slice(position, end) == target;
42822 }
42823
42824 /**
42825 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
42826 * corresponding HTML entities.
42827 *
42828 * **Note:** No other characters are escaped. To escape additional
42829 * characters use a third-party library like [_he_](https://mths.be/he).
42830 *
42831 * Though the ">" character is escaped for symmetry, characters like
42832 * ">" and "/" don't need escaping in HTML and have no special meaning
42833 * unless they're part of a tag or unquoted attribute value. See
42834 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
42835 * (under "semi-related fun fact") for more details.
42836 *
42837 * When working with HTML you should always
42838 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
42839 * XSS vectors.
42840 *
42841 * @static
42842 * @since 0.1.0
42843 * @memberOf _
42844 * @category String
42845 * @param {string} [string=''] The string to escape.
42846 * @returns {string} Returns the escaped string.
42847 * @example
42848 *
42849 * _.escape('fred, barney, & pebbles');
42850 * // => 'fred, barney, &amp; pebbles'
42851 */
42852 function escape(string) {
42853 string = toString(string);
42854 return (string && reHasUnescapedHtml.test(string))
42855 ? string.replace(reUnescapedHtml, escapeHtmlChar)
42856 : string;
42857 }
42858
42859 /**
42860 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
42861 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
42862 *
42863 * @static
42864 * @memberOf _
42865 * @since 3.0.0
42866 * @category String
42867 * @param {string} [string=''] The string to escape.
42868 * @returns {string} Returns the escaped string.
42869 * @example
42870 *
42871 * _.escapeRegExp('[lodash](https://lodash.com/)');
42872 * // => '\[lodash\]\(https://lodash\.com/\)'
42873 */
42874 function escapeRegExp(string) {
42875 string = toString(string);
42876 return (string && reHasRegExpChar.test(string))
42877 ? string.replace(reRegExpChar, '\\$&')
42878 : string;
42879 }
42880
42881 /**
42882 * Converts `string` to
42883 * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
42884 *
42885 * @static
42886 * @memberOf _
42887 * @since 3.0.0
42888 * @category String
42889 * @param {string} [string=''] The string to convert.
42890 * @returns {string} Returns the kebab cased string.
42891 * @example
42892 *
42893 * _.kebabCase('Foo Bar');
42894 * // => 'foo-bar'
42895 *
42896 * _.kebabCase('fooBar');
42897 * // => 'foo-bar'
42898 *
42899 * _.kebabCase('__FOO_BAR__');
42900 * // => 'foo-bar'
42901 */
42902 var kebabCase = createCompounder(function(result, word, index) {
42903 return result + (index ? '-' : '') + word.toLowerCase();
42904 });
42905
42906 /**
42907 * Converts `string`, as space separated words, to lower case.
42908 *
42909 * @static
42910 * @memberOf _
42911 * @since 4.0.0
42912 * @category String
42913 * @param {string} [string=''] The string to convert.
42914 * @returns {string} Returns the lower cased string.
42915 * @example
42916 *
42917 * _.lowerCase('--Foo-Bar--');
42918 * // => 'foo bar'
42919 *
42920 * _.lowerCase('fooBar');
42921 * // => 'foo bar'
42922 *
42923 * _.lowerCase('__FOO_BAR__');
42924 * // => 'foo bar'
42925 */
42926 var lowerCase = createCompounder(function(result, word, index) {
42927 return result + (index ? ' ' : '') + word.toLowerCase();
42928 });
42929
42930 /**
42931 * Converts the first character of `string` to lower case.
42932 *
42933 * @static
42934 * @memberOf _
42935 * @since 4.0.0
42936 * @category String
42937 * @param {string} [string=''] The string to convert.
42938 * @returns {string} Returns the converted string.
42939 * @example
42940 *
42941 * _.lowerFirst('Fred');
42942 * // => 'fred'
42943 *
42944 * _.lowerFirst('FRED');
42945 * // => 'fRED'
42946 */
42947 var lowerFirst = createCaseFirst('toLowerCase');
42948
42949 /**
42950 * Pads `string` on the left and right sides if it's shorter than `length`.
42951 * Padding characters are truncated if they can't be evenly divided by `length`.
42952 *
42953 * @static
42954 * @memberOf _
42955 * @since 3.0.0
42956 * @category String
42957 * @param {string} [string=''] The string to pad.
42958 * @param {number} [length=0] The padding length.
42959 * @param {string} [chars=' '] The string used as padding.
42960 * @returns {string} Returns the padded string.
42961 * @example
42962 *
42963 * _.pad('abc', 8);
42964 * // => ' abc '
42965 *
42966 * _.pad('abc', 8, '_-');
42967 * // => '_-abc_-_'
42968 *
42969 * _.pad('abc', 3);
42970 * // => 'abc'
42971 */
42972 function pad(string, length, chars) {
42973 string = toString(string);
42974 length = toInteger(length);
42975
42976 var strLength = length ? stringSize(string) : 0;
42977 if (!length || strLength >= length) {
42978 return string;
42979 }
42980 var mid = (length - strLength) / 2;
42981 return (
42982 createPadding(nativeFloor(mid), chars) +
42983 string +
42984 createPadding(nativeCeil(mid), chars)
42985 );
42986 }
42987
42988 /**
42989 * Pads `string` on the right side if it's shorter than `length`. Padding
42990 * characters are truncated if they exceed `length`.
42991 *
42992 * @static
42993 * @memberOf _
42994 * @since 4.0.0
42995 * @category String
42996 * @param {string} [string=''] The string to pad.
42997 * @param {number} [length=0] The padding length.
42998 * @param {string} [chars=' '] The string used as padding.
42999 * @returns {string} Returns the padded string.
43000 * @example
43001 *
43002 * _.padEnd('abc', 6);
43003 * // => 'abc '
43004 *
43005 * _.padEnd('abc', 6, '_-');
43006 * // => 'abc_-_'
43007 *
43008 * _.padEnd('abc', 3);
43009 * // => 'abc'
43010 */
43011 function padEnd(string, length, chars) {
43012 string = toString(string);
43013 length = toInteger(length);
43014
43015 var strLength = length ? stringSize(string) : 0;
43016 return (length && strLength < length)
43017 ? (string + createPadding(length - strLength, chars))
43018 : string;
43019 }
43020
43021 /**
43022 * Pads `string` on the left side if it's shorter than `length`. Padding
43023 * characters are truncated if they exceed `length`.
43024 *
43025 * @static
43026 * @memberOf _
43027 * @since 4.0.0
43028 * @category String
43029 * @param {string} [string=''] The string to pad.
43030 * @param {number} [length=0] The padding length.
43031 * @param {string} [chars=' '] The string used as padding.
43032 * @returns {string} Returns the padded string.
43033 * @example
43034 *
43035 * _.padStart('abc', 6);
43036 * // => ' abc'
43037 *
43038 * _.padStart('abc', 6, '_-');
43039 * // => '_-_abc'
43040 *
43041 * _.padStart('abc', 3);
43042 * // => 'abc'
43043 */
43044 function padStart(string, length, chars) {
43045 string = toString(string);
43046 length = toInteger(length);
43047
43048 var strLength = length ? stringSize(string) : 0;
43049 return (length && strLength < length)
43050 ? (createPadding(length - strLength, chars) + string)
43051 : string;
43052 }
43053
43054 /**
43055 * Converts `string` to an integer of the specified radix. If `radix` is
43056 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
43057 * hexadecimal, in which case a `radix` of `16` is used.
43058 *
43059 * **Note:** This method aligns with the
43060 * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
43061 *
43062 * @static
43063 * @memberOf _
43064 * @since 1.1.0
43065 * @category String
43066 * @param {string} string The string to convert.
43067 * @param {number} [radix=10] The radix to interpret `value` by.
43068 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43069 * @returns {number} Returns the converted integer.
43070 * @example
43071 *
43072 * _.parseInt('08');
43073 * // => 8
43074 *
43075 * _.map(['6', '08', '10'], _.parseInt);
43076 * // => [6, 8, 10]
43077 */
43078 function parseInt(string, radix, guard) {
43079 if (guard || radix == null) {
43080 radix = 0;
43081 } else if (radix) {
43082 radix = +radix;
43083 }
43084 return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
43085 }
43086
43087 /**
43088 * Repeats the given string `n` times.
43089 *
43090 * @static
43091 * @memberOf _
43092 * @since 3.0.0
43093 * @category String
43094 * @param {string} [string=''] The string to repeat.
43095 * @param {number} [n=1] The number of times to repeat the string.
43096 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43097 * @returns {string} Returns the repeated string.
43098 * @example
43099 *
43100 * _.repeat('*', 3);
43101 * // => '***'
43102 *
43103 * _.repeat('abc', 2);
43104 * // => 'abcabc'
43105 *
43106 * _.repeat('abc', 0);
43107 * // => ''
43108 */
43109 function repeat(string, n, guard) {
43110 if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
43111 n = 1;
43112 } else {
43113 n = toInteger(n);
43114 }
43115 return baseRepeat(toString(string), n);
43116 }
43117
43118 /**
43119 * Replaces matches for `pattern` in `string` with `replacement`.
43120 *
43121 * **Note:** This method is based on
43122 * [`String#replace`](https://mdn.io/String/replace).
43123 *
43124 * @static
43125 * @memberOf _
43126 * @since 4.0.0
43127 * @category String
43128 * @param {string} [string=''] The string to modify.
43129 * @param {RegExp|string} pattern The pattern to replace.
43130 * @param {Function|string} replacement The match replacement.
43131 * @returns {string} Returns the modified string.
43132 * @example
43133 *
43134 * _.replace('Hi Fred', 'Fred', 'Barney');
43135 * // => 'Hi Barney'
43136 */
43137 function replace() {
43138 var args = arguments,
43139 string = toString(args[0]);
43140
43141 return args.length < 3 ? string : string.replace(args[1], args[2]);
43142 }
43143
43144 /**
43145 * Converts `string` to
43146 * [snake case](https://en.wikipedia.org/wiki/Snake_case).
43147 *
43148 * @static
43149 * @memberOf _
43150 * @since 3.0.0
43151 * @category String
43152 * @param {string} [string=''] The string to convert.
43153 * @returns {string} Returns the snake cased string.
43154 * @example
43155 *
43156 * _.snakeCase('Foo Bar');
43157 * // => 'foo_bar'
43158 *
43159 * _.snakeCase('fooBar');
43160 * // => 'foo_bar'
43161 *
43162 * _.snakeCase('--FOO-BAR--');
43163 * // => 'foo_bar'
43164 */
43165 var snakeCase = createCompounder(function(result, word, index) {
43166 return result + (index ? '_' : '') + word.toLowerCase();
43167 });
43168
43169 /**
43170 * Splits `string` by `separator`.
43171 *
43172 * **Note:** This method is based on
43173 * [`String#split`](https://mdn.io/String/split).
43174 *
43175 * @static
43176 * @memberOf _
43177 * @since 4.0.0
43178 * @category String
43179 * @param {string} [string=''] The string to split.
43180 * @param {RegExp|string} separator The separator pattern to split by.
43181 * @param {number} [limit] The length to truncate results to.
43182 * @returns {Array} Returns the string segments.
43183 * @example
43184 *
43185 * _.split('a-b-c', '-', 2);
43186 * // => ['a', 'b']
43187 */
43188 function split(string, separator, limit) {
43189 if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
43190 separator = limit = undefined;
43191 }
43192 limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
43193 if (!limit) {
43194 return [];
43195 }
43196 string = toString(string);
43197 if (string && (
43198 typeof separator == 'string' ||
43199 (separator != null && !isRegExp(separator))
43200 )) {
43201 separator = baseToString(separator);
43202 if (!separator && hasUnicode(string)) {
43203 return castSlice(stringToArray(string), 0, limit);
43204 }
43205 }
43206 return string.split(separator, limit);
43207 }
43208
43209 /**
43210 * Converts `string` to
43211 * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
43212 *
43213 * @static
43214 * @memberOf _
43215 * @since 3.1.0
43216 * @category String
43217 * @param {string} [string=''] The string to convert.
43218 * @returns {string} Returns the start cased string.
43219 * @example
43220 *
43221 * _.startCase('--foo-bar--');
43222 * // => 'Foo Bar'
43223 *
43224 * _.startCase('fooBar');
43225 * // => 'Foo Bar'
43226 *
43227 * _.startCase('__FOO_BAR__');
43228 * // => 'FOO BAR'
43229 */
43230 var startCase = createCompounder(function(result, word, index) {
43231 return result + (index ? ' ' : '') + upperFirst(word);
43232 });
43233
43234 /**
43235 * Checks if `string` starts with the given target string.
43236 *
43237 * @static
43238 * @memberOf _
43239 * @since 3.0.0
43240 * @category String
43241 * @param {string} [string=''] The string to inspect.
43242 * @param {string} [target] The string to search for.
43243 * @param {number} [position=0] The position to search from.
43244 * @returns {boolean} Returns `true` if `string` starts with `target`,
43245 * else `false`.
43246 * @example
43247 *
43248 * _.startsWith('abc', 'a');
43249 * // => true
43250 *
43251 * _.startsWith('abc', 'b');
43252 * // => false
43253 *
43254 * _.startsWith('abc', 'b', 1);
43255 * // => true
43256 */
43257 function startsWith(string, target, position) {
43258 string = toString(string);
43259 position = position == null
43260 ? 0
43261 : baseClamp(toInteger(position), 0, string.length);
43262
43263 target = baseToString(target);
43264 return string.slice(position, position + target.length) == target;
43265 }
43266
43267 /**
43268 * Creates a compiled template function that can interpolate data properties
43269 * in "interpolate" delimiters, HTML-escape interpolated data properties in
43270 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
43271 * properties may be accessed as free variables in the template. If a setting
43272 * object is given, it takes precedence over `_.templateSettings` values.
43273 *
43274 * **Note:** In the development build `_.template` utilizes
43275 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
43276 * for easier debugging.
43277 *
43278 * For more information on precompiling templates see
43279 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
43280 *
43281 * For more information on Chrome extension sandboxes see
43282 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
43283 *
43284 * @static
43285 * @since 0.1.0
43286 * @memberOf _
43287 * @category String
43288 * @param {string} [string=''] The template string.
43289 * @param {Object} [options={}] The options object.
43290 * @param {RegExp} [options.escape=_.templateSettings.escape]
43291 * The HTML "escape" delimiter.
43292 * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
43293 * The "evaluate" delimiter.
43294 * @param {Object} [options.imports=_.templateSettings.imports]
43295 * An object to import into the template as free variables.
43296 * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
43297 * The "interpolate" delimiter.
43298 * @param {string} [options.sourceURL='lodash.templateSources[n]']
43299 * The sourceURL of the compiled template.
43300 * @param {string} [options.variable='obj']
43301 * The data object variable name.
43302 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43303 * @returns {Function} Returns the compiled template function.
43304 * @example
43305 *
43306 * // Use the "interpolate" delimiter to create a compiled template.
43307 * var compiled = _.template('hello <%= user %>!');
43308 * compiled({ 'user': 'fred' });
43309 * // => 'hello fred!'
43310 *
43311 * // Use the HTML "escape" delimiter to escape data property values.
43312 * var compiled = _.template('<b><%- value %></b>');
43313 * compiled({ 'value': '<script>' });
43314 * // => '<b>&lt;script&gt;</b>'
43315 *
43316 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
43317 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
43318 * compiled({ 'users': ['fred', 'barney'] });
43319 * // => '<li>fred</li><li>barney</li>'
43320 *
43321 * // Use the internal `print` function in "evaluate" delimiters.
43322 * var compiled = _.template('<% print("hello " + user); %>!');
43323 * compiled({ 'user': 'barney' });
43324 * // => 'hello barney!'
43325 *
43326 * // Use the ES template literal delimiter as an "interpolate" delimiter.
43327 * // Disable support by replacing the "interpolate" delimiter.
43328 * var compiled = _.template('hello ${ user }!');
43329 * compiled({ 'user': 'pebbles' });
43330 * // => 'hello pebbles!'
43331 *
43332 * // Use backslashes to treat delimiters as plain text.
43333 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
43334 * compiled({ 'value': 'ignored' });
43335 * // => '<%- value %>'
43336 *
43337 * // Use the `imports` option to import `jQuery` as `jq`.
43338 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
43339 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
43340 * compiled({ 'users': ['fred', 'barney'] });
43341 * // => '<li>fred</li><li>barney</li>'
43342 *
43343 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
43344 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
43345 * compiled(data);
43346 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
43347 *
43348 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
43349 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
43350 * compiled.source;
43351 * // => function(data) {
43352 * // var __t, __p = '';
43353 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
43354 * // return __p;
43355 * // }
43356 *
43357 * // Use custom template delimiters.
43358 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
43359 * var compiled = _.template('hello {{ user }}!');
43360 * compiled({ 'user': 'mustache' });
43361 * // => 'hello mustache!'
43362 *
43363 * // Use the `source` property to inline compiled templates for meaningful
43364 * // line numbers in error messages and stack traces.
43365 * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
43366 * var JST = {\
43367 * "main": ' + _.template(mainText).source + '\
43368 * };\
43369 * ');
43370 */
43371 function template(string, options, guard) {
43372 // Based on John Resig's `tmpl` implementation
43373 // (http://ejohn.org/blog/javascript-micro-templating/)
43374 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
43375 var settings = lodash.templateSettings;
43376
43377 if (guard && isIterateeCall(string, options, guard)) {
43378 options = undefined;
43379 }
43380 string = toString(string);
43381 options = assignInWith({}, options, settings, customDefaultsAssignIn);
43382
43383 var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
43384 importsKeys = keys(imports),
43385 importsValues = baseValues(imports, importsKeys);
43386
43387 var isEscaping,
43388 isEvaluating,
43389 index = 0,
43390 interpolate = options.interpolate || reNoMatch,
43391 source = "__p += '";
43392
43393 // Compile the regexp to match each delimiter.
43394 var reDelimiters = RegExp(
43395 (options.escape || reNoMatch).source + '|' +
43396 interpolate.source + '|' +
43397 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
43398 (options.evaluate || reNoMatch).source + '|$'
43399 , 'g');
43400
43401 // Use a sourceURL for easier debugging.
43402 // The sourceURL gets injected into the source that's eval-ed, so be careful
43403 // with lookup (in case of e.g. prototype pollution), and strip newlines if any.
43404 // A newline wouldn't be a valid sourceURL anyway, and it'd enable code injection.
43405 var sourceURL = '//# sourceURL=' +
43406 (hasOwnProperty.call(options, 'sourceURL')
43407 ? (options.sourceURL + '').replace(/[\r\n]/g, ' ')
43408 : ('lodash.templateSources[' + (++templateCounter) + ']')
43409 ) + '\n';
43410
43411 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
43412 interpolateValue || (interpolateValue = esTemplateValue);
43413
43414 // Escape characters that can't be included in string literals.
43415 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
43416
43417 // Replace delimiters with snippets.
43418 if (escapeValue) {
43419 isEscaping = true;
43420 source += "' +\n__e(" + escapeValue + ") +\n'";
43421 }
43422 if (evaluateValue) {
43423 isEvaluating = true;
43424 source += "';\n" + evaluateValue + ";\n__p += '";
43425 }
43426 if (interpolateValue) {
43427 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
43428 }
43429 index = offset + match.length;
43430
43431 // The JS engine embedded in Adobe products needs `match` returned in
43432 // order to produce the correct `offset` value.
43433 return match;
43434 });
43435
43436 source += "';\n";
43437
43438 // If `variable` is not specified wrap a with-statement around the generated
43439 // code to add the data object to the top of the scope chain.
43440 // Like with sourceURL, we take care to not check the option's prototype,
43441 // as this configuration is a code injection vector.
43442 var variable = hasOwnProperty.call(options, 'variable') && options.variable;
43443 if (!variable) {
43444 source = 'with (obj) {\n' + source + '\n}\n';
43445 }
43446 // Cleanup code by stripping empty strings.
43447 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
43448 .replace(reEmptyStringMiddle, '$1')
43449 .replace(reEmptyStringTrailing, '$1;');
43450
43451 // Frame code as the function body.
43452 source = 'function(' + (variable || 'obj') + ') {\n' +
43453 (variable
43454 ? ''
43455 : 'obj || (obj = {});\n'
43456 ) +
43457 "var __t, __p = ''" +
43458 (isEscaping
43459 ? ', __e = _.escape'
43460 : ''
43461 ) +
43462 (isEvaluating
43463 ? ', __j = Array.prototype.join;\n' +
43464 "function print() { __p += __j.call(arguments, '') }\n"
43465 : ';\n'
43466 ) +
43467 source +
43468 'return __p\n}';
43469
43470 var result = attempt(function() {
43471 return Function(importsKeys, sourceURL + 'return ' + source)
43472 .apply(undefined, importsValues);
43473 });
43474
43475 // Provide the compiled function's source by its `toString` method or
43476 // the `source` property as a convenience for inlining compiled templates.
43477 result.source = source;
43478 if (isError(result)) {
43479 throw result;
43480 }
43481 return result;
43482 }
43483
43484 /**
43485 * Converts `string`, as a whole, to lower case just like
43486 * [String#toLowerCase](https://mdn.io/toLowerCase).
43487 *
43488 * @static
43489 * @memberOf _
43490 * @since 4.0.0
43491 * @category String
43492 * @param {string} [string=''] The string to convert.
43493 * @returns {string} Returns the lower cased string.
43494 * @example
43495 *
43496 * _.toLower('--Foo-Bar--');
43497 * // => '--foo-bar--'
43498 *
43499 * _.toLower('fooBar');
43500 * // => 'foobar'
43501 *
43502 * _.toLower('__FOO_BAR__');
43503 * // => '__foo_bar__'
43504 */
43505 function toLower(value) {
43506 return toString(value).toLowerCase();
43507 }
43508
43509 /**
43510 * Converts `string`, as a whole, to upper case just like
43511 * [String#toUpperCase](https://mdn.io/toUpperCase).
43512 *
43513 * @static
43514 * @memberOf _
43515 * @since 4.0.0
43516 * @category String
43517 * @param {string} [string=''] The string to convert.
43518 * @returns {string} Returns the upper cased string.
43519 * @example
43520 *
43521 * _.toUpper('--foo-bar--');
43522 * // => '--FOO-BAR--'
43523 *
43524 * _.toUpper('fooBar');
43525 * // => 'FOOBAR'
43526 *
43527 * _.toUpper('__foo_bar__');
43528 * // => '__FOO_BAR__'
43529 */
43530 function toUpper(value) {
43531 return toString(value).toUpperCase();
43532 }
43533
43534 /**
43535 * Removes leading and trailing whitespace or specified characters from `string`.
43536 *
43537 * @static
43538 * @memberOf _
43539 * @since 3.0.0
43540 * @category String
43541 * @param {string} [string=''] The string to trim.
43542 * @param {string} [chars=whitespace] The characters to trim.
43543 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43544 * @returns {string} Returns the trimmed string.
43545 * @example
43546 *
43547 * _.trim(' abc ');
43548 * // => 'abc'
43549 *
43550 * _.trim('-_-abc-_-', '_-');
43551 * // => 'abc'
43552 *
43553 * _.map([' foo ', ' bar '], _.trim);
43554 * // => ['foo', 'bar']
43555 */
43556 function trim(string, chars, guard) {
43557 string = toString(string);
43558 if (string && (guard || chars === undefined)) {
43559 return string.replace(reTrim, '');
43560 }
43561 if (!string || !(chars = baseToString(chars))) {
43562 return string;
43563 }
43564 var strSymbols = stringToArray(string),
43565 chrSymbols = stringToArray(chars),
43566 start = charsStartIndex(strSymbols, chrSymbols),
43567 end = charsEndIndex(strSymbols, chrSymbols) + 1;
43568
43569 return castSlice(strSymbols, start, end).join('');
43570 }
43571
43572 /**
43573 * Removes trailing whitespace or specified characters from `string`.
43574 *
43575 * @static
43576 * @memberOf _
43577 * @since 4.0.0
43578 * @category String
43579 * @param {string} [string=''] The string to trim.
43580 * @param {string} [chars=whitespace] The characters to trim.
43581 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43582 * @returns {string} Returns the trimmed string.
43583 * @example
43584 *
43585 * _.trimEnd(' abc ');
43586 * // => ' abc'
43587 *
43588 * _.trimEnd('-_-abc-_-', '_-');
43589 * // => '-_-abc'
43590 */
43591 function trimEnd(string, chars, guard) {
43592 string = toString(string);
43593 if (string && (guard || chars === undefined)) {
43594 return string.replace(reTrimEnd, '');
43595 }
43596 if (!string || !(chars = baseToString(chars))) {
43597 return string;
43598 }
43599 var strSymbols = stringToArray(string),
43600 end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
43601
43602 return castSlice(strSymbols, 0, end).join('');
43603 }
43604
43605 /**
43606 * Removes leading whitespace or specified characters from `string`.
43607 *
43608 * @static
43609 * @memberOf _
43610 * @since 4.0.0
43611 * @category String
43612 * @param {string} [string=''] The string to trim.
43613 * @param {string} [chars=whitespace] The characters to trim.
43614 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43615 * @returns {string} Returns the trimmed string.
43616 * @example
43617 *
43618 * _.trimStart(' abc ');
43619 * // => 'abc '
43620 *
43621 * _.trimStart('-_-abc-_-', '_-');
43622 * // => 'abc-_-'
43623 */
43624 function trimStart(string, chars, guard) {
43625 string = toString(string);
43626 if (string && (guard || chars === undefined)) {
43627 return string.replace(reTrimStart, '');
43628 }
43629 if (!string || !(chars = baseToString(chars))) {
43630 return string;
43631 }
43632 var strSymbols = stringToArray(string),
43633 start = charsStartIndex(strSymbols, stringToArray(chars));
43634
43635 return castSlice(strSymbols, start).join('');
43636 }
43637
43638 /**
43639 * Truncates `string` if it's longer than the given maximum string length.
43640 * The last characters of the truncated string are replaced with the omission
43641 * string which defaults to "...".
43642 *
43643 * @static
43644 * @memberOf _
43645 * @since 4.0.0
43646 * @category String
43647 * @param {string} [string=''] The string to truncate.
43648 * @param {Object} [options={}] The options object.
43649 * @param {number} [options.length=30] The maximum string length.
43650 * @param {string} [options.omission='...'] The string to indicate text is omitted.
43651 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
43652 * @returns {string} Returns the truncated string.
43653 * @example
43654 *
43655 * _.truncate('hi-diddly-ho there, neighborino');
43656 * // => 'hi-diddly-ho there, neighbo...'
43657 *
43658 * _.truncate('hi-diddly-ho there, neighborino', {
43659 * 'length': 24,
43660 * 'separator': ' '
43661 * });
43662 * // => 'hi-diddly-ho there,...'
43663 *
43664 * _.truncate('hi-diddly-ho there, neighborino', {
43665 * 'length': 24,
43666 * 'separator': /,? +/
43667 * });
43668 * // => 'hi-diddly-ho there...'
43669 *
43670 * _.truncate('hi-diddly-ho there, neighborino', {
43671 * 'omission': ' [...]'
43672 * });
43673 * // => 'hi-diddly-ho there, neig [...]'
43674 */
43675 function truncate(string, options) {
43676 var length = DEFAULT_TRUNC_LENGTH,
43677 omission = DEFAULT_TRUNC_OMISSION;
43678
43679 if (isObject(options)) {
43680 var separator = 'separator' in options ? options.separator : separator;
43681 length = 'length' in options ? toInteger(options.length) : length;
43682 omission = 'omission' in options ? baseToString(options.omission) : omission;
43683 }
43684 string = toString(string);
43685
43686 var strLength = string.length;
43687 if (hasUnicode(string)) {
43688 var strSymbols = stringToArray(string);
43689 strLength = strSymbols.length;
43690 }
43691 if (length >= strLength) {
43692 return string;
43693 }
43694 var end = length - stringSize(omission);
43695 if (end < 1) {
43696 return omission;
43697 }
43698 var result = strSymbols
43699 ? castSlice(strSymbols, 0, end).join('')
43700 : string.slice(0, end);
43701
43702 if (separator === undefined) {
43703 return result + omission;
43704 }
43705 if (strSymbols) {
43706 end += (result.length - end);
43707 }
43708 if (isRegExp(separator)) {
43709 if (string.slice(end).search(separator)) {
43710 var match,
43711 substring = result;
43712
43713 if (!separator.global) {
43714 separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
43715 }
43716 separator.lastIndex = 0;
43717 while ((match = separator.exec(substring))) {
43718 var newEnd = match.index;
43719 }
43720 result = result.slice(0, newEnd === undefined ? end : newEnd);
43721 }
43722 } else if (string.indexOf(baseToString(separator), end) != end) {
43723 var index = result.lastIndexOf(separator);
43724 if (index > -1) {
43725 result = result.slice(0, index);
43726 }
43727 }
43728 return result + omission;
43729 }
43730
43731 /**
43732 * The inverse of `_.escape`; this method converts the HTML entities
43733 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
43734 * their corresponding characters.
43735 *
43736 * **Note:** No other HTML entities are unescaped. To unescape additional
43737 * HTML entities use a third-party library like [_he_](https://mths.be/he).
43738 *
43739 * @static
43740 * @memberOf _
43741 * @since 0.6.0
43742 * @category String
43743 * @param {string} [string=''] The string to unescape.
43744 * @returns {string} Returns the unescaped string.
43745 * @example
43746 *
43747 * _.unescape('fred, barney, &amp; pebbles');
43748 * // => 'fred, barney, & pebbles'
43749 */
43750 function unescape(string) {
43751 string = toString(string);
43752 return (string && reHasEscapedHtml.test(string))
43753 ? string.replace(reEscapedHtml, unescapeHtmlChar)
43754 : string;
43755 }
43756
43757 /**
43758 * Converts `string`, as space separated words, to upper case.
43759 *
43760 * @static
43761 * @memberOf _
43762 * @since 4.0.0
43763 * @category String
43764 * @param {string} [string=''] The string to convert.
43765 * @returns {string} Returns the upper cased string.
43766 * @example
43767 *
43768 * _.upperCase('--foo-bar');
43769 * // => 'FOO BAR'
43770 *
43771 * _.upperCase('fooBar');
43772 * // => 'FOO BAR'
43773 *
43774 * _.upperCase('__foo_bar__');
43775 * // => 'FOO BAR'
43776 */
43777 var upperCase = createCompounder(function(result, word, index) {
43778 return result + (index ? ' ' : '') + word.toUpperCase();
43779 });
43780
43781 /**
43782 * Converts the first character of `string` to upper case.
43783 *
43784 * @static
43785 * @memberOf _
43786 * @since 4.0.0
43787 * @category String
43788 * @param {string} [string=''] The string to convert.
43789 * @returns {string} Returns the converted string.
43790 * @example
43791 *
43792 * _.upperFirst('fred');
43793 * // => 'Fred'
43794 *
43795 * _.upperFirst('FRED');
43796 * // => 'FRED'
43797 */
43798 var upperFirst = createCaseFirst('toUpperCase');
43799
43800 /**
43801 * Splits `string` into an array of its words.
43802 *
43803 * @static
43804 * @memberOf _
43805 * @since 3.0.0
43806 * @category String
43807 * @param {string} [string=''] The string to inspect.
43808 * @param {RegExp|string} [pattern] The pattern to match words.
43809 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
43810 * @returns {Array} Returns the words of `string`.
43811 * @example
43812 *
43813 * _.words('fred, barney, & pebbles');
43814 * // => ['fred', 'barney', 'pebbles']
43815 *
43816 * _.words('fred, barney, & pebbles', /[^, ]+/g);
43817 * // => ['fred', 'barney', '&', 'pebbles']
43818 */
43819 function words(string, pattern, guard) {
43820 string = toString(string);
43821 pattern = guard ? undefined : pattern;
43822
43823 if (pattern === undefined) {
43824 return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
43825 }
43826 return string.match(pattern) || [];
43827 }
43828
43829 /*------------------------------------------------------------------------*/
43830
43831 /**
43832 * Attempts to invoke `func`, returning either the result or the caught error
43833 * object. Any additional arguments are provided to `func` when it's invoked.
43834 *
43835 * @static
43836 * @memberOf _
43837 * @since 3.0.0
43838 * @category Util
43839 * @param {Function} func The function to attempt.
43840 * @param {...*} [args] The arguments to invoke `func` with.
43841 * @returns {*} Returns the `func` result or error object.
43842 * @example
43843 *
43844 * // Avoid throwing errors for invalid selectors.
43845 * var elements = _.attempt(function(selector) {
43846 * return document.querySelectorAll(selector);
43847 * }, '>_>');
43848 *
43849 * if (_.isError(elements)) {
43850 * elements = [];
43851 * }
43852 */
43853 var attempt = baseRest(function(func, args) {
43854 try {
43855 return apply(func, undefined, args);
43856 } catch (e) {
43857 return isError(e) ? e : new Error(e);
43858 }
43859 });
43860
43861 /**
43862 * Binds methods of an object to the object itself, overwriting the existing
43863 * method.
43864 *
43865 * **Note:** This method doesn't set the "length" property of bound functions.
43866 *
43867 * @static
43868 * @since 0.1.0
43869 * @memberOf _
43870 * @category Util
43871 * @param {Object} object The object to bind and assign the bound methods to.
43872 * @param {...(string|string[])} methodNames The object method names to bind.
43873 * @returns {Object} Returns `object`.
43874 * @example
43875 *
43876 * var view = {
43877 * 'label': 'docs',
43878 * 'click': function() {
43879 * console.log('clicked ' + this.label);
43880 * }
43881 * };
43882 *
43883 * _.bindAll(view, ['click']);
43884 * jQuery(element).on('click', view.click);
43885 * // => Logs 'clicked docs' when clicked.
43886 */
43887 var bindAll = flatRest(function(object, methodNames) {
43888 arrayEach(methodNames, function(key) {
43889 key = toKey(key);
43890 baseAssignValue(object, key, bind(object[key], object));
43891 });
43892 return object;
43893 });
43894
43895 /**
43896 * Creates a function that iterates over `pairs` and invokes the corresponding
43897 * function of the first predicate to return truthy. The predicate-function
43898 * pairs are invoked with the `this` binding and arguments of the created
43899 * function.
43900 *
43901 * @static
43902 * @memberOf _
43903 * @since 4.0.0
43904 * @category Util
43905 * @param {Array} pairs The predicate-function pairs.
43906 * @returns {Function} Returns the new composite function.
43907 * @example
43908 *
43909 * var func = _.cond([
43910 * [_.matches({ 'a': 1 }), _.constant('matches A')],
43911 * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
43912 * [_.stubTrue, _.constant('no match')]
43913 * ]);
43914 *
43915 * func({ 'a': 1, 'b': 2 });
43916 * // => 'matches A'
43917 *
43918 * func({ 'a': 0, 'b': 1 });
43919 * // => 'matches B'
43920 *
43921 * func({ 'a': '1', 'b': '2' });
43922 * // => 'no match'
43923 */
43924 function cond(pairs) {
43925 var length = pairs == null ? 0 : pairs.length,
43926 toIteratee = getIteratee();
43927
43928 pairs = !length ? [] : arrayMap(pairs, function(pair) {
43929 if (typeof pair[1] != 'function') {
43930 throw new TypeError(FUNC_ERROR_TEXT);
43931 }
43932 return [toIteratee(pair[0]), pair[1]];
43933 });
43934
43935 return baseRest(function(args) {
43936 var index = -1;
43937 while (++index < length) {
43938 var pair = pairs[index];
43939 if (apply(pair[0], this, args)) {
43940 return apply(pair[1], this, args);
43941 }
43942 }
43943 });
43944 }
43945
43946 /**
43947 * Creates a function that invokes the predicate properties of `source` with
43948 * the corresponding property values of a given object, returning `true` if
43949 * all predicates return truthy, else `false`.
43950 *
43951 * **Note:** The created function is equivalent to `_.conformsTo` with
43952 * `source` partially applied.
43953 *
43954 * @static
43955 * @memberOf _
43956 * @since 4.0.0
43957 * @category Util
43958 * @param {Object} source The object of property predicates to conform to.
43959 * @returns {Function} Returns the new spec function.
43960 * @example
43961 *
43962 * var objects = [
43963 * { 'a': 2, 'b': 1 },
43964 * { 'a': 1, 'b': 2 }
43965 * ];
43966 *
43967 * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
43968 * // => [{ 'a': 1, 'b': 2 }]
43969 */
43970 function conforms(source) {
43971 return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
43972 }
43973
43974 /**
43975 * Creates a function that returns `value`.
43976 *
43977 * @static
43978 * @memberOf _
43979 * @since 2.4.0
43980 * @category Util
43981 * @param {*} value The value to return from the new function.
43982 * @returns {Function} Returns the new constant function.
43983 * @example
43984 *
43985 * var objects = _.times(2, _.constant({ 'a': 1 }));
43986 *
43987 * console.log(objects);
43988 * // => [{ 'a': 1 }, { 'a': 1 }]
43989 *
43990 * console.log(objects[0] === objects[1]);
43991 * // => true
43992 */
43993 function constant(value) {
43994 return function() {
43995 return value;
43996 };
43997 }
43998
43999 /**
44000 * Checks `value` to determine whether a default value should be returned in
44001 * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
44002 * or `undefined`.
44003 *
44004 * @static
44005 * @memberOf _
44006 * @since 4.14.0
44007 * @category Util
44008 * @param {*} value The value to check.
44009 * @param {*} defaultValue The default value.
44010 * @returns {*} Returns the resolved value.
44011 * @example
44012 *
44013 * _.defaultTo(1, 10);
44014 * // => 1
44015 *
44016 * _.defaultTo(undefined, 10);
44017 * // => 10
44018 */
44019 function defaultTo(value, defaultValue) {
44020 return (value == null || value !== value) ? defaultValue : value;
44021 }
44022
44023 /**
44024 * Creates a function that returns the result of invoking the given functions
44025 * with the `this` binding of the created function, where each successive
44026 * invocation is supplied the return value of the previous.
44027 *
44028 * @static
44029 * @memberOf _
44030 * @since 3.0.0
44031 * @category Util
44032 * @param {...(Function|Function[])} [funcs] The functions to invoke.
44033 * @returns {Function} Returns the new composite function.
44034 * @see _.flowRight
44035 * @example
44036 *
44037 * function square(n) {
44038 * return n * n;
44039 * }
44040 *
44041 * var addSquare = _.flow([_.add, square]);
44042 * addSquare(1, 2);
44043 * // => 9
44044 */
44045 var flow = createFlow();
44046
44047 /**
44048 * This method is like `_.flow` except that it creates a function that
44049 * invokes the given functions from right to left.
44050 *
44051 * @static
44052 * @since 3.0.0
44053 * @memberOf _
44054 * @category Util
44055 * @param {...(Function|Function[])} [funcs] The functions to invoke.
44056 * @returns {Function} Returns the new composite function.
44057 * @see _.flow
44058 * @example
44059 *
44060 * function square(n) {
44061 * return n * n;
44062 * }
44063 *
44064 * var addSquare = _.flowRight([square, _.add]);
44065 * addSquare(1, 2);
44066 * // => 9
44067 */
44068 var flowRight = createFlow(true);
44069
44070 /**
44071 * This method returns the first argument it receives.
44072 *
44073 * @static
44074 * @since 0.1.0
44075 * @memberOf _
44076 * @category Util
44077 * @param {*} value Any value.
44078 * @returns {*} Returns `value`.
44079 * @example
44080 *
44081 * var object = { 'a': 1 };
44082 *
44083 * console.log(_.identity(object) === object);
44084 * // => true
44085 */
44086 function identity(value) {
44087 return value;
44088 }
44089
44090 /**
44091 * Creates a function that invokes `func` with the arguments of the created
44092 * function. If `func` is a property name, the created function returns the
44093 * property value for a given element. If `func` is an array or object, the
44094 * created function returns `true` for elements that contain the equivalent
44095 * source properties, otherwise it returns `false`.
44096 *
44097 * @static
44098 * @since 4.0.0
44099 * @memberOf _
44100 * @category Util
44101 * @param {*} [func=_.identity] The value to convert to a callback.
44102 * @returns {Function} Returns the callback.
44103 * @example
44104 *
44105 * var users = [
44106 * { 'user': 'barney', 'age': 36, 'active': true },
44107 * { 'user': 'fred', 'age': 40, 'active': false }
44108 * ];
44109 *
44110 * // The `_.matches` iteratee shorthand.
44111 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
44112 * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
44113 *
44114 * // The `_.matchesProperty` iteratee shorthand.
44115 * _.filter(users, _.iteratee(['user', 'fred']));
44116 * // => [{ 'user': 'fred', 'age': 40 }]
44117 *
44118 * // The `_.property` iteratee shorthand.
44119 * _.map(users, _.iteratee('user'));
44120 * // => ['barney', 'fred']
44121 *
44122 * // Create custom iteratee shorthands.
44123 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
44124 * return !_.isRegExp(func) ? iteratee(func) : function(string) {
44125 * return func.test(string);
44126 * };
44127 * });
44128 *
44129 * _.filter(['abc', 'def'], /ef/);
44130 * // => ['def']
44131 */
44132 function iteratee(func) {
44133 return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
44134 }
44135
44136 /**
44137 * Creates a function that performs a partial deep comparison between a given
44138 * object and `source`, returning `true` if the given object has equivalent
44139 * property values, else `false`.
44140 *
44141 * **Note:** The created function is equivalent to `_.isMatch` with `source`
44142 * partially applied.
44143 *
44144 * Partial comparisons will match empty array and empty object `source`
44145 * values against any array or object value, respectively. See `_.isEqual`
44146 * for a list of supported value comparisons.
44147 *
44148 * @static
44149 * @memberOf _
44150 * @since 3.0.0
44151 * @category Util
44152 * @param {Object} source The object of property values to match.
44153 * @returns {Function} Returns the new spec function.
44154 * @example
44155 *
44156 * var objects = [
44157 * { 'a': 1, 'b': 2, 'c': 3 },
44158 * { 'a': 4, 'b': 5, 'c': 6 }
44159 * ];
44160 *
44161 * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
44162 * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
44163 */
44164 function matches(source) {
44165 return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
44166 }
44167
44168 /**
44169 * Creates a function that performs a partial deep comparison between the
44170 * value at `path` of a given object to `srcValue`, returning `true` if the
44171 * object value is equivalent, else `false`.
44172 *
44173 * **Note:** Partial comparisons will match empty array and empty object
44174 * `srcValue` values against any array or object value, respectively. See
44175 * `_.isEqual` for a list of supported value comparisons.
44176 *
44177 * @static
44178 * @memberOf _
44179 * @since 3.2.0
44180 * @category Util
44181 * @param {Array|string} path The path of the property to get.
44182 * @param {*} srcValue The value to match.
44183 * @returns {Function} Returns the new spec function.
44184 * @example
44185 *
44186 * var objects = [
44187 * { 'a': 1, 'b': 2, 'c': 3 },
44188 * { 'a': 4, 'b': 5, 'c': 6 }
44189 * ];
44190 *
44191 * _.find(objects, _.matchesProperty('a', 4));
44192 * // => { 'a': 4, 'b': 5, 'c': 6 }
44193 */
44194 function matchesProperty(path, srcValue) {
44195 return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
44196 }
44197
44198 /**
44199 * Creates a function that invokes the method at `path` of a given object.
44200 * Any additional arguments are provided to the invoked method.
44201 *
44202 * @static
44203 * @memberOf _
44204 * @since 3.7.0
44205 * @category Util
44206 * @param {Array|string} path The path of the method to invoke.
44207 * @param {...*} [args] The arguments to invoke the method with.
44208 * @returns {Function} Returns the new invoker function.
44209 * @example
44210 *
44211 * var objects = [
44212 * { 'a': { 'b': _.constant(2) } },
44213 * { 'a': { 'b': _.constant(1) } }
44214 * ];
44215 *
44216 * _.map(objects, _.method('a.b'));
44217 * // => [2, 1]
44218 *
44219 * _.map(objects, _.method(['a', 'b']));
44220 * // => [2, 1]
44221 */
44222 var method = baseRest(function(path, args) {
44223 return function(object) {
44224 return baseInvoke(object, path, args);
44225 };
44226 });
44227
44228 /**
44229 * The opposite of `_.method`; this method creates a function that invokes
44230 * the method at a given path of `object`. Any additional arguments are
44231 * provided to the invoked method.
44232 *
44233 * @static
44234 * @memberOf _
44235 * @since 3.7.0
44236 * @category Util
44237 * @param {Object} object The object to query.
44238 * @param {...*} [args] The arguments to invoke the method with.
44239 * @returns {Function} Returns the new invoker function.
44240 * @example
44241 *
44242 * var array = _.times(3, _.constant),
44243 * object = { 'a': array, 'b': array, 'c': array };
44244 *
44245 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
44246 * // => [2, 0]
44247 *
44248 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
44249 * // => [2, 0]
44250 */
44251 var methodOf = baseRest(function(object, args) {
44252 return function(path) {
44253 return baseInvoke(object, path, args);
44254 };
44255 });
44256
44257 /**
44258 * Adds all own enumerable string keyed function properties of a source
44259 * object to the destination object. If `object` is a function, then methods
44260 * are added to its prototype as well.
44261 *
44262 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
44263 * avoid conflicts caused by modifying the original.
44264 *
44265 * @static
44266 * @since 0.1.0
44267 * @memberOf _
44268 * @category Util
44269 * @param {Function|Object} [object=lodash] The destination object.
44270 * @param {Object} source The object of functions to add.
44271 * @param {Object} [options={}] The options object.
44272 * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
44273 * @returns {Function|Object} Returns `object`.
44274 * @example
44275 *
44276 * function vowels(string) {
44277 * return _.filter(string, function(v) {
44278 * return /[aeiou]/i.test(v);
44279 * });
44280 * }
44281 *
44282 * _.mixin({ 'vowels': vowels });
44283 * _.vowels('fred');
44284 * // => ['e']
44285 *
44286 * _('fred').vowels().value();
44287 * // => ['e']
44288 *
44289 * _.mixin({ 'vowels': vowels }, { 'chain': false });
44290 * _('fred').vowels();
44291 * // => ['e']
44292 */
44293 function mixin(object, source, options) {
44294 var props = keys(source),
44295 methodNames = baseFunctions(source, props);
44296
44297 if (options == null &&
44298 !(isObject(source) && (methodNames.length || !props.length))) {
44299 options = source;
44300 source = object;
44301 object = this;
44302 methodNames = baseFunctions(source, keys(source));
44303 }
44304 var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
44305 isFunc = isFunction(object);
44306
44307 arrayEach(methodNames, function(methodName) {
44308 var func = source[methodName];
44309 object[methodName] = func;
44310 if (isFunc) {
44311 object.prototype[methodName] = function() {
44312 var chainAll = this.__chain__;
44313 if (chain || chainAll) {
44314 var result = object(this.__wrapped__),
44315 actions = result.__actions__ = copyArray(this.__actions__);
44316
44317 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
44318 result.__chain__ = chainAll;
44319 return result;
44320 }
44321 return func.apply(object, arrayPush([this.value()], arguments));
44322 };
44323 }
44324 });
44325
44326 return object;
44327 }
44328
44329 /**
44330 * Reverts the `_` variable to its previous value and returns a reference to
44331 * the `lodash` function.
44332 *
44333 * @static
44334 * @since 0.1.0
44335 * @memberOf _
44336 * @category Util
44337 * @returns {Function} Returns the `lodash` function.
44338 * @example
44339 *
44340 * var lodash = _.noConflict();
44341 */
44342 function noConflict() {
44343 if (root._ === this) {
44344 root._ = oldDash;
44345 }
44346 return this;
44347 }
44348
44349 /**
44350 * This method returns `undefined`.
44351 *
44352 * @static
44353 * @memberOf _
44354 * @since 2.3.0
44355 * @category Util
44356 * @example
44357 *
44358 * _.times(2, _.noop);
44359 * // => [undefined, undefined]
44360 */
44361 function noop() {
44362 // No operation performed.
44363 }
44364
44365 /**
44366 * Creates a function that gets the argument at index `n`. If `n` is negative,
44367 * the nth argument from the end is returned.
44368 *
44369 * @static
44370 * @memberOf _
44371 * @since 4.0.0
44372 * @category Util
44373 * @param {number} [n=0] The index of the argument to return.
44374 * @returns {Function} Returns the new pass-thru function.
44375 * @example
44376 *
44377 * var func = _.nthArg(1);
44378 * func('a', 'b', 'c', 'd');
44379 * // => 'b'
44380 *
44381 * var func = _.nthArg(-2);
44382 * func('a', 'b', 'c', 'd');
44383 * // => 'c'
44384 */
44385 function nthArg(n) {
44386 n = toInteger(n);
44387 return baseRest(function(args) {
44388 return baseNth(args, n);
44389 });
44390 }
44391
44392 /**
44393 * Creates a function that invokes `iteratees` with the arguments it receives
44394 * and returns their results.
44395 *
44396 * @static
44397 * @memberOf _
44398 * @since 4.0.0
44399 * @category Util
44400 * @param {...(Function|Function[])} [iteratees=[_.identity]]
44401 * The iteratees to invoke.
44402 * @returns {Function} Returns the new function.
44403 * @example
44404 *
44405 * var func = _.over([Math.max, Math.min]);
44406 *
44407 * func(1, 2, 3, 4);
44408 * // => [4, 1]
44409 */
44410 var over = createOver(arrayMap);
44411
44412 /**
44413 * Creates a function that checks if **all** of the `predicates` return
44414 * truthy when invoked with the arguments it receives.
44415 *
44416 * @static
44417 * @memberOf _
44418 * @since 4.0.0
44419 * @category Util
44420 * @param {...(Function|Function[])} [predicates=[_.identity]]
44421 * The predicates to check.
44422 * @returns {Function} Returns the new function.
44423 * @example
44424 *
44425 * var func = _.overEvery([Boolean, isFinite]);
44426 *
44427 * func('1');
44428 * // => true
44429 *
44430 * func(null);
44431 * // => false
44432 *
44433 * func(NaN);
44434 * // => false
44435 */
44436 var overEvery = createOver(arrayEvery);
44437
44438 /**
44439 * Creates a function that checks if **any** of the `predicates` return
44440 * truthy when invoked with the arguments it receives.
44441 *
44442 * @static
44443 * @memberOf _
44444 * @since 4.0.0
44445 * @category Util
44446 * @param {...(Function|Function[])} [predicates=[_.identity]]
44447 * The predicates to check.
44448 * @returns {Function} Returns the new function.
44449 * @example
44450 *
44451 * var func = _.overSome([Boolean, isFinite]);
44452 *
44453 * func('1');
44454 * // => true
44455 *
44456 * func(null);
44457 * // => true
44458 *
44459 * func(NaN);
44460 * // => false
44461 */
44462 var overSome = createOver(arraySome);
44463
44464 /**
44465 * Creates a function that returns the value at `path` of a given object.
44466 *
44467 * @static
44468 * @memberOf _
44469 * @since 2.4.0
44470 * @category Util
44471 * @param {Array|string} path The path of the property to get.
44472 * @returns {Function} Returns the new accessor function.
44473 * @example
44474 *
44475 * var objects = [
44476 * { 'a': { 'b': 2 } },
44477 * { 'a': { 'b': 1 } }
44478 * ];
44479 *
44480 * _.map(objects, _.property('a.b'));
44481 * // => [2, 1]
44482 *
44483 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
44484 * // => [1, 2]
44485 */
44486 function property(path) {
44487 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
44488 }
44489
44490 /**
44491 * The opposite of `_.property`; this method creates a function that returns
44492 * the value at a given path of `object`.
44493 *
44494 * @static
44495 * @memberOf _
44496 * @since 3.0.0
44497 * @category Util
44498 * @param {Object} object The object to query.
44499 * @returns {Function} Returns the new accessor function.
44500 * @example
44501 *
44502 * var array = [0, 1, 2],
44503 * object = { 'a': array, 'b': array, 'c': array };
44504 *
44505 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
44506 * // => [2, 0]
44507 *
44508 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
44509 * // => [2, 0]
44510 */
44511 function propertyOf(object) {
44512 return function(path) {
44513 return object == null ? undefined : baseGet(object, path);
44514 };
44515 }
44516
44517 /**
44518 * Creates an array of numbers (positive and/or negative) progressing from
44519 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
44520 * `start` is specified without an `end` or `step`. If `end` is not specified,
44521 * it's set to `start` with `start` then set to `0`.
44522 *
44523 * **Note:** JavaScript follows the IEEE-754 standard for resolving
44524 * floating-point values which can produce unexpected results.
44525 *
44526 * @static
44527 * @since 0.1.0
44528 * @memberOf _
44529 * @category Util
44530 * @param {number} [start=0] The start of the range.
44531 * @param {number} end The end of the range.
44532 * @param {number} [step=1] The value to increment or decrement by.
44533 * @returns {Array} Returns the range of numbers.
44534 * @see _.inRange, _.rangeRight
44535 * @example
44536 *
44537 * _.range(4);
44538 * // => [0, 1, 2, 3]
44539 *
44540 * _.range(-4);
44541 * // => [0, -1, -2, -3]
44542 *
44543 * _.range(1, 5);
44544 * // => [1, 2, 3, 4]
44545 *
44546 * _.range(0, 20, 5);
44547 * // => [0, 5, 10, 15]
44548 *
44549 * _.range(0, -4, -1);
44550 * // => [0, -1, -2, -3]
44551 *
44552 * _.range(1, 4, 0);
44553 * // => [1, 1, 1]
44554 *
44555 * _.range(0);
44556 * // => []
44557 */
44558 var range = createRange();
44559
44560 /**
44561 * This method is like `_.range` except that it populates values in
44562 * descending order.
44563 *
44564 * @static
44565 * @memberOf _
44566 * @since 4.0.0
44567 * @category Util
44568 * @param {number} [start=0] The start of the range.
44569 * @param {number} end The end of the range.
44570 * @param {number} [step=1] The value to increment or decrement by.
44571 * @returns {Array} Returns the range of numbers.
44572 * @see _.inRange, _.range
44573 * @example
44574 *
44575 * _.rangeRight(4);
44576 * // => [3, 2, 1, 0]
44577 *
44578 * _.rangeRight(-4);
44579 * // => [-3, -2, -1, 0]
44580 *
44581 * _.rangeRight(1, 5);
44582 * // => [4, 3, 2, 1]
44583 *
44584 * _.rangeRight(0, 20, 5);
44585 * // => [15, 10, 5, 0]
44586 *
44587 * _.rangeRight(0, -4, -1);
44588 * // => [-3, -2, -1, 0]
44589 *
44590 * _.rangeRight(1, 4, 0);
44591 * // => [1, 1, 1]
44592 *
44593 * _.rangeRight(0);
44594 * // => []
44595 */
44596 var rangeRight = createRange(true);
44597
44598 /**
44599 * This method returns a new empty array.
44600 *
44601 * @static
44602 * @memberOf _
44603 * @since 4.13.0
44604 * @category Util
44605 * @returns {Array} Returns the new empty array.
44606 * @example
44607 *
44608 * var arrays = _.times(2, _.stubArray);
44609 *
44610 * console.log(arrays);
44611 * // => [[], []]
44612 *
44613 * console.log(arrays[0] === arrays[1]);
44614 * // => false
44615 */
44616 function stubArray() {
44617 return [];
44618 }
44619
44620 /**
44621 * This method returns `false`.
44622 *
44623 * @static
44624 * @memberOf _
44625 * @since 4.13.0
44626 * @category Util
44627 * @returns {boolean} Returns `false`.
44628 * @example
44629 *
44630 * _.times(2, _.stubFalse);
44631 * // => [false, false]
44632 */
44633 function stubFalse() {
44634 return false;
44635 }
44636
44637 /**
44638 * This method returns a new empty object.
44639 *
44640 * @static
44641 * @memberOf _
44642 * @since 4.13.0
44643 * @category Util
44644 * @returns {Object} Returns the new empty object.
44645 * @example
44646 *
44647 * var objects = _.times(2, _.stubObject);
44648 *
44649 * console.log(objects);
44650 * // => [{}, {}]
44651 *
44652 * console.log(objects[0] === objects[1]);
44653 * // => false
44654 */
44655 function stubObject() {
44656 return {};
44657 }
44658
44659 /**
44660 * This method returns an empty string.
44661 *
44662 * @static
44663 * @memberOf _
44664 * @since 4.13.0
44665 * @category Util
44666 * @returns {string} Returns the empty string.
44667 * @example
44668 *
44669 * _.times(2, _.stubString);
44670 * // => ['', '']
44671 */
44672 function stubString() {
44673 return '';
44674 }
44675
44676 /**
44677 * This method returns `true`.
44678 *
44679 * @static
44680 * @memberOf _
44681 * @since 4.13.0
44682 * @category Util
44683 * @returns {boolean} Returns `true`.
44684 * @example
44685 *
44686 * _.times(2, _.stubTrue);
44687 * // => [true, true]
44688 */
44689 function stubTrue() {
44690 return true;
44691 }
44692
44693 /**
44694 * Invokes the iteratee `n` times, returning an array of the results of
44695 * each invocation. The iteratee is invoked with one argument; (index).
44696 *
44697 * @static
44698 * @since 0.1.0
44699 * @memberOf _
44700 * @category Util
44701 * @param {number} n The number of times to invoke `iteratee`.
44702 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
44703 * @returns {Array} Returns the array of results.
44704 * @example
44705 *
44706 * _.times(3, String);
44707 * // => ['0', '1', '2']
44708 *
44709 * _.times(4, _.constant(0));
44710 * // => [0, 0, 0, 0]
44711 */
44712 function times(n, iteratee) {
44713 n = toInteger(n);
44714 if (n < 1 || n > MAX_SAFE_INTEGER) {
44715 return [];
44716 }
44717 var index = MAX_ARRAY_LENGTH,
44718 length = nativeMin(n, MAX_ARRAY_LENGTH);
44719
44720 iteratee = getIteratee(iteratee);
44721 n -= MAX_ARRAY_LENGTH;
44722
44723 var result = baseTimes(length, iteratee);
44724 while (++index < n) {
44725 iteratee(index);
44726 }
44727 return result;
44728 }
44729
44730 /**
44731 * Converts `value` to a property path array.
44732 *
44733 * @static
44734 * @memberOf _
44735 * @since 4.0.0
44736 * @category Util
44737 * @param {*} value The value to convert.
44738 * @returns {Array} Returns the new property path array.
44739 * @example
44740 *
44741 * _.toPath('a.b.c');
44742 * // => ['a', 'b', 'c']
44743 *
44744 * _.toPath('a[0].b.c');
44745 * // => ['a', '0', 'b', 'c']
44746 */
44747 function toPath(value) {
44748 if (isArray(value)) {
44749 return arrayMap(value, toKey);
44750 }
44751 return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
44752 }
44753
44754 /**
44755 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
44756 *
44757 * @static
44758 * @since 0.1.0
44759 * @memberOf _
44760 * @category Util
44761 * @param {string} [prefix=''] The value to prefix the ID with.
44762 * @returns {string} Returns the unique ID.
44763 * @example
44764 *
44765 * _.uniqueId('contact_');
44766 * // => 'contact_104'
44767 *
44768 * _.uniqueId();
44769 * // => '105'
44770 */
44771 function uniqueId(prefix) {
44772 var id = ++idCounter;
44773 return toString(prefix) + id;
44774 }
44775
44776 /*------------------------------------------------------------------------*/
44777
44778 /**
44779 * Adds two numbers.
44780 *
44781 * @static
44782 * @memberOf _
44783 * @since 3.4.0
44784 * @category Math
44785 * @param {number} augend The first number in an addition.
44786 * @param {number} addend The second number in an addition.
44787 * @returns {number} Returns the total.
44788 * @example
44789 *
44790 * _.add(6, 4);
44791 * // => 10
44792 */
44793 var add = createMathOperation(function(augend, addend) {
44794 return augend + addend;
44795 }, 0);
44796
44797 /**
44798 * Computes `number` rounded up to `precision`.
44799 *
44800 * @static
44801 * @memberOf _
44802 * @since 3.10.0
44803 * @category Math
44804 * @param {number} number The number to round up.
44805 * @param {number} [precision=0] The precision to round up to.
44806 * @returns {number} Returns the rounded up number.
44807 * @example
44808 *
44809 * _.ceil(4.006);
44810 * // => 5
44811 *
44812 * _.ceil(6.004, 2);
44813 * // => 6.01
44814 *
44815 * _.ceil(6040, -2);
44816 * // => 6100
44817 */
44818 var ceil = createRound('ceil');
44819
44820 /**
44821 * Divide two numbers.
44822 *
44823 * @static
44824 * @memberOf _
44825 * @since 4.7.0
44826 * @category Math
44827 * @param {number} dividend The first number in a division.
44828 * @param {number} divisor The second number in a division.
44829 * @returns {number} Returns the quotient.
44830 * @example
44831 *
44832 * _.divide(6, 4);
44833 * // => 1.5
44834 */
44835 var divide = createMathOperation(function(dividend, divisor) {
44836 return dividend / divisor;
44837 }, 1);
44838
44839 /**
44840 * Computes `number` rounded down to `precision`.
44841 *
44842 * @static
44843 * @memberOf _
44844 * @since 3.10.0
44845 * @category Math
44846 * @param {number} number The number to round down.
44847 * @param {number} [precision=0] The precision to round down to.
44848 * @returns {number} Returns the rounded down number.
44849 * @example
44850 *
44851 * _.floor(4.006);
44852 * // => 4
44853 *
44854 * _.floor(0.046, 2);
44855 * // => 0.04
44856 *
44857 * _.floor(4060, -2);
44858 * // => 4000
44859 */
44860 var floor = createRound('floor');
44861
44862 /**
44863 * Computes the maximum value of `array`. If `array` is empty or falsey,
44864 * `undefined` is returned.
44865 *
44866 * @static
44867 * @since 0.1.0
44868 * @memberOf _
44869 * @category Math
44870 * @param {Array} array The array to iterate over.
44871 * @returns {*} Returns the maximum value.
44872 * @example
44873 *
44874 * _.max([4, 2, 8, 6]);
44875 * // => 8
44876 *
44877 * _.max([]);
44878 * // => undefined
44879 */
44880 function max(array) {
44881 return (array && array.length)
44882 ? baseExtremum(array, identity, baseGt)
44883 : undefined;
44884 }
44885
44886 /**
44887 * This method is like `_.max` except that it accepts `iteratee` which is
44888 * invoked for each element in `array` to generate the criterion by which
44889 * the value is ranked. The iteratee is invoked with one argument: (value).
44890 *
44891 * @static
44892 * @memberOf _
44893 * @since 4.0.0
44894 * @category Math
44895 * @param {Array} array The array to iterate over.
44896 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
44897 * @returns {*} Returns the maximum value.
44898 * @example
44899 *
44900 * var objects = [{ 'n': 1 }, { 'n': 2 }];
44901 *
44902 * _.maxBy(objects, function(o) { return o.n; });
44903 * // => { 'n': 2 }
44904 *
44905 * // The `_.property` iteratee shorthand.
44906 * _.maxBy(objects, 'n');
44907 * // => { 'n': 2 }
44908 */
44909 function maxBy(array, iteratee) {
44910 return (array && array.length)
44911 ? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
44912 : undefined;
44913 }
44914
44915 /**
44916 * Computes the mean of the values in `array`.
44917 *
44918 * @static
44919 * @memberOf _
44920 * @since 4.0.0
44921 * @category Math
44922 * @param {Array} array The array to iterate over.
44923 * @returns {number} Returns the mean.
44924 * @example
44925 *
44926 * _.mean([4, 2, 8, 6]);
44927 * // => 5
44928 */
44929 function mean(array) {
44930 return baseMean(array, identity);
44931 }
44932
44933 /**
44934 * This method is like `_.mean` except that it accepts `iteratee` which is
44935 * invoked for each element in `array` to generate the value to be averaged.
44936 * The iteratee is invoked with one argument: (value).
44937 *
44938 * @static
44939 * @memberOf _
44940 * @since 4.7.0
44941 * @category Math
44942 * @param {Array} array The array to iterate over.
44943 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
44944 * @returns {number} Returns the mean.
44945 * @example
44946 *
44947 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
44948 *
44949 * _.meanBy(objects, function(o) { return o.n; });
44950 * // => 5
44951 *
44952 * // The `_.property` iteratee shorthand.
44953 * _.meanBy(objects, 'n');
44954 * // => 5
44955 */
44956 function meanBy(array, iteratee) {
44957 return baseMean(array, getIteratee(iteratee, 2));
44958 }
44959
44960 /**
44961 * Computes the minimum value of `array`. If `array` is empty or falsey,
44962 * `undefined` is returned.
44963 *
44964 * @static
44965 * @since 0.1.0
44966 * @memberOf _
44967 * @category Math
44968 * @param {Array} array The array to iterate over.
44969 * @returns {*} Returns the minimum value.
44970 * @example
44971 *
44972 * _.min([4, 2, 8, 6]);
44973 * // => 2
44974 *
44975 * _.min([]);
44976 * // => undefined
44977 */
44978 function min(array) {
44979 return (array && array.length)
44980 ? baseExtremum(array, identity, baseLt)
44981 : undefined;
44982 }
44983
44984 /**
44985 * This method is like `_.min` except that it accepts `iteratee` which is
44986 * invoked for each element in `array` to generate the criterion by which
44987 * the value is ranked. The iteratee is invoked with one argument: (value).
44988 *
44989 * @static
44990 * @memberOf _
44991 * @since 4.0.0
44992 * @category Math
44993 * @param {Array} array The array to iterate over.
44994 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
44995 * @returns {*} Returns the minimum value.
44996 * @example
44997 *
44998 * var objects = [{ 'n': 1 }, { 'n': 2 }];
44999 *
45000 * _.minBy(objects, function(o) { return o.n; });
45001 * // => { 'n': 1 }
45002 *
45003 * // The `_.property` iteratee shorthand.
45004 * _.minBy(objects, 'n');
45005 * // => { 'n': 1 }
45006 */
45007 function minBy(array, iteratee) {
45008 return (array && array.length)
45009 ? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
45010 : undefined;
45011 }
45012
45013 /**
45014 * Multiply two numbers.
45015 *
45016 * @static
45017 * @memberOf _
45018 * @since 4.7.0
45019 * @category Math
45020 * @param {number} multiplier The first number in a multiplication.
45021 * @param {number} multiplicand The second number in a multiplication.
45022 * @returns {number} Returns the product.
45023 * @example
45024 *
45025 * _.multiply(6, 4);
45026 * // => 24
45027 */
45028 var multiply = createMathOperation(function(multiplier, multiplicand) {
45029 return multiplier * multiplicand;
45030 }, 1);
45031
45032 /**
45033 * Computes `number` rounded to `precision`.
45034 *
45035 * @static
45036 * @memberOf _
45037 * @since 3.10.0
45038 * @category Math
45039 * @param {number} number The number to round.
45040 * @param {number} [precision=0] The precision to round to.
45041 * @returns {number} Returns the rounded number.
45042 * @example
45043 *
45044 * _.round(4.006);
45045 * // => 4
45046 *
45047 * _.round(4.006, 2);
45048 * // => 4.01
45049 *
45050 * _.round(4060, -2);
45051 * // => 4100
45052 */
45053 var round = createRound('round');
45054
45055 /**
45056 * Subtract two numbers.
45057 *
45058 * @static
45059 * @memberOf _
45060 * @since 4.0.0
45061 * @category Math
45062 * @param {number} minuend The first number in a subtraction.
45063 * @param {number} subtrahend The second number in a subtraction.
45064 * @returns {number} Returns the difference.
45065 * @example
45066 *
45067 * _.subtract(6, 4);
45068 * // => 2
45069 */
45070 var subtract = createMathOperation(function(minuend, subtrahend) {
45071 return minuend - subtrahend;
45072 }, 0);
45073
45074 /**
45075 * Computes the sum of the values in `array`.
45076 *
45077 * @static
45078 * @memberOf _
45079 * @since 3.4.0
45080 * @category Math
45081 * @param {Array} array The array to iterate over.
45082 * @returns {number} Returns the sum.
45083 * @example
45084 *
45085 * _.sum([4, 2, 8, 6]);
45086 * // => 20
45087 */
45088 function sum(array) {
45089 return (array && array.length)
45090 ? baseSum(array, identity)
45091 : 0;
45092 }
45093
45094 /**
45095 * This method is like `_.sum` except that it accepts `iteratee` which is
45096 * invoked for each element in `array` to generate the value to be summed.
45097 * The iteratee is invoked with one argument: (value).
45098 *
45099 * @static
45100 * @memberOf _
45101 * @since 4.0.0
45102 * @category Math
45103 * @param {Array} array The array to iterate over.
45104 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
45105 * @returns {number} Returns the sum.
45106 * @example
45107 *
45108 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
45109 *
45110 * _.sumBy(objects, function(o) { return o.n; });
45111 * // => 20
45112 *
45113 * // The `_.property` iteratee shorthand.
45114 * _.sumBy(objects, 'n');
45115 * // => 20
45116 */
45117 function sumBy(array, iteratee) {
45118 return (array && array.length)
45119 ? baseSum(array, getIteratee(iteratee, 2))
45120 : 0;
45121 }
45122
45123 /*------------------------------------------------------------------------*/
45124
45125 // Add methods that return wrapped values in chain sequences.
45126 lodash.after = after;
45127 lodash.ary = ary;
45128 lodash.assign = assign;
45129 lodash.assignIn = assignIn;
45130 lodash.assignInWith = assignInWith;
45131 lodash.assignWith = assignWith;
45132 lodash.at = at;
45133 lodash.before = before;
45134 lodash.bind = bind;
45135 lodash.bindAll = bindAll;
45136 lodash.bindKey = bindKey;
45137 lodash.castArray = castArray;
45138 lodash.chain = chain;
45139 lodash.chunk = chunk;
45140 lodash.compact = compact;
45141 lodash.concat = concat;
45142 lodash.cond = cond;
45143 lodash.conforms = conforms;
45144 lodash.constant = constant;
45145 lodash.countBy = countBy;
45146 lodash.create = create;
45147 lodash.curry = curry;
45148 lodash.curryRight = curryRight;
45149 lodash.debounce = debounce;
45150 lodash.defaults = defaults;
45151 lodash.defaultsDeep = defaultsDeep;
45152 lodash.defer = defer;
45153 lodash.delay = delay;
45154 lodash.difference = difference;
45155 lodash.differenceBy = differenceBy;
45156 lodash.differenceWith = differenceWith;
45157 lodash.drop = drop;
45158 lodash.dropRight = dropRight;
45159 lodash.dropRightWhile = dropRightWhile;
45160 lodash.dropWhile = dropWhile;
45161 lodash.fill = fill;
45162 lodash.filter = filter;
45163 lodash.flatMap = flatMap;
45164 lodash.flatMapDeep = flatMapDeep;
45165 lodash.flatMapDepth = flatMapDepth;
45166 lodash.flatten = flatten;
45167 lodash.flattenDeep = flattenDeep;
45168 lodash.flattenDepth = flattenDepth;
45169 lodash.flip = flip;
45170 lodash.flow = flow;
45171 lodash.flowRight = flowRight;
45172 lodash.fromPairs = fromPairs;
45173 lodash.functions = functions;
45174 lodash.functionsIn = functionsIn;
45175 lodash.groupBy = groupBy;
45176 lodash.initial = initial;
45177 lodash.intersection = intersection;
45178 lodash.intersectionBy = intersectionBy;
45179 lodash.intersectionWith = intersectionWith;
45180 lodash.invert = invert;
45181 lodash.invertBy = invertBy;
45182 lodash.invokeMap = invokeMap;
45183 lodash.iteratee = iteratee;
45184 lodash.keyBy = keyBy;
45185 lodash.keys = keys;
45186 lodash.keysIn = keysIn;
45187 lodash.map = map;
45188 lodash.mapKeys = mapKeys;
45189 lodash.mapValues = mapValues;
45190 lodash.matches = matches;
45191 lodash.matchesProperty = matchesProperty;
45192 lodash.memoize = memoize;
45193 lodash.merge = merge;
45194 lodash.mergeWith = mergeWith;
45195 lodash.method = method;
45196 lodash.methodOf = methodOf;
45197 lodash.mixin = mixin;
45198 lodash.negate = negate;
45199 lodash.nthArg = nthArg;
45200 lodash.omit = omit;
45201 lodash.omitBy = omitBy;
45202 lodash.once = once;
45203 lodash.orderBy = orderBy;
45204 lodash.over = over;
45205 lodash.overArgs = overArgs;
45206 lodash.overEvery = overEvery;
45207 lodash.overSome = overSome;
45208 lodash.partial = partial;
45209 lodash.partialRight = partialRight;
45210 lodash.partition = partition;
45211 lodash.pick = pick;
45212 lodash.pickBy = pickBy;
45213 lodash.property = property;
45214 lodash.propertyOf = propertyOf;
45215 lodash.pull = pull;
45216 lodash.pullAll = pullAll;
45217 lodash.pullAllBy = pullAllBy;
45218 lodash.pullAllWith = pullAllWith;
45219 lodash.pullAt = pullAt;
45220 lodash.range = range;
45221 lodash.rangeRight = rangeRight;
45222 lodash.rearg = rearg;
45223 lodash.reject = reject;
45224 lodash.remove = remove;
45225 lodash.rest = rest;
45226 lodash.reverse = reverse;
45227 lodash.sampleSize = sampleSize;
45228 lodash.set = set;
45229 lodash.setWith = setWith;
45230 lodash.shuffle = shuffle;
45231 lodash.slice = slice;
45232 lodash.sortBy = sortBy;
45233 lodash.sortedUniq = sortedUniq;
45234 lodash.sortedUniqBy = sortedUniqBy;
45235 lodash.split = split;
45236 lodash.spread = spread;
45237 lodash.tail = tail;
45238 lodash.take = take;
45239 lodash.takeRight = takeRight;
45240 lodash.takeRightWhile = takeRightWhile;
45241 lodash.takeWhile = takeWhile;
45242 lodash.tap = tap;
45243 lodash.throttle = throttle;
45244 lodash.thru = thru;
45245 lodash.toArray = toArray;
45246 lodash.toPairs = toPairs;
45247 lodash.toPairsIn = toPairsIn;
45248 lodash.toPath = toPath;
45249 lodash.toPlainObject = toPlainObject;
45250 lodash.transform = transform;
45251 lodash.unary = unary;
45252 lodash.union = union;
45253 lodash.unionBy = unionBy;
45254 lodash.unionWith = unionWith;
45255 lodash.uniq = uniq;
45256 lodash.uniqBy = uniqBy;
45257 lodash.uniqWith = uniqWith;
45258 lodash.unset = unset;
45259 lodash.unzip = unzip;
45260 lodash.unzipWith = unzipWith;
45261 lodash.update = update;
45262 lodash.updateWith = updateWith;
45263 lodash.values = values;
45264 lodash.valuesIn = valuesIn;
45265 lodash.without = without;
45266 lodash.words = words;
45267 lodash.wrap = wrap;
45268 lodash.xor = xor;
45269 lodash.xorBy = xorBy;
45270 lodash.xorWith = xorWith;
45271 lodash.zip = zip;
45272 lodash.zipObject = zipObject;
45273 lodash.zipObjectDeep = zipObjectDeep;
45274 lodash.zipWith = zipWith;
45275
45276 // Add aliases.
45277 lodash.entries = toPairs;
45278 lodash.entriesIn = toPairsIn;
45279 lodash.extend = assignIn;
45280 lodash.extendWith = assignInWith;
45281
45282 // Add methods to `lodash.prototype`.
45283 mixin(lodash, lodash);
45284
45285 /*------------------------------------------------------------------------*/
45286
45287 // Add methods that return unwrapped values in chain sequences.
45288 lodash.add = add;
45289 lodash.attempt = attempt;
45290 lodash.camelCase = camelCase;
45291 lodash.capitalize = capitalize;
45292 lodash.ceil = ceil;
45293 lodash.clamp = clamp;
45294 lodash.clone = clone;
45295 lodash.cloneDeep = cloneDeep;
45296 lodash.cloneDeepWith = cloneDeepWith;
45297 lodash.cloneWith = cloneWith;
45298 lodash.conformsTo = conformsTo;
45299 lodash.deburr = deburr;
45300 lodash.defaultTo = defaultTo;
45301 lodash.divide = divide;
45302 lodash.endsWith = endsWith;
45303 lodash.eq = eq;
45304 lodash.escape = escape;
45305 lodash.escapeRegExp = escapeRegExp;
45306 lodash.every = every;
45307 lodash.find = find;
45308 lodash.findIndex = findIndex;
45309 lodash.findKey = findKey;
45310 lodash.findLast = findLast;
45311 lodash.findLastIndex = findLastIndex;
45312 lodash.findLastKey = findLastKey;
45313 lodash.floor = floor;
45314 lodash.forEach = forEach;
45315 lodash.forEachRight = forEachRight;
45316 lodash.forIn = forIn;
45317 lodash.forInRight = forInRight;
45318 lodash.forOwn = forOwn;
45319 lodash.forOwnRight = forOwnRight;
45320 lodash.get = get;
45321 lodash.gt = gt;
45322 lodash.gte = gte;
45323 lodash.has = has;
45324 lodash.hasIn = hasIn;
45325 lodash.head = head;
45326 lodash.identity = identity;
45327 lodash.includes = includes;
45328 lodash.indexOf = indexOf;
45329 lodash.inRange = inRange;
45330 lodash.invoke = invoke;
45331 lodash.isArguments = isArguments;
45332 lodash.isArray = isArray;
45333 lodash.isArrayBuffer = isArrayBuffer;
45334 lodash.isArrayLike = isArrayLike;
45335 lodash.isArrayLikeObject = isArrayLikeObject;
45336 lodash.isBoolean = isBoolean;
45337 lodash.isBuffer = isBuffer;
45338 lodash.isDate = isDate;
45339 lodash.isElement = isElement;
45340 lodash.isEmpty = isEmpty;
45341 lodash.isEqual = isEqual;
45342 lodash.isEqualWith = isEqualWith;
45343 lodash.isError = isError;
45344 lodash.isFinite = isFinite;
45345 lodash.isFunction = isFunction;
45346 lodash.isInteger = isInteger;
45347 lodash.isLength = isLength;
45348 lodash.isMap = isMap;
45349 lodash.isMatch = isMatch;
45350 lodash.isMatchWith = isMatchWith;
45351 lodash.isNaN = isNaN;
45352 lodash.isNative = isNative;
45353 lodash.isNil = isNil;
45354 lodash.isNull = isNull;
45355 lodash.isNumber = isNumber;
45356 lodash.isObject = isObject;
45357 lodash.isObjectLike = isObjectLike;
45358 lodash.isPlainObject = isPlainObject;
45359 lodash.isRegExp = isRegExp;
45360 lodash.isSafeInteger = isSafeInteger;
45361 lodash.isSet = isSet;
45362 lodash.isString = isString;
45363 lodash.isSymbol = isSymbol;
45364 lodash.isTypedArray = isTypedArray;
45365 lodash.isUndefined = isUndefined;
45366 lodash.isWeakMap = isWeakMap;
45367 lodash.isWeakSet = isWeakSet;
45368 lodash.join = join;
45369 lodash.kebabCase = kebabCase;
45370 lodash.last = last;
45371 lodash.lastIndexOf = lastIndexOf;
45372 lodash.lowerCase = lowerCase;
45373 lodash.lowerFirst = lowerFirst;
45374 lodash.lt = lt;
45375 lodash.lte = lte;
45376 lodash.max = max;
45377 lodash.maxBy = maxBy;
45378 lodash.mean = mean;
45379 lodash.meanBy = meanBy;
45380 lodash.min = min;
45381 lodash.minBy = minBy;
45382 lodash.stubArray = stubArray;
45383 lodash.stubFalse = stubFalse;
45384 lodash.stubObject = stubObject;
45385 lodash.stubString = stubString;
45386 lodash.stubTrue = stubTrue;
45387 lodash.multiply = multiply;
45388 lodash.nth = nth;
45389 lodash.noConflict = noConflict;
45390 lodash.noop = noop;
45391 lodash.now = now;
45392 lodash.pad = pad;
45393 lodash.padEnd = padEnd;
45394 lodash.padStart = padStart;
45395 lodash.parseInt = parseInt;
45396 lodash.random = random;
45397 lodash.reduce = reduce;
45398 lodash.reduceRight = reduceRight;
45399 lodash.repeat = repeat;
45400 lodash.replace = replace;
45401 lodash.result = result;
45402 lodash.round = round;
45403 lodash.runInContext = runInContext;
45404 lodash.sample = sample;
45405 lodash.size = size;
45406 lodash.snakeCase = snakeCase;
45407 lodash.some = some;
45408 lodash.sortedIndex = sortedIndex;
45409 lodash.sortedIndexBy = sortedIndexBy;
45410 lodash.sortedIndexOf = sortedIndexOf;
45411 lodash.sortedLastIndex = sortedLastIndex;
45412 lodash.sortedLastIndexBy = sortedLastIndexBy;
45413 lodash.sortedLastIndexOf = sortedLastIndexOf;
45414 lodash.startCase = startCase;
45415 lodash.startsWith = startsWith;
45416 lodash.subtract = subtract;
45417 lodash.sum = sum;
45418 lodash.sumBy = sumBy;
45419 lodash.template = template;
45420 lodash.times = times;
45421 lodash.toFinite = toFinite;
45422 lodash.toInteger = toInteger;
45423 lodash.toLength = toLength;
45424 lodash.toLower = toLower;
45425 lodash.toNumber = toNumber;
45426 lodash.toSafeInteger = toSafeInteger;
45427 lodash.toString = toString;
45428 lodash.toUpper = toUpper;
45429 lodash.trim = trim;
45430 lodash.trimEnd = trimEnd;
45431 lodash.trimStart = trimStart;
45432 lodash.truncate = truncate;
45433 lodash.unescape = unescape;
45434 lodash.uniqueId = uniqueId;
45435 lodash.upperCase = upperCase;
45436 lodash.upperFirst = upperFirst;
45437
45438 // Add aliases.
45439 lodash.each = forEach;
45440 lodash.eachRight = forEachRight;
45441 lodash.first = head;
45442
45443 mixin(lodash, (function() {
45444 var source = {};
45445 baseForOwn(lodash, function(func, methodName) {
45446 if (!hasOwnProperty.call(lodash.prototype, methodName)) {
45447 source[methodName] = func;
45448 }
45449 });
45450 return source;
45451 }()), { 'chain': false });
45452
45453 /*------------------------------------------------------------------------*/
45454
45455 /**
45456 * The semantic version number.
45457 *
45458 * @static
45459 * @memberOf _
45460 * @type {string}
45461 */
45462 lodash.VERSION = VERSION;
45463
45464 // Assign default placeholders.
45465 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
45466 lodash[methodName].placeholder = lodash;
45467 });
45468
45469 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
45470 arrayEach(['drop', 'take'], function(methodName, index) {
45471 LazyWrapper.prototype[methodName] = function(n) {
45472 n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
45473
45474 var result = (this.__filtered__ && !index)
45475 ? new LazyWrapper(this)
45476 : this.clone();
45477
45478 if (result.__filtered__) {
45479 result.__takeCount__ = nativeMin(n, result.__takeCount__);
45480 } else {
45481 result.__views__.push({
45482 'size': nativeMin(n, MAX_ARRAY_LENGTH),
45483 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
45484 });
45485 }
45486 return result;
45487 };
45488
45489 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
45490 return this.reverse()[methodName](n).reverse();
45491 };
45492 });
45493
45494 // Add `LazyWrapper` methods that accept an `iteratee` value.
45495 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
45496 var type = index + 1,
45497 isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
45498
45499 LazyWrapper.prototype[methodName] = function(iteratee) {
45500 var result = this.clone();
45501 result.__iteratees__.push({
45502 'iteratee': getIteratee(iteratee, 3),
45503 'type': type
45504 });
45505 result.__filtered__ = result.__filtered__ || isFilter;
45506 return result;
45507 };
45508 });
45509
45510 // Add `LazyWrapper` methods for `_.head` and `_.last`.
45511 arrayEach(['head', 'last'], function(methodName, index) {
45512 var takeName = 'take' + (index ? 'Right' : '');
45513
45514 LazyWrapper.prototype[methodName] = function() {
45515 return this[takeName](1).value()[0];
45516 };
45517 });
45518
45519 // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
45520 arrayEach(['initial', 'tail'], function(methodName, index) {
45521 var dropName = 'drop' + (index ? '' : 'Right');
45522
45523 LazyWrapper.prototype[methodName] = function() {
45524 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
45525 };
45526 });
45527
45528 LazyWrapper.prototype.compact = function() {
45529 return this.filter(identity);
45530 };
45531
45532 LazyWrapper.prototype.find = function(predicate) {
45533 return this.filter(predicate).head();
45534 };
45535
45536 LazyWrapper.prototype.findLast = function(predicate) {
45537 return this.reverse().find(predicate);
45538 };
45539
45540 LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
45541 if (typeof path == 'function') {
45542 return new LazyWrapper(this);
45543 }
45544 return this.map(function(value) {
45545 return baseInvoke(value, path, args);
45546 });
45547 });
45548
45549 LazyWrapper.prototype.reject = function(predicate) {
45550 return this.filter(negate(getIteratee(predicate)));
45551 };
45552
45553 LazyWrapper.prototype.slice = function(start, end) {
45554 start = toInteger(start);
45555
45556 var result = this;
45557 if (result.__filtered__ && (start > 0 || end < 0)) {
45558 return new LazyWrapper(result);
45559 }
45560 if (start < 0) {
45561 result = result.takeRight(-start);
45562 } else if (start) {
45563 result = result.drop(start);
45564 }
45565 if (end !== undefined) {
45566 end = toInteger(end);
45567 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
45568 }
45569 return result;
45570 };
45571
45572 LazyWrapper.prototype.takeRightWhile = function(predicate) {
45573 return this.reverse().takeWhile(predicate).reverse();
45574 };
45575
45576 LazyWrapper.prototype.toArray = function() {
45577 return this.take(MAX_ARRAY_LENGTH);
45578 };
45579
45580 // Add `LazyWrapper` methods to `lodash.prototype`.
45581 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
45582 var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
45583 isTaker = /^(?:head|last)$/.test(methodName),
45584 lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
45585 retUnwrapped = isTaker || /^find/.test(methodName);
45586
45587 if (!lodashFunc) {
45588 return;
45589 }
45590 lodash.prototype[methodName] = function() {
45591 var value = this.__wrapped__,
45592 args = isTaker ? [1] : arguments,
45593 isLazy = value instanceof LazyWrapper,
45594 iteratee = args[0],
45595 useLazy = isLazy || isArray(value);
45596
45597 var interceptor = function(value) {
45598 var result = lodashFunc.apply(lodash, arrayPush([value], args));
45599 return (isTaker && chainAll) ? result[0] : result;
45600 };
45601
45602 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
45603 // Avoid lazy use if the iteratee has a "length" value other than `1`.
45604 isLazy = useLazy = false;
45605 }
45606 var chainAll = this.__chain__,
45607 isHybrid = !!this.__actions__.length,
45608 isUnwrapped = retUnwrapped && !chainAll,
45609 onlyLazy = isLazy && !isHybrid;
45610
45611 if (!retUnwrapped && useLazy) {
45612 value = onlyLazy ? value : new LazyWrapper(this);
45613 var result = func.apply(value, args);
45614 result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
45615 return new LodashWrapper(result, chainAll);
45616 }
45617 if (isUnwrapped && onlyLazy) {
45618 return func.apply(this, args);
45619 }
45620 result = this.thru(interceptor);
45621 return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
45622 };
45623 });
45624
45625 // Add `Array` methods to `lodash.prototype`.
45626 arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
45627 var func = arrayProto[methodName],
45628 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
45629 retUnwrapped = /^(?:pop|shift)$/.test(methodName);
45630
45631 lodash.prototype[methodName] = function() {
45632 var args = arguments;
45633 if (retUnwrapped && !this.__chain__) {
45634 var value = this.value();
45635 return func.apply(isArray(value) ? value : [], args);
45636 }
45637 return this[chainName](function(value) {
45638 return func.apply(isArray(value) ? value : [], args);
45639 });
45640 };
45641 });
45642
45643 // Map minified method names to their real names.
45644 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
45645 var lodashFunc = lodash[methodName];
45646 if (lodashFunc) {
45647 var key = lodashFunc.name + '';
45648 if (!hasOwnProperty.call(realNames, key)) {
45649 realNames[key] = [];
45650 }
45651 realNames[key].push({ 'name': methodName, 'func': lodashFunc });
45652 }
45653 });
45654
45655 realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
45656 'name': 'wrapper',
45657 'func': undefined
45658 }];
45659
45660 // Add methods to `LazyWrapper`.
45661 LazyWrapper.prototype.clone = lazyClone;
45662 LazyWrapper.prototype.reverse = lazyReverse;
45663 LazyWrapper.prototype.value = lazyValue;
45664
45665 // Add chain sequence methods to the `lodash` wrapper.
45666 lodash.prototype.at = wrapperAt;
45667 lodash.prototype.chain = wrapperChain;
45668 lodash.prototype.commit = wrapperCommit;
45669 lodash.prototype.next = wrapperNext;
45670 lodash.prototype.plant = wrapperPlant;
45671 lodash.prototype.reverse = wrapperReverse;
45672 lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
45673
45674 // Add lazy aliases.
45675 lodash.prototype.first = lodash.prototype.head;
45676
45677 if (symIterator) {
45678 lodash.prototype[symIterator] = wrapperToIterator;
45679 }
45680 return lodash;
45681 });
45682
45683 /*--------------------------------------------------------------------------*/
45684
45685 // Export lodash.
45686 var _ = runInContext();
45687
45688 // Some AMD build optimizers, like r.js, check for condition patterns like:
45689 if (true) {
45690 // Expose Lodash on the global object to prevent errors when Lodash is
45691 // loaded by a script tag in the presence of an AMD loader.
45692 // See http://requirejs.org/docs/errors.html#mismatch for more details.
45693 // Use `_.noConflict` to remove Lodash from the global object.
45694 root._ = _;
45695
45696 // Define as an anonymous module so, through path mapping, it can be
45697 // referenced as the "underscore" module.
45698 !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
45699 return _;
45700 }).call(exports, __webpack_require__, exports, module),
45701 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
45702 }
45703 // Check for `exports` after `define` in case a build optimizer adds it.
45704 else {}
45705}.call(this));
45706
45707/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(404)(module)))
45708
45709/***/ }),
45710/* 404 */
45711/***/ (function(module, exports) {
45712
45713module.exports = function (module) {
45714 if (!module.webpackPolyfill) {
45715 module.deprecate = function () {};
45716
45717 module.paths = []; // module.parent = undefined by default
45718
45719 if (!module.children) module.children = [];
45720 Object.defineProperty(module, "loaded", {
45721 enumerable: true,
45722 get: function get() {
45723 return module.l;
45724 }
45725 });
45726 Object.defineProperty(module, "id", {
45727 enumerable: true,
45728 get: function get() {
45729 return module.i;
45730 }
45731 });
45732 module.webpackPolyfill = 1;
45733 }
45734
45735 return module;
45736};
45737
45738/***/ }),
45739/* 405 */
45740/***/ (function(module, exports, __webpack_require__) {
45741
45742"use strict";
45743/**
45744 * @fileoverview Defines environment settings and globals.
45745 * @author Elan Shanker
45746 */
45747 //------------------------------------------------------------------------------
45748// Requirements
45749//------------------------------------------------------------------------------
45750
45751function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
45752
45753function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
45754
45755function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
45756
45757const globals = __webpack_require__(406); //------------------------------------------------------------------------------
45758// Helpers
45759//------------------------------------------------------------------------------
45760
45761/**
45762 * Get the object that has difference.
45763 * @param {Record<string,boolean>} current The newer object.
45764 * @param {Record<string,boolean>} prev The older object.
45765 * @returns {Record<string,boolean>} The difference object.
45766 */
45767
45768
45769function getDiff(current, prev) {
45770 const retv = {};
45771
45772 for (const [key, value] of Object.entries(current)) {
45773 if (!Object.hasOwnProperty.call(prev, key)) {
45774 retv[key] = value;
45775 }
45776 }
45777
45778 return retv;
45779}
45780
45781const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
45782
45783const newGlobals2017 = {
45784 Atomics: false,
45785 SharedArrayBuffer: false
45786};
45787const newGlobals2020 = {
45788 BigInt: false,
45789 BigInt64Array: false,
45790 BigUint64Array: false,
45791 globalThis: false
45792}; //------------------------------------------------------------------------------
45793// Public Interface
45794//------------------------------------------------------------------------------
45795
45796/** @type {Map<string, import("../lib/shared/types").Environment>} */
45797
45798module.exports = new Map(Object.entries({
45799 // Language
45800 builtin: {
45801 globals: globals.es5
45802 },
45803 es6: {
45804 globals: newGlobals2015,
45805 parserOptions: {
45806 ecmaVersion: 6
45807 }
45808 },
45809 es2015: {
45810 globals: newGlobals2015,
45811 parserOptions: {
45812 ecmaVersion: 6
45813 }
45814 },
45815 es2017: {
56c4a2cb 45816 globals: _objectSpread(_objectSpread({}, newGlobals2015), newGlobals2017),
eb39fafa
DC
45817 parserOptions: {
45818 ecmaVersion: 8
45819 }
45820 },
45821 es2020: {
56c4a2cb 45822 globals: _objectSpread(_objectSpread(_objectSpread({}, newGlobals2015), newGlobals2017), newGlobals2020),
eb39fafa
DC
45823 parserOptions: {
45824 ecmaVersion: 11
45825 }
45826 },
45827 // Platforms
45828 browser: {
45829 globals: globals.browser
45830 },
45831 node: {
45832 globals: globals.node,
45833 parserOptions: {
45834 ecmaFeatures: {
45835 globalReturn: true
45836 }
45837 }
45838 },
45839 "shared-node-browser": {
45840 globals: globals["shared-node-browser"]
45841 },
45842 worker: {
45843 globals: globals.worker
45844 },
45845 serviceworker: {
45846 globals: globals.serviceworker
45847 },
45848 // Frameworks
45849 commonjs: {
45850 globals: globals.commonjs,
45851 parserOptions: {
45852 ecmaFeatures: {
45853 globalReturn: true
45854 }
45855 }
45856 },
45857 amd: {
45858 globals: globals.amd
45859 },
45860 mocha: {
45861 globals: globals.mocha
45862 },
45863 jasmine: {
45864 globals: globals.jasmine
45865 },
45866 jest: {
45867 globals: globals.jest
45868 },
45869 phantomjs: {
45870 globals: globals.phantomjs
45871 },
45872 jquery: {
45873 globals: globals.jquery
45874 },
45875 qunit: {
45876 globals: globals.qunit
45877 },
45878 prototypejs: {
45879 globals: globals.prototypejs
45880 },
45881 shelljs: {
45882 globals: globals.shelljs
45883 },
45884 meteor: {
45885 globals: globals.meteor
45886 },
45887 mongo: {
45888 globals: globals.mongo
45889 },
45890 protractor: {
45891 globals: globals.protractor
45892 },
45893 applescript: {
45894 globals: globals.applescript
45895 },
45896 nashorn: {
45897 globals: globals.nashorn
45898 },
45899 atomtest: {
45900 globals: globals.atomtest
45901 },
45902 embertest: {
45903 globals: globals.embertest
45904 },
45905 webextensions: {
45906 globals: globals.webextensions
45907 },
45908 greasemonkey: {
45909 globals: globals.greasemonkey
45910 }
45911}));
45912
45913/***/ }),
45914/* 406 */
45915/***/ (function(module, exports, __webpack_require__) {
45916
45917"use strict";
45918
45919
45920module.exports = __webpack_require__(407);
45921
45922/***/ }),
45923/* 407 */
45924/***/ (function(module) {
45925
45926module.exports = JSON.parse("{\"builtin\":{\"Array\":false,\"ArrayBuffer\":false,\"Atomics\":false,\"BigInt\":false,\"BigInt64Array\":false,\"BigUint64Array\":false,\"Boolean\":false,\"constructor\":false,\"DataView\":false,\"Date\":false,\"decodeURI\":false,\"decodeURIComponent\":false,\"encodeURI\":false,\"encodeURIComponent\":false,\"Error\":false,\"escape\":false,\"eval\":false,\"EvalError\":false,\"Float32Array\":false,\"Float64Array\":false,\"Function\":false,\"globalThis\":false,\"hasOwnProperty\":false,\"Infinity\":false,\"Int16Array\":false,\"Int32Array\":false,\"Int8Array\":false,\"isFinite\":false,\"isNaN\":false,\"isPrototypeOf\":false,\"JSON\":false,\"Map\":false,\"Math\":false,\"NaN\":false,\"Number\":false,\"Object\":false,\"parseFloat\":false,\"parseInt\":false,\"Promise\":false,\"propertyIsEnumerable\":false,\"Proxy\":false,\"RangeError\":false,\"ReferenceError\":false,\"Reflect\":false,\"RegExp\":false,\"Set\":false,\"SharedArrayBuffer\":false,\"String\":false,\"Symbol\":false,\"SyntaxError\":false,\"toLocaleString\":false,\"toString\":false,\"TypeError\":false,\"Uint16Array\":false,\"Uint32Array\":false,\"Uint8Array\":false,\"Uint8ClampedArray\":false,\"undefined\":false,\"unescape\":false,\"URIError\":false,\"valueOf\":false,\"WeakMap\":false,\"WeakSet\":false},\"es5\":{\"Array\":false,\"Boolean\":false,\"constructor\":false,\"Date\":false,\"decodeURI\":false,\"decodeURIComponent\":false,\"encodeURI\":false,\"encodeURIComponent\":false,\"Error\":false,\"escape\":false,\"eval\":false,\"EvalError\":false,\"Function\":false,\"hasOwnProperty\":false,\"Infinity\":false,\"isFinite\":false,\"isNaN\":false,\"isPrototypeOf\":false,\"JSON\":false,\"Math\":false,\"NaN\":false,\"Number\":false,\"Object\":false,\"parseFloat\":false,\"parseInt\":false,\"propertyIsEnumerable\":false,\"RangeError\":false,\"ReferenceError\":false,\"RegExp\":false,\"String\":false,\"SyntaxError\":false,\"toLocaleString\":false,\"toString\":false,\"TypeError\":false,\"undefined\":false,\"unescape\":false,\"URIError\":false,\"valueOf\":false},\"es2015\":{\"Array\":false,\"ArrayBuffer\":false,\"Boolean\":false,\"constructor\":false,\"DataView\":false,\"Date\":false,\"decodeURI\":false,\"decodeURIComponent\":false,\"encodeURI\":false,\"encodeURIComponent\":false,\"Error\":false,\"escape\":false,\"eval\":false,\"EvalError\":false,\"Float32Array\":false,\"Float64Array\":false,\"Function\":false,\"hasOwnProperty\":false,\"Infinity\":false,\"Int16Array\":false,\"Int32Array\":false,\"Int8Array\":false,\"isFinite\":false,\"isNaN\":false,\"isPrototypeOf\":false,\"JSON\":false,\"Map\":false,\"Math\":false,\"NaN\":false,\"Number\":false,\"Object\":false,\"parseFloat\":false,\"parseInt\":false,\"Promise\":false,\"propertyIsEnumerable\":false,\"Proxy\":false,\"RangeError\":false,\"ReferenceError\":false,\"Reflect\":false,\"RegExp\":false,\"Set\":false,\"String\":false,\"Symbol\":false,\"SyntaxError\":false,\"toLocaleString\":false,\"toString\":false,\"TypeError\":false,\"Uint16Array\":false,\"Uint32Array\":false,\"Uint8Array\":false,\"Uint8ClampedArray\":false,\"undefined\":false,\"unescape\":false,\"URIError\":false,\"valueOf\":false,\"WeakMap\":false,\"WeakSet\":false},\"es2017\":{\"Array\":false,\"ArrayBuffer\":false,\"Atomics\":false,\"Boolean\":false,\"constructor\":false,\"DataView\":false,\"Date\":false,\"decodeURI\":false,\"decodeURIComponent\":false,\"encodeURI\":false,\"encodeURIComponent\":false,\"Error\":false,\"escape\":false,\"eval\":false,\"EvalError\":false,\"Float32Array\":false,\"Float64Array\":false,\"Function\":false,\"hasOwnProperty\":false,\"Infinity\":false,\"Int16Array\":false,\"Int32Array\":false,\"Int8Array\":false,\"isFinite\":false,\"isNaN\":false,\"isPrototypeOf\":false,\"JSON\":false,\"Map\":false,\"Math\":false,\"NaN\":false,\"Number\":false,\"Object\":false,\"parseFloat\":false,\"parseInt\":false,\"Promise\":false,\"propertyIsEnumerable\":false,\"Proxy\":false,\"RangeError\":false,\"ReferenceError\":false,\"Reflect\":false,\"RegExp\":false,\"Set\":false,\"SharedArrayBuffer\":false,\"String\":false,\"Symbol\":false,\"SyntaxError\":false,\"toLocaleString\":false,\"toString\":false,\"TypeError\":false,\"Uint16Array\":false,\"Uint32Array\":false,\"Uint8Array\":false,\"Uint8ClampedArray\":false,\"undefined\":false,\"unescape\":false,\"URIError\":false,\"valueOf\":false,\"WeakMap\":false,\"WeakSet\":false},\"browser\":{\"AbortController\":false,\"AbortSignal\":false,\"addEventListener\":false,\"alert\":false,\"AnalyserNode\":false,\"Animation\":false,\"AnimationEffectReadOnly\":false,\"AnimationEffectTiming\":false,\"AnimationEffectTimingReadOnly\":false,\"AnimationEvent\":false,\"AnimationPlaybackEvent\":false,\"AnimationTimeline\":false,\"applicationCache\":false,\"ApplicationCache\":false,\"ApplicationCacheErrorEvent\":false,\"atob\":false,\"Attr\":false,\"Audio\":false,\"AudioBuffer\":false,\"AudioBufferSourceNode\":false,\"AudioContext\":false,\"AudioDestinationNode\":false,\"AudioListener\":false,\"AudioNode\":false,\"AudioParam\":false,\"AudioProcessingEvent\":false,\"AudioScheduledSourceNode\":false,\"AudioWorkletGlobalScope \":false,\"AudioWorkletNode\":false,\"AudioWorkletProcessor\":false,\"BarProp\":false,\"BaseAudioContext\":false,\"BatteryManager\":false,\"BeforeUnloadEvent\":false,\"BiquadFilterNode\":false,\"Blob\":false,\"BlobEvent\":false,\"blur\":false,\"BroadcastChannel\":false,\"btoa\":false,\"BudgetService\":false,\"ByteLengthQueuingStrategy\":false,\"Cache\":false,\"caches\":false,\"CacheStorage\":false,\"cancelAnimationFrame\":false,\"cancelIdleCallback\":false,\"CanvasCaptureMediaStreamTrack\":false,\"CanvasGradient\":false,\"CanvasPattern\":false,\"CanvasRenderingContext2D\":false,\"ChannelMergerNode\":false,\"ChannelSplitterNode\":false,\"CharacterData\":false,\"clearInterval\":false,\"clearTimeout\":false,\"clientInformation\":false,\"ClipboardEvent\":false,\"close\":false,\"closed\":false,\"CloseEvent\":false,\"Comment\":false,\"CompositionEvent\":false,\"confirm\":false,\"console\":false,\"ConstantSourceNode\":false,\"ConvolverNode\":false,\"CountQueuingStrategy\":false,\"createImageBitmap\":false,\"Credential\":false,\"CredentialsContainer\":false,\"crypto\":false,\"Crypto\":false,\"CryptoKey\":false,\"CSS\":false,\"CSSConditionRule\":false,\"CSSFontFaceRule\":false,\"CSSGroupingRule\":false,\"CSSImportRule\":false,\"CSSKeyframeRule\":false,\"CSSKeyframesRule\":false,\"CSSMediaRule\":false,\"CSSNamespaceRule\":false,\"CSSPageRule\":false,\"CSSRule\":false,\"CSSRuleList\":false,\"CSSStyleDeclaration\":false,\"CSSStyleRule\":false,\"CSSStyleSheet\":false,\"CSSSupportsRule\":false,\"CustomElementRegistry\":false,\"customElements\":false,\"CustomEvent\":false,\"DataTransfer\":false,\"DataTransferItem\":false,\"DataTransferItemList\":false,\"defaultstatus\":false,\"defaultStatus\":false,\"DelayNode\":false,\"DeviceMotionEvent\":false,\"DeviceOrientationEvent\":false,\"devicePixelRatio\":false,\"dispatchEvent\":false,\"document\":false,\"Document\":false,\"DocumentFragment\":false,\"DocumentType\":false,\"DOMError\":false,\"DOMException\":false,\"DOMImplementation\":false,\"DOMMatrix\":false,\"DOMMatrixReadOnly\":false,\"DOMParser\":false,\"DOMPoint\":false,\"DOMPointReadOnly\":false,\"DOMQuad\":false,\"DOMRect\":false,\"DOMRectReadOnly\":false,\"DOMStringList\":false,\"DOMStringMap\":false,\"DOMTokenList\":false,\"DragEvent\":false,\"DynamicsCompressorNode\":false,\"Element\":false,\"ErrorEvent\":false,\"event\":false,\"Event\":false,\"EventSource\":false,\"EventTarget\":false,\"external\":false,\"fetch\":false,\"File\":false,\"FileList\":false,\"FileReader\":false,\"find\":false,\"focus\":false,\"FocusEvent\":false,\"FontFace\":false,\"FontFaceSetLoadEvent\":false,\"FormData\":false,\"frameElement\":false,\"frames\":false,\"GainNode\":false,\"Gamepad\":false,\"GamepadButton\":false,\"GamepadEvent\":false,\"getComputedStyle\":false,\"getSelection\":false,\"HashChangeEvent\":false,\"Headers\":false,\"history\":false,\"History\":false,\"HTMLAllCollection\":false,\"HTMLAnchorElement\":false,\"HTMLAreaElement\":false,\"HTMLAudioElement\":false,\"HTMLBaseElement\":false,\"HTMLBodyElement\":false,\"HTMLBRElement\":false,\"HTMLButtonElement\":false,\"HTMLCanvasElement\":false,\"HTMLCollection\":false,\"HTMLContentElement\":false,\"HTMLDataElement\":false,\"HTMLDataListElement\":false,\"HTMLDetailsElement\":false,\"HTMLDialogElement\":false,\"HTMLDirectoryElement\":false,\"HTMLDivElement\":false,\"HTMLDListElement\":false,\"HTMLDocument\":false,\"HTMLElement\":false,\"HTMLEmbedElement\":false,\"HTMLFieldSetElement\":false,\"HTMLFontElement\":false,\"HTMLFormControlsCollection\":false,\"HTMLFormElement\":false,\"HTMLFrameElement\":false,\"HTMLFrameSetElement\":false,\"HTMLHeadElement\":false,\"HTMLHeadingElement\":false,\"HTMLHRElement\":false,\"HTMLHtmlElement\":false,\"HTMLIFrameElement\":false,\"HTMLImageElement\":false,\"HTMLInputElement\":false,\"HTMLLabelElement\":false,\"HTMLLegendElement\":false,\"HTMLLIElement\":false,\"HTMLLinkElement\":false,\"HTMLMapElement\":false,\"HTMLMarqueeElement\":false,\"HTMLMediaElement\":false,\"HTMLMenuElement\":false,\"HTMLMetaElement\":false,\"HTMLMeterElement\":false,\"HTMLModElement\":false,\"HTMLObjectElement\":false,\"HTMLOListElement\":false,\"HTMLOptGroupElement\":false,\"HTMLOptionElement\":false,\"HTMLOptionsCollection\":false,\"HTMLOutputElement\":false,\"HTMLParagraphElement\":false,\"HTMLParamElement\":false,\"HTMLPictureElement\":false,\"HTMLPreElement\":false,\"HTMLProgressElement\":false,\"HTMLQuoteElement\":false,\"HTMLScriptElement\":false,\"HTMLSelectElement\":false,\"HTMLShadowElement\":false,\"HTMLSlotElement\":false,\"HTMLSourceElement\":false,\"HTMLSpanElement\":false,\"HTMLStyleElement\":false,\"HTMLTableCaptionElement\":false,\"HTMLTableCellElement\":false,\"HTMLTableColElement\":false,\"HTMLTableElement\":false,\"HTMLTableRowElement\":false,\"HTMLTableSectionElement\":false,\"HTMLTemplateElement\":false,\"HTMLTextAreaElement\":false,\"HTMLTimeElement\":false,\"HTMLTitleElement\":false,\"HTMLTrackElement\":false,\"HTMLUListElement\":false,\"HTMLUnknownElement\":false,\"HTMLVideoElement\":false,\"IDBCursor\":false,\"IDBCursorWithValue\":false,\"IDBDatabase\":false,\"IDBFactory\":false,\"IDBIndex\":false,\"IDBKeyRange\":false,\"IDBObjectStore\":false,\"IDBOpenDBRequest\":false,\"IDBRequest\":false,\"IDBTransaction\":false,\"IDBVersionChangeEvent\":false,\"IdleDeadline\":false,\"IIRFilterNode\":false,\"Image\":false,\"ImageBitmap\":false,\"ImageBitmapRenderingContext\":false,\"ImageCapture\":false,\"ImageData\":false,\"indexedDB\":false,\"innerHeight\":false,\"innerWidth\":false,\"InputEvent\":false,\"IntersectionObserver\":false,\"IntersectionObserverEntry\":false,\"Intl\":false,\"isSecureContext\":false,\"KeyboardEvent\":false,\"KeyframeEffect\":false,\"KeyframeEffectReadOnly\":false,\"length\":false,\"localStorage\":false,\"location\":true,\"Location\":false,\"locationbar\":false,\"matchMedia\":false,\"MediaDeviceInfo\":false,\"MediaDevices\":false,\"MediaElementAudioSourceNode\":false,\"MediaEncryptedEvent\":false,\"MediaError\":false,\"MediaKeyMessageEvent\":false,\"MediaKeySession\":false,\"MediaKeyStatusMap\":false,\"MediaKeySystemAccess\":false,\"MediaList\":false,\"MediaQueryList\":false,\"MediaQueryListEvent\":false,\"MediaRecorder\":false,\"MediaSettingsRange\":false,\"MediaSource\":false,\"MediaStream\":false,\"MediaStreamAudioDestinationNode\":false,\"MediaStreamAudioSourceNode\":false,\"MediaStreamEvent\":false,\"MediaStreamTrack\":false,\"MediaStreamTrackEvent\":false,\"menubar\":false,\"MessageChannel\":false,\"MessageEvent\":false,\"MessagePort\":false,\"MIDIAccess\":false,\"MIDIConnectionEvent\":false,\"MIDIInput\":false,\"MIDIInputMap\":false,\"MIDIMessageEvent\":false,\"MIDIOutput\":false,\"MIDIOutputMap\":false,\"MIDIPort\":false,\"MimeType\":false,\"MimeTypeArray\":false,\"MouseEvent\":false,\"moveBy\":false,\"moveTo\":false,\"MutationEvent\":false,\"MutationObserver\":false,\"MutationRecord\":false,\"name\":false,\"NamedNodeMap\":false,\"NavigationPreloadManager\":false,\"navigator\":false,\"Navigator\":false,\"NetworkInformation\":false,\"Node\":false,\"NodeFilter\":false,\"NodeIterator\":false,\"NodeList\":false,\"Notification\":false,\"OfflineAudioCompletionEvent\":false,\"OfflineAudioContext\":false,\"offscreenBuffering\":false,\"OffscreenCanvas\":true,\"onabort\":true,\"onafterprint\":true,\"onanimationend\":true,\"onanimationiteration\":true,\"onanimationstart\":true,\"onappinstalled\":true,\"onauxclick\":true,\"onbeforeinstallprompt\":true,\"onbeforeprint\":true,\"onbeforeunload\":true,\"onblur\":true,\"oncancel\":true,\"oncanplay\":true,\"oncanplaythrough\":true,\"onchange\":true,\"onclick\":true,\"onclose\":true,\"oncontextmenu\":true,\"oncuechange\":true,\"ondblclick\":true,\"ondevicemotion\":true,\"ondeviceorientation\":true,\"ondeviceorientationabsolute\":true,\"ondrag\":true,\"ondragend\":true,\"ondragenter\":true,\"ondragleave\":true,\"ondragover\":true,\"ondragstart\":true,\"ondrop\":true,\"ondurationchange\":true,\"onemptied\":true,\"onended\":true,\"onerror\":true,\"onfocus\":true,\"ongotpointercapture\":true,\"onhashchange\":true,\"oninput\":true,\"oninvalid\":true,\"onkeydown\":true,\"onkeypress\":true,\"onkeyup\":true,\"onlanguagechange\":true,\"onload\":true,\"onloadeddata\":true,\"onloadedmetadata\":true,\"onloadstart\":true,\"onlostpointercapture\":true,\"onmessage\":true,\"onmessageerror\":true,\"onmousedown\":true,\"onmouseenter\":true,\"onmouseleave\":true,\"onmousemove\":true,\"onmouseout\":true,\"onmouseover\":true,\"onmouseup\":true,\"onmousewheel\":true,\"onoffline\":true,\"ononline\":true,\"onpagehide\":true,\"onpageshow\":true,\"onpause\":true,\"onplay\":true,\"onplaying\":true,\"onpointercancel\":true,\"onpointerdown\":true,\"onpointerenter\":true,\"onpointerleave\":true,\"onpointermove\":true,\"onpointerout\":true,\"onpointerover\":true,\"onpointerup\":true,\"onpopstate\":true,\"onprogress\":true,\"onratechange\":true,\"onrejectionhandled\":true,\"onreset\":true,\"onresize\":true,\"onscroll\":true,\"onsearch\":true,\"onseeked\":true,\"onseeking\":true,\"onselect\":true,\"onstalled\":true,\"onstorage\":true,\"onsubmit\":true,\"onsuspend\":true,\"ontimeupdate\":true,\"ontoggle\":true,\"ontransitionend\":true,\"onunhandledrejection\":true,\"onunload\":true,\"onvolumechange\":true,\"onwaiting\":true,\"onwheel\":true,\"open\":false,\"openDatabase\":false,\"opener\":false,\"Option\":false,\"origin\":false,\"OscillatorNode\":false,\"outerHeight\":false,\"outerWidth\":false,\"PageTransitionEvent\":false,\"pageXOffset\":false,\"pageYOffset\":false,\"PannerNode\":false,\"parent\":false,\"Path2D\":false,\"PaymentAddress\":false,\"PaymentRequest\":false,\"PaymentRequestUpdateEvent\":false,\"PaymentResponse\":false,\"performance\":false,\"Performance\":false,\"PerformanceEntry\":false,\"PerformanceLongTaskTiming\":false,\"PerformanceMark\":false,\"PerformanceMeasure\":false,\"PerformanceNavigation\":false,\"PerformanceNavigationTiming\":false,\"PerformanceObserver\":false,\"PerformanceObserverEntryList\":false,\"PerformancePaintTiming\":false,\"PerformanceResourceTiming\":false,\"PerformanceTiming\":false,\"PeriodicWave\":false,\"Permissions\":false,\"PermissionStatus\":false,\"personalbar\":false,\"PhotoCapabilities\":false,\"Plugin\":false,\"PluginArray\":false,\"PointerEvent\":false,\"PopStateEvent\":false,\"postMessage\":false,\"Presentation\":false,\"PresentationAvailability\":false,\"PresentationConnection\":false,\"PresentationConnectionAvailableEvent\":false,\"PresentationConnectionCloseEvent\":false,\"PresentationConnectionList\":false,\"PresentationReceiver\":false,\"PresentationRequest\":false,\"print\":false,\"ProcessingInstruction\":false,\"ProgressEvent\":false,\"PromiseRejectionEvent\":false,\"prompt\":false,\"PushManager\":false,\"PushSubscription\":false,\"PushSubscriptionOptions\":false,\"queueMicrotask\":false,\"RadioNodeList\":false,\"Range\":false,\"ReadableStream\":false,\"registerProcessor\":false,\"RemotePlayback\":false,\"removeEventListener\":false,\"Request\":false,\"requestAnimationFrame\":false,\"requestIdleCallback\":false,\"resizeBy\":false,\"ResizeObserver\":false,\"ResizeObserverEntry\":false,\"resizeTo\":false,\"Response\":false,\"RTCCertificate\":false,\"RTCDataChannel\":false,\"RTCDataChannelEvent\":false,\"RTCDtlsTransport\":false,\"RTCIceCandidate\":false,\"RTCIceGatherer\":false,\"RTCIceTransport\":false,\"RTCPeerConnection\":false,\"RTCPeerConnectionIceEvent\":false,\"RTCRtpContributingSource\":false,\"RTCRtpReceiver\":false,\"RTCRtpSender\":false,\"RTCSctpTransport\":false,\"RTCSessionDescription\":false,\"RTCStatsReport\":false,\"RTCTrackEvent\":false,\"screen\":false,\"Screen\":false,\"screenLeft\":false,\"ScreenOrientation\":false,\"screenTop\":false,\"screenX\":false,\"screenY\":false,\"ScriptProcessorNode\":false,\"scroll\":false,\"scrollbars\":false,\"scrollBy\":false,\"scrollTo\":false,\"scrollX\":false,\"scrollY\":false,\"SecurityPolicyViolationEvent\":false,\"Selection\":false,\"self\":false,\"ServiceWorker\":false,\"ServiceWorkerContainer\":false,\"ServiceWorkerRegistration\":false,\"sessionStorage\":false,\"setInterval\":false,\"setTimeout\":false,\"ShadowRoot\":false,\"SharedWorker\":false,\"SourceBuffer\":false,\"SourceBufferList\":false,\"speechSynthesis\":false,\"SpeechSynthesisEvent\":false,\"SpeechSynthesisUtterance\":false,\"StaticRange\":false,\"status\":false,\"statusbar\":false,\"StereoPannerNode\":false,\"stop\":false,\"Storage\":false,\"StorageEvent\":false,\"StorageManager\":false,\"styleMedia\":false,\"StyleSheet\":false,\"StyleSheetList\":false,\"SubtleCrypto\":false,\"SVGAElement\":false,\"SVGAngle\":false,\"SVGAnimatedAngle\":false,\"SVGAnimatedBoolean\":false,\"SVGAnimatedEnumeration\":false,\"SVGAnimatedInteger\":false,\"SVGAnimatedLength\":false,\"SVGAnimatedLengthList\":false,\"SVGAnimatedNumber\":false,\"SVGAnimatedNumberList\":false,\"SVGAnimatedPreserveAspectRatio\":false,\"SVGAnimatedRect\":false,\"SVGAnimatedString\":false,\"SVGAnimatedTransformList\":false,\"SVGAnimateElement\":false,\"SVGAnimateMotionElement\":false,\"SVGAnimateTransformElement\":false,\"SVGAnimationElement\":false,\"SVGCircleElement\":false,\"SVGClipPathElement\":false,\"SVGComponentTransferFunctionElement\":false,\"SVGDefsElement\":false,\"SVGDescElement\":false,\"SVGDiscardElement\":false,\"SVGElement\":false,\"SVGEllipseElement\":false,\"SVGFEBlendElement\":false,\"SVGFEColorMatrixElement\":false,\"SVGFEComponentTransferElement\":false,\"SVGFECompositeElement\":false,\"SVGFEConvolveMatrixElement\":false,\"SVGFEDiffuseLightingElement\":false,\"SVGFEDisplacementMapElement\":false,\"SVGFEDistantLightElement\":false,\"SVGFEDropShadowElement\":false,\"SVGFEFloodElement\":false,\"SVGFEFuncAElement\":false,\"SVGFEFuncBElement\":false,\"SVGFEFuncGElement\":false,\"SVGFEFuncRElement\":false,\"SVGFEGaussianBlurElement\":false,\"SVGFEImageElement\":false,\"SVGFEMergeElement\":false,\"SVGFEMergeNodeElement\":false,\"SVGFEMorphologyElement\":false,\"SVGFEOffsetElement\":false,\"SVGFEPointLightElement\":false,\"SVGFESpecularLightingElement\":false,\"SVGFESpotLightElement\":false,\"SVGFETileElement\":false,\"SVGFETurbulenceElement\":false,\"SVGFilterElement\":false,\"SVGForeignObjectElement\":false,\"SVGGElement\":false,\"SVGGeometryElement\":false,\"SVGGradientElement\":false,\"SVGGraphicsElement\":false,\"SVGImageElement\":false,\"SVGLength\":false,\"SVGLengthList\":false,\"SVGLinearGradientElement\":false,\"SVGLineElement\":false,\"SVGMarkerElement\":false,\"SVGMaskElement\":false,\"SVGMatrix\":false,\"SVGMetadataElement\":false,\"SVGMPathElement\":false,\"SVGNumber\":false,\"SVGNumberList\":false,\"SVGPathElement\":false,\"SVGPatternElement\":false,\"SVGPoint\":false,\"SVGPointList\":false,\"SVGPolygonElement\":false,\"SVGPolylineElement\":false,\"SVGPreserveAspectRatio\":false,\"SVGRadialGradientElement\":false,\"SVGRect\":false,\"SVGRectElement\":false,\"SVGScriptElement\":false,\"SVGSetElement\":false,\"SVGStopElement\":false,\"SVGStringList\":false,\"SVGStyleElement\":false,\"SVGSVGElement\":false,\"SVGSwitchElement\":false,\"SVGSymbolElement\":false,\"SVGTextContentElement\":false,\"SVGTextElement\":false,\"SVGTextPathElement\":false,\"SVGTextPositioningElement\":false,\"SVGTitleElement\":false,\"SVGTransform\":false,\"SVGTransformList\":false,\"SVGTSpanElement\":false,\"SVGUnitTypes\":false,\"SVGUseElement\":false,\"SVGViewElement\":false,\"TaskAttributionTiming\":false,\"Text\":false,\"TextDecoder\":false,\"TextEncoder\":false,\"TextEvent\":false,\"TextMetrics\":false,\"TextTrack\":false,\"TextTrackCue\":false,\"TextTrackCueList\":false,\"TextTrackList\":false,\"TimeRanges\":false,\"toolbar\":false,\"top\":false,\"Touch\":false,\"TouchEvent\":false,\"TouchList\":false,\"TrackEvent\":false,\"TransitionEvent\":false,\"TreeWalker\":false,\"UIEvent\":false,\"URL\":false,\"URLSearchParams\":false,\"ValidityState\":false,\"visualViewport\":false,\"VisualViewport\":false,\"VTTCue\":false,\"WaveShaperNode\":false,\"WebAssembly\":false,\"WebGL2RenderingContext\":false,\"WebGLActiveInfo\":false,\"WebGLBuffer\":false,\"WebGLContextEvent\":false,\"WebGLFramebuffer\":false,\"WebGLProgram\":false,\"WebGLQuery\":false,\"WebGLRenderbuffer\":false,\"WebGLRenderingContext\":false,\"WebGLSampler\":false,\"WebGLShader\":false,\"WebGLShaderPrecisionFormat\":false,\"WebGLSync\":false,\"WebGLTexture\":false,\"WebGLTransformFeedback\":false,\"WebGLUniformLocation\":false,\"WebGLVertexArrayObject\":false,\"WebSocket\":false,\"WheelEvent\":false,\"window\":false,\"Window\":false,\"Worker\":false,\"WritableStream\":false,\"XMLDocument\":false,\"XMLHttpRequest\":false,\"XMLHttpRequestEventTarget\":false,\"XMLHttpRequestUpload\":false,\"XMLSerializer\":false,\"XPathEvaluator\":false,\"XPathExpression\":false,\"XPathResult\":false,\"XSLTProcessor\":false},\"worker\":{\"addEventListener\":false,\"applicationCache\":false,\"atob\":false,\"Blob\":false,\"BroadcastChannel\":false,\"btoa\":false,\"Cache\":false,\"caches\":false,\"clearInterval\":false,\"clearTimeout\":false,\"close\":true,\"console\":false,\"fetch\":false,\"FileReaderSync\":false,\"FormData\":false,\"Headers\":false,\"IDBCursor\":false,\"IDBCursorWithValue\":false,\"IDBDatabase\":false,\"IDBFactory\":false,\"IDBIndex\":false,\"IDBKeyRange\":false,\"IDBObjectStore\":false,\"IDBOpenDBRequest\":false,\"IDBRequest\":false,\"IDBTransaction\":false,\"IDBVersionChangeEvent\":false,\"ImageData\":false,\"importScripts\":true,\"indexedDB\":false,\"location\":false,\"MessageChannel\":false,\"MessagePort\":false,\"name\":false,\"navigator\":false,\"Notification\":false,\"onclose\":true,\"onconnect\":true,\"onerror\":true,\"onlanguagechange\":true,\"onmessage\":true,\"onoffline\":true,\"ononline\":true,\"onrejectionhandled\":true,\"onunhandledrejection\":true,\"performance\":false,\"Performance\":false,\"PerformanceEntry\":false,\"PerformanceMark\":false,\"PerformanceMeasure\":false,\"PerformanceNavigation\":false,\"PerformanceResourceTiming\":false,\"PerformanceTiming\":false,\"postMessage\":true,\"Promise\":false,\"queueMicrotask\":false,\"removeEventListener\":false,\"Request\":false,\"Response\":false,\"self\":true,\"ServiceWorkerRegistration\":false,\"setInterval\":false,\"setTimeout\":false,\"TextDecoder\":false,\"TextEncoder\":false,\"URL\":false,\"URLSearchParams\":false,\"WebSocket\":false,\"Worker\":false,\"WorkerGlobalScope\":false,\"XMLHttpRequest\":false},\"node\":{\"__dirname\":false,\"__filename\":false,\"Buffer\":false,\"clearImmediate\":false,\"clearInterval\":false,\"clearTimeout\":false,\"console\":false,\"exports\":true,\"global\":false,\"Intl\":false,\"module\":false,\"process\":false,\"queueMicrotask\":false,\"require\":false,\"setImmediate\":false,\"setInterval\":false,\"setTimeout\":false,\"TextDecoder\":false,\"TextEncoder\":false,\"URL\":false,\"URLSearchParams\":false},\"nodeBuiltin\":{\"Buffer\":false,\"clearImmediate\":false,\"clearInterval\":false,\"clearTimeout\":false,\"console\":false,\"global\":false,\"Intl\":false,\"process\":false,\"queueMicrotask\":false,\"setImmediate\":false,\"setInterval\":false,\"setTimeout\":false,\"TextDecoder\":false,\"TextEncoder\":false,\"URL\":false,\"URLSearchParams\":false},\"commonjs\":{\"exports\":true,\"global\":false,\"module\":false,\"require\":false},\"amd\":{\"define\":false,\"require\":false},\"mocha\":{\"after\":false,\"afterEach\":false,\"before\":false,\"beforeEach\":false,\"context\":false,\"describe\":false,\"it\":false,\"mocha\":false,\"run\":false,\"setup\":false,\"specify\":false,\"suite\":false,\"suiteSetup\":false,\"suiteTeardown\":false,\"teardown\":false,\"test\":false,\"xcontext\":false,\"xdescribe\":false,\"xit\":false,\"xspecify\":false},\"jasmine\":{\"afterAll\":false,\"afterEach\":false,\"beforeAll\":false,\"beforeEach\":false,\"describe\":false,\"expect\":false,\"expectAsync\":false,\"fail\":false,\"fdescribe\":false,\"fit\":false,\"it\":false,\"jasmine\":false,\"pending\":false,\"runs\":false,\"spyOn\":false,\"spyOnAllFunctions\":false,\"spyOnProperty\":false,\"waits\":false,\"waitsFor\":false,\"xdescribe\":false,\"xit\":false},\"jest\":{\"afterAll\":false,\"afterEach\":false,\"beforeAll\":false,\"beforeEach\":false,\"describe\":false,\"expect\":false,\"fdescribe\":false,\"fit\":false,\"it\":false,\"jest\":false,\"pit\":false,\"require\":false,\"test\":false,\"xdescribe\":false,\"xit\":false,\"xtest\":false},\"qunit\":{\"asyncTest\":false,\"deepEqual\":false,\"equal\":false,\"expect\":false,\"module\":false,\"notDeepEqual\":false,\"notEqual\":false,\"notOk\":false,\"notPropEqual\":false,\"notStrictEqual\":false,\"ok\":false,\"propEqual\":false,\"QUnit\":false,\"raises\":false,\"start\":false,\"stop\":false,\"strictEqual\":false,\"test\":false,\"throws\":false},\"phantomjs\":{\"console\":true,\"exports\":true,\"phantom\":true,\"require\":true,\"WebPage\":true},\"couch\":{\"emit\":false,\"exports\":false,\"getRow\":false,\"log\":false,\"module\":false,\"provides\":false,\"require\":false,\"respond\":false,\"send\":false,\"start\":false,\"sum\":false},\"rhino\":{\"defineClass\":false,\"deserialize\":false,\"gc\":false,\"help\":false,\"importClass\":false,\"importPackage\":false,\"java\":false,\"load\":false,\"loadClass\":false,\"Packages\":false,\"print\":false,\"quit\":false,\"readFile\":false,\"readUrl\":false,\"runCommand\":false,\"seal\":false,\"serialize\":false,\"spawn\":false,\"sync\":false,\"toint32\":false,\"version\":false},\"nashorn\":{\"__DIR__\":false,\"__FILE__\":false,\"__LINE__\":false,\"com\":false,\"edu\":false,\"exit\":false,\"java\":false,\"Java\":false,\"javafx\":false,\"JavaImporter\":false,\"javax\":false,\"JSAdapter\":false,\"load\":false,\"loadWithNewGlobal\":false,\"org\":false,\"Packages\":false,\"print\":false,\"quit\":false},\"wsh\":{\"ActiveXObject\":true,\"CollectGarbage\":true,\"Debug\":true,\"Enumerator\":true,\"GetObject\":true,\"RuntimeObject\":true,\"ScriptEngine\":true,\"ScriptEngineBuildVersion\":true,\"ScriptEngineMajorVersion\":true,\"ScriptEngineMinorVersion\":true,\"VBArray\":true,\"WScript\":true,\"WSH\":true,\"XDomainRequest\":true},\"jquery\":{\"$\":false,\"jQuery\":false},\"yui\":{\"YAHOO\":false,\"YAHOO_config\":false,\"YUI\":false,\"YUI_config\":false},\"shelljs\":{\"cat\":false,\"cd\":false,\"chmod\":false,\"config\":false,\"cp\":false,\"dirs\":false,\"echo\":false,\"env\":false,\"error\":false,\"exec\":false,\"exit\":false,\"find\":false,\"grep\":false,\"ln\":false,\"ls\":false,\"mkdir\":false,\"mv\":false,\"popd\":false,\"pushd\":false,\"pwd\":false,\"rm\":false,\"sed\":false,\"set\":false,\"target\":false,\"tempdir\":false,\"test\":false,\"touch\":false,\"which\":false},\"prototypejs\":{\"$\":false,\"$$\":false,\"$A\":false,\"$break\":false,\"$continue\":false,\"$F\":false,\"$H\":false,\"$R\":false,\"$w\":false,\"Abstract\":false,\"Ajax\":false,\"Autocompleter\":false,\"Builder\":false,\"Class\":false,\"Control\":false,\"Draggable\":false,\"Draggables\":false,\"Droppables\":false,\"Effect\":false,\"Element\":false,\"Enumerable\":false,\"Event\":false,\"Field\":false,\"Form\":false,\"Hash\":false,\"Insertion\":false,\"ObjectRange\":false,\"PeriodicalExecuter\":false,\"Position\":false,\"Prototype\":false,\"Scriptaculous\":false,\"Selector\":false,\"Sortable\":false,\"SortableObserver\":false,\"Sound\":false,\"Template\":false,\"Toggle\":false,\"Try\":false},\"meteor\":{\"_\":false,\"$\":false,\"Accounts\":false,\"AccountsClient\":false,\"AccountsCommon\":false,\"AccountsServer\":false,\"App\":false,\"Assets\":false,\"Blaze\":false,\"check\":false,\"Cordova\":false,\"DDP\":false,\"DDPRateLimiter\":false,\"DDPServer\":false,\"Deps\":false,\"EJSON\":false,\"Email\":false,\"HTTP\":false,\"Log\":false,\"Match\":false,\"Meteor\":false,\"Mongo\":false,\"MongoInternals\":false,\"Npm\":false,\"Package\":false,\"Plugin\":false,\"process\":false,\"Random\":false,\"ReactiveDict\":false,\"ReactiveVar\":false,\"Router\":false,\"ServiceConfiguration\":false,\"Session\":false,\"share\":false,\"Spacebars\":false,\"Template\":false,\"Tinytest\":false,\"Tracker\":false,\"UI\":false,\"Utils\":false,\"WebApp\":false,\"WebAppInternals\":false},\"mongo\":{\"_isWindows\":false,\"_rand\":false,\"BulkWriteResult\":false,\"cat\":false,\"cd\":false,\"connect\":false,\"db\":false,\"getHostName\":false,\"getMemInfo\":false,\"hostname\":false,\"ISODate\":false,\"listFiles\":false,\"load\":false,\"ls\":false,\"md5sumFile\":false,\"mkdir\":false,\"Mongo\":false,\"NumberInt\":false,\"NumberLong\":false,\"ObjectId\":false,\"PlanCache\":false,\"print\":false,\"printjson\":false,\"pwd\":false,\"quit\":false,\"removeFile\":false,\"rs\":false,\"sh\":false,\"UUID\":false,\"version\":false,\"WriteResult\":false},\"applescript\":{\"$\":false,\"Application\":false,\"Automation\":false,\"console\":false,\"delay\":false,\"Library\":false,\"ObjC\":false,\"ObjectSpecifier\":false,\"Path\":false,\"Progress\":false,\"Ref\":false},\"serviceworker\":{\"addEventListener\":false,\"applicationCache\":false,\"atob\":false,\"Blob\":false,\"BroadcastChannel\":false,\"btoa\":false,\"Cache\":false,\"caches\":false,\"CacheStorage\":false,\"clearInterval\":false,\"clearTimeout\":false,\"Client\":false,\"clients\":false,\"Clients\":false,\"close\":true,\"console\":false,\"ExtendableEvent\":false,\"ExtendableMessageEvent\":false,\"fetch\":false,\"FetchEvent\":false,\"FileReaderSync\":false,\"FormData\":false,\"Headers\":false,\"IDBCursor\":false,\"IDBCursorWithValue\":false,\"IDBDatabase\":false,\"IDBFactory\":false,\"IDBIndex\":false,\"IDBKeyRange\":false,\"IDBObjectStore\":false,\"IDBOpenDBRequest\":false,\"IDBRequest\":false,\"IDBTransaction\":false,\"IDBVersionChangeEvent\":false,\"ImageData\":false,\"importScripts\":false,\"indexedDB\":false,\"location\":false,\"MessageChannel\":false,\"MessagePort\":false,\"name\":false,\"navigator\":false,\"Notification\":false,\"onclose\":true,\"onconnect\":true,\"onerror\":true,\"onfetch\":true,\"oninstall\":true,\"onlanguagechange\":true,\"onmessage\":true,\"onmessageerror\":true,\"onnotificationclick\":true,\"onnotificationclose\":true,\"onoffline\":true,\"ononline\":true,\"onpush\":true,\"onpushsubscriptionchange\":true,\"onrejectionhandled\":true,\"onsync\":true,\"onunhandledrejection\":true,\"performance\":false,\"Performance\":false,\"PerformanceEntry\":false,\"PerformanceMark\":false,\"PerformanceMeasure\":false,\"PerformanceNavigation\":false,\"PerformanceResourceTiming\":false,\"PerformanceTiming\":false,\"postMessage\":true,\"Promise\":false,\"queueMicrotask\":false,\"registration\":false,\"removeEventListener\":false,\"Request\":false,\"Response\":false,\"self\":false,\"ServiceWorker\":false,\"ServiceWorkerContainer\":false,\"ServiceWorkerGlobalScope\":false,\"ServiceWorkerMessageEvent\":false,\"ServiceWorkerRegistration\":false,\"setInterval\":false,\"setTimeout\":false,\"skipWaiting\":false,\"TextDecoder\":false,\"TextEncoder\":false,\"URL\":false,\"URLSearchParams\":false,\"WebSocket\":false,\"WindowClient\":false,\"Worker\":false,\"WorkerGlobalScope\":false,\"XMLHttpRequest\":false},\"atomtest\":{\"advanceClock\":false,\"fakeClearInterval\":false,\"fakeClearTimeout\":false,\"fakeSetInterval\":false,\"fakeSetTimeout\":false,\"resetTimeouts\":false,\"waitsForPromise\":false},\"embertest\":{\"andThen\":false,\"click\":false,\"currentPath\":false,\"currentRouteName\":false,\"currentURL\":false,\"fillIn\":false,\"find\":false,\"findAll\":false,\"findWithAssert\":false,\"keyEvent\":false,\"pauseTest\":false,\"resumeTest\":false,\"triggerEvent\":false,\"visit\":false,\"wait\":false},\"protractor\":{\"$\":false,\"$$\":false,\"browser\":false,\"by\":false,\"By\":false,\"DartObject\":false,\"element\":false,\"protractor\":false},\"shared-node-browser\":{\"clearInterval\":false,\"clearTimeout\":false,\"console\":false,\"setInterval\":false,\"setTimeout\":false,\"URL\":false,\"URLSearchParams\":false},\"webextensions\":{\"browser\":false,\"chrome\":false,\"opr\":false},\"greasemonkey\":{\"cloneInto\":false,\"createObjectIn\":false,\"exportFunction\":false,\"GM\":false,\"GM_addStyle\":false,\"GM_deleteValue\":false,\"GM_getResourceText\":false,\"GM_getResourceURL\":false,\"GM_getValue\":false,\"GM_info\":false,\"GM_listValues\":false,\"GM_log\":false,\"GM_openInTab\":false,\"GM_registerMenuCommand\":false,\"GM_setClipboard\":false,\"GM_setValue\":false,\"GM_xmlhttpRequest\":false,\"unsafeWindow\":false},\"devtools\":{\"$\":false,\"$_\":false,\"$$\":false,\"$0\":false,\"$1\":false,\"$2\":false,\"$3\":false,\"$4\":false,\"$x\":false,\"chrome\":false,\"clear\":false,\"copy\":false,\"debug\":false,\"dir\":false,\"dirxml\":false,\"getEventListeners\":false,\"inspect\":false,\"keys\":false,\"monitor\":false,\"monitorEvents\":false,\"profile\":false,\"profileEnd\":false,\"queryObjects\":false,\"table\":false,\"undebug\":false,\"unmonitor\":false,\"unmonitorEvents\":false,\"values\":false}}");
45927
45928/***/ }),
45929/* 408 */
45930/***/ (function(module) {
45931
6a5a0f88 45932module.exports = JSON.parse("{\"name\":\"eslint\",\"version\":\"7.1.0\",\"author\":\"Nicholas C. Zakas <nicholas+npm@nczconsulting.com>\",\"description\":\"An AST-based pattern checker for JavaScript.\",\"bin\":{\"eslint\":\"./bin/eslint.js\"},\"main\":\"./lib/api.js\",\"scripts\":{\"test\":\"node Makefile.js test\",\"test:cli\":\"mocha\",\"lint\":\"node Makefile.js lint\",\"fix\":\"node Makefile.js lint -- fix\",\"fuzz\":\"node Makefile.js fuzz\",\"generate-release\":\"node Makefile.js generateRelease\",\"generate-alpharelease\":\"node Makefile.js generatePrerelease -- alpha\",\"generate-betarelease\":\"node Makefile.js generatePrerelease -- beta\",\"generate-rcrelease\":\"node Makefile.js generatePrerelease -- rc\",\"publish-release\":\"node Makefile.js publishRelease\",\"docs\":\"node Makefile.js docs\",\"gensite\":\"node Makefile.js gensite\",\"webpack\":\"node Makefile.js webpack\",\"perf\":\"node Makefile.js perf\"},\"gitHooks\":{\"pre-commit\":\"lint-staged\"},\"lint-staged\":{\"*.js\":[\"eslint --fix\",\"git add\"],\"*.md\":\"markdownlint\"},\"files\":[\"LICENSE\",\"README.md\",\"bin\",\"conf\",\"lib\",\"messages\"],\"repository\":\"eslint/eslint\",\"funding\":\"https://opencollective.com/eslint\",\"homepage\":\"https://eslint.org\",\"bugs\":\"https://github.com/eslint/eslint/issues/\",\"dependencies\":{\"@babel/code-frame\":\"^7.0.0\",\"ajv\":\"^6.10.0\",\"chalk\":\"^4.0.0\",\"cross-spawn\":\"^7.0.2\",\"debug\":\"^4.0.1\",\"doctrine\":\"^3.0.0\",\"eslint-scope\":\"^5.0.0\",\"eslint-utils\":\"^2.0.0\",\"eslint-visitor-keys\":\"^1.1.0\",\"espree\":\"^7.0.0\",\"esquery\":\"^1.2.0\",\"esutils\":\"^2.0.2\",\"file-entry-cache\":\"^5.0.1\",\"functional-red-black-tree\":\"^1.0.1\",\"glob-parent\":\"^5.0.0\",\"globals\":\"^12.1.0\",\"ignore\":\"^4.0.6\",\"import-fresh\":\"^3.0.0\",\"imurmurhash\":\"^0.1.4\",\"inquirer\":\"^7.0.0\",\"is-glob\":\"^4.0.0\",\"js-yaml\":\"^3.13.1\",\"json-stable-stringify-without-jsonify\":\"^1.0.1\",\"levn\":\"^0.4.1\",\"lodash\":\"^4.17.14\",\"minimatch\":\"^3.0.4\",\"natural-compare\":\"^1.4.0\",\"optionator\":\"^0.9.1\",\"progress\":\"^2.0.0\",\"regexpp\":\"^3.1.0\",\"semver\":\"^7.2.1\",\"strip-ansi\":\"^6.0.0\",\"strip-json-comments\":\"^3.1.0\",\"table\":\"^5.2.3\",\"text-table\":\"^0.2.0\",\"v8-compile-cache\":\"^2.0.3\"},\"devDependencies\":{\"@babel/core\":\"^7.4.3\",\"@babel/preset-env\":\"^7.4.3\",\"acorn\":\"^7.1.1\",\"babel-loader\":\"^8.0.5\",\"chai\":\"^4.0.1\",\"cheerio\":\"^0.22.0\",\"common-tags\":\"^1.8.0\",\"core-js\":\"^3.1.3\",\"dateformat\":\"^3.0.3\",\"ejs\":\"^3.0.2\",\"escape-string-regexp\":\"^3.0.0\",\"eslint\":\"file:.\",\"eslint-config-eslint\":\"file:packages/eslint-config-eslint\",\"eslint-plugin-eslint-plugin\":\"^2.2.1\",\"eslint-plugin-internal-rules\":\"file:tools/internal-rules\",\"eslint-plugin-jsdoc\":\"^22.1.0\",\"eslint-plugin-node\":\"^11.1.0\",\"eslint-release\":\"^2.0.0\",\"eslump\":\"^2.0.0\",\"esprima\":\"^4.0.1\",\"glob\":\"^7.1.6\",\"jsdoc\":\"^3.5.5\",\"karma\":\"^4.0.1\",\"karma-chrome-launcher\":\"^3.1.0\",\"karma-mocha\":\"^1.3.0\",\"karma-mocha-reporter\":\"^2.2.3\",\"karma-webpack\":\"^4.0.0-rc.6\",\"leche\":\"^2.2.3\",\"lint-staged\":\"^10.1.2\",\"load-perf\":\"^0.2.0\",\"markdownlint\":\"^0.19.0\",\"markdownlint-cli\":\"^0.22.0\",\"memfs\":\"^3.0.1\",\"mocha\":\"^7.1.1\",\"mocha-junit-reporter\":\"^1.23.0\",\"npm-license\":\"^0.3.3\",\"nyc\":\"^15.0.1\",\"proxyquire\":\"^2.0.1\",\"puppeteer\":\"^2.1.1\",\"recast\":\"^0.19.0\",\"regenerator-runtime\":\"^0.13.2\",\"shelljs\":\"^0.8.2\",\"sinon\":\"^9.0.1\",\"temp\":\"^0.9.0\",\"webpack\":\"^4.35.0\",\"webpack-cli\":\"^3.3.5\",\"yorkie\":\"^2.0.0\"},\"keywords\":[\"ast\",\"lint\",\"javascript\",\"ecmascript\",\"espree\"],\"license\":\"MIT\",\"engines\":{\"node\":\"^10.12.0 || >=12.0.0\"}}");
eb39fafa
DC
45933
45934/***/ }),
45935/* 409 */
45936/***/ (function(module, exports, __webpack_require__) {
45937
45938"use strict";
45939/**
45940 * @fileoverview Common utils for AST.
45941 *
45942 * This file contains only shared items for core and rules.
45943 * If you make a utility for rules, please see `../rules/utils/ast-utils.js`.
45944 *
45945 * @author Toru Nagashima <https://github.com/mysticatea>
45946 */
45947
45948
45949const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u;
45950const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u;
45951const shebangPattern = /^#!([^\r\n]+)/u;
45952/**
45953 * Creates a version of the `lineBreakPattern` regex with the global flag.
45954 * Global regexes are mutable, so this needs to be a function instead of a constant.
45955 * @returns {RegExp} A global regular expression that matches line terminators
45956 */
45957
45958function createGlobalLinebreakMatcher() {
45959 return new RegExp(lineBreakPattern.source, "gu");
45960}
45961
45962module.exports = {
45963 breakableTypePattern,
45964 lineBreakPattern,
45965 createGlobalLinebreakMatcher,
45966 shebangPattern
45967};
45968
45969/***/ }),
45970/* 410 */
45971/***/ (function(module, exports, __webpack_require__) {
45972
45973"use strict";
45974/**
45975 * @fileoverview Config file operations. This file must be usable in the browser,
45976 * so no Node-specific code can be here.
45977 * @author Nicholas C. Zakas
45978 */
45979 //------------------------------------------------------------------------------
45980// Private
45981//------------------------------------------------------------------------------
45982
45983const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
45984 RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
45985 map[value] = index;
45986 return map;
45987}, {}),
45988 VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"]; //------------------------------------------------------------------------------
45989// Public Interface
45990//------------------------------------------------------------------------------
45991
45992module.exports = {
45993 /**
45994 * Normalizes the severity value of a rule's configuration to a number
45995 * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
45996 * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
45997 * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
45998 * whose first element is one of the above values. Strings are matched case-insensitively.
45999 * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
46000 */
46001 getRuleSeverity(ruleConfig) {
46002 const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
46003
46004 if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
46005 return severityValue;
46006 }
46007
46008 if (typeof severityValue === "string") {
46009 return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
46010 }
46011
46012 return 0;
46013 },
46014
46015 /**
46016 * Converts old-style severity settings (0, 1, 2) into new-style
46017 * severity settings (off, warn, error) for all rules. Assumption is that severity
46018 * values have already been validated as correct.
46019 * @param {Object} config The config object to normalize.
46020 * @returns {void}
46021 */
46022 normalizeToStrings(config) {
46023 if (config.rules) {
46024 Object.keys(config.rules).forEach(ruleId => {
46025 const ruleConfig = config.rules[ruleId];
46026
46027 if (typeof ruleConfig === "number") {
46028 config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
46029 } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
46030 ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
46031 }
46032 });
46033 }
46034 },
46035
46036 /**
46037 * Determines if the severity for the given rule configuration represents an error.
46038 * @param {int|string|Array} ruleConfig The configuration for an individual rule.
46039 * @returns {boolean} True if the rule represents an error, false if not.
46040 */
46041 isErrorSeverity(ruleConfig) {
46042 return module.exports.getRuleSeverity(ruleConfig) === 2;
46043 },
46044
46045 /**
46046 * Checks whether a given config has valid severity or not.
46047 * @param {number|string|Array} ruleConfig The configuration for an individual rule.
46048 * @returns {boolean} `true` if the configuration has valid severity.
46049 */
46050 isValidSeverity(ruleConfig) {
46051 let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
46052
46053 if (typeof severity === "string") {
46054 severity = severity.toLowerCase();
46055 }
46056
46057 return VALID_SEVERITIES.indexOf(severity) !== -1;
46058 },
46059
46060 /**
46061 * Checks whether every rule of a given config has valid severity or not.
46062 * @param {Object} config The configuration for rules.
46063 * @returns {boolean} `true` if the configuration has valid severity.
46064 */
46065 isEverySeverityValid(config) {
46066 return Object.keys(config).every(ruleId => this.isValidSeverity(config[ruleId]));
46067 },
46068
46069 /**
46070 * Normalizes a value for a global in a config
46071 * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
46072 * a global directive comment
46073 * @returns {("readable"|"writeable"|"off")} The value normalized as a string
46074 * @throws Error if global value is invalid
46075 */
46076 normalizeConfigGlobal(configuredValue) {
46077 switch (configuredValue) {
46078 case "off":
46079 return "off";
46080
46081 case true:
46082 case "true":
46083 case "writeable":
46084 case "writable":
46085 return "writable";
46086
46087 case null:
46088 case false:
46089 case "false":
46090 case "readable":
46091 case "readonly":
46092 return "readonly";
46093
46094 default:
46095 throw new Error("'".concat(configuredValue, "' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')"));
46096 }
46097 }
46098
46099};
46100
46101/***/ }),
46102/* 411 */
46103/***/ (function(module, exports, __webpack_require__) {
46104
46105"use strict";
46106/**
46107 * @fileoverview Validates configs.
46108 * @author Brandon Mills
46109 */
46110 //------------------------------------------------------------------------------
46111// Requirements
46112//------------------------------------------------------------------------------
46113
46114const util = __webpack_require__(412),
46115 configSchema = __webpack_require__(413),
46116 BuiltInEnvironments = __webpack_require__(405),
46117 BuiltInRules = __webpack_require__(414),
46118 ConfigOps = __webpack_require__(410),
46119 {
46120 emitDeprecationWarning
6a5a0f88 46121} = __webpack_require__(727);
eb39fafa 46122
6a5a0f88 46123const ajv = __webpack_require__(728)();
eb39fafa
DC
46124
46125const ruleValidators = new WeakMap();
46126const noop = Function.prototype; //------------------------------------------------------------------------------
46127// Private
46128//------------------------------------------------------------------------------
46129
46130let validateSchema;
46131const severityMap = {
46132 error: 2,
46133 warn: 1,
46134 off: 0
46135};
46136/**
46137 * Gets a complete options schema for a rule.
46138 * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
46139 * @returns {Object} JSON Schema for the rule's options.
46140 */
46141
46142function getRuleOptionsSchema(rule) {
46143 if (!rule) {
46144 return null;
46145 }
46146
46147 const schema = rule.schema || rule.meta && rule.meta.schema; // Given a tuple of schemas, insert warning level at the beginning
46148
46149 if (Array.isArray(schema)) {
46150 if (schema.length) {
46151 return {
46152 type: "array",
46153 items: schema,
46154 minItems: 0,
46155 maxItems: schema.length
46156 };
46157 }
46158
46159 return {
46160 type: "array",
46161 minItems: 0,
46162 maxItems: 0
46163 };
46164 } // Given a full schema, leave it alone
46165
46166
46167 return schema || null;
46168}
46169/**
46170 * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
46171 * @param {options} options The given options for the rule.
46172 * @returns {number|string} The rule's severity value
46173 */
46174
46175
46176function validateRuleSeverity(options) {
46177 const severity = Array.isArray(options) ? options[0] : options;
46178 const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
46179
46180 if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
46181 return normSeverity;
46182 }
46183
46184 throw new Error("\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '".concat(util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, ""), "').\n"));
46185}
46186/**
46187 * Validates the non-severity options passed to a rule, based on its schema.
46188 * @param {{create: Function}} rule The rule to validate
46189 * @param {Array} localOptions The options for the rule, excluding severity
46190 * @returns {void}
46191 */
46192
46193
46194function validateRuleSchema(rule, localOptions) {
46195 if (!ruleValidators.has(rule)) {
46196 const schema = getRuleOptionsSchema(rule);
46197
46198 if (schema) {
46199 ruleValidators.set(rule, ajv.compile(schema));
46200 }
46201 }
46202
46203 const validateRule = ruleValidators.get(rule);
46204
46205 if (validateRule) {
46206 validateRule(localOptions);
46207
46208 if (validateRule.errors) {
46209 throw new Error(validateRule.errors.map(error => "\tValue ".concat(JSON.stringify(error.data), " ").concat(error.message, ".\n")).join(""));
46210 }
46211 }
46212}
46213/**
46214 * Validates a rule's options against its schema.
46215 * @param {{create: Function}|null} rule The rule that the config is being validated for
46216 * @param {string} ruleId The rule's unique name.
46217 * @param {Array|number} options The given options for the rule.
46218 * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
46219 * no source is prepended to the message.
46220 * @returns {void}
46221 */
46222
46223
46224function validateRuleOptions(rule, ruleId, options, source = null) {
46225 try {
46226 const severity = validateRuleSeverity(options);
46227
46228 if (severity !== 0) {
46229 validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
46230 }
46231 } catch (err) {
46232 const enhancedMessage = "Configuration for rule \"".concat(ruleId, "\" is invalid:\n").concat(err.message);
46233
46234 if (typeof source === "string") {
46235 throw new Error("".concat(source, ":\n\t").concat(enhancedMessage));
46236 } else {
46237 throw new Error(enhancedMessage);
46238 }
46239 }
46240}
46241/**
46242 * Validates an environment object
46243 * @param {Object} environment The environment config object to validate.
46244 * @param {string} source The name of the configuration source to report in any errors.
46245 * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
46246 * @returns {void}
46247 */
46248
46249
46250function validateEnvironment(environment, source, getAdditionalEnv = noop) {
46251 // not having an environment is ok
46252 if (!environment) {
46253 return;
46254 }
46255
46256 Object.keys(environment).forEach(id => {
46257 const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
46258
46259 if (!env) {
46260 const message = "".concat(source, ":\n\tEnvironment key \"").concat(id, "\" is unknown\n");
46261 throw new Error(message);
46262 }
46263 });
46264}
46265/**
46266 * Validates a rules config object
46267 * @param {Object} rulesConfig The rules config object to validate.
46268 * @param {string} source The name of the configuration source to report in any errors.
46269 * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
46270 * @returns {void}
46271 */
46272
46273
46274function validateRules(rulesConfig, source, getAdditionalRule = noop) {
46275 if (!rulesConfig) {
46276 return;
46277 }
46278
46279 Object.keys(rulesConfig).forEach(id => {
46280 const rule = getAdditionalRule(id) || BuiltInRules.get(id) || null;
46281 validateRuleOptions(rule, id, rulesConfig[id], source);
46282 });
46283}
46284/**
46285 * Validates a `globals` section of a config file
46286 * @param {Object} globalsConfig The `globals` section
46287 * @param {string|null} source The name of the configuration source to report in the event of an error.
46288 * @returns {void}
46289 */
46290
46291
46292function validateGlobals(globalsConfig, source = null) {
46293 if (!globalsConfig) {
46294 return;
46295 }
46296
46297 Object.entries(globalsConfig).forEach(([configuredGlobal, configuredValue]) => {
46298 try {
46299 ConfigOps.normalizeConfigGlobal(configuredValue);
46300 } catch (err) {
46301 throw new Error("ESLint configuration of global '".concat(configuredGlobal, "' in ").concat(source, " is invalid:\n").concat(err.message));
46302 }
46303 });
46304}
46305/**
46306 * Validate `processor` configuration.
46307 * @param {string|undefined} processorName The processor name.
46308 * @param {string} source The name of config file.
46309 * @param {function(id:string): Processor} getProcessor The getter of defined processors.
46310 * @returns {void}
46311 */
46312
46313
46314function validateProcessor(processorName, source, getProcessor) {
46315 if (processorName && !getProcessor(processorName)) {
46316 throw new Error("ESLint configuration of processor in '".concat(source, "' is invalid: '").concat(processorName, "' was not found."));
46317 }
46318}
46319/**
46320 * Formats an array of schema validation errors.
46321 * @param {Array} errors An array of error messages to format.
46322 * @returns {string} Formatted error message
46323 */
46324
46325
46326function formatErrors(errors) {
46327 return errors.map(error => {
46328 if (error.keyword === "additionalProperties") {
46329 const formattedPropertyPath = error.dataPath.length ? "".concat(error.dataPath.slice(1), ".").concat(error.params.additionalProperty) : error.params.additionalProperty;
46330 return "Unexpected top-level property \"".concat(formattedPropertyPath, "\"");
46331 }
46332
46333 if (error.keyword === "type") {
46334 const formattedField = error.dataPath.slice(1);
46335 const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
46336 const formattedValue = JSON.stringify(error.data);
46337 return "Property \"".concat(formattedField, "\" is the wrong type (expected ").concat(formattedExpectedType, " but got `").concat(formattedValue, "`)");
46338 }
46339
46340 const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
46341 return "\"".concat(field, "\" ").concat(error.message, ". Value: ").concat(JSON.stringify(error.data));
46342 }).map(message => "\t- ".concat(message, ".\n")).join("");
46343}
46344/**
46345 * Validates the top level properties of the config object.
46346 * @param {Object} config The config object to validate.
46347 * @param {string} source The name of the configuration source to report in any errors.
46348 * @returns {void}
46349 */
46350
46351
46352function validateConfigSchema(config, source = null) {
46353 validateSchema = validateSchema || ajv.compile(configSchema);
46354
46355 if (!validateSchema(config)) {
46356 throw new Error("ESLint configuration in ".concat(source, " is invalid:\n").concat(formatErrors(validateSchema.errors)));
46357 }
46358
46359 if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
46360 emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
46361 }
46362}
46363/**
46364 * Validates an entire config object.
46365 * @param {Object} config The config object to validate.
46366 * @param {string} source The name of the configuration source to report in any errors.
46367 * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
46368 * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
46369 * @returns {void}
46370 */
46371
46372
46373function validate(config, source, getAdditionalRule, getAdditionalEnv) {
46374 validateConfigSchema(config, source);
46375 validateRules(config.rules, source, getAdditionalRule);
46376 validateEnvironment(config.env, source, getAdditionalEnv);
46377 validateGlobals(config.globals, source);
46378
46379 for (const override of config.overrides || []) {
46380 validateRules(override.rules, source, getAdditionalRule);
46381 validateEnvironment(override.env, source, getAdditionalEnv);
46382 validateGlobals(config.globals, source);
46383 }
46384}
46385
46386const validated = new WeakSet();
46387/**
46388 * Validate config array object.
46389 * @param {ConfigArray} configArray The config array to validate.
46390 * @returns {void}
46391 */
46392
46393function validateConfigArray(configArray) {
46394 const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
46395 const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
46396 const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); // Validate.
46397
46398 for (const element of configArray) {
46399 if (validated.has(element)) {
46400 continue;
46401 }
46402
46403 validated.add(element);
46404 validateEnvironment(element.env, element.name, getPluginEnv);
46405 validateGlobals(element.globals, element.name);
46406 validateProcessor(element.processor, element.name, getPluginProcessor);
46407 validateRules(element.rules, element.name, getPluginRule);
46408 }
46409} //------------------------------------------------------------------------------
46410// Public Interface
46411//------------------------------------------------------------------------------
46412
46413
46414module.exports = {
46415 getRuleOptionsSchema,
46416 validate,
46417 validateConfigArray,
46418 validateConfigSchema,
46419 validateRuleOptions
46420};
46421
46422/***/ }),
46423/* 412 */
46424/***/ (function(module, exports) {
46425
46426module.exports = require("util");
46427
46428/***/ }),
46429/* 413 */
46430/***/ (function(module, exports, __webpack_require__) {
46431
46432"use strict";
46433/**
46434 * @fileoverview Defines a schema for configs.
46435 * @author Sylvan Mably
46436 */
46437
46438
46439function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
46440
46441function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
46442
46443function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
46444
46445const baseConfigProperties = {
46446 $schema: {
46447 type: "string"
46448 },
46449 env: {
46450 type: "object"
46451 },
46452 extends: {
46453 $ref: "#/definitions/stringOrStrings"
46454 },
46455 globals: {
46456 type: "object"
46457 },
46458 overrides: {
46459 type: "array",
46460 items: {
46461 $ref: "#/definitions/overrideConfig"
46462 },
46463 additionalItems: false
46464 },
46465 parser: {
46466 type: ["string", "null"]
46467 },
46468 parserOptions: {
46469 type: "object"
46470 },
46471 plugins: {
46472 type: "array"
46473 },
46474 processor: {
46475 type: "string"
46476 },
46477 rules: {
46478 type: "object"
46479 },
46480 settings: {
46481 type: "object"
46482 },
46483 noInlineConfig: {
46484 type: "boolean"
46485 },
46486 reportUnusedDisableDirectives: {
46487 type: "boolean"
46488 },
46489 ecmaFeatures: {
46490 type: "object"
46491 } // deprecated; logs a warning when used
46492
46493};
46494const configSchema = {
46495 definitions: {
46496 stringOrStrings: {
46497 oneOf: [{
46498 type: "string"
46499 }, {
46500 type: "array",
46501 items: {
46502 type: "string"
46503 },
46504 additionalItems: false
46505 }]
46506 },
46507 stringOrStringsRequired: {
46508 oneOf: [{
46509 type: "string"
46510 }, {
46511 type: "array",
46512 items: {
46513 type: "string"
46514 },
46515 additionalItems: false,
46516 minItems: 1
46517 }]
46518 },
46519 // Config at top-level.
46520 objectConfig: {
46521 type: "object",
46522 properties: _objectSpread({
46523 root: {
46524 type: "boolean"
46525 },
46526 ignorePatterns: {
46527 $ref: "#/definitions/stringOrStrings"
46528 }
46529 }, baseConfigProperties),
46530 additionalProperties: false
46531 },
46532 // Config in `overrides`.
46533 overrideConfig: {
46534 type: "object",
46535 properties: _objectSpread({
46536 excludedFiles: {
46537 $ref: "#/definitions/stringOrStrings"
46538 },
46539 files: {
46540 $ref: "#/definitions/stringOrStringsRequired"
46541 }
46542 }, baseConfigProperties),
46543 required: ["files"],
46544 additionalProperties: false
46545 }
46546 },
46547 $ref: "#/definitions/objectConfig"
46548};
46549module.exports = configSchema;
46550
46551/***/ }),
46552/* 414 */
46553/***/ (function(module, exports, __webpack_require__) {
46554
46555"use strict";
46556/**
46557 * @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without
46558 * using the file-system directly.
46559 * @author Peter (Somogyvari) Metz
46560 */
46561
46562/* eslint sort-keys: ["error", "asc"] */
46563
46564const {
46565 LazyLoadingRuleMap
46566} = __webpack_require__(415);
46567/** @type {Map<string, import("../shared/types").Rule>} */
46568
46569
46570module.exports = new LazyLoadingRuleMap(Object.entries({
46571 "accessor-pairs": () => __webpack_require__(425),
46572 "array-bracket-newline": () => __webpack_require__(431),
46573 "array-bracket-spacing": () => __webpack_require__(432),
46574 "array-callback-return": () => __webpack_require__(433),
46575 "array-element-newline": () => __webpack_require__(434),
46576 "arrow-body-style": () => __webpack_require__(435),
46577 "arrow-parens": () => __webpack_require__(436),
46578 "arrow-spacing": () => __webpack_require__(437),
46579 "block-scoped-var": () => __webpack_require__(438),
46580 "block-spacing": () => __webpack_require__(439),
46581 "brace-style": () => __webpack_require__(440),
46582 "callback-return": () => __webpack_require__(441),
46583 camelcase: () => __webpack_require__(442),
46584 "capitalized-comments": () => __webpack_require__(443),
46585 "class-methods-use-this": () => __webpack_require__(445),
46586 "comma-dangle": () => __webpack_require__(446),
46587 "comma-spacing": () => __webpack_require__(447),
46588 "comma-style": () => __webpack_require__(448),
46589 complexity: () => __webpack_require__(449),
46590 "computed-property-spacing": () => __webpack_require__(450),
46591 "consistent-return": () => __webpack_require__(451),
46592 "consistent-this": () => __webpack_require__(452),
46593 "constructor-super": () => __webpack_require__(453),
46594 curly: () => __webpack_require__(454),
46595 "default-case": () => __webpack_require__(455),
46596 "default-case-last": () => __webpack_require__(456),
46597 "default-param-last": () => __webpack_require__(457),
46598 "dot-location": () => __webpack_require__(458),
46599 "dot-notation": () => __webpack_require__(459),
46600 "eol-last": () => __webpack_require__(461),
46601 eqeqeq: () => __webpack_require__(462),
46602 "for-direction": () => __webpack_require__(463),
46603 "func-call-spacing": () => __webpack_require__(464),
46604 "func-name-matching": () => __webpack_require__(465),
46605 "func-names": () => __webpack_require__(466),
46606 "func-style": () => __webpack_require__(467),
46607 "function-call-argument-newline": () => __webpack_require__(468),
46608 "function-paren-newline": () => __webpack_require__(469),
46609 "generator-star-spacing": () => __webpack_require__(470),
46610 "getter-return": () => __webpack_require__(471),
46611 "global-require": () => __webpack_require__(472),
46612 "grouped-accessor-pairs": () => __webpack_require__(473),
46613 "guard-for-in": () => __webpack_require__(474),
46614 "handle-callback-err": () => __webpack_require__(475),
46615 "id-blacklist": () => __webpack_require__(476),
46616 "id-length": () => __webpack_require__(477),
46617 "id-match": () => __webpack_require__(478),
46618 "implicit-arrow-linebreak": () => __webpack_require__(479),
46619 indent: () => __webpack_require__(480),
46620 "indent-legacy": () => __webpack_require__(482),
46621 "init-declarations": () => __webpack_require__(483),
46622 "jsx-quotes": () => __webpack_require__(484),
46623 "key-spacing": () => __webpack_require__(485),
46624 "keyword-spacing": () => __webpack_require__(486),
46625 "line-comment-position": () => __webpack_require__(487),
46626 "linebreak-style": () => __webpack_require__(488),
46627 "lines-around-comment": () => __webpack_require__(489),
46628 "lines-around-directive": () => __webpack_require__(490),
46629 "lines-between-class-members": () => __webpack_require__(491),
46630 "max-classes-per-file": () => __webpack_require__(492),
46631 "max-depth": () => __webpack_require__(493),
46632 "max-len": () => __webpack_require__(494),
46633 "max-lines": () => __webpack_require__(495),
46634 "max-lines-per-function": () => __webpack_require__(496),
46635 "max-nested-callbacks": () => __webpack_require__(497),
46636 "max-params": () => __webpack_require__(498),
46637 "max-statements": () => __webpack_require__(499),
46638 "max-statements-per-line": () => __webpack_require__(500),
46639 "multiline-comment-style": () => __webpack_require__(501),
46640 "multiline-ternary": () => __webpack_require__(502),
46641 "new-cap": () => __webpack_require__(503),
46642 "new-parens": () => __webpack_require__(504),
46643 "newline-after-var": () => __webpack_require__(505),
46644 "newline-before-return": () => __webpack_require__(506),
46645 "newline-per-chained-call": () => __webpack_require__(507),
46646 "no-alert": () => __webpack_require__(508),
46647 "no-array-constructor": () => __webpack_require__(509),
46648 "no-async-promise-executor": () => __webpack_require__(510),
46649 "no-await-in-loop": () => __webpack_require__(511),
46650 "no-bitwise": () => __webpack_require__(512),
46651 "no-buffer-constructor": () => __webpack_require__(513),
46652 "no-caller": () => __webpack_require__(514),
46653 "no-case-declarations": () => __webpack_require__(515),
46654 "no-catch-shadow": () => __webpack_require__(516),
46655 "no-class-assign": () => __webpack_require__(517),
46656 "no-compare-neg-zero": () => __webpack_require__(518),
46657 "no-cond-assign": () => __webpack_require__(519),
46658 "no-confusing-arrow": () => __webpack_require__(520),
46659 "no-console": () => __webpack_require__(521),
46660 "no-const-assign": () => __webpack_require__(522),
46661 "no-constant-condition": () => __webpack_require__(523),
46662 "no-constructor-return": () => __webpack_require__(524),
46663 "no-continue": () => __webpack_require__(525),
46664 "no-control-regex": () => __webpack_require__(526),
46665 "no-debugger": () => __webpack_require__(528),
46666 "no-delete-var": () => __webpack_require__(529),
46667 "no-div-regex": () => __webpack_require__(530),
46668 "no-dupe-args": () => __webpack_require__(531),
46669 "no-dupe-class-members": () => __webpack_require__(532),
46670 "no-dupe-else-if": () => __webpack_require__(533),
46671 "no-dupe-keys": () => __webpack_require__(534),
46672 "no-duplicate-case": () => __webpack_require__(535),
46673 "no-duplicate-imports": () => __webpack_require__(536),
46674 "no-else-return": () => __webpack_require__(537),
46675 "no-empty": () => __webpack_require__(539),
46676 "no-empty-character-class": () => __webpack_require__(540),
46677 "no-empty-function": () => __webpack_require__(541),
46678 "no-empty-pattern": () => __webpack_require__(542),
46679 "no-eq-null": () => __webpack_require__(543),
46680 "no-eval": () => __webpack_require__(544),
46681 "no-ex-assign": () => __webpack_require__(545),
46682 "no-extend-native": () => __webpack_require__(546),
46683 "no-extra-bind": () => __webpack_require__(547),
46684 "no-extra-boolean-cast": () => __webpack_require__(548),
46685 "no-extra-label": () => __webpack_require__(550),
46686 "no-extra-parens": () => __webpack_require__(551),
46687 "no-extra-semi": () => __webpack_require__(552),
46688 "no-fallthrough": () => __webpack_require__(553),
46689 "no-floating-decimal": () => __webpack_require__(554),
46690 "no-func-assign": () => __webpack_require__(555),
46691 "no-global-assign": () => __webpack_require__(556),
46692 "no-implicit-coercion": () => __webpack_require__(557),
46693 "no-implicit-globals": () => __webpack_require__(558),
46694 "no-implied-eval": () => __webpack_require__(559),
46695 "no-import-assign": () => __webpack_require__(560),
46696 "no-inline-comments": () => __webpack_require__(561),
46697 "no-inner-declarations": () => __webpack_require__(562),
46698 "no-invalid-regexp": () => __webpack_require__(563),
46699 "no-invalid-this": () => __webpack_require__(564),
46700 "no-irregular-whitespace": () => __webpack_require__(565),
46701 "no-iterator": () => __webpack_require__(566),
46702 "no-label-var": () => __webpack_require__(567),
46703 "no-labels": () => __webpack_require__(568),
46704 "no-lone-blocks": () => __webpack_require__(569),
46705 "no-lonely-if": () => __webpack_require__(570),
46706 "no-loop-func": () => __webpack_require__(571),
6a5a0f88
TL
46707 "no-loss-of-precision": () => __webpack_require__(572),
46708 "no-magic-numbers": () => __webpack_require__(573),
46709 "no-misleading-character-class": () => __webpack_require__(574),
46710 "no-mixed-operators": () => __webpack_require__(580),
46711 "no-mixed-requires": () => __webpack_require__(581),
46712 "no-mixed-spaces-and-tabs": () => __webpack_require__(582),
46713 "no-multi-assign": () => __webpack_require__(583),
46714 "no-multi-spaces": () => __webpack_require__(584),
46715 "no-multi-str": () => __webpack_require__(585),
46716 "no-multiple-empty-lines": () => __webpack_require__(586),
46717 "no-native-reassign": () => __webpack_require__(587),
46718 "no-negated-condition": () => __webpack_require__(588),
46719 "no-negated-in-lhs": () => __webpack_require__(589),
46720 "no-nested-ternary": () => __webpack_require__(590),
46721 "no-new": () => __webpack_require__(591),
46722 "no-new-func": () => __webpack_require__(592),
46723 "no-new-object": () => __webpack_require__(593),
46724 "no-new-require": () => __webpack_require__(594),
46725 "no-new-symbol": () => __webpack_require__(595),
46726 "no-new-wrappers": () => __webpack_require__(596),
46727 "no-obj-calls": () => __webpack_require__(597),
46728 "no-octal": () => __webpack_require__(598),
46729 "no-octal-escape": () => __webpack_require__(599),
46730 "no-param-reassign": () => __webpack_require__(600),
46731 "no-path-concat": () => __webpack_require__(601),
46732 "no-plusplus": () => __webpack_require__(602),
46733 "no-process-env": () => __webpack_require__(603),
46734 "no-process-exit": () => __webpack_require__(604),
46735 "no-proto": () => __webpack_require__(605),
46736 "no-prototype-builtins": () => __webpack_require__(606),
46737 "no-redeclare": () => __webpack_require__(607),
46738 "no-regex-spaces": () => __webpack_require__(608),
46739 "no-restricted-exports": () => __webpack_require__(609),
46740 "no-restricted-globals": () => __webpack_require__(610),
46741 "no-restricted-imports": () => __webpack_require__(611),
46742 "no-restricted-modules": () => __webpack_require__(613),
46743 "no-restricted-properties": () => __webpack_require__(614),
46744 "no-restricted-syntax": () => __webpack_require__(615),
46745 "no-return-assign": () => __webpack_require__(616),
46746 "no-return-await": () => __webpack_require__(617),
46747 "no-script-url": () => __webpack_require__(618),
46748 "no-self-assign": () => __webpack_require__(619),
46749 "no-self-compare": () => __webpack_require__(620),
46750 "no-sequences": () => __webpack_require__(621),
46751 "no-setter-return": () => __webpack_require__(622),
46752 "no-shadow": () => __webpack_require__(623),
46753 "no-shadow-restricted-names": () => __webpack_require__(624),
46754 "no-spaced-func": () => __webpack_require__(625),
46755 "no-sparse-arrays": () => __webpack_require__(626),
46756 "no-sync": () => __webpack_require__(627),
46757 "no-tabs": () => __webpack_require__(628),
46758 "no-template-curly-in-string": () => __webpack_require__(629),
46759 "no-ternary": () => __webpack_require__(630),
46760 "no-this-before-super": () => __webpack_require__(631),
46761 "no-throw-literal": () => __webpack_require__(632),
46762 "no-trailing-spaces": () => __webpack_require__(633),
46763 "no-undef": () => __webpack_require__(634),
46764 "no-undef-init": () => __webpack_require__(635),
46765 "no-undefined": () => __webpack_require__(636),
46766 "no-underscore-dangle": () => __webpack_require__(637),
46767 "no-unexpected-multiline": () => __webpack_require__(638),
46768 "no-unmodified-loop-condition": () => __webpack_require__(639),
46769 "no-unneeded-ternary": () => __webpack_require__(641),
46770 "no-unreachable": () => __webpack_require__(642),
46771 "no-unsafe-finally": () => __webpack_require__(643),
46772 "no-unsafe-negation": () => __webpack_require__(644),
46773 "no-unused-expressions": () => __webpack_require__(645),
46774 "no-unused-labels": () => __webpack_require__(646),
46775 "no-unused-vars": () => __webpack_require__(647),
46776 "no-use-before-define": () => __webpack_require__(648),
46777 "no-useless-backreference": () => __webpack_require__(649),
46778 "no-useless-call": () => __webpack_require__(650),
46779 "no-useless-catch": () => __webpack_require__(651),
46780 "no-useless-computed-key": () => __webpack_require__(652),
46781 "no-useless-concat": () => __webpack_require__(653),
46782 "no-useless-constructor": () => __webpack_require__(654),
46783 "no-useless-escape": () => __webpack_require__(655),
46784 "no-useless-rename": () => __webpack_require__(656),
46785 "no-useless-return": () => __webpack_require__(657),
46786 "no-var": () => __webpack_require__(658),
46787 "no-void": () => __webpack_require__(659),
46788 "no-warning-comments": () => __webpack_require__(660),
46789 "no-whitespace-before-property": () => __webpack_require__(661),
46790 "no-with": () => __webpack_require__(662),
46791 "nonblock-statement-body-position": () => __webpack_require__(663),
46792 "object-curly-newline": () => __webpack_require__(664),
46793 "object-curly-spacing": () => __webpack_require__(665),
46794 "object-property-newline": () => __webpack_require__(666),
46795 "object-shorthand": () => __webpack_require__(667),
46796 "one-var": () => __webpack_require__(668),
46797 "one-var-declaration-per-line": () => __webpack_require__(669),
46798 "operator-assignment": () => __webpack_require__(670),
46799 "operator-linebreak": () => __webpack_require__(671),
46800 "padded-blocks": () => __webpack_require__(672),
46801 "padding-line-between-statements": () => __webpack_require__(673),
46802 "prefer-arrow-callback": () => __webpack_require__(674),
46803 "prefer-const": () => __webpack_require__(675),
46804 "prefer-destructuring": () => __webpack_require__(676),
46805 "prefer-exponentiation-operator": () => __webpack_require__(677),
46806 "prefer-named-capture-group": () => __webpack_require__(678),
46807 "prefer-numeric-literals": () => __webpack_require__(679),
46808 "prefer-object-spread": () => __webpack_require__(680),
46809 "prefer-promise-reject-errors": () => __webpack_require__(681),
46810 "prefer-reflect": () => __webpack_require__(682),
46811 "prefer-regex-literals": () => __webpack_require__(683),
46812 "prefer-rest-params": () => __webpack_require__(684),
46813 "prefer-spread": () => __webpack_require__(685),
46814 "prefer-template": () => __webpack_require__(686),
46815 "quote-props": () => __webpack_require__(687),
46816 quotes: () => __webpack_require__(688),
46817 radix: () => __webpack_require__(689),
46818 "require-atomic-updates": () => __webpack_require__(690),
46819 "require-await": () => __webpack_require__(691),
46820 "require-jsdoc": () => __webpack_require__(692),
46821 "require-unicode-regexp": () => __webpack_require__(693),
46822 "require-yield": () => __webpack_require__(694),
46823 "rest-spread-spacing": () => __webpack_require__(695),
46824 semi: () => __webpack_require__(696),
46825 "semi-spacing": () => __webpack_require__(697),
46826 "semi-style": () => __webpack_require__(698),
46827 "sort-imports": () => __webpack_require__(699),
46828 "sort-keys": () => __webpack_require__(700),
46829 "sort-vars": () => __webpack_require__(702),
46830 "space-before-blocks": () => __webpack_require__(703),
46831 "space-before-function-paren": () => __webpack_require__(704),
46832 "space-in-parens": () => __webpack_require__(705),
46833 "space-infix-ops": () => __webpack_require__(706),
46834 "space-unary-ops": () => __webpack_require__(707),
46835 "spaced-comment": () => __webpack_require__(708),
46836 strict: () => __webpack_require__(709),
46837 "switch-colon-spacing": () => __webpack_require__(710),
46838 "symbol-description": () => __webpack_require__(711),
46839 "template-curly-spacing": () => __webpack_require__(712),
46840 "template-tag-spacing": () => __webpack_require__(713),
46841 "unicode-bom": () => __webpack_require__(714),
46842 "use-isnan": () => __webpack_require__(715),
46843 "valid-jsdoc": () => __webpack_require__(716),
46844 "valid-typeof": () => __webpack_require__(721),
46845 "vars-on-top": () => __webpack_require__(722),
46846 "wrap-iife": () => __webpack_require__(723),
46847 "wrap-regex": () => __webpack_require__(724),
46848 "yield-star-spacing": () => __webpack_require__(725),
46849 yoda: () => __webpack_require__(726)
eb39fafa
DC
46850}));
46851
46852/***/ }),
46853/* 415 */
46854/***/ (function(module, exports, __webpack_require__) {
46855
46856"use strict";
46857/**
46858 * @fileoverview `Map` to load rules lazily.
46859 * @author Toru Nagashima <https://github.com/mysticatea>
46860 */
46861
46862
46863const debug = __webpack_require__(416)("eslint:rules");
46864/** @typedef {import("./types").Rule} Rule */
46865
46866/**
46867 * The `Map` object that loads each rule when it's accessed.
46868 * @example
46869 * const rules = new LazyLoadingRuleMap([
46870 * ["eqeqeq", () => require("eqeqeq")],
46871 * ["semi", () => require("semi")],
46872 * ["no-unused-vars", () => require("no-unused-vars")],
46873 * ])
46874 *
46875 * rules.get("semi") // call `() => require("semi")` here.
46876 *
46877 * @extends {Map<string, () => Rule>}
46878 */
46879
46880
46881class LazyLoadingRuleMap extends Map {
46882 /**
46883 * Initialize this map.
46884 * @param {Array<[string, function(): Rule]>} loaders The rule loaders.
46885 */
46886 constructor(loaders) {
46887 let remaining = loaders.length;
46888 super(debug.enabled ? loaders.map(([ruleId, load]) => {
46889 let cache = null;
46890 return [ruleId, () => {
46891 if (!cache) {
46892 debug("Loading rule %o (remaining=%d)", ruleId, --remaining);
46893 cache = load();
46894 }
46895
46896 return cache;
46897 }];
46898 }) : loaders); // `super(...iterable)` uses `this.set()`, so disable it here.
46899
46900 Object.defineProperty(LazyLoadingRuleMap.prototype, "set", {
46901 configurable: true,
46902 value: void 0
46903 });
46904 }
46905 /**
46906 * Get a rule.
46907 * Each rule will be loaded on the first access.
46908 * @param {string} ruleId The rule ID to get.
46909 * @returns {Rule|undefined} The rule.
46910 */
46911
46912
46913 get(ruleId) {
46914 const load = super.get(ruleId);
46915 return load && load();
46916 }
46917 /**
46918 * Iterate rules.
46919 * @returns {IterableIterator<Rule>} Rules.
46920 */
46921
46922
46923 *values() {
46924 for (const load of super.values()) {
46925 yield load();
46926 }
46927 }
46928 /**
46929 * Iterate rules.
46930 * @returns {IterableIterator<[string, Rule]>} Rules.
46931 */
46932
46933
46934 *entries() {
46935 for (const [ruleId, load] of super.entries()) {
46936 yield [ruleId, load()];
46937 }
46938 }
46939 /**
46940 * Call a function with each rule.
46941 * @param {Function} callbackFn The callback function.
46942 * @param {any} [thisArg] The object to pass to `this` of the callback function.
46943 * @returns {void}
46944 */
46945
46946
46947 forEach(callbackFn, thisArg) {
46948 for (const [ruleId, load] of super.entries()) {
46949 callbackFn.call(thisArg, load(), ruleId, this);
46950 }
46951 }
46952
46953} // Forbid mutation.
46954
46955
46956Object.defineProperties(LazyLoadingRuleMap.prototype, {
46957 clear: {
46958 configurable: true,
46959 value: void 0
46960 },
46961 delete: {
46962 configurable: true,
46963 value: void 0
46964 },
46965 [Symbol.iterator]: {
46966 configurable: true,
46967 writable: true,
46968 value: LazyLoadingRuleMap.prototype.entries
46969 }
46970});
46971module.exports = {
46972 LazyLoadingRuleMap
46973};
46974
46975/***/ }),
46976/* 416 */
46977/***/ (function(module, exports, __webpack_require__) {
46978
46979/**
46980 * Detect Electron renderer / nwjs process, which is node, but we should
46981 * treat as a browser.
46982 */
46983if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
46984 module.exports = __webpack_require__(417);
46985} else {
46986 module.exports = __webpack_require__(420);
46987}
46988
46989/***/ }),
46990/* 417 */
46991/***/ (function(module, exports, __webpack_require__) {
46992
46993/* eslint-env browser */
46994
46995/**
46996 * This is the web browser implementation of `debug()`.
46997 */
46998exports.log = log;
46999exports.formatArgs = formatArgs;
47000exports.save = save;
47001exports.load = load;
47002exports.useColors = useColors;
47003exports.storage = localstorage();
47004/**
47005 * Colors.
47006 */
47007
47008exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
47009/**
47010 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
47011 * and the Firebug extension (any Firefox version) are known
47012 * to support "%c" CSS customizations.
47013 *
47014 * TODO: add a `localStorage` variable to explicitly enable/disable colors
47015 */
47016// eslint-disable-next-line complexity
47017
47018function useColors() {
47019 // NB: In an Electron preload script, document will be defined but not fully
47020 // initialized. Since we know we're in Chrome, we'll just detect this case
47021 // explicitly
47022 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
47023 return true;
47024 } // Internet Explorer and Edge do not support colors.
47025
47026
47027 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
47028 return false;
47029 } // Is webkit? http://stackoverflow.com/a/16459606/376773
47030 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
47031
47032
47033 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
47034 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
47035 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
47036 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
47037 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
47038}
47039/**
47040 * Colorize log arguments if enabled.
47041 *
47042 * @api public
47043 */
47044
47045
47046function formatArgs(args) {
47047 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
47048
47049 if (!this.useColors) {
47050 return;
47051 }
47052
47053 const c = 'color: ' + this.color;
47054 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
47055 // arguments passed either before or after the %c, so we need to
47056 // figure out the correct index to insert the CSS into
47057
47058 let index = 0;
47059 let lastC = 0;
47060 args[0].replace(/%[a-zA-Z%]/g, match => {
47061 if (match === '%%') {
47062 return;
47063 }
47064
47065 index++;
47066
47067 if (match === '%c') {
47068 // We only are interested in the *last* %c
47069 // (the user may have provided their own)
47070 lastC = index;
47071 }
47072 });
47073 args.splice(lastC, 0, c);
47074}
47075/**
47076 * Invokes `console.log()` when available.
47077 * No-op when `console.log` is not a "function".
47078 *
47079 * @api public
47080 */
47081
47082
47083function log(...args) {
47084 // This hackery is required for IE8/9, where
47085 // the `console.log` function doesn't have 'apply'
47086 return typeof console === 'object' && console.log && console.log(...args);
47087}
47088/**
47089 * Save `namespaces`.
47090 *
47091 * @param {String} namespaces
47092 * @api private
47093 */
47094
47095
47096function save(namespaces) {
47097 try {
47098 if (namespaces) {
47099 exports.storage.setItem('debug', namespaces);
47100 } else {
47101 exports.storage.removeItem('debug');
47102 }
47103 } catch (error) {// Swallow
47104 // XXX (@Qix-) should we be logging these?
47105 }
47106}
47107/**
47108 * Load `namespaces`.
47109 *
47110 * @return {String} returns the previously persisted debug modes
47111 * @api private
47112 */
47113
47114
47115function load() {
47116 let r;
47117
47118 try {
47119 r = exports.storage.getItem('debug');
47120 } catch (error) {} // Swallow
47121 // XXX (@Qix-) should we be logging these?
47122 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
47123
47124
47125 if (!r && typeof process !== 'undefined' && 'env' in process) {
47126 r = process.env.DEBUG;
47127 }
47128
47129 return r;
47130}
47131/**
47132 * Localstorage attempts to return the localstorage.
47133 *
47134 * This is necessary because safari throws
47135 * when a user disables cookies/localstorage
47136 * and you attempt to access it.
47137 *
47138 * @return {LocalStorage}
47139 * @api private
47140 */
47141
47142
47143function localstorage() {
47144 try {
47145 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
47146 // The Browser also has localStorage in the global context.
47147 return localStorage;
47148 } catch (error) {// Swallow
47149 // XXX (@Qix-) should we be logging these?
47150 }
47151}
47152
47153module.exports = __webpack_require__(418)(exports);
47154const {
47155 formatters
47156} = module.exports;
47157/**
47158 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
47159 */
47160
47161formatters.j = function (v) {
47162 try {
47163 return JSON.stringify(v);
47164 } catch (error) {
47165 return '[UnexpectedJSONParseError]: ' + error.message;
47166 }
47167};
47168
47169/***/ }),
47170/* 418 */
47171/***/ (function(module, exports, __webpack_require__) {
47172
47173/**
47174 * This is the common logic for both the Node.js and web browser
47175 * implementations of `debug()`.
47176 */
47177function setup(env) {
47178 createDebug.debug = createDebug;
47179 createDebug.default = createDebug;
47180 createDebug.coerce = coerce;
47181 createDebug.disable = disable;
47182 createDebug.enable = enable;
47183 createDebug.enabled = enabled;
47184 createDebug.humanize = __webpack_require__(419);
47185 Object.keys(env).forEach(key => {
47186 createDebug[key] = env[key];
47187 });
47188 /**
47189 * Active `debug` instances.
47190 */
47191
47192 createDebug.instances = [];
47193 /**
47194 * The currently active debug mode names, and names to skip.
47195 */
47196
47197 createDebug.names = [];
47198 createDebug.skips = [];
47199 /**
47200 * Map of special "%n" handling functions, for the debug "format" argument.
47201 *
47202 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
47203 */
47204
47205 createDebug.formatters = {};
47206 /**
47207 * Selects a color for a debug namespace
47208 * @param {String} namespace The namespace string for the for the debug instance to be colored
47209 * @return {Number|String} An ANSI color code for the given namespace
47210 * @api private
47211 */
47212
47213 function selectColor(namespace) {
47214 let hash = 0;
47215
47216 for (let i = 0; i < namespace.length; i++) {
47217 hash = (hash << 5) - hash + namespace.charCodeAt(i);
47218 hash |= 0; // Convert to 32bit integer
47219 }
47220
47221 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
47222 }
47223
47224 createDebug.selectColor = selectColor;
47225 /**
47226 * Create a debugger with the given `namespace`.
47227 *
47228 * @param {String} namespace
47229 * @return {Function}
47230 * @api public
47231 */
47232
47233 function createDebug(namespace) {
47234 let prevTime;
47235
47236 function debug(...args) {
47237 // Disabled?
47238 if (!debug.enabled) {
47239 return;
47240 }
47241
47242 const self = debug; // Set `diff` timestamp
47243
47244 const curr = Number(new Date());
47245 const ms = curr - (prevTime || curr);
47246 self.diff = ms;
47247 self.prev = prevTime;
47248 self.curr = curr;
47249 prevTime = curr;
47250 args[0] = createDebug.coerce(args[0]);
47251
47252 if (typeof args[0] !== 'string') {
47253 // Anything else let's inspect with %O
47254 args.unshift('%O');
47255 } // Apply any `formatters` transformations
47256
47257
47258 let index = 0;
47259 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
47260 // If we encounter an escaped % then don't increase the array index
47261 if (match === '%%') {
47262 return match;
47263 }
47264
47265 index++;
47266 const formatter = createDebug.formatters[format];
47267
47268 if (typeof formatter === 'function') {
47269 const val = args[index];
47270 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
47271
47272 args.splice(index, 1);
47273 index--;
47274 }
47275
47276 return match;
47277 }); // Apply env-specific formatting (colors, etc.)
47278
47279 createDebug.formatArgs.call(self, args);
47280 const logFn = self.log || createDebug.log;
47281 logFn.apply(self, args);
47282 }
47283
47284 debug.namespace = namespace;
47285 debug.enabled = createDebug.enabled(namespace);
47286 debug.useColors = createDebug.useColors();
47287 debug.color = selectColor(namespace);
47288 debug.destroy = destroy;
47289 debug.extend = extend; // Debug.formatArgs = formatArgs;
47290 // debug.rawLog = rawLog;
47291 // env-specific initialization logic for debug instances
47292
47293 if (typeof createDebug.init === 'function') {
47294 createDebug.init(debug);
47295 }
47296
47297 createDebug.instances.push(debug);
47298 return debug;
47299 }
47300
47301 function destroy() {
47302 const index = createDebug.instances.indexOf(this);
47303
47304 if (index !== -1) {
47305 createDebug.instances.splice(index, 1);
47306 return true;
47307 }
47308
47309 return false;
47310 }
47311
47312 function extend(namespace, delimiter) {
47313 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
47314 newDebug.log = this.log;
47315 return newDebug;
47316 }
47317 /**
47318 * Enables a debug mode by namespaces. This can include modes
47319 * separated by a colon and wildcards.
47320 *
47321 * @param {String} namespaces
47322 * @api public
47323 */
47324
47325
47326 function enable(namespaces) {
47327 createDebug.save(namespaces);
47328 createDebug.names = [];
47329 createDebug.skips = [];
47330 let i;
47331 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
47332 const len = split.length;
47333
47334 for (i = 0; i < len; i++) {
47335 if (!split[i]) {
47336 // ignore empty strings
47337 continue;
47338 }
47339
47340 namespaces = split[i].replace(/\*/g, '.*?');
47341
47342 if (namespaces[0] === '-') {
47343 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
47344 } else {
47345 createDebug.names.push(new RegExp('^' + namespaces + '$'));
47346 }
47347 }
47348
47349 for (i = 0; i < createDebug.instances.length; i++) {
47350 const instance = createDebug.instances[i];
47351 instance.enabled = createDebug.enabled(instance.namespace);
47352 }
47353 }
47354 /**
47355 * Disable debug output.
47356 *
47357 * @return {String} namespaces
47358 * @api public
47359 */
47360
47361
47362 function disable() {
47363 const namespaces = [...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)].join(',');
47364 createDebug.enable('');
47365 return namespaces;
47366 }
47367 /**
47368 * Returns true if the given mode name is enabled, false otherwise.
47369 *
47370 * @param {String} name
47371 * @return {Boolean}
47372 * @api public
47373 */
47374
47375
47376 function enabled(name) {
47377 if (name[name.length - 1] === '*') {
47378 return true;
47379 }
47380
47381 let i;
47382 let len;
47383
47384 for (i = 0, len = createDebug.skips.length; i < len; i++) {
47385 if (createDebug.skips[i].test(name)) {
47386 return false;
47387 }
47388 }
47389
47390 for (i = 0, len = createDebug.names.length; i < len; i++) {
47391 if (createDebug.names[i].test(name)) {
47392 return true;
47393 }
47394 }
47395
47396 return false;
47397 }
47398 /**
47399 * Convert regexp to namespace
47400 *
47401 * @param {RegExp} regxep
47402 * @return {String} namespace
47403 * @api private
47404 */
47405
47406
47407 function toNamespace(regexp) {
47408 return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
47409 }
47410 /**
47411 * Coerce `val`.
47412 *
47413 * @param {Mixed} val
47414 * @return {Mixed}
47415 * @api private
47416 */
47417
47418
47419 function coerce(val) {
47420 if (val instanceof Error) {
47421 return val.stack || val.message;
47422 }
47423
47424 return val;
47425 }
47426
47427 createDebug.enable(createDebug.load());
47428 return createDebug;
47429}
47430
47431module.exports = setup;
47432
47433/***/ }),
47434/* 419 */
47435/***/ (function(module, exports) {
47436
47437/**
47438 * Helpers.
47439 */
47440var s = 1000;
47441var m = s * 60;
47442var h = m * 60;
47443var d = h * 24;
47444var w = d * 7;
47445var y = d * 365.25;
47446/**
47447 * Parse or format the given `val`.
47448 *
47449 * Options:
47450 *
47451 * - `long` verbose formatting [false]
47452 *
47453 * @param {String|Number} val
47454 * @param {Object} [options]
47455 * @throws {Error} throw an error if val is not a non-empty string or a number
47456 * @return {String|Number}
47457 * @api public
47458 */
47459
47460module.exports = function (val, options) {
47461 options = options || {};
47462 var type = typeof val;
47463
47464 if (type === 'string' && val.length > 0) {
47465 return parse(val);
47466 } else if (type === 'number' && isFinite(val)) {
47467 return options.long ? fmtLong(val) : fmtShort(val);
47468 }
47469
47470 throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
47471};
47472/**
47473 * Parse the given `str` and return milliseconds.
47474 *
47475 * @param {String} str
47476 * @return {Number}
47477 * @api private
47478 */
47479
47480
47481function parse(str) {
47482 str = String(str);
47483
47484 if (str.length > 100) {
47485 return;
47486 }
47487
47488 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
47489
47490 if (!match) {
47491 return;
47492 }
47493
47494 var n = parseFloat(match[1]);
47495 var type = (match[2] || 'ms').toLowerCase();
47496
47497 switch (type) {
47498 case 'years':
47499 case 'year':
47500 case 'yrs':
47501 case 'yr':
47502 case 'y':
47503 return n * y;
47504
47505 case 'weeks':
47506 case 'week':
47507 case 'w':
47508 return n * w;
47509
47510 case 'days':
47511 case 'day':
47512 case 'd':
47513 return n * d;
47514
47515 case 'hours':
47516 case 'hour':
47517 case 'hrs':
47518 case 'hr':
47519 case 'h':
47520 return n * h;
47521
47522 case 'minutes':
47523 case 'minute':
47524 case 'mins':
47525 case 'min':
47526 case 'm':
47527 return n * m;
47528
47529 case 'seconds':
47530 case 'second':
47531 case 'secs':
47532 case 'sec':
47533 case 's':
47534 return n * s;
47535
47536 case 'milliseconds':
47537 case 'millisecond':
47538 case 'msecs':
47539 case 'msec':
47540 case 'ms':
47541 return n;
47542
47543 default:
47544 return undefined;
47545 }
47546}
47547/**
47548 * Short format for `ms`.
47549 *
47550 * @param {Number} ms
47551 * @return {String}
47552 * @api private
47553 */
47554
47555
47556function fmtShort(ms) {
47557 var msAbs = Math.abs(ms);
47558
47559 if (msAbs >= d) {
47560 return Math.round(ms / d) + 'd';
47561 }
47562
47563 if (msAbs >= h) {
47564 return Math.round(ms / h) + 'h';
47565 }
47566
47567 if (msAbs >= m) {
47568 return Math.round(ms / m) + 'm';
47569 }
47570
47571 if (msAbs >= s) {
47572 return Math.round(ms / s) + 's';
47573 }
47574
47575 return ms + 'ms';
47576}
47577/**
47578 * Long format for `ms`.
47579 *
47580 * @param {Number} ms
47581 * @return {String}
47582 * @api private
47583 */
47584
47585
47586function fmtLong(ms) {
47587 var msAbs = Math.abs(ms);
47588
47589 if (msAbs >= d) {
47590 return plural(ms, msAbs, d, 'day');
47591 }
47592
47593 if (msAbs >= h) {
47594 return plural(ms, msAbs, h, 'hour');
47595 }
47596
47597 if (msAbs >= m) {
47598 return plural(ms, msAbs, m, 'minute');
47599 }
47600
47601 if (msAbs >= s) {
47602 return plural(ms, msAbs, s, 'second');
47603 }
47604
47605 return ms + ' ms';
47606}
47607/**
47608 * Pluralization helper.
47609 */
47610
47611
47612function plural(ms, msAbs, n, name) {
47613 var isPlural = msAbs >= n * 1.5;
47614 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
47615}
47616
47617/***/ }),
47618/* 420 */
47619/***/ (function(module, exports, __webpack_require__) {
47620
47621/**
47622 * Module dependencies.
47623 */
47624const tty = __webpack_require__(421);
47625
47626const util = __webpack_require__(412);
47627/**
47628 * This is the Node.js implementation of `debug()`.
47629 */
47630
47631
47632exports.init = init;
47633exports.log = log;
47634exports.formatArgs = formatArgs;
47635exports.save = save;
47636exports.load = load;
47637exports.useColors = useColors;
47638/**
47639 * Colors.
47640 */
47641
47642exports.colors = [6, 2, 3, 4, 5, 1];
47643
47644try {
47645 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
47646 // eslint-disable-next-line import/no-extraneous-dependencies
47647 const supportsColor = __webpack_require__(422);
47648
47649 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
47650 exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221];
47651 }
47652} catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be.
47653
47654/**
47655 * Build up the default `inspectOpts` object from the environment variables.
47656 *
47657 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
47658 */
47659
47660
47661exports.inspectOpts = Object.keys(process.env).filter(key => {
47662 return /^debug_/i.test(key);
47663}).reduce((obj, key) => {
47664 // Camel-case
47665 const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
47666 return k.toUpperCase();
47667 }); // Coerce string value into JS value
47668
47669 let val = process.env[key];
47670
47671 if (/^(yes|on|true|enabled)$/i.test(val)) {
47672 val = true;
47673 } else if (/^(no|off|false|disabled)$/i.test(val)) {
47674 val = false;
47675 } else if (val === 'null') {
47676 val = null;
47677 } else {
47678 val = Number(val);
47679 }
47680
47681 obj[prop] = val;
47682 return obj;
47683}, {});
47684/**
47685 * Is stdout a TTY? Colored output is enabled when `true`.
47686 */
47687
47688function useColors() {
47689 return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
47690}
47691/**
47692 * Adds ANSI color escape codes if enabled.
47693 *
47694 * @api public
47695 */
47696
47697
47698function formatArgs(args) {
47699 const {
47700 namespace: name,
47701 useColors
47702 } = this;
47703
47704 if (useColors) {
47705 const c = this.color;
47706 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
47707 const prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m");
47708 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
47709 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
47710 } else {
47711 args[0] = getDate() + name + ' ' + args[0];
47712 }
47713}
47714
47715function getDate() {
47716 if (exports.inspectOpts.hideDate) {
47717 return '';
47718 }
47719
47720 return new Date().toISOString() + ' ';
47721}
47722/**
47723 * Invokes `util.format()` with the specified arguments and writes to stderr.
47724 */
47725
47726
47727function log(...args) {
47728 return process.stderr.write(util.format(...args) + '\n');
47729}
47730/**
47731 * Save `namespaces`.
47732 *
47733 * @param {String} namespaces
47734 * @api private
47735 */
47736
47737
47738function save(namespaces) {
47739 if (namespaces) {
47740 process.env.DEBUG = namespaces;
47741 } else {
47742 // If you set a process.env field to null or undefined, it gets cast to the
47743 // string 'null' or 'undefined'. Just delete instead.
47744 delete process.env.DEBUG;
47745 }
47746}
47747/**
47748 * Load `namespaces`.
47749 *
47750 * @return {String} returns the previously persisted debug modes
47751 * @api private
47752 */
47753
47754
47755function load() {
47756 return process.env.DEBUG;
47757}
47758/**
47759 * Init logic for `debug` instances.
47760 *
47761 * Create a new `inspectOpts` object in case `useColors` is set
47762 * differently for a particular `debug` instance.
47763 */
47764
47765
47766function init(debug) {
47767 debug.inspectOpts = {};
47768 const keys = Object.keys(exports.inspectOpts);
47769
47770 for (let i = 0; i < keys.length; i++) {
47771 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
47772 }
47773}
47774
47775module.exports = __webpack_require__(418)(exports);
47776const {
47777 formatters
47778} = module.exports;
47779/**
47780 * Map %o to `util.inspect()`, all on a single line.
47781 */
47782
47783formatters.o = function (v) {
47784 this.inspectOpts.colors = this.useColors;
47785 return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, ' ');
47786};
47787/**
47788 * Map %O to `util.inspect()`, allowing multiple lines if needed.
47789 */
47790
47791
47792formatters.O = function (v) {
47793 this.inspectOpts.colors = this.useColors;
47794 return util.inspect(v, this.inspectOpts);
47795};
47796
47797/***/ }),
47798/* 421 */
47799/***/ (function(module, exports) {
47800
47801module.exports = require("tty");
47802
47803/***/ }),
47804/* 422 */
47805/***/ (function(module, exports, __webpack_require__) {
47806
47807"use strict";
47808
47809
47810const os = __webpack_require__(423);
47811
47812const hasFlag = __webpack_require__(424);
47813
47814const env = process.env;
47815let forceColor;
47816
47817if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
47818 forceColor = false;
47819} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
47820 forceColor = true;
47821}
47822
47823if ('FORCE_COLOR' in env) {
47824 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
47825}
47826
47827function translateLevel(level) {
47828 if (level === 0) {
47829 return false;
47830 }
47831
47832 return {
47833 level,
47834 hasBasic: true,
47835 has256: level >= 2,
47836 has16m: level >= 3
47837 };
47838}
47839
47840function supportsColor(stream) {
47841 if (forceColor === false) {
47842 return 0;
47843 }
47844
47845 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
47846 return 3;
47847 }
47848
47849 if (hasFlag('color=256')) {
47850 return 2;
47851 }
47852
47853 if (stream && !stream.isTTY && forceColor !== true) {
47854 return 0;
47855 }
47856
47857 const min = forceColor ? 1 : 0;
47858
47859 if (process.platform === 'win32') {
47860 // Node.js 7.5.0 is the first version of Node.js to include a patch to
47861 // libuv that enables 256 color output on Windows. Anything earlier and it
47862 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
47863 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
47864 // release that supports 256 colors. Windows 10 build 14931 is the first release
47865 // that supports 16m/TrueColor.
47866 const osRelease = os.release().split('.');
47867
47868 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
47869 return Number(osRelease[2]) >= 14931 ? 3 : 2;
47870 }
47871
47872 return 1;
47873 }
47874
47875 if ('CI' in env) {
47876 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
47877 return 1;
47878 }
47879
47880 return min;
47881 }
47882
47883 if ('TEAMCITY_VERSION' in env) {
47884 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
47885 }
47886
47887 if (env.COLORTERM === 'truecolor') {
47888 return 3;
47889 }
47890
47891 if ('TERM_PROGRAM' in env) {
47892 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
47893
47894 switch (env.TERM_PROGRAM) {
47895 case 'iTerm.app':
47896 return version >= 3 ? 3 : 2;
47897
47898 case 'Apple_Terminal':
47899 return 2;
47900 // No default
47901 }
47902 }
47903
47904 if (/-256(color)?$/i.test(env.TERM)) {
47905 return 2;
47906 }
47907
47908 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
47909 return 1;
47910 }
47911
47912 if ('COLORTERM' in env) {
47913 return 1;
47914 }
47915
47916 if (env.TERM === 'dumb') {
47917 return min;
47918 }
47919
47920 return min;
47921}
47922
47923function getSupportLevel(stream) {
47924 const level = supportsColor(stream);
47925 return translateLevel(level);
47926}
47927
47928module.exports = {
47929 supportsColor: getSupportLevel,
47930 stdout: getSupportLevel(process.stdout),
47931 stderr: getSupportLevel(process.stderr)
47932};
47933
47934/***/ }),
47935/* 423 */
47936/***/ (function(module, exports) {
47937
47938module.exports = require("os");
47939
47940/***/ }),
47941/* 424 */
47942/***/ (function(module, exports, __webpack_require__) {
47943
47944"use strict";
47945
47946
47947module.exports = (flag, argv) => {
47948 argv = argv || process.argv;
47949 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
47950 const pos = argv.indexOf(prefix + flag);
47951 const terminatorPos = argv.indexOf('--');
47952 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
47953};
47954
47955/***/ }),
47956/* 425 */
47957/***/ (function(module, exports, __webpack_require__) {
47958
47959"use strict";
47960/**
6a5a0f88 47961 * @fileoverview Rule to enforce getter and setter pairs in objects and classes.
eb39fafa
DC
47962 * @author Gyandeep Singh
47963 */
47964 //------------------------------------------------------------------------------
47965// Requirements
47966//------------------------------------------------------------------------------
47967
47968const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
47969// Typedefs
47970//------------------------------------------------------------------------------
47971
47972/**
47973 * Property name if it can be computed statically, otherwise the list of the tokens of the key node.
47974 * @typedef {string|Token[]} Key
47975 */
47976
47977/**
47978 * Accessor nodes with the same key.
47979 * @typedef {Object} AccessorData
47980 * @property {Key} key Accessor's key
47981 * @property {ASTNode[]} getters List of getter nodes.
47982 * @property {ASTNode[]} setters List of setter nodes.
47983 */
47984//------------------------------------------------------------------------------
47985// Helpers
47986//------------------------------------------------------------------------------
47987
47988/**
47989 * Checks whether or not the given lists represent the equal tokens in the same order.
47990 * Tokens are compared by their properties, not by instance.
47991 * @param {Token[]} left First list of tokens.
47992 * @param {Token[]} right Second list of tokens.
47993 * @returns {boolean} `true` if the lists have same tokens.
47994 */
47995
47996
47997function areEqualTokenLists(left, right) {
47998 if (left.length !== right.length) {
47999 return false;
48000 }
48001
48002 for (let i = 0; i < left.length; i++) {
48003 const leftToken = left[i],
48004 rightToken = right[i];
48005
48006 if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) {
48007 return false;
48008 }
48009 }
48010
48011 return true;
48012}
48013/**
48014 * Checks whether or not the given keys are equal.
48015 * @param {Key} left First key.
48016 * @param {Key} right Second key.
48017 * @returns {boolean} `true` if the keys are equal.
48018 */
48019
48020
48021function areEqualKeys(left, right) {
48022 if (typeof left === "string" && typeof right === "string") {
48023 // Statically computed names.
48024 return left === right;
48025 }
48026
48027 if (Array.isArray(left) && Array.isArray(right)) {
48028 // Token lists.
48029 return areEqualTokenLists(left, right);
48030 }
48031
48032 return false;
48033}
48034/**
48035 * Checks whether or not a given node is of an accessor kind ('get' or 'set').
48036 * @param {ASTNode} node A node to check.
48037 * @returns {boolean} `true` if the node is of an accessor kind.
48038 */
48039
48040
48041function isAccessorKind(node) {
48042 return node.kind === "get" || node.kind === "set";
48043}
48044/**
48045 * Checks whether or not a given node is an `Identifier` node which was named a given name.
48046 * @param {ASTNode} node A node to check.
48047 * @param {string} name An expected name of the node.
48048 * @returns {boolean} `true` if the node is an `Identifier` node which was named as expected.
48049 */
48050
48051
48052function isIdentifier(node, name) {
48053 return node.type === "Identifier" && node.name === name;
48054}
48055/**
48056 * Checks whether or not a given node is an argument of a specified method call.
48057 * @param {ASTNode} node A node to check.
48058 * @param {number} index An expected index of the node in arguments.
48059 * @param {string} object An expected name of the object of the method.
48060 * @param {string} property An expected name of the method.
48061 * @returns {boolean} `true` if the node is an argument of the specified method call.
48062 */
48063
48064
48065function isArgumentOfMethodCall(node, index, object, property) {
48066 const parent = node.parent;
48067 return parent.type === "CallExpression" && parent.callee.type === "MemberExpression" && parent.callee.computed === false && isIdentifier(parent.callee.object, object) && isIdentifier(parent.callee.property, property) && parent.arguments[index] === node;
48068}
48069/**
48070 * Checks whether or not a given node is a property descriptor.
48071 * @param {ASTNode} node A node to check.
48072 * @returns {boolean} `true` if the node is a property descriptor.
48073 */
48074
48075
48076function isPropertyDescriptor(node) {
48077 // Object.defineProperty(obj, "foo", {set: ...})
48078 if (isArgumentOfMethodCall(node, 2, "Object", "defineProperty") || isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty")) {
48079 return true;
48080 }
48081 /*
48082 * Object.defineProperties(obj, {foo: {set: ...}})
48083 * Object.create(proto, {foo: {set: ...}})
48084 */
48085
48086
48087 const grandparent = node.parent.parent;
48088 return grandparent.type === "ObjectExpression" && (isArgumentOfMethodCall(grandparent, 1, "Object", "create") || isArgumentOfMethodCall(grandparent, 1, "Object", "defineProperties"));
48089} //------------------------------------------------------------------------------
48090// Rule Definition
48091//------------------------------------------------------------------------------
48092
48093
48094module.exports = {
48095 meta: {
48096 type: "suggestion",
48097 docs: {
48098 description: "enforce getter and setter pairs in objects and classes",
48099 category: "Best Practices",
48100 recommended: false,
48101 url: "https://eslint.org/docs/rules/accessor-pairs"
48102 },
48103 schema: [{
48104 type: "object",
48105 properties: {
48106 getWithoutSet: {
48107 type: "boolean",
48108 default: false
48109 },
48110 setWithoutGet: {
48111 type: "boolean",
48112 default: true
48113 },
48114 enforceForClassMembers: {
48115 type: "boolean",
48116 default: true
48117 }
48118 },
48119 additionalProperties: false
48120 }],
48121 messages: {
48122 missingGetterInPropertyDescriptor: "Getter is not present in property descriptor.",
48123 missingSetterInPropertyDescriptor: "Setter is not present in property descriptor.",
48124 missingGetterInObjectLiteral: "Getter is not present for {{ name }}.",
48125 missingSetterInObjectLiteral: "Setter is not present for {{ name }}.",
48126 missingGetterInClass: "Getter is not present for class {{ name }}.",
48127 missingSetterInClass: "Setter is not present for class {{ name }}."
48128 }
48129 },
48130
48131 create(context) {
48132 const config = context.options[0] || {};
48133 const checkGetWithoutSet = config.getWithoutSet === true;
48134 const checkSetWithoutGet = config.setWithoutGet !== false;
48135 const enforceForClassMembers = config.enforceForClassMembers !== false;
48136 const sourceCode = context.getSourceCode();
48137 /**
48138 * Reports the given node.
48139 * @param {ASTNode} node The node to report.
48140 * @param {string} messageKind "missingGetter" or "missingSetter".
48141 * @returns {void}
48142 * @private
48143 */
48144
48145 function report(node, messageKind) {
48146 if (node.type === "Property") {
48147 context.report({
48148 node,
48149 messageId: "".concat(messageKind, "InObjectLiteral"),
48150 loc: astUtils.getFunctionHeadLoc(node.value, sourceCode),
48151 data: {
48152 name: astUtils.getFunctionNameWithKind(node.value)
48153 }
48154 });
48155 } else if (node.type === "MethodDefinition") {
48156 context.report({
48157 node,
48158 messageId: "".concat(messageKind, "InClass"),
48159 loc: astUtils.getFunctionHeadLoc(node.value, sourceCode),
48160 data: {
48161 name: astUtils.getFunctionNameWithKind(node.value)
48162 }
48163 });
48164 } else {
48165 context.report({
48166 node,
48167 messageId: "".concat(messageKind, "InPropertyDescriptor")
48168 });
48169 }
48170 }
48171 /**
48172 * Reports each of the nodes in the given list using the same messageId.
48173 * @param {ASTNode[]} nodes Nodes to report.
48174 * @param {string} messageKind "missingGetter" or "missingSetter".
48175 * @returns {void}
48176 * @private
48177 */
48178
48179
48180 function reportList(nodes, messageKind) {
48181 for (const node of nodes) {
48182 report(node, messageKind);
48183 }
48184 }
48185 /**
48186 * Creates a new `AccessorData` object for the given getter or setter node.
48187 * @param {ASTNode} node A getter or setter node.
48188 * @returns {AccessorData} New `AccessorData` object that contains the given node.
48189 * @private
48190 */
48191
48192
48193 function createAccessorData(node) {
48194 const name = astUtils.getStaticPropertyName(node);
48195 const key = name !== null ? name : sourceCode.getTokens(node.key);
48196 return {
48197 key,
48198 getters: node.kind === "get" ? [node] : [],
48199 setters: node.kind === "set" ? [node] : []
48200 };
48201 }
48202 /**
48203 * Merges the given `AccessorData` object into the given accessors list.
48204 * @param {AccessorData[]} accessors The list to merge into.
48205 * @param {AccessorData} accessorData The object to merge.
48206 * @returns {AccessorData[]} The same instance with the merged object.
48207 * @private
48208 */
48209
48210
48211 function mergeAccessorData(accessors, accessorData) {
48212 const equalKeyElement = accessors.find(a => areEqualKeys(a.key, accessorData.key));
48213
48214 if (equalKeyElement) {
48215 equalKeyElement.getters.push(...accessorData.getters);
48216 equalKeyElement.setters.push(...accessorData.setters);
48217 } else {
48218 accessors.push(accessorData);
48219 }
48220
48221 return accessors;
48222 }
48223 /**
48224 * Checks accessor pairs in the given list of nodes.
48225 * @param {ASTNode[]} nodes The list to check.
48226 * @returns {void}
48227 * @private
48228 */
48229
48230
48231 function checkList(nodes) {
48232 const accessors = nodes.filter(isAccessorKind).map(createAccessorData).reduce(mergeAccessorData, []);
48233
48234 for (const {
48235 getters,
48236 setters
48237 } of accessors) {
48238 if (checkSetWithoutGet && setters.length && !getters.length) {
48239 reportList(setters, "missingGetter");
48240 }
48241
48242 if (checkGetWithoutSet && getters.length && !setters.length) {
48243 reportList(getters, "missingSetter");
48244 }
48245 }
48246 }
48247 /**
48248 * Checks accessor pairs in an object literal.
48249 * @param {ASTNode} node `ObjectExpression` node to check.
48250 * @returns {void}
48251 * @private
48252 */
48253
48254
48255 function checkObjectLiteral(node) {
48256 checkList(node.properties.filter(p => p.type === "Property"));
48257 }
48258 /**
48259 * Checks accessor pairs in a property descriptor.
48260 * @param {ASTNode} node Property descriptor `ObjectExpression` node to check.
48261 * @returns {void}
48262 * @private
48263 */
48264
48265
48266 function checkPropertyDescriptor(node) {
48267 const namesToCheck = node.properties.filter(p => p.type === "Property" && p.kind === "init" && !p.computed).map(({
48268 key
48269 }) => key.name);
48270 const hasGetter = namesToCheck.includes("get");
48271 const hasSetter = namesToCheck.includes("set");
48272
48273 if (checkSetWithoutGet && hasSetter && !hasGetter) {
48274 report(node, "missingGetter");
48275 }
48276
48277 if (checkGetWithoutSet && hasGetter && !hasSetter) {
48278 report(node, "missingSetter");
48279 }
48280 }
48281 /**
48282 * Checks the given object expression as an object literal and as a possible property descriptor.
48283 * @param {ASTNode} node `ObjectExpression` node to check.
48284 * @returns {void}
48285 * @private
48286 */
48287
48288
48289 function checkObjectExpression(node) {
48290 checkObjectLiteral(node);
48291
48292 if (isPropertyDescriptor(node)) {
48293 checkPropertyDescriptor(node);
48294 }
48295 }
48296 /**
48297 * Checks the given class body.
48298 * @param {ASTNode} node `ClassBody` node to check.
48299 * @returns {void}
48300 * @private
48301 */
48302
48303
48304 function checkClassBody(node) {
48305 const methodDefinitions = node.body.filter(m => m.type === "MethodDefinition");
48306 checkList(methodDefinitions.filter(m => m.static));
48307 checkList(methodDefinitions.filter(m => !m.static));
48308 }
48309
48310 const listeners = {};
48311
48312 if (checkSetWithoutGet || checkGetWithoutSet) {
48313 listeners.ObjectExpression = checkObjectExpression;
48314
48315 if (enforceForClassMembers) {
48316 listeners.ClassBody = checkClassBody;
48317 }
48318 }
48319
48320 return listeners;
48321 }
48322
48323};
48324
48325/***/ }),
48326/* 426 */
48327/***/ (function(module, exports, __webpack_require__) {
48328
48329"use strict";
48330/**
48331 * @fileoverview Common utils for AST.
48332 * @author Gyandeep Singh
48333 */
48334 //------------------------------------------------------------------------------
48335// Requirements
48336//------------------------------------------------------------------------------
48337
48338const esutils = __webpack_require__(427);
48339
48340const espree = __webpack_require__(394);
48341
48342const lodash = __webpack_require__(403);
48343
48344const {
48345 breakableTypePattern,
48346 createGlobalLinebreakMatcher,
48347 lineBreakPattern,
48348 shebangPattern
48349} = __webpack_require__(409); //------------------------------------------------------------------------------
48350// Helpers
48351//------------------------------------------------------------------------------
48352
48353
48354const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
48355const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
48356const arrayOrTypedArrayPattern = /Array$/u;
48357const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u;
48358const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
48359const thisTagPattern = /^[\s*]*@this/mu;
48360const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
48361const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); // A set of node types that can contain a list of statements
48362
48363const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]);
48364const DECIMAL_INTEGER_PATTERN = /^(0|[1-9]\d*)$/u;
48365const OCTAL_ESCAPE_PATTERN = /^(?:[^\\]|\\[^0-7]|\\0(?![0-9]))*\\(?:[1-7]|0[0-9])/u;
48366/**
48367 * Checks reference if is non initializer and writable.
48368 * @param {Reference} reference A reference to check.
48369 * @param {int} index The index of the reference in the references.
48370 * @param {Reference[]} references The array that the reference belongs to.
48371 * @returns {boolean} Success/Failure
48372 * @private
48373 */
48374
48375function isModifyingReference(reference, index, references) {
48376 const identifier = reference.identifier;
48377 /*
48378 * Destructuring assignments can have multiple default value, so
48379 * possibly there are multiple writeable references for the same
48380 * identifier.
48381 */
48382
48383 const modifyingDifferentIdentifier = index === 0 || references[index - 1].identifier !== identifier;
48384 return identifier && reference.init === false && reference.isWrite() && modifyingDifferentIdentifier;
48385}
48386/**
48387 * Checks whether the given string starts with uppercase or not.
48388 * @param {string} s The string to check.
48389 * @returns {boolean} `true` if the string starts with uppercase.
48390 */
48391
48392
48393function startsWithUpperCase(s) {
48394 return s[0] !== s[0].toLocaleLowerCase();
48395}
48396/**
48397 * Checks whether or not a node is a constructor.
48398 * @param {ASTNode} node A function node to check.
48399 * @returns {boolean} Wehether or not a node is a constructor.
48400 */
48401
48402
48403function isES5Constructor(node) {
48404 return node.id && startsWithUpperCase(node.id.name);
48405}
48406/**
48407 * Finds a function node from ancestors of a node.
48408 * @param {ASTNode} node A start node to find.
48409 * @returns {Node|null} A found function node.
48410 */
48411
48412
48413function getUpperFunction(node) {
48414 for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
48415 if (anyFunctionPattern.test(currentNode.type)) {
48416 return currentNode;
48417 }
48418 }
48419
48420 return null;
48421}
48422/**
48423 * Checks whether a given node is a function node or not.
48424 * The following types are function nodes:
48425 *
48426 * - ArrowFunctionExpression
48427 * - FunctionDeclaration
48428 * - FunctionExpression
48429 * @param {ASTNode|null} node A node to check.
48430 * @returns {boolean} `true` if the node is a function node.
48431 */
48432
48433
48434function isFunction(node) {
48435 return Boolean(node && anyFunctionPattern.test(node.type));
48436}
48437/**
48438 * Checks whether a given node is a loop node or not.
48439 * The following types are loop nodes:
48440 *
48441 * - DoWhileStatement
48442 * - ForInStatement
48443 * - ForOfStatement
48444 * - ForStatement
48445 * - WhileStatement
48446 * @param {ASTNode|null} node A node to check.
48447 * @returns {boolean} `true` if the node is a loop node.
48448 */
48449
48450
48451function isLoop(node) {
48452 return Boolean(node && anyLoopPattern.test(node.type));
48453}
48454/**
48455 * Checks whether the given node is in a loop or not.
48456 * @param {ASTNode} node The node to check.
48457 * @returns {boolean} `true` if the node is in a loop.
48458 */
48459
48460
48461function isInLoop(node) {
48462 for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) {
48463 if (isLoop(currentNode)) {
48464 return true;
48465 }
48466 }
48467
48468 return false;
48469}
48470/**
48471 * Checks whether or not a node is `null` or `undefined`.
48472 * @param {ASTNode} node A node to check.
48473 * @returns {boolean} Whether or not the node is a `null` or `undefined`.
48474 * @public
48475 */
48476
48477
48478function isNullOrUndefined(node) {
48479 return module.exports.isNullLiteral(node) || node.type === "Identifier" && node.name === "undefined" || node.type === "UnaryExpression" && node.operator === "void";
48480}
48481/**
48482 * Checks whether or not a node is callee.
48483 * @param {ASTNode} node A node to check.
48484 * @returns {boolean} Whether or not the node is callee.
48485 */
48486
48487
48488function isCallee(node) {
48489 return node.parent.type === "CallExpression" && node.parent.callee === node;
48490}
48491/**
48492 * Checks whether or not a node is `Reflect.apply`.
48493 * @param {ASTNode} node A node to check.
48494 * @returns {boolean} Whether or not the node is a `Reflect.apply`.
48495 */
48496
48497
48498function isReflectApply(node) {
48499 return node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "Reflect" && node.property.type === "Identifier" && node.property.name === "apply" && node.computed === false;
48500}
48501/**
48502 * Checks whether or not a node is `Array.from`.
48503 * @param {ASTNode} node A node to check.
48504 * @returns {boolean} Whether or not the node is a `Array.from`.
48505 */
48506
48507
48508function isArrayFromMethod(node) {
48509 return node.type === "MemberExpression" && node.object.type === "Identifier" && arrayOrTypedArrayPattern.test(node.object.name) && node.property.type === "Identifier" && node.property.name === "from" && node.computed === false;
48510}
48511/**
48512 * Checks whether or not a node is a method which has `thisArg`.
48513 * @param {ASTNode} node A node to check.
48514 * @returns {boolean} Whether or not the node is a method which has `thisArg`.
48515 */
48516
48517
48518function isMethodWhichHasThisArg(node) {
48519 for (let currentNode = node; currentNode.type === "MemberExpression" && !currentNode.computed; currentNode = currentNode.property) {
48520 if (currentNode.property.type === "Identifier") {
48521 return arrayMethodPattern.test(currentNode.property.name);
48522 }
48523 }
48524
48525 return false;
48526}
48527/**
48528 * Creates the negate function of the given function.
48529 * @param {Function} f The function to negate.
48530 * @returns {Function} Negated function.
48531 */
48532
48533
48534function negate(f) {
48535 return token => !f(token);
48536}
48537/**
48538 * Checks whether or not a node has a `@this` tag in its comments.
48539 * @param {ASTNode} node A node to check.
48540 * @param {SourceCode} sourceCode A SourceCode instance to get comments.
48541 * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
48542 */
48543
48544
48545function hasJSDocThisTag(node, sourceCode) {
48546 const jsdocComment = sourceCode.getJSDocComment(node);
48547
48548 if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
48549 return true;
48550 } // Checks `@this` in its leading comments for callbacks,
48551 // because callbacks don't have its JSDoc comment.
48552 // e.g.
48553 // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
48554
48555
48556 return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value));
48557}
48558/**
48559 * Determines if a node is surrounded by parentheses.
48560 * @param {SourceCode} sourceCode The ESLint source code object
48561 * @param {ASTNode} node The node to be checked.
48562 * @returns {boolean} True if the node is parenthesised.
48563 * @private
48564 */
48565
48566
48567function isParenthesised(sourceCode, node) {
48568 const previousToken = sourceCode.getTokenBefore(node),
48569 nextToken = sourceCode.getTokenAfter(node);
48570 return Boolean(previousToken && nextToken) && previousToken.value === "(" && previousToken.range[1] <= node.range[0] && nextToken.value === ")" && nextToken.range[0] >= node.range[1];
48571}
48572/**
48573 * Checks if the given token is an arrow token or not.
48574 * @param {Token} token The token to check.
48575 * @returns {boolean} `true` if the token is an arrow token.
48576 */
48577
48578
48579function isArrowToken(token) {
48580 return token.value === "=>" && token.type === "Punctuator";
48581}
48582/**
48583 * Checks if the given token is a comma token or not.
48584 * @param {Token} token The token to check.
48585 * @returns {boolean} `true` if the token is a comma token.
48586 */
48587
48588
48589function isCommaToken(token) {
48590 return token.value === "," && token.type === "Punctuator";
48591}
48592/**
48593 * Checks if the given token is a dot token or not.
48594 * @param {Token} token The token to check.
48595 * @returns {boolean} `true` if the token is a dot token.
48596 */
48597
48598
48599function isDotToken(token) {
48600 return token.value === "." && token.type === "Punctuator";
48601}
48602/**
48603 * Checks if the given token is a semicolon token or not.
48604 * @param {Token} token The token to check.
48605 * @returns {boolean} `true` if the token is a semicolon token.
48606 */
48607
48608
48609function isSemicolonToken(token) {
48610 return token.value === ";" && token.type === "Punctuator";
48611}
48612/**
48613 * Checks if the given token is a colon token or not.
48614 * @param {Token} token The token to check.
48615 * @returns {boolean} `true` if the token is a colon token.
48616 */
48617
48618
48619function isColonToken(token) {
48620 return token.value === ":" && token.type === "Punctuator";
48621}
48622/**
48623 * Checks if the given token is an opening parenthesis token or not.
48624 * @param {Token} token The token to check.
48625 * @returns {boolean} `true` if the token is an opening parenthesis token.
48626 */
48627
48628
48629function isOpeningParenToken(token) {
48630 return token.value === "(" && token.type === "Punctuator";
48631}
48632/**
48633 * Checks if the given token is a closing parenthesis token or not.
48634 * @param {Token} token The token to check.
48635 * @returns {boolean} `true` if the token is a closing parenthesis token.
48636 */
48637
48638
48639function isClosingParenToken(token) {
48640 return token.value === ")" && token.type === "Punctuator";
48641}
48642/**
48643 * Checks if the given token is an opening square bracket token or not.
48644 * @param {Token} token The token to check.
48645 * @returns {boolean} `true` if the token is an opening square bracket token.
48646 */
48647
48648
48649function isOpeningBracketToken(token) {
48650 return token.value === "[" && token.type === "Punctuator";
48651}
48652/**
48653 * Checks if the given token is a closing square bracket token or not.
48654 * @param {Token} token The token to check.
48655 * @returns {boolean} `true` if the token is a closing square bracket token.
48656 */
48657
48658
48659function isClosingBracketToken(token) {
48660 return token.value === "]" && token.type === "Punctuator";
48661}
48662/**
48663 * Checks if the given token is an opening brace token or not.
48664 * @param {Token} token The token to check.
48665 * @returns {boolean} `true` if the token is an opening brace token.
48666 */
48667
48668
48669function isOpeningBraceToken(token) {
48670 return token.value === "{" && token.type === "Punctuator";
48671}
48672/**
48673 * Checks if the given token is a closing brace token or not.
48674 * @param {Token} token The token to check.
48675 * @returns {boolean} `true` if the token is a closing brace token.
48676 */
48677
48678
48679function isClosingBraceToken(token) {
48680 return token.value === "}" && token.type === "Punctuator";
48681}
48682/**
48683 * Checks if the given token is a comment token or not.
48684 * @param {Token} token The token to check.
48685 * @returns {boolean} `true` if the token is a comment token.
48686 */
48687
48688
48689function isCommentToken(token) {
48690 return token.type === "Line" || token.type === "Block" || token.type === "Shebang";
48691}
48692/**
48693 * Checks if the given token is a keyword token or not.
48694 * @param {Token} token The token to check.
48695 * @returns {boolean} `true` if the token is a keyword token.
48696 */
48697
48698
48699function isKeywordToken(token) {
48700 return token.type === "Keyword";
48701}
48702/**
48703 * Gets the `(` token of the given function node.
48704 * @param {ASTNode} node The function node to get.
48705 * @param {SourceCode} sourceCode The source code object to get tokens.
48706 * @returns {Token} `(` token.
48707 */
48708
48709
48710function getOpeningParenOfParams(node, sourceCode) {
48711 return node.id ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) : sourceCode.getFirstToken(node, isOpeningParenToken);
48712}
48713/**
48714 * Checks whether or not the tokens of two given nodes are same.
48715 * @param {ASTNode} left A node 1 to compare.
48716 * @param {ASTNode} right A node 2 to compare.
48717 * @param {SourceCode} sourceCode The ESLint source code object.
48718 * @returns {boolean} the source code for the given node.
48719 */
48720
48721
48722function equalTokens(left, right, sourceCode) {
48723 const tokensL = sourceCode.getTokens(left);
48724 const tokensR = sourceCode.getTokens(right);
48725
48726 if (tokensL.length !== tokensR.length) {
48727 return false;
48728 }
48729
48730 for (let i = 0; i < tokensL.length; ++i) {
48731 if (tokensL[i].type !== tokensR[i].type || tokensL[i].value !== tokensR[i].value) {
48732 return false;
48733 }
48734 }
48735
48736 return true;
48737} //------------------------------------------------------------------------------
48738// Public Interface
48739//------------------------------------------------------------------------------
48740
48741
48742module.exports = {
48743 COMMENTS_IGNORE_PATTERN,
48744 LINEBREAKS,
48745 LINEBREAK_MATCHER: lineBreakPattern,
48746 SHEBANG_MATCHER: shebangPattern,
48747 STATEMENT_LIST_PARENTS,
48748
48749 /**
48750 * Determines whether two adjacent tokens are on the same line.
48751 * @param {Object} left The left token object.
48752 * @param {Object} right The right token object.
48753 * @returns {boolean} Whether or not the tokens are on the same line.
48754 * @public
48755 */
48756 isTokenOnSameLine(left, right) {
48757 return left.loc.end.line === right.loc.start.line;
48758 },
48759
48760 isNullOrUndefined,
48761 isCallee,
48762 isES5Constructor,
48763 getUpperFunction,
48764 isFunction,
48765 isLoop,
48766 isInLoop,
48767 isArrayFromMethod,
48768 isParenthesised,
48769 createGlobalLinebreakMatcher,
48770 equalTokens,
48771 isArrowToken,
48772 isClosingBraceToken,
48773 isClosingBracketToken,
48774 isClosingParenToken,
48775 isColonToken,
48776 isCommaToken,
48777 isCommentToken,
48778 isDotToken,
48779 isKeywordToken,
48780 isNotClosingBraceToken: negate(isClosingBraceToken),
48781 isNotClosingBracketToken: negate(isClosingBracketToken),
48782 isNotClosingParenToken: negate(isClosingParenToken),
48783 isNotColonToken: negate(isColonToken),
48784 isNotCommaToken: negate(isCommaToken),
48785 isNotDotToken: negate(isDotToken),
48786 isNotOpeningBraceToken: negate(isOpeningBraceToken),
48787 isNotOpeningBracketToken: negate(isOpeningBracketToken),
48788 isNotOpeningParenToken: negate(isOpeningParenToken),
48789 isNotSemicolonToken: negate(isSemicolonToken),
48790 isOpeningBraceToken,
48791 isOpeningBracketToken,
48792 isOpeningParenToken,
48793 isSemicolonToken,
48794
48795 /**
48796 * Checks whether or not a given node is a string literal.
48797 * @param {ASTNode} node A node to check.
48798 * @returns {boolean} `true` if the node is a string literal.
48799 */
48800 isStringLiteral(node) {
48801 return node.type === "Literal" && typeof node.value === "string" || node.type === "TemplateLiteral";
48802 },
48803
48804 /**
48805 * Checks whether a given node is a breakable statement or not.
48806 * The node is breakable if the node is one of the following type:
48807 *
48808 * - DoWhileStatement
48809 * - ForInStatement
48810 * - ForOfStatement
48811 * - ForStatement
48812 * - SwitchStatement
48813 * - WhileStatement
48814 * @param {ASTNode} node A node to check.
48815 * @returns {boolean} `true` if the node is breakable.
48816 */
48817 isBreakableStatement(node) {
48818 return breakableTypePattern.test(node.type);
48819 },
48820
48821 /**
48822 * Gets references which are non initializer and writable.
48823 * @param {Reference[]} references An array of references.
48824 * @returns {Reference[]} An array of only references which are non initializer and writable.
48825 * @public
48826 */
48827 getModifyingReferences(references) {
48828 return references.filter(isModifyingReference);
48829 },
48830
48831 /**
48832 * Validate that a string passed in is surrounded by the specified character
48833 * @param {string} val The text to check.
48834 * @param {string} character The character to see if it's surrounded by.
48835 * @returns {boolean} True if the text is surrounded by the character, false if not.
48836 * @private
48837 */
48838 isSurroundedBy(val, character) {
48839 return val[0] === character && val[val.length - 1] === character;
48840 },
48841
48842 /**
48843 * Returns whether the provided node is an ESLint directive comment or not
48844 * @param {Line|Block} node The comment token to be checked
48845 * @returns {boolean} `true` if the node is an ESLint directive comment
48846 */
48847 isDirectiveComment(node) {
48848 const comment = node.value.trim();
48849 return node.type === "Line" && comment.indexOf("eslint-") === 0 || node.type === "Block" && (comment.indexOf("global ") === 0 || comment.indexOf("eslint ") === 0 || comment.indexOf("eslint-") === 0);
48850 },
48851
48852 /**
48853 * Gets the trailing statement of a given node.
48854 *
48855 * if (code)
48856 * consequent;
48857 *
48858 * When taking this `IfStatement`, returns `consequent;` statement.
48859 * @param {ASTNode} A node to get.
48860 * @returns {ASTNode|null} The trailing statement's node.
48861 */
48862 getTrailingStatement: esutils.ast.trailingStatement,
48863
48864 /**
48865 * Finds the variable by a given name in a given scope and its upper scopes.
48866 * @param {eslint-scope.Scope} initScope A scope to start find.
48867 * @param {string} name A variable name to find.
48868 * @returns {eslint-scope.Variable|null} A found variable or `null`.
48869 */
48870 getVariableByName(initScope, name) {
48871 let scope = initScope;
48872
48873 while (scope) {
48874 const variable = scope.set.get(name);
48875
48876 if (variable) {
48877 return variable;
48878 }
48879
48880 scope = scope.upper;
48881 }
48882
48883 return null;
48884 },
48885
48886 /**
48887 * Checks whether or not a given function node is the default `this` binding.
48888 *
48889 * First, this checks the node:
48890 *
48891 * - The function name does not start with uppercase. It's a convention to capitalize the names
48892 * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
48893 * - The function does not have a JSDoc comment that has a @this tag.
48894 *
48895 * Next, this checks the location of the node.
48896 * If the location is below, this judges `this` is valid.
48897 *
48898 * - The location is not on an object literal.
48899 * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
48900 * functions only, as the name of the variable is considered to be the name of the function in this case.
48901 * This check is not performed if `capIsConstructor` is set to `false`.
48902 * - The location is not on an ES2015 class.
48903 * - Its `bind`/`call`/`apply` method is not called directly.
48904 * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
48905 * @param {ASTNode} node A function node to check.
48906 * @param {SourceCode} sourceCode A SourceCode instance to get comments.
48907 * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
48908 * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
48909 * @returns {boolean} The function node is the default `this` binding.
48910 */
48911 isDefaultThisBinding(node, sourceCode, {
48912 capIsConstructor = true
48913 } = {}) {
48914 if (capIsConstructor && isES5Constructor(node) || hasJSDocThisTag(node, sourceCode)) {
48915 return false;
48916 }
48917
48918 const isAnonymous = node.id === null;
48919 let currentNode = node;
48920
48921 while (currentNode) {
48922 const parent = currentNode.parent;
48923
48924 switch (parent.type) {
48925 /*
48926 * Looks up the destination.
48927 * e.g., obj.foo = nativeFoo || function foo() { ... };
48928 */
48929 case "LogicalExpression":
48930 case "ConditionalExpression":
48931 currentNode = parent;
48932 break;
48933
48934 /*
48935 * If the upper function is IIFE, checks the destination of the return value.
48936 * e.g.
48937 * obj.foo = (function() {
48938 * // setup...
48939 * return function foo() { ... };
48940 * })();
48941 * obj.foo = (() =>
48942 * function foo() { ... }
48943 * )();
48944 */
48945
48946 case "ReturnStatement":
48947 {
48948 const func = getUpperFunction(parent);
48949
48950 if (func === null || !isCallee(func)) {
48951 return true;
48952 }
48953
48954 currentNode = func.parent;
48955 break;
48956 }
48957
48958 case "ArrowFunctionExpression":
48959 if (currentNode !== parent.body || !isCallee(parent)) {
48960 return true;
48961 }
48962
48963 currentNode = parent.parent;
48964 break;
48965
48966 /*
48967 * e.g.
48968 * var obj = { foo() { ... } };
48969 * var obj = { foo: function() { ... } };
48970 * class A { constructor() { ... } }
48971 * class A { foo() { ... } }
48972 * class A { get foo() { ... } }
48973 * class A { set foo() { ... } }
48974 * class A { static foo() { ... } }
48975 */
48976
48977 case "Property":
48978 case "MethodDefinition":
48979 return parent.value !== currentNode;
48980
48981 /*
48982 * e.g.
48983 * obj.foo = function foo() { ... };
48984 * Foo = function() { ... };
48985 * [obj.foo = function foo() { ... }] = a;
48986 * [Foo = function() { ... }] = a;
48987 */
48988
48989 case "AssignmentExpression":
48990 case "AssignmentPattern":
48991 if (parent.left.type === "MemberExpression") {
48992 return false;
48993 }
48994
48995 if (capIsConstructor && isAnonymous && parent.left.type === "Identifier" && startsWithUpperCase(parent.left.name)) {
48996 return false;
48997 }
48998
48999 return true;
49000
49001 /*
49002 * e.g.
49003 * var Foo = function() { ... };
49004 */
49005
49006 case "VariableDeclarator":
49007 return !(capIsConstructor && isAnonymous && parent.init === currentNode && parent.id.type === "Identifier" && startsWithUpperCase(parent.id.name));
49008
49009 /*
49010 * e.g.
49011 * var foo = function foo() { ... }.bind(obj);
49012 * (function foo() { ... }).call(obj);
49013 * (function foo() { ... }).apply(obj, []);
49014 */
49015
49016 case "MemberExpression":
49017 return parent.object !== currentNode || parent.property.type !== "Identifier" || !bindOrCallOrApplyPattern.test(parent.property.name) || !isCallee(parent) || parent.parent.arguments.length === 0 || isNullOrUndefined(parent.parent.arguments[0]);
49018
49019 /*
49020 * e.g.
49021 * Reflect.apply(function() {}, obj, []);
49022 * Array.from([], function() {}, obj);
49023 * list.forEach(function() {}, obj);
49024 */
49025
49026 case "CallExpression":
49027 if (isReflectApply(parent.callee)) {
49028 return parent.arguments.length !== 3 || parent.arguments[0] !== currentNode || isNullOrUndefined(parent.arguments[1]);
49029 }
49030
49031 if (isArrayFromMethod(parent.callee)) {
49032 return parent.arguments.length !== 3 || parent.arguments[1] !== currentNode || isNullOrUndefined(parent.arguments[2]);
49033 }
49034
49035 if (isMethodWhichHasThisArg(parent.callee)) {
49036 return parent.arguments.length !== 2 || parent.arguments[0] !== currentNode || isNullOrUndefined(parent.arguments[1]);
49037 }
49038
49039 return true;
49040 // Otherwise `this` is default.
49041
49042 default:
49043 return true;
49044 }
49045 }
49046 /* istanbul ignore next */
49047
49048
49049 return true;
49050 },
49051
49052 /**
49053 * Get the precedence level based on the node type
49054 * @param {ASTNode} node node to evaluate
49055 * @returns {int} precedence level
49056 * @private
49057 */
49058 getPrecedence(node) {
49059 switch (node.type) {
49060 case "SequenceExpression":
49061 return 0;
49062
49063 case "AssignmentExpression":
49064 case "ArrowFunctionExpression":
49065 case "YieldExpression":
49066 return 1;
49067
49068 case "ConditionalExpression":
49069 return 3;
49070
49071 case "LogicalExpression":
49072 switch (node.operator) {
49073 case "||":
49074 return 4;
49075
49076 case "&&":
49077 return 5;
49078 // no default
49079 }
49080
49081 /* falls through */
49082
49083 case "BinaryExpression":
49084 switch (node.operator) {
49085 case "|":
49086 return 6;
49087
49088 case "^":
49089 return 7;
49090
49091 case "&":
49092 return 8;
49093
49094 case "==":
49095 case "!=":
49096 case "===":
49097 case "!==":
49098 return 9;
49099
49100 case "<":
49101 case "<=":
49102 case ">":
49103 case ">=":
49104 case "in":
49105 case "instanceof":
49106 return 10;
49107
49108 case "<<":
49109 case ">>":
49110 case ">>>":
49111 return 11;
49112
49113 case "+":
49114 case "-":
49115 return 12;
49116
49117 case "*":
49118 case "/":
49119 case "%":
49120 return 13;
49121
49122 case "**":
49123 return 15;
49124 // no default
49125 }
49126
49127 /* falls through */
49128
49129 case "UnaryExpression":
49130 case "AwaitExpression":
49131 return 16;
49132
49133 case "UpdateExpression":
49134 return 17;
49135
49136 case "CallExpression":
49137 case "ImportExpression":
49138 return 18;
49139
49140 case "NewExpression":
49141 return 19;
49142
49143 default:
49144 return 20;
49145 }
49146 },
49147
49148 /**
49149 * Checks whether the given node is an empty block node or not.
49150 * @param {ASTNode|null} node The node to check.
49151 * @returns {boolean} `true` if the node is an empty block.
49152 */
49153 isEmptyBlock(node) {
49154 return Boolean(node && node.type === "BlockStatement" && node.body.length === 0);
49155 },
49156
49157 /**
49158 * Checks whether the given node is an empty function node or not.
49159 * @param {ASTNode|null} node The node to check.
49160 * @returns {boolean} `true` if the node is an empty function.
49161 */
49162 isEmptyFunction(node) {
49163 return isFunction(node) && module.exports.isEmptyBlock(node.body);
49164 },
49165
49166 /**
49167 * Returns the result of the string conversion applied to the evaluated value of the given expression node,
49168 * if it can be determined statically.
49169 *
49170 * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only.
49171 * In all other cases, this function returns `null`.
49172 * @param {ASTNode} node Expression node.
49173 * @returns {string|null} String value if it can be determined. Otherwise, `null`.
49174 */
49175 getStaticStringValue(node) {
49176 switch (node.type) {
49177 case "Literal":
49178 if (node.value === null) {
49179 if (module.exports.isNullLiteral(node)) {
49180 return String(node.value); // "null"
49181 }
49182
49183 if (node.regex) {
49184 return "/".concat(node.regex.pattern, "/").concat(node.regex.flags);
49185 }
49186
49187 if (node.bigint) {
49188 return node.bigint;
49189 } // Otherwise, this is an unknown literal. The function will return null.
49190
49191 } else {
49192 return String(node.value);
49193 }
49194
49195 break;
49196
49197 case "TemplateLiteral":
49198 if (node.expressions.length === 0 && node.quasis.length === 1) {
49199 return node.quasis[0].value.cooked;
49200 }
49201
49202 break;
49203 // no default
49204 }
49205
49206 return null;
49207 },
49208
49209 /**
49210 * Gets the property name of a given node.
49211 * The node can be a MemberExpression, a Property, or a MethodDefinition.
49212 *
49213 * If the name is dynamic, this returns `null`.
49214 *
49215 * For examples:
49216 *
49217 * a.b // => "b"
49218 * a["b"] // => "b"
49219 * a['b'] // => "b"
49220 * a[`b`] // => "b"
49221 * a[100] // => "100"
49222 * a[b] // => null
49223 * a["a" + "b"] // => null
49224 * a[tag`b`] // => null
49225 * a[`${b}`] // => null
49226 *
49227 * let a = {b: 1} // => "b"
49228 * let a = {["b"]: 1} // => "b"
49229 * let a = {['b']: 1} // => "b"
49230 * let a = {[`b`]: 1} // => "b"
49231 * let a = {[100]: 1} // => "100"
49232 * let a = {[b]: 1} // => null
49233 * let a = {["a" + "b"]: 1} // => null
49234 * let a = {[tag`b`]: 1} // => null
49235 * let a = {[`${b}`]: 1} // => null
49236 * @param {ASTNode} node The node to get.
49237 * @returns {string|null} The property name if static. Otherwise, null.
49238 */
49239 getStaticPropertyName(node) {
49240 let prop;
49241
49242 switch (node && node.type) {
49243 case "Property":
49244 case "MethodDefinition":
49245 prop = node.key;
49246 break;
49247
49248 case "MemberExpression":
49249 prop = node.property;
49250 break;
49251 // no default
49252 }
49253
49254 if (prop) {
49255 if (prop.type === "Identifier" && !node.computed) {
49256 return prop.name;
49257 }
49258
49259 return module.exports.getStaticStringValue(prop);
49260 }
49261
49262 return null;
49263 },
49264
49265 /**
49266 * Get directives from directive prologue of a Program or Function node.
49267 * @param {ASTNode} node The node to check.
49268 * @returns {ASTNode[]} The directives found in the directive prologue.
49269 */
49270 getDirectivePrologue(node) {
49271 const directives = []; // Directive prologues only occur at the top of files or functions.
49272
49273 if (node.type === "Program" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ||
49274 /*
49275 * Do not check arrow functions with implicit return.
49276 * `() => "use strict";` returns the string `"use strict"`.
49277 */
49278 node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement") {
49279 const statements = node.type === "Program" ? node.body : node.body.body;
49280
49281 for (const statement of statements) {
49282 if (statement.type === "ExpressionStatement" && statement.expression.type === "Literal") {
49283 directives.push(statement);
49284 } else {
49285 break;
49286 }
49287 }
49288 }
49289
49290 return directives;
49291 },
49292
49293 /**
49294 * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
49295 * after the node will be parsed as a decimal point, rather than a property-access dot.
49296 * @param {ASTNode} node The node to check.
49297 * @returns {boolean} `true` if this node is a decimal integer.
49298 * @example
49299 *
49300 * 5 // true
49301 * 5. // false
49302 * 5.0 // false
49303 * 05 // false
49304 * 0x5 // false
49305 * 0b101 // false
49306 * 0o5 // false
49307 * 5e0 // false
49308 * '5' // false
49309 * 5n // false
49310 */
49311 isDecimalInteger(node) {
49312 return node.type === "Literal" && typeof node.value === "number" && DECIMAL_INTEGER_PATTERN.test(node.raw);
49313 },
49314
49315 /**
49316 * Determines whether this token is a decimal integer numeric token.
49317 * This is similar to isDecimalInteger(), but for tokens.
49318 * @param {Token} token The token to check.
49319 * @returns {boolean} `true` if this token is a decimal integer.
49320 */
49321 isDecimalIntegerNumericToken(token) {
49322 return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value);
49323 },
49324
49325 /**
49326 * Gets the name and kind of the given function node.
49327 *
49328 * - `function foo() {}` .................... `function 'foo'`
49329 * - `(function foo() {})` .................. `function 'foo'`
49330 * - `(function() {})` ...................... `function`
49331 * - `function* foo() {}` ................... `generator function 'foo'`
49332 * - `(function* foo() {})` ................. `generator function 'foo'`
49333 * - `(function*() {})` ..................... `generator function`
49334 * - `() => {}` ............................. `arrow function`
49335 * - `async () => {}` ....................... `async arrow function`
49336 * - `({ foo: function foo() {} })` ......... `method 'foo'`
49337 * - `({ foo: function() {} })` ............. `method 'foo'`
49338 * - `({ ['foo']: function() {} })` ......... `method 'foo'`
49339 * - `({ [foo]: function() {} })` ........... `method`
49340 * - `({ foo() {} })` ....................... `method 'foo'`
49341 * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
49342 * - `({ foo: function*() {} })` ............ `generator method 'foo'`
49343 * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
49344 * - `({ [foo]: function*() {} })` .......... `generator method`
49345 * - `({ *foo() {} })` ...................... `generator method 'foo'`
49346 * - `({ foo: async function foo() {} })` ... `async method 'foo'`
49347 * - `({ foo: async function() {} })` ....... `async method 'foo'`
49348 * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
49349 * - `({ [foo]: async function() {} })` ..... `async method`
49350 * - `({ async foo() {} })` ................. `async method 'foo'`
49351 * - `({ get foo() {} })` ................... `getter 'foo'`
49352 * - `({ set foo(a) {} })` .................. `setter 'foo'`
49353 * - `class A { constructor() {} }` ......... `constructor`
49354 * - `class A { foo() {} }` ................. `method 'foo'`
49355 * - `class A { *foo() {} }` ................ `generator method 'foo'`
49356 * - `class A { async foo() {} }` ........... `async method 'foo'`
49357 * - `class A { ['foo']() {} }` ............. `method 'foo'`
49358 * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
49359 * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
49360 * - `class A { [foo]() {} }` ............... `method`
49361 * - `class A { *[foo]() {} }` .............. `generator method`
49362 * - `class A { async [foo]() {} }` ......... `async method`
49363 * - `class A { get foo() {} }` ............. `getter 'foo'`
49364 * - `class A { set foo(a) {} }` ............ `setter 'foo'`
49365 * - `class A { static foo() {} }` .......... `static method 'foo'`
49366 * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
49367 * - `class A { static async foo() {} }` .... `static async method 'foo'`
49368 * - `class A { static get foo() {} }` ...... `static getter 'foo'`
49369 * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
49370 * @param {ASTNode} node The function node to get.
49371 * @returns {string} The name and kind of the function node.
49372 */
49373 getFunctionNameWithKind(node) {
49374 const parent = node.parent;
49375 const tokens = [];
49376
49377 if (parent.type === "MethodDefinition" && parent.static) {
49378 tokens.push("static");
49379 }
49380
49381 if (node.async) {
49382 tokens.push("async");
49383 }
49384
49385 if (node.generator) {
49386 tokens.push("generator");
49387 }
49388
49389 if (node.type === "ArrowFunctionExpression") {
49390 tokens.push("arrow", "function");
49391 } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
49392 if (parent.kind === "constructor") {
49393 return "constructor";
49394 }
49395
49396 if (parent.kind === "get") {
49397 tokens.push("getter");
49398 } else if (parent.kind === "set") {
49399 tokens.push("setter");
49400 } else {
49401 tokens.push("method");
49402 }
49403 } else {
49404 tokens.push("function");
49405 }
49406
49407 if (node.id) {
49408 tokens.push("'".concat(node.id.name, "'"));
49409 } else {
49410 const name = module.exports.getStaticPropertyName(parent);
49411
49412 if (name !== null) {
49413 tokens.push("'".concat(name, "'"));
49414 }
49415 }
49416
49417 return tokens.join(" ");
49418 },
49419
49420 /**
49421 * Gets the location of the given function node for reporting.
49422 *
49423 * - `function foo() {}`
49424 * ^^^^^^^^^^^^
49425 * - `(function foo() {})`
49426 * ^^^^^^^^^^^^
49427 * - `(function() {})`
49428 * ^^^^^^^^
49429 * - `function* foo() {}`
49430 * ^^^^^^^^^^^^^
49431 * - `(function* foo() {})`
49432 * ^^^^^^^^^^^^^
49433 * - `(function*() {})`
49434 * ^^^^^^^^^
49435 * - `() => {}`
49436 * ^^
49437 * - `async () => {}`
49438 * ^^
49439 * - `({ foo: function foo() {} })`
49440 * ^^^^^^^^^^^^^^^^^
49441 * - `({ foo: function() {} })`
49442 * ^^^^^^^^^^^^^
49443 * - `({ ['foo']: function() {} })`
49444 * ^^^^^^^^^^^^^^^^^
49445 * - `({ [foo]: function() {} })`
49446 * ^^^^^^^^^^^^^^^
49447 * - `({ foo() {} })`
49448 * ^^^
49449 * - `({ foo: function* foo() {} })`
49450 * ^^^^^^^^^^^^^^^^^^
49451 * - `({ foo: function*() {} })`
49452 * ^^^^^^^^^^^^^^
49453 * - `({ ['foo']: function*() {} })`
49454 * ^^^^^^^^^^^^^^^^^^
49455 * - `({ [foo]: function*() {} })`
49456 * ^^^^^^^^^^^^^^^^
49457 * - `({ *foo() {} })`
49458 * ^^^^
49459 * - `({ foo: async function foo() {} })`
49460 * ^^^^^^^^^^^^^^^^^^^^^^^
49461 * - `({ foo: async function() {} })`
49462 * ^^^^^^^^^^^^^^^^^^^
49463 * - `({ ['foo']: async function() {} })`
49464 * ^^^^^^^^^^^^^^^^^^^^^^^
49465 * - `({ [foo]: async function() {} })`
49466 * ^^^^^^^^^^^^^^^^^^^^^
49467 * - `({ async foo() {} })`
49468 * ^^^^^^^^^
49469 * - `({ get foo() {} })`
49470 * ^^^^^^^
49471 * - `({ set foo(a) {} })`
49472 * ^^^^^^^
49473 * - `class A { constructor() {} }`
49474 * ^^^^^^^^^^^
49475 * - `class A { foo() {} }`
49476 * ^^^
49477 * - `class A { *foo() {} }`
49478 * ^^^^
49479 * - `class A { async foo() {} }`
49480 * ^^^^^^^^^
49481 * - `class A { ['foo']() {} }`
49482 * ^^^^^^^
49483 * - `class A { *['foo']() {} }`
49484 * ^^^^^^^^
49485 * - `class A { async ['foo']() {} }`
49486 * ^^^^^^^^^^^^^
49487 * - `class A { [foo]() {} }`
49488 * ^^^^^
49489 * - `class A { *[foo]() {} }`
49490 * ^^^^^^
49491 * - `class A { async [foo]() {} }`
49492 * ^^^^^^^^^^^
49493 * - `class A { get foo() {} }`
49494 * ^^^^^^^
49495 * - `class A { set foo(a) {} }`
49496 * ^^^^^^^
49497 * - `class A { static foo() {} }`
49498 * ^^^^^^^^^^
49499 * - `class A { static *foo() {} }`
49500 * ^^^^^^^^^^^
49501 * - `class A { static async foo() {} }`
49502 * ^^^^^^^^^^^^^^^^
49503 * - `class A { static get foo() {} }`
49504 * ^^^^^^^^^^^^^^
49505 * - `class A { static set foo(a) {} }`
49506 * ^^^^^^^^^^^^^^
49507 * @param {ASTNode} node The function node to get.
49508 * @param {SourceCode} sourceCode The source code object to get tokens.
49509 * @returns {string} The location of the function node for reporting.
49510 */
49511 getFunctionHeadLoc(node, sourceCode) {
49512 const parent = node.parent;
49513 let start = null;
49514 let end = null;
49515
49516 if (node.type === "ArrowFunctionExpression") {
49517 const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
49518 start = arrowToken.loc.start;
49519 end = arrowToken.loc.end;
49520 } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
49521 start = parent.loc.start;
49522 end = getOpeningParenOfParams(node, sourceCode).loc.start;
49523 } else {
49524 start = node.loc.start;
49525 end = getOpeningParenOfParams(node, sourceCode).loc.start;
49526 }
49527
49528 return {
49529 start: Object.assign({}, start),
49530 end: Object.assign({}, end)
49531 };
49532 },
49533
49534 /**
49535 * Gets next location when the result is not out of bound, otherwise returns null.
6a5a0f88
TL
49536 *
49537 * Assumptions:
49538 *
49539 * - The given location represents a valid location in the given source code.
49540 * - Columns are 0-based.
49541 * - Lines are 1-based.
49542 * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location.
49543 * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end.
49544 * The start (column 0) of that extra line is considered to be a valid location.
49545 *
49546 * Examples of successive locations (line, column):
49547 *
49548 * code: foo
49549 * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null
49550 *
49551 * code: foo<LF>
49552 * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
49553 *
49554 * code: foo<CR><LF>
49555 * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
49556 *
49557 * code: a<LF>b
49558 * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null
49559 *
49560 * code: a<LF>b<LF>
49561 * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
49562 *
49563 * code: a<CR><LF>b<CR><LF>
49564 * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
49565 *
49566 * code: a<LF><LF>
49567 * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null
49568 *
49569 * code: <LF>
49570 * locations: (1, 0) -> (2, 0) -> null
49571 *
49572 * code:
49573 * locations: (1, 0) -> null
eb39fafa
DC
49574 * @param {SourceCode} sourceCode The sourceCode
49575 * @param {{line: number, column: number}} location The location
49576 * @returns {{line: number, column: number} | null} Next location
49577 */
6a5a0f88
TL
49578 getNextLocation(sourceCode, {
49579 line,
49580 column
49581 }) {
49582 if (column < sourceCode.lines[line - 1].length) {
49583 return {
49584 line,
49585 column: column + 1
49586 };
49587 }
eb39fafa 49588
6a5a0f88
TL
49589 if (line < sourceCode.lines.length) {
49590 return {
49591 line: line + 1,
49592 column: 0
49593 };
eb39fafa
DC
49594 }
49595
6a5a0f88 49596 return null;
eb39fafa
DC
49597 },
49598
49599 /**
49600 * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
49601 * surrounding the node.
49602 * @param {SourceCode} sourceCode The source code object
49603 * @param {ASTNode} node An expression node
49604 * @returns {string} The text representing the node, with all surrounding parentheses included
49605 */
49606 getParenthesisedText(sourceCode, node) {
49607 let leftToken = sourceCode.getFirstToken(node);
49608 let rightToken = sourceCode.getLastToken(node);
49609
49610 while (sourceCode.getTokenBefore(leftToken) && sourceCode.getTokenBefore(leftToken).type === "Punctuator" && sourceCode.getTokenBefore(leftToken).value === "(" && sourceCode.getTokenAfter(rightToken) && sourceCode.getTokenAfter(rightToken).type === "Punctuator" && sourceCode.getTokenAfter(rightToken).value === ")") {
49611 leftToken = sourceCode.getTokenBefore(leftToken);
49612 rightToken = sourceCode.getTokenAfter(rightToken);
49613 }
49614
49615 return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]);
49616 },
49617
49618 /*
49619 * Determine if a node has a possiblity to be an Error object
49620 * @param {ASTNode} node ASTNode to check
49621 * @returns {boolean} True if there is a chance it contains an Error obj
49622 */
49623 couldBeError(node) {
49624 switch (node.type) {
49625 case "Identifier":
49626 case "CallExpression":
49627 case "NewExpression":
49628 case "MemberExpression":
49629 case "TaggedTemplateExpression":
49630 case "YieldExpression":
49631 case "AwaitExpression":
49632 return true;
49633 // possibly an error object.
49634
49635 case "AssignmentExpression":
49636 return module.exports.couldBeError(node.right);
49637
49638 case "SequenceExpression":
49639 {
49640 const exprs = node.expressions;
49641 return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]);
49642 }
49643
49644 case "LogicalExpression":
49645 return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
49646
49647 case "ConditionalExpression":
49648 return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate);
49649
49650 default:
49651 return false;
49652 }
49653 },
49654
49655 /**
49656 * Determines whether the given node is a `null` literal.
49657 * @param {ASTNode} node The node to check
49658 * @returns {boolean} `true` if the node is a `null` literal
49659 */
49660 isNullLiteral(node) {
49661 /*
49662 * Checking `node.value === null` does not guarantee that a literal is a null literal.
49663 * When parsing values that cannot be represented in the current environment (e.g. unicode
49664 * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to
49665 * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
49666 * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
49667 */
49668 return node.type === "Literal" && node.value === null && !node.regex && !node.bigint;
49669 },
49670
49671 /**
49672 * Check if a given node is a numeric literal or not.
49673 * @param {ASTNode} node The node to check.
49674 * @returns {boolean} `true` if the node is a number or bigint literal.
49675 */
49676 isNumericLiteral(node) {
49677 return node.type === "Literal" && (typeof node.value === "number" || Boolean(node.bigint));
49678 },
49679
49680 /**
49681 * Determines whether two tokens can safely be placed next to each other without merging into a single token
49682 * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
49683 * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
49684 * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
49685 * next to each other, behavior is undefined (although it should return `true` in most cases).
49686 */
49687 canTokensBeAdjacent(leftValue, rightValue) {
49688 const espreeOptions = {
49689 ecmaVersion: espree.latestEcmaVersion,
49690 comment: true,
49691 range: true
49692 };
49693 let leftToken;
49694
49695 if (typeof leftValue === "string") {
49696 let tokens;
49697
49698 try {
49699 tokens = espree.tokenize(leftValue, espreeOptions);
49700 } catch (e) {
49701 return false;
49702 }
49703
49704 const comments = tokens.comments;
49705 leftToken = tokens[tokens.length - 1];
49706
49707 if (comments.length) {
49708 const lastComment = comments[comments.length - 1];
49709
49710 if (lastComment.range[0] > leftToken.range[0]) {
49711 leftToken = lastComment;
49712 }
49713 }
49714 } else {
49715 leftToken = leftValue;
49716 }
49717
49718 if (leftToken.type === "Shebang") {
49719 return false;
49720 }
49721
49722 let rightToken;
49723
49724 if (typeof rightValue === "string") {
49725 let tokens;
49726
49727 try {
49728 tokens = espree.tokenize(rightValue, espreeOptions);
49729 } catch (e) {
49730 return false;
49731 }
49732
49733 const comments = tokens.comments;
49734 rightToken = tokens[0];
49735
49736 if (comments.length) {
49737 const firstComment = comments[0];
49738
49739 if (firstComment.range[0] < rightToken.range[0]) {
49740 rightToken = firstComment;
49741 }
49742 }
49743 } else {
49744 rightToken = rightValue;
49745 }
49746
49747 if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") {
49748 if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") {
49749 const PLUS_TOKENS = new Set(["+", "++"]);
49750 const MINUS_TOKENS = new Set(["-", "--"]);
49751 return !(PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) || MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value));
49752 }
49753
49754 if (leftToken.type === "Punctuator" && leftToken.value === "/") {
49755 return !["Block", "Line", "RegularExpression"].includes(rightToken.type);
49756 }
49757
49758 return true;
49759 }
49760
49761 if (leftToken.type === "String" || rightToken.type === "String" || leftToken.type === "Template" || rightToken.type === "Template") {
49762 return true;
49763 }
49764
49765 if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) {
49766 return true;
49767 }
49768
49769 if (leftToken.type === "Block" || rightToken.type === "Block" || rightToken.type === "Line") {
49770 return true;
49771 }
49772
49773 return false;
49774 },
49775
49776 /**
49777 * Get the `loc` object of a given name in a `/*globals` directive comment.
49778 * @param {SourceCode} sourceCode The source code to convert index to loc.
49779 * @param {Comment} comment The `/*globals` directive comment which include the name.
49780 * @param {string} name The name to find.
49781 * @returns {SourceLocation} The `loc` object.
49782 */
49783 getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
49784 const namePattern = new RegExp("[\\s,]".concat(lodash.escapeRegExp(name), "(?:$|[\\s,:])"), "gu"); // To ignore the first text "global".
49785
49786 namePattern.lastIndex = comment.value.indexOf("global") + 6; // Search a given variable name.
49787
49788 const match = namePattern.exec(comment.value); // Convert the index to loc.
49789
49790 const start = sourceCode.getLocFromIndex(comment.range[0] + "/*".length + (match ? match.index + 1 : 0));
49791 const end = {
49792 line: start.line,
49793 column: start.column + (match ? name.length : 1)
49794 };
49795 return {
49796 start,
49797 end
49798 };
49799 },
49800
49801 /**
49802 * Determines whether the given raw string contains an octal escape sequence.
49803 *
49804 * "\1", "\2" ... "\7"
49805 * "\00", "\01" ... "\09"
49806 *
49807 * "\0", when not followed by a digit, is not an octal escape sequence.
49808 * @param {string} rawString A string in its raw representation.
49809 * @returns {boolean} `true` if the string contains at least one octal escape sequence.
49810 */
49811 hasOctalEscapeSequence(rawString) {
49812 return OCTAL_ESCAPE_PATTERN.test(rawString);
49813 }
49814
49815};
49816
49817/***/ }),
49818/* 427 */
49819/***/ (function(module, exports, __webpack_require__) {
49820
49821/*
49822 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
49823
49824 Redistribution and use in source and binary forms, with or without
49825 modification, are permitted provided that the following conditions are met:
49826
49827 * Redistributions of source code must retain the above copyright
49828 notice, this list of conditions and the following disclaimer.
49829 * Redistributions in binary form must reproduce the above copyright
49830 notice, this list of conditions and the following disclaimer in the
49831 documentation and/or other materials provided with the distribution.
49832
49833 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
49834 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49835 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49836 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
49837 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49838 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
49839 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
49840 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
49841 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
49842 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49843*/
49844(function () {
49845 'use strict';
49846
49847 exports.ast = __webpack_require__(428);
49848 exports.code = __webpack_require__(429);
49849 exports.keyword = __webpack_require__(430);
49850})();
49851/* vim: set sw=4 ts=4 et tw=80 : */
49852
49853/***/ }),
49854/* 428 */
49855/***/ (function(module, exports) {
49856
49857/*
49858 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
49859
49860 Redistribution and use in source and binary forms, with or without
49861 modification, are permitted provided that the following conditions are met:
49862
49863 * Redistributions of source code must retain the above copyright
49864 notice, this list of conditions and the following disclaimer.
49865 * Redistributions in binary form must reproduce the above copyright
49866 notice, this list of conditions and the following disclaimer in the
49867 documentation and/or other materials provided with the distribution.
49868
49869 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
49870 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49871 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49872 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
49873 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49874 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
49875 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
49876 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
49877 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
49878 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49879*/
49880(function () {
49881 'use strict';
49882
49883 function isExpression(node) {
49884 if (node == null) {
49885 return false;
49886 }
49887
49888 switch (node.type) {
49889 case 'ArrayExpression':
49890 case 'AssignmentExpression':
49891 case 'BinaryExpression':
49892 case 'CallExpression':
49893 case 'ConditionalExpression':
49894 case 'FunctionExpression':
49895 case 'Identifier':
49896 case 'Literal':
49897 case 'LogicalExpression':
49898 case 'MemberExpression':
49899 case 'NewExpression':
49900 case 'ObjectExpression':
49901 case 'SequenceExpression':
49902 case 'ThisExpression':
49903 case 'UnaryExpression':
49904 case 'UpdateExpression':
49905 return true;
49906 }
49907
49908 return false;
49909 }
49910
49911 function isIterationStatement(node) {
49912 if (node == null) {
49913 return false;
49914 }
49915
49916 switch (node.type) {
49917 case 'DoWhileStatement':
49918 case 'ForInStatement':
49919 case 'ForStatement':
49920 case 'WhileStatement':
49921 return true;
49922 }
49923
49924 return false;
49925 }
49926
49927 function isStatement(node) {
49928 if (node == null) {
49929 return false;
49930 }
49931
49932 switch (node.type) {
49933 case 'BlockStatement':
49934 case 'BreakStatement':
49935 case 'ContinueStatement':
49936 case 'DebuggerStatement':
49937 case 'DoWhileStatement':
49938 case 'EmptyStatement':
49939 case 'ExpressionStatement':
49940 case 'ForInStatement':
49941 case 'ForStatement':
49942 case 'IfStatement':
49943 case 'LabeledStatement':
49944 case 'ReturnStatement':
49945 case 'SwitchStatement':
49946 case 'ThrowStatement':
49947 case 'TryStatement':
49948 case 'VariableDeclaration':
49949 case 'WhileStatement':
49950 case 'WithStatement':
49951 return true;
49952 }
49953
49954 return false;
49955 }
49956
49957 function isSourceElement(node) {
49958 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
49959 }
49960
49961 function trailingStatement(node) {
49962 switch (node.type) {
49963 case 'IfStatement':
49964 if (node.alternate != null) {
49965 return node.alternate;
49966 }
49967
49968 return node.consequent;
49969
49970 case 'LabeledStatement':
49971 case 'ForStatement':
49972 case 'ForInStatement':
49973 case 'WhileStatement':
49974 case 'WithStatement':
49975 return node.body;
49976 }
49977
49978 return null;
49979 }
49980
49981 function isProblematicIfStatement(node) {
49982 var current;
49983
49984 if (node.type !== 'IfStatement') {
49985 return false;
49986 }
49987
49988 if (node.alternate == null) {
49989 return false;
49990 }
49991
49992 current = node.consequent;
49993
49994 do {
49995 if (current.type === 'IfStatement') {
49996 if (current.alternate == null) {
49997 return true;
49998 }
49999 }
50000
50001 current = trailingStatement(current);
50002 } while (current);
50003
50004 return false;
50005 }
50006
50007 module.exports = {
50008 isExpression: isExpression,
50009 isStatement: isStatement,
50010 isIterationStatement: isIterationStatement,
50011 isSourceElement: isSourceElement,
50012 isProblematicIfStatement: isProblematicIfStatement,
50013 trailingStatement: trailingStatement
50014 };
50015})();
50016/* vim: set sw=4 ts=4 et tw=80 : */
50017
50018/***/ }),
50019/* 429 */
50020/***/ (function(module, exports) {
50021
50022/*
50023 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
50024 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
50025
50026 Redistribution and use in source and binary forms, with or without
50027 modification, are permitted provided that the following conditions are met:
50028
50029 * Redistributions of source code must retain the above copyright
50030 notice, this list of conditions and the following disclaimer.
50031 * Redistributions in binary form must reproduce the above copyright
50032 notice, this list of conditions and the following disclaimer in the
50033 documentation and/or other materials provided with the distribution.
50034
50035 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
50036 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50037 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50038 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
50039 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
50040 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
50041 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
50042 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
50043 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
50044 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50045*/
50046(function () {
50047 'use strict';
50048
50049 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
50050
50051 ES5Regex = {
50052 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
50053 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,
50054 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
50055 NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
50056 };
50057 ES6Regex = {
50058 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
50059 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
50060 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
50061 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
50062 };
50063
50064 function isDecimalDigit(ch) {
50065 return 0x30 <= ch && ch <= 0x39; // 0..9
50066 }
50067
50068 function isHexDigit(ch) {
50069 return 0x30 <= ch && ch <= 0x39 || // 0..9
50070 0x61 <= ch && ch <= 0x66 || // a..f
50071 0x41 <= ch && ch <= 0x46; // A..F
50072 }
50073
50074 function isOctalDigit(ch) {
50075 return ch >= 0x30 && ch <= 0x37; // 0..7
50076 } // 7.2 White Space
50077
50078
50079 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
50080
50081 function isWhiteSpace(ch) {
50082 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
50083 } // 7.3 Line Terminators
50084
50085
50086 function isLineTerminator(ch) {
50087 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
50088 } // 7.6 Identifier Names and Identifiers
50089
50090
50091 function fromCodePoint(cp) {
50092 if (cp <= 0xFFFF) {
50093 return String.fromCharCode(cp);
50094 }
50095
50096 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
50097 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
50098 return cu1 + cu2;
50099 }
50100
50101 IDENTIFIER_START = new Array(0x80);
50102
50103 for (ch = 0; ch < 0x80; ++ch) {
50104 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
50105 ch >= 0x41 && ch <= 0x5A || // A..Z
50106 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
50107 }
50108
50109 IDENTIFIER_PART = new Array(0x80);
50110
50111 for (ch = 0; ch < 0x80; ++ch) {
50112 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
50113 ch >= 0x41 && ch <= 0x5A || // A..Z
50114 ch >= 0x30 && ch <= 0x39 || // 0..9
50115 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
50116 }
50117
50118 function isIdentifierStartES5(ch) {
50119 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
50120 }
50121
50122 function isIdentifierPartES5(ch) {
50123 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
50124 }
50125
50126 function isIdentifierStartES6(ch) {
50127 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
50128 }
50129
50130 function isIdentifierPartES6(ch) {
50131 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
50132 }
50133
50134 module.exports = {
50135 isDecimalDigit: isDecimalDigit,
50136 isHexDigit: isHexDigit,
50137 isOctalDigit: isOctalDigit,
50138 isWhiteSpace: isWhiteSpace,
50139 isLineTerminator: isLineTerminator,
50140 isIdentifierStartES5: isIdentifierStartES5,
50141 isIdentifierPartES5: isIdentifierPartES5,
50142 isIdentifierStartES6: isIdentifierStartES6,
50143 isIdentifierPartES6: isIdentifierPartES6
50144 };
50145})();
50146/* vim: set sw=4 ts=4 et tw=80 : */
50147
50148/***/ }),
50149/* 430 */
50150/***/ (function(module, exports, __webpack_require__) {
50151
50152/*
50153 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
50154
50155 Redistribution and use in source and binary forms, with or without
50156 modification, are permitted provided that the following conditions are met:
50157
50158 * Redistributions of source code must retain the above copyright
50159 notice, this list of conditions and the following disclaimer.
50160 * Redistributions in binary form must reproduce the above copyright
50161 notice, this list of conditions and the following disclaimer in the
50162 documentation and/or other materials provided with the distribution.
50163
50164 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
50165 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50166 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50167 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
50168 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
50169 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
50170 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
50171 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
50172 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
50173 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50174*/
50175(function () {
50176 'use strict';
50177
50178 var code = __webpack_require__(429);
50179
50180 function isStrictModeReservedWordES6(id) {
50181 switch (id) {
50182 case 'implements':
50183 case 'interface':
50184 case 'package':
50185 case 'private':
50186 case 'protected':
50187 case 'public':
50188 case 'static':
50189 case 'let':
50190 return true;
50191
50192 default:
50193 return false;
50194 }
50195 }
50196
50197 function isKeywordES5(id, strict) {
50198 // yield should not be treated as keyword under non-strict mode.
50199 if (!strict && id === 'yield') {
50200 return false;
50201 }
50202
50203 return isKeywordES6(id, strict);
50204 }
50205
50206 function isKeywordES6(id, strict) {
50207 if (strict && isStrictModeReservedWordES6(id)) {
50208 return true;
50209 }
50210
50211 switch (id.length) {
50212 case 2:
50213 return id === 'if' || id === 'in' || id === 'do';
50214
50215 case 3:
50216 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
50217
50218 case 4:
50219 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
50220
50221 case 5:
50222 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
50223
50224 case 6:
50225 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
50226
50227 case 7:
50228 return id === 'default' || id === 'finally' || id === 'extends';
50229
50230 case 8:
50231 return id === 'function' || id === 'continue' || id === 'debugger';
50232
50233 case 10:
50234 return id === 'instanceof';
50235
50236 default:
50237 return false;
50238 }
50239 }
50240
50241 function isReservedWordES5(id, strict) {
50242 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
50243 }
50244
50245 function isReservedWordES6(id, strict) {
50246 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
50247 }
50248
50249 function isRestrictedWord(id) {
50250 return id === 'eval' || id === 'arguments';
50251 }
50252
50253 function isIdentifierNameES5(id) {
50254 var i, iz, ch;
50255
50256 if (id.length === 0) {
50257 return false;
50258 }
50259
50260 ch = id.charCodeAt(0);
50261
50262 if (!code.isIdentifierStartES5(ch)) {
50263 return false;
50264 }
50265
50266 for (i = 1, iz = id.length; i < iz; ++i) {
50267 ch = id.charCodeAt(i);
50268
50269 if (!code.isIdentifierPartES5(ch)) {
50270 return false;
50271 }
50272 }
50273
50274 return true;
50275 }
50276
50277 function decodeUtf16(lead, trail) {
50278 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
50279 }
50280
50281 function isIdentifierNameES6(id) {
50282 var i, iz, ch, lowCh, check;
50283
50284 if (id.length === 0) {
50285 return false;
50286 }
50287
50288 check = code.isIdentifierStartES6;
50289
50290 for (i = 0, iz = id.length; i < iz; ++i) {
50291 ch = id.charCodeAt(i);
50292
50293 if (0xD800 <= ch && ch <= 0xDBFF) {
50294 ++i;
50295
50296 if (i >= iz) {
50297 return false;
50298 }
50299
50300 lowCh = id.charCodeAt(i);
50301
50302 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
50303 return false;
50304 }
50305
50306 ch = decodeUtf16(ch, lowCh);
50307 }
50308
50309 if (!check(ch)) {
50310 return false;
50311 }
50312
50313 check = code.isIdentifierPartES6;
50314 }
50315
50316 return true;
50317 }
50318
50319 function isIdentifierES5(id, strict) {
50320 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
50321 }
50322
50323 function isIdentifierES6(id, strict) {
50324 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
50325 }
50326
50327 module.exports = {
50328 isKeywordES5: isKeywordES5,
50329 isKeywordES6: isKeywordES6,
50330 isReservedWordES5: isReservedWordES5,
50331 isReservedWordES6: isReservedWordES6,
50332 isRestrictedWord: isRestrictedWord,
50333 isIdentifierNameES5: isIdentifierNameES5,
50334 isIdentifierNameES6: isIdentifierNameES6,
50335 isIdentifierES5: isIdentifierES5,
50336 isIdentifierES6: isIdentifierES6
50337 };
50338})();
50339/* vim: set sw=4 ts=4 et tw=80 : */
50340
50341/***/ }),
50342/* 431 */
50343/***/ (function(module, exports, __webpack_require__) {
50344
50345"use strict";
50346/**
50347 * @fileoverview Rule to enforce linebreaks after open and before close array brackets
50348 * @author Jan Peer Stöcklmair <https://github.com/JPeer264>
50349 */
50350
50351
50352const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
50353// Rule Definition
50354//------------------------------------------------------------------------------
50355
50356
50357module.exports = {
50358 meta: {
50359 type: "layout",
50360 docs: {
50361 description: "enforce linebreaks after opening and before closing array brackets",
50362 category: "Stylistic Issues",
50363 recommended: false,
50364 url: "https://eslint.org/docs/rules/array-bracket-newline"
50365 },
50366 fixable: "whitespace",
50367 schema: [{
50368 oneOf: [{
50369 enum: ["always", "never", "consistent"]
50370 }, {
50371 type: "object",
50372 properties: {
50373 multiline: {
50374 type: "boolean"
50375 },
50376 minItems: {
50377 type: ["integer", "null"],
50378 minimum: 0
50379 }
50380 },
50381 additionalProperties: false
50382 }]
50383 }],
50384 messages: {
50385 unexpectedOpeningLinebreak: "There should be no linebreak after '['.",
50386 unexpectedClosingLinebreak: "There should be no linebreak before ']'.",
50387 missingOpeningLinebreak: "A linebreak is required after '['.",
50388 missingClosingLinebreak: "A linebreak is required before ']'."
50389 }
50390 },
50391
50392 create(context) {
50393 const sourceCode = context.getSourceCode(); //----------------------------------------------------------------------
50394 // Helpers
50395 //----------------------------------------------------------------------
50396
50397 /**
50398 * Normalizes a given option value.
50399 * @param {string|Object|undefined} option An option value to parse.
50400 * @returns {{multiline: boolean, minItems: number}} Normalized option object.
50401 */
50402
50403 function normalizeOptionValue(option) {
50404 let consistent = false;
50405 let multiline = false;
50406 let minItems = 0;
50407
50408 if (option) {
50409 if (option === "consistent") {
50410 consistent = true;
50411 minItems = Number.POSITIVE_INFINITY;
50412 } else if (option === "always" || option.minItems === 0) {
50413 minItems = 0;
50414 } else if (option === "never") {
50415 minItems = Number.POSITIVE_INFINITY;
50416 } else {
50417 multiline = Boolean(option.multiline);
50418 minItems = option.minItems || Number.POSITIVE_INFINITY;
50419 }
50420 } else {
50421 consistent = false;
50422 multiline = true;
50423 minItems = Number.POSITIVE_INFINITY;
50424 }
50425
50426 return {
50427 consistent,
50428 multiline,
50429 minItems
50430 };
50431 }
50432 /**
50433 * Normalizes a given option value.
50434 * @param {string|Object|undefined} options An option value to parse.
50435 * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
50436 */
50437
50438
50439 function normalizeOptions(options) {
50440 const value = normalizeOptionValue(options);
50441 return {
50442 ArrayExpression: value,
50443 ArrayPattern: value
50444 };
50445 }
50446 /**
50447 * Reports that there shouldn't be a linebreak after the first token
50448 * @param {ASTNode} node The node to report in the event of an error.
50449 * @param {Token} token The token to use for the report.
50450 * @returns {void}
50451 */
50452
50453
50454 function reportNoBeginningLinebreak(node, token) {
50455 context.report({
50456 node,
50457 loc: token.loc,
50458 messageId: "unexpectedOpeningLinebreak",
50459
50460 fix(fixer) {
50461 const nextToken = sourceCode.getTokenAfter(token, {
50462 includeComments: true
50463 });
50464
50465 if (astUtils.isCommentToken(nextToken)) {
50466 return null;
50467 }
50468
50469 return fixer.removeRange([token.range[1], nextToken.range[0]]);
50470 }
50471
50472 });
50473 }
50474 /**
50475 * Reports that there shouldn't be a linebreak before the last token
50476 * @param {ASTNode} node The node to report in the event of an error.
50477 * @param {Token} token The token to use for the report.
50478 * @returns {void}
50479 */
50480
50481
50482 function reportNoEndingLinebreak(node, token) {
50483 context.report({
50484 node,
50485 loc: token.loc,
50486 messageId: "unexpectedClosingLinebreak",
50487
50488 fix(fixer) {
50489 const previousToken = sourceCode.getTokenBefore(token, {
50490 includeComments: true
50491 });
50492
50493 if (astUtils.isCommentToken(previousToken)) {
50494 return null;
50495 }
50496
50497 return fixer.removeRange([previousToken.range[1], token.range[0]]);
50498 }
50499
50500 });
50501 }
50502 /**
50503 * Reports that there should be a linebreak after the first token
50504 * @param {ASTNode} node The node to report in the event of an error.
50505 * @param {Token} token The token to use for the report.
50506 * @returns {void}
50507 */
50508
50509
50510 function reportRequiredBeginningLinebreak(node, token) {
50511 context.report({
50512 node,
50513 loc: token.loc,
50514 messageId: "missingOpeningLinebreak",
50515
50516 fix(fixer) {
50517 return fixer.insertTextAfter(token, "\n");
50518 }
50519
50520 });
50521 }
50522 /**
50523 * Reports that there should be a linebreak before the last token
50524 * @param {ASTNode} node The node to report in the event of an error.
50525 * @param {Token} token The token to use for the report.
50526 * @returns {void}
50527 */
50528
50529
50530 function reportRequiredEndingLinebreak(node, token) {
50531 context.report({
50532 node,
50533 loc: token.loc,
50534 messageId: "missingClosingLinebreak",
50535
50536 fix(fixer) {
50537 return fixer.insertTextBefore(token, "\n");
50538 }
50539
50540 });
50541 }
50542 /**
50543 * Reports a given node if it violated this rule.
50544 * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node.
50545 * @returns {void}
50546 */
50547
50548
50549 function check(node) {
50550 const elements = node.elements;
50551 const normalizedOptions = normalizeOptions(context.options[0]);
50552 const options = normalizedOptions[node.type];
50553 const openBracket = sourceCode.getFirstToken(node);
50554 const closeBracket = sourceCode.getLastToken(node);
50555 const firstIncComment = sourceCode.getTokenAfter(openBracket, {
50556 includeComments: true
50557 });
50558 const lastIncComment = sourceCode.getTokenBefore(closeBracket, {
50559 includeComments: true
50560 });
50561 const first = sourceCode.getTokenAfter(openBracket);
50562 const last = sourceCode.getTokenBefore(closeBracket);
50563 const needsLinebreaks = elements.length >= options.minItems || options.multiline && elements.length > 0 && firstIncComment.loc.start.line !== lastIncComment.loc.end.line || elements.length === 0 && firstIncComment.type === "Block" && firstIncComment.loc.start.line !== lastIncComment.loc.end.line && firstIncComment === lastIncComment || options.consistent && openBracket.loc.end.line !== first.loc.start.line;
50564 /*
50565 * Use tokens or comments to check multiline or not.
50566 * But use only tokens to check whether linebreaks are needed.
50567 * This allows:
50568 * var arr = [ // eslint-disable-line foo
50569 * 'a'
50570 * ]
50571 */
50572
50573 if (needsLinebreaks) {
50574 if (astUtils.isTokenOnSameLine(openBracket, first)) {
50575 reportRequiredBeginningLinebreak(node, openBracket);
50576 }
50577
50578 if (astUtils.isTokenOnSameLine(last, closeBracket)) {
50579 reportRequiredEndingLinebreak(node, closeBracket);
50580 }
50581 } else {
50582 if (!astUtils.isTokenOnSameLine(openBracket, first)) {
50583 reportNoBeginningLinebreak(node, openBracket);
50584 }
50585
50586 if (!astUtils.isTokenOnSameLine(last, closeBracket)) {
50587 reportNoEndingLinebreak(node, closeBracket);
50588 }
50589 }
50590 } //----------------------------------------------------------------------
50591 // Public
50592 //----------------------------------------------------------------------
50593
50594
50595 return {
50596 ArrayPattern: check,
50597 ArrayExpression: check
50598 };
50599 }
50600
50601};
50602
50603/***/ }),
50604/* 432 */
50605/***/ (function(module, exports, __webpack_require__) {
50606
50607"use strict";
50608/**
50609 * @fileoverview Disallows or enforces spaces inside of array brackets.
50610 * @author Jamund Ferguson
50611 */
50612
50613
50614const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
50615// Rule Definition
50616//------------------------------------------------------------------------------
50617
50618
50619module.exports = {
50620 meta: {
50621 type: "layout",
50622 docs: {
50623 description: "enforce consistent spacing inside array brackets",
50624 category: "Stylistic Issues",
50625 recommended: false,
50626 url: "https://eslint.org/docs/rules/array-bracket-spacing"
50627 },
50628 fixable: "whitespace",
50629 schema: [{
50630 enum: ["always", "never"]
50631 }, {
50632 type: "object",
50633 properties: {
50634 singleValue: {
50635 type: "boolean"
50636 },
50637 objectsInArrays: {
50638 type: "boolean"
50639 },
50640 arraysInArrays: {
50641 type: "boolean"
50642 }
50643 },
50644 additionalProperties: false
50645 }],
50646 messages: {
50647 unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.",
50648 unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.",
50649 missingSpaceAfter: "A space is required after '{{tokenValue}}'.",
50650 missingSpaceBefore: "A space is required before '{{tokenValue}}'."
50651 }
50652 },
50653
50654 create(context) {
50655 const spaced = context.options[0] === "always",
50656 sourceCode = context.getSourceCode();
50657 /**
50658 * Determines whether an option is set, relative to the spacing option.
50659 * If spaced is "always", then check whether option is set to false.
50660 * If spaced is "never", then check whether option is set to true.
50661 * @param {Object} option The option to exclude.
50662 * @returns {boolean} Whether or not the property is excluded.
50663 */
50664
50665 function isOptionSet(option) {
50666 return context.options[1] ? context.options[1][option] === !spaced : false;
50667 }
50668
50669 const options = {
50670 spaced,
50671 singleElementException: isOptionSet("singleValue"),
50672 objectsInArraysException: isOptionSet("objectsInArrays"),
50673 arraysInArraysException: isOptionSet("arraysInArrays")
50674 }; //--------------------------------------------------------------------------
50675 // Helpers
50676 //--------------------------------------------------------------------------
50677
50678 /**
50679 * Reports that there shouldn't be a space after the first token
50680 * @param {ASTNode} node The node to report in the event of an error.
50681 * @param {Token} token The token to use for the report.
50682 * @returns {void}
50683 */
50684
50685 function reportNoBeginningSpace(node, token) {
50686 const nextToken = sourceCode.getTokenAfter(token);
50687 context.report({
50688 node,
50689 loc: {
50690 start: token.loc.end,
50691 end: nextToken.loc.start
50692 },
50693 messageId: "unexpectedSpaceAfter",
50694 data: {
50695 tokenValue: token.value
50696 },
50697
50698 fix(fixer) {
50699 return fixer.removeRange([token.range[1], nextToken.range[0]]);
50700 }
50701
50702 });
50703 }
50704 /**
50705 * Reports that there shouldn't be a space before the last token
50706 * @param {ASTNode} node The node to report in the event of an error.
50707 * @param {Token} token The token to use for the report.
50708 * @returns {void}
50709 */
50710
50711
50712 function reportNoEndingSpace(node, token) {
50713 const previousToken = sourceCode.getTokenBefore(token);
50714 context.report({
50715 node,
50716 loc: {
50717 start: previousToken.loc.end,
50718 end: token.loc.start
50719 },
50720 messageId: "unexpectedSpaceBefore",
50721 data: {
50722 tokenValue: token.value
50723 },
50724
50725 fix(fixer) {
50726 return fixer.removeRange([previousToken.range[1], token.range[0]]);
50727 }
50728
50729 });
50730 }
50731 /**
50732 * Reports that there should be a space after the first token
50733 * @param {ASTNode} node The node to report in the event of an error.
50734 * @param {Token} token The token to use for the report.
50735 * @returns {void}
50736 */
50737
50738
50739 function reportRequiredBeginningSpace(node, token) {
50740 context.report({
50741 node,
50742 loc: token.loc,
50743 messageId: "missingSpaceAfter",
50744 data: {
50745 tokenValue: token.value
50746 },
50747
50748 fix(fixer) {
50749 return fixer.insertTextAfter(token, " ");
50750 }
50751
50752 });
50753 }
50754 /**
50755 * Reports that there should be a space before the last token
50756 * @param {ASTNode} node The node to report in the event of an error.
50757 * @param {Token} token The token to use for the report.
50758 * @returns {void}
50759 */
50760
50761
50762 function reportRequiredEndingSpace(node, token) {
50763 context.report({
50764 node,
50765 loc: token.loc,
50766 messageId: "missingSpaceBefore",
50767 data: {
50768 tokenValue: token.value
50769 },
50770
50771 fix(fixer) {
50772 return fixer.insertTextBefore(token, " ");
50773 }
50774
50775 });
50776 }
50777 /**
50778 * Determines if a node is an object type
50779 * @param {ASTNode} node The node to check.
50780 * @returns {boolean} Whether or not the node is an object type.
50781 */
50782
50783
50784 function isObjectType(node) {
50785 return node && (node.type === "ObjectExpression" || node.type === "ObjectPattern");
50786 }
50787 /**
50788 * Determines if a node is an array type
50789 * @param {ASTNode} node The node to check.
50790 * @returns {boolean} Whether or not the node is an array type.
50791 */
50792
50793
50794 function isArrayType(node) {
50795 return node && (node.type === "ArrayExpression" || node.type === "ArrayPattern");
50796 }
50797 /**
50798 * Validates the spacing around array brackets
50799 * @param {ASTNode} node The node we're checking for spacing
50800 * @returns {void}
50801 */
50802
50803
50804 function validateArraySpacing(node) {
50805 if (options.spaced && node.elements.length === 0) {
50806 return;
50807 }
50808
50809 const first = sourceCode.getFirstToken(node),
50810 second = sourceCode.getFirstToken(node, 1),
50811 last = node.typeAnnotation ? sourceCode.getTokenBefore(node.typeAnnotation) : sourceCode.getLastToken(node),
50812 penultimate = sourceCode.getTokenBefore(last),
50813 firstElement = node.elements[0],
50814 lastElement = node.elements[node.elements.length - 1];
50815 const openingBracketMustBeSpaced = options.objectsInArraysException && isObjectType(firstElement) || options.arraysInArraysException && isArrayType(firstElement) || options.singleElementException && node.elements.length === 1 ? !options.spaced : options.spaced;
50816 const closingBracketMustBeSpaced = options.objectsInArraysException && isObjectType(lastElement) || options.arraysInArraysException && isArrayType(lastElement) || options.singleElementException && node.elements.length === 1 ? !options.spaced : options.spaced;
50817
50818 if (astUtils.isTokenOnSameLine(first, second)) {
50819 if (openingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(first, second)) {
50820 reportRequiredBeginningSpace(node, first);
50821 }
50822
50823 if (!openingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(first, second)) {
50824 reportNoBeginningSpace(node, first);
50825 }
50826 }
50827
50828 if (first !== penultimate && astUtils.isTokenOnSameLine(penultimate, last)) {
50829 if (closingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(penultimate, last)) {
50830 reportRequiredEndingSpace(node, last);
50831 }
50832
50833 if (!closingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(penultimate, last)) {
50834 reportNoEndingSpace(node, last);
50835 }
50836 }
50837 } //--------------------------------------------------------------------------
50838 // Public
50839 //--------------------------------------------------------------------------
50840
50841
50842 return {
50843 ArrayPattern: validateArraySpacing,
50844 ArrayExpression: validateArraySpacing
50845 };
50846 }
50847
50848};
50849
50850/***/ }),
50851/* 433 */
50852/***/ (function(module, exports, __webpack_require__) {
50853
50854"use strict";
50855/**
50856 * @fileoverview Rule to enforce return statements in callbacks of array's methods
50857 * @author Toru Nagashima
50858 */
50859 //------------------------------------------------------------------------------
50860// Requirements
50861//------------------------------------------------------------------------------
50862
50863const lodash = __webpack_require__(403);
50864
50865const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
50866// Helpers
50867//------------------------------------------------------------------------------
50868
50869
50870const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
50871const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort)$/u;
50872/**
50873 * Checks a given code path segment is reachable.
50874 * @param {CodePathSegment} segment A segment to check.
50875 * @returns {boolean} `true` if the segment is reachable.
50876 */
50877
50878function isReachable(segment) {
50879 return segment.reachable;
50880}
eb39fafa
DC
50881/**
50882 * Checks a given node is a MemberExpression node which has the specified name's
50883 * property.
50884 * @param {ASTNode} node A node to check.
50885 * @returns {boolean} `true` if the node is a MemberExpression node which has
50886 * the specified name's property
50887 */
50888
50889
50890function isTargetMethod(node) {
50891 return node.type === "MemberExpression" && TARGET_METHODS.test(astUtils.getStaticPropertyName(node) || "");
50892}
50893/**
50894 * Checks whether or not a given node is a function expression which is the
50895 * callback of an array method, returning the method name.
50896 * @param {ASTNode} node A node to check. This is one of
50897 * FunctionExpression or ArrowFunctionExpression.
50898 * @returns {string} The method name if the node is a callback method,
50899 * null otherwise.
50900 */
50901
50902
50903function getArrayMethodName(node) {
50904 let currentNode = node;
50905
50906 while (currentNode) {
50907 const parent = currentNode.parent;
50908
50909 switch (parent.type) {
50910 /*
50911 * Looks up the destination. e.g.,
50912 * foo.every(nativeFoo || function foo() { ... });
50913 */
50914 case "LogicalExpression":
50915 case "ConditionalExpression":
50916 currentNode = parent;
50917 break;
50918
50919 /*
50920 * If the upper function is IIFE, checks the destination of the return value.
50921 * e.g.
50922 * foo.every((function() {
50923 * // setup...
50924 * return function callback() { ... };
50925 * })());
50926 */
50927
50928 case "ReturnStatement":
50929 {
50930 const func = astUtils.getUpperFunction(parent);
50931
50932 if (func === null || !astUtils.isCallee(func)) {
50933 return null;
50934 }
50935
50936 currentNode = func.parent;
50937 break;
50938 }
50939
50940 /*
50941 * e.g.
50942 * Array.from([], function() {});
50943 * list.every(function() {});
50944 */
50945
50946 case "CallExpression":
50947 if (astUtils.isArrayFromMethod(parent.callee)) {
50948 if (parent.arguments.length >= 2 && parent.arguments[1] === currentNode) {
50949 return "from";
50950 }
50951 }
50952
50953 if (isTargetMethod(parent.callee)) {
50954 if (parent.arguments.length >= 1 && parent.arguments[0] === currentNode) {
50955 return astUtils.getStaticPropertyName(parent.callee);
50956 }
50957 }
50958
50959 return null;
50960 // Otherwise this node is not target.
50961
50962 default:
50963 return null;
50964 }
50965 }
50966 /* istanbul ignore next: unreachable */
50967
50968
50969 return null;
50970} //------------------------------------------------------------------------------
50971// Rule Definition
50972//------------------------------------------------------------------------------
50973
50974
50975module.exports = {
50976 meta: {
50977 type: "problem",
50978 docs: {
50979 description: "enforce `return` statements in callbacks of array methods",
50980 category: "Best Practices",
50981 recommended: false,
50982 url: "https://eslint.org/docs/rules/array-callback-return"
50983 },
50984 schema: [{
50985 type: "object",
50986 properties: {
50987 allowImplicit: {
50988 type: "boolean",
50989 default: false
50990 },
50991 checkForEach: {
50992 type: "boolean",
50993 default: false
50994 }
50995 },
50996 additionalProperties: false
50997 }],
50998 messages: {
50999 expectedAtEnd: "Expected to return a value at the end of {{name}}.",
51000 expectedInside: "Expected to return a value in {{name}}.",
51001 expectedReturnValue: "{{name}} expected a return value.",
51002 expectedNoReturnValue: "{{name}} did not expect a return value."
51003 }
51004 },
51005
51006 create(context) {
51007 const options = context.options[0] || {
51008 allowImplicit: false,
51009 checkForEach: false
51010 };
56c4a2cb 51011 const sourceCode = context.getSourceCode();
eb39fafa
DC
51012 let funcInfo = {
51013 arrayMethodName: null,
51014 upper: null,
51015 codePath: null,
51016 hasReturn: false,
51017 shouldCheck: false,
51018 node: null
51019 };
51020 /**
51021 * Checks whether or not the last code path segment is reachable.
51022 * Then reports this function if the segment is reachable.
51023 *
51024 * If the last code path segment is reachable, there are paths which are not
51025 * returned or thrown.
51026 * @param {ASTNode} node A node to check.
51027 * @returns {void}
51028 */
51029
51030 function checkLastSegment(node) {
51031 if (!funcInfo.shouldCheck) {
51032 return;
51033 }
51034
51035 let messageId = null;
51036
51037 if (funcInfo.arrayMethodName === "forEach") {
51038 if (options.checkForEach && node.type === "ArrowFunctionExpression" && node.expression) {
51039 messageId = "expectedNoReturnValue";
51040 }
51041 } else {
51042 if (node.body.type === "BlockStatement" && funcInfo.codePath.currentSegments.some(isReachable)) {
51043 messageId = funcInfo.hasReturn ? "expectedAtEnd" : "expectedInside";
51044 }
51045 }
51046
51047 if (messageId) {
56c4a2cb 51048 let name = astUtils.getFunctionNameWithKind(node);
eb39fafa
DC
51049 name = messageId === "expectedNoReturnValue" ? lodash.upperFirst(name) : name;
51050 context.report({
51051 node,
56c4a2cb 51052 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
eb39fafa
DC
51053 messageId,
51054 data: {
51055 name
51056 }
51057 });
51058 }
51059 }
51060
51061 return {
51062 // Stacks this function's information.
51063 onCodePathStart(codePath, node) {
51064 let methodName = null;
51065
51066 if (TARGET_NODE_TYPE.test(node.type)) {
51067 methodName = getArrayMethodName(node);
51068 }
51069
51070 funcInfo = {
51071 arrayMethodName: methodName,
51072 upper: funcInfo,
51073 codePath,
51074 hasReturn: false,
51075 shouldCheck: methodName && !node.async && !node.generator,
51076 node
51077 };
51078 },
51079
51080 // Pops this function's information.
51081 onCodePathEnd() {
51082 funcInfo = funcInfo.upper;
51083 },
51084
51085 // Checks the return statement is valid.
51086 ReturnStatement(node) {
51087 if (!funcInfo.shouldCheck) {
51088 return;
51089 }
51090
51091 funcInfo.hasReturn = true;
51092 let messageId = null;
51093
51094 if (funcInfo.arrayMethodName === "forEach") {
51095 // if checkForEach: true, returning a value at any path inside a forEach is not allowed
51096 if (options.checkForEach && node.argument) {
51097 messageId = "expectedNoReturnValue";
51098 }
51099 } else {
51100 // if allowImplicit: false, should also check node.argument
51101 if (!options.allowImplicit && !node.argument) {
51102 messageId = "expectedReturnValue";
51103 }
51104 }
51105
51106 if (messageId) {
51107 context.report({
51108 node,
51109 messageId,
51110 data: {
51111 name: lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node))
51112 }
51113 });
51114 }
51115 },
51116
51117 // Reports a given function if the last path is reachable.
51118 "FunctionExpression:exit": checkLastSegment,
51119 "ArrowFunctionExpression:exit": checkLastSegment
51120 };
51121 }
51122
51123};
51124
51125/***/ }),
51126/* 434 */
51127/***/ (function(module, exports, __webpack_require__) {
51128
51129"use strict";
51130/**
51131 * @fileoverview Rule to enforce line breaks after each array element
51132 * @author Jan Peer Stöcklmair <https://github.com/JPeer264>
51133 */
51134
51135
51136const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
51137// Rule Definition
51138//------------------------------------------------------------------------------
51139
51140
51141module.exports = {
51142 meta: {
51143 type: "layout",
51144 docs: {
51145 description: "enforce line breaks after each array element",
51146 category: "Stylistic Issues",
51147 recommended: false,
51148 url: "https://eslint.org/docs/rules/array-element-newline"
51149 },
51150 fixable: "whitespace",
51151 schema: {
51152 definitions: {
51153 basicConfig: {
51154 oneOf: [{
51155 enum: ["always", "never", "consistent"]
51156 }, {
51157 type: "object",
51158 properties: {
51159 multiline: {
51160 type: "boolean"
51161 },
51162 minItems: {
51163 type: ["integer", "null"],
51164 minimum: 0
51165 }
51166 },
51167 additionalProperties: false
51168 }]
51169 }
51170 },
51171 items: [{
51172 oneOf: [{
51173 $ref: "#/definitions/basicConfig"
51174 }, {
51175 type: "object",
51176 properties: {
51177 ArrayExpression: {
51178 $ref: "#/definitions/basicConfig"
51179 },
51180 ArrayPattern: {
51181 $ref: "#/definitions/basicConfig"
51182 }
51183 },
51184 additionalProperties: false,
51185 minProperties: 1
51186 }]
51187 }]
51188 },
51189 messages: {
51190 unexpectedLineBreak: "There should be no linebreak here.",
51191 missingLineBreak: "There should be a linebreak after this element."
51192 }
51193 },
51194
51195 create(context) {
51196 const sourceCode = context.getSourceCode(); //----------------------------------------------------------------------
51197 // Helpers
51198 //----------------------------------------------------------------------
51199
51200 /**
51201 * Normalizes a given option value.
51202 * @param {string|Object|undefined} providedOption An option value to parse.
51203 * @returns {{multiline: boolean, minItems: number}} Normalized option object.
51204 */
51205
51206 function normalizeOptionValue(providedOption) {
51207 let consistent = false;
51208 let multiline = false;
51209 let minItems;
51210 const option = providedOption || "always";
51211
51212 if (!option || option === "always" || option.minItems === 0) {
51213 minItems = 0;
51214 } else if (option === "never") {
51215 minItems = Number.POSITIVE_INFINITY;
51216 } else if (option === "consistent") {
51217 consistent = true;
51218 minItems = Number.POSITIVE_INFINITY;
51219 } else {
51220 multiline = Boolean(option.multiline);
51221 minItems = option.minItems || Number.POSITIVE_INFINITY;
51222 }
51223
51224 return {
51225 consistent,
51226 multiline,
51227 minItems
51228 };
51229 }
51230 /**
51231 * Normalizes a given option value.
51232 * @param {string|Object|undefined} options An option value to parse.
51233 * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
51234 */
51235
51236
51237 function normalizeOptions(options) {
51238 if (options && (options.ArrayExpression || options.ArrayPattern)) {
51239 let expressionOptions, patternOptions;
51240
51241 if (options.ArrayExpression) {
51242 expressionOptions = normalizeOptionValue(options.ArrayExpression);
51243 }
51244
51245 if (options.ArrayPattern) {
51246 patternOptions = normalizeOptionValue(options.ArrayPattern);
51247 }
51248
51249 return {
51250 ArrayExpression: expressionOptions,
51251 ArrayPattern: patternOptions
51252 };
51253 }
51254
51255 const value = normalizeOptionValue(options);
51256 return {
51257 ArrayExpression: value,
51258 ArrayPattern: value
51259 };
51260 }
51261 /**
51262 * Reports that there shouldn't be a line break after the first token
51263 * @param {Token} token The token to use for the report.
51264 * @returns {void}
51265 */
51266
51267
51268 function reportNoLineBreak(token) {
51269 const tokenBefore = sourceCode.getTokenBefore(token, {
51270 includeComments: true
51271 });
51272 context.report({
51273 loc: {
51274 start: tokenBefore.loc.end,
51275 end: token.loc.start
51276 },
51277 messageId: "unexpectedLineBreak",
51278
51279 fix(fixer) {
51280 if (astUtils.isCommentToken(tokenBefore)) {
51281 return null;
51282 }
51283
51284 if (!astUtils.isTokenOnSameLine(tokenBefore, token)) {
51285 return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ");
51286 }
51287 /*
51288 * This will check if the comma is on the same line as the next element
51289 * Following array:
51290 * [
51291 * 1
51292 * , 2
51293 * , 3
51294 * ]
51295 *
51296 * will be fixed to:
51297 * [
51298 * 1, 2, 3
51299 * ]
51300 */
51301
51302
51303 const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, {
51304 includeComments: true
51305 });
51306
51307 if (astUtils.isCommentToken(twoTokensBefore)) {
51308 return null;
51309 }
51310
51311 return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], "");
51312 }
51313
51314 });
51315 }
51316 /**
51317 * Reports that there should be a line break after the first token
51318 * @param {Token} token The token to use for the report.
51319 * @returns {void}
51320 */
51321
51322
51323 function reportRequiredLineBreak(token) {
51324 const tokenBefore = sourceCode.getTokenBefore(token, {
51325 includeComments: true
51326 });
51327 context.report({
51328 loc: {
51329 start: tokenBefore.loc.end,
51330 end: token.loc.start
51331 },
51332 messageId: "missingLineBreak",
51333
51334 fix(fixer) {
51335 return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n");
51336 }
51337
51338 });
51339 }
51340 /**
51341 * Reports a given node if it violated this rule.
51342 * @param {ASTNode} node A node to check. This is an ObjectExpression node or an ObjectPattern node.
51343 * @returns {void}
51344 */
51345
51346
51347 function check(node) {
51348 const elements = node.elements;
51349 const normalizedOptions = normalizeOptions(context.options[0]);
51350 const options = normalizedOptions[node.type];
51351
51352 if (!options) {
51353 return;
51354 }
51355
51356 let elementBreak = false;
51357 /*
51358 * MULTILINE: true
51359 * loop through every element and check
51360 * if at least one element has linebreaks inside
51361 * this ensures that following is not valid (due to elements are on the same line):
51362 *
51363 * [
51364 * 1,
51365 * 2,
51366 * 3
51367 * ]
51368 */
51369
51370 if (options.multiline) {
51371 elementBreak = elements.filter(element => element !== null).some(element => element.loc.start.line !== element.loc.end.line);
51372 }
51373
51374 const linebreaksCount = node.elements.map((element, i) => {
51375 const previousElement = elements[i - 1];
51376
51377 if (i === 0 || element === null || previousElement === null) {
51378 return false;
51379 }
51380
51381 const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken);
51382 const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken);
51383 const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken);
51384 return !astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement);
51385 }).filter(isBreak => isBreak === true).length;
51386 const needsLinebreaks = elements.length >= options.minItems || options.multiline && elementBreak || options.consistent && linebreaksCount > 0 && linebreaksCount < node.elements.length;
51387 elements.forEach((element, i) => {
51388 const previousElement = elements[i - 1];
51389
51390 if (i === 0 || element === null || previousElement === null) {
51391 return;
51392 }
51393
51394 const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken);
51395 const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken);
51396 const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken);
51397
51398 if (needsLinebreaks) {
51399 if (astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) {
51400 reportRequiredLineBreak(firstTokenOfCurrentElement);
51401 }
51402 } else {
51403 if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) {
51404 reportNoLineBreak(firstTokenOfCurrentElement);
51405 }
51406 }
51407 });
51408 } //----------------------------------------------------------------------
51409 // Public
51410 //----------------------------------------------------------------------
51411
51412
51413 return {
51414 ArrayPattern: check,
51415 ArrayExpression: check
51416 };
51417 }
51418
51419};
51420
51421/***/ }),
51422/* 435 */
51423/***/ (function(module, exports, __webpack_require__) {
51424
51425"use strict";
51426/**
51427 * @fileoverview Rule to require braces in arrow function body.
51428 * @author Alberto Rodríguez
51429 */
51430 //------------------------------------------------------------------------------
51431// Requirements
51432//------------------------------------------------------------------------------
51433
51434const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
51435// Rule Definition
51436//------------------------------------------------------------------------------
51437
51438
51439module.exports = {
51440 meta: {
51441 type: "suggestion",
51442 docs: {
51443 description: "require braces around arrow function bodies",
51444 category: "ECMAScript 6",
51445 recommended: false,
51446 url: "https://eslint.org/docs/rules/arrow-body-style"
51447 },
51448 schema: {
51449 anyOf: [{
51450 type: "array",
51451 items: [{
51452 enum: ["always", "never"]
51453 }],
51454 minItems: 0,
51455 maxItems: 1
51456 }, {
51457 type: "array",
51458 items: [{
51459 enum: ["as-needed"]
51460 }, {
51461 type: "object",
51462 properties: {
51463 requireReturnForObjectLiteral: {
51464 type: "boolean"
51465 }
51466 },
51467 additionalProperties: false
51468 }],
51469 minItems: 0,
51470 maxItems: 2
51471 }]
51472 },
51473 fixable: "code",
51474 messages: {
51475 unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.",
51476 unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.",
51477 unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.",
51478 unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.",
51479 expectedBlock: "Expected block statement surrounding arrow body."
51480 }
51481 },
51482
51483 create(context) {
51484 const options = context.options;
51485 const always = options[0] === "always";
51486 const asNeeded = !options[0] || options[0] === "as-needed";
51487 const never = options[0] === "never";
51488 const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
51489 const sourceCode = context.getSourceCode();
51490 /**
51491 * Checks whether the given node has ASI problem or not.
51492 * @param {Token} token The token to check.
51493 * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed.
51494 */
51495
51496 function hasASIProblem(token) {
51497 return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value);
51498 }
51499 /**
51500 * Gets the closing parenthesis which is the pair of the given opening parenthesis.
51501 * @param {Token} token The opening parenthesis token to get.
51502 * @returns {Token} The found closing parenthesis token.
51503 */
51504
51505
51506 function findClosingParen(token) {
51507 let node = sourceCode.getNodeByRangeIndex(token.range[0]);
51508
51509 while (!astUtils.isParenthesised(sourceCode, node)) {
51510 node = node.parent;
51511 }
51512
51513 return sourceCode.getTokenAfter(node);
51514 }
51515 /**
51516 * Determines whether a arrow function body needs braces
51517 * @param {ASTNode} node The arrow function node.
51518 * @returns {void}
51519 */
51520
51521
51522 function validate(node) {
51523 const arrowBody = node.body;
51524
51525 if (arrowBody.type === "BlockStatement") {
51526 const blockBody = arrowBody.body;
51527
51528 if (blockBody.length !== 1 && !never) {
51529 return;
51530 }
51531
51532 if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") {
51533 return;
51534 }
51535
51536 if (never || asNeeded && blockBody[0].type === "ReturnStatement") {
51537 let messageId;
51538
51539 if (blockBody.length === 0) {
51540 messageId = "unexpectedEmptyBlock";
51541 } else if (blockBody.length > 1) {
51542 messageId = "unexpectedOtherBlock";
51543 } else if (blockBody[0].argument === null) {
51544 messageId = "unexpectedSingleBlock";
51545 } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], {
51546 skip: 1
51547 }))) {
51548 messageId = "unexpectedObjectBlock";
51549 } else {
51550 messageId = "unexpectedSingleBlock";
51551 }
51552
51553 context.report({
51554 node,
51555 loc: arrowBody.loc.start,
51556 messageId,
51557
51558 fix(fixer) {
51559 const fixes = [];
51560
51561 if (blockBody.length !== 1 || blockBody[0].type !== "ReturnStatement" || !blockBody[0].argument || hasASIProblem(sourceCode.getTokenAfter(arrowBody))) {
51562 return fixes;
51563 }
51564
51565 const openingBrace = sourceCode.getFirstToken(arrowBody);
51566 const closingBrace = sourceCode.getLastToken(arrowBody);
51567 const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1);
51568 const lastValueToken = sourceCode.getLastToken(blockBody[0]);
51569 const commentsExist = sourceCode.commentsExistBetween(openingBrace, firstValueToken) || sourceCode.commentsExistBetween(lastValueToken, closingBrace);
51570 /*
51571 * Remove tokens around the return value.
51572 * If comments don't exist, remove extra spaces as well.
51573 */
51574
51575 if (commentsExist) {
51576 fixes.push(fixer.remove(openingBrace), fixer.remove(closingBrace), fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword
51577 );
51578 } else {
51579 fixes.push(fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]), fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]]));
51580 }
51581 /*
51582 * If the first token of the reutrn value is `{` or the return value is a sequence expression,
51583 * enclose the return value by parentheses to avoid syntax error.
51584 */
51585
51586
51587 if (astUtils.isOpeningBraceToken(firstValueToken) || blockBody[0].argument.type === "SequenceExpression") {
51588 fixes.push(fixer.insertTextBefore(firstValueToken, "("), fixer.insertTextAfter(lastValueToken, ")"));
51589 }
51590 /*
51591 * If the last token of the return statement is semicolon, remove it.
51592 * Non-block arrow body is an expression, not a statement.
51593 */
51594
51595
51596 if (astUtils.isSemicolonToken(lastValueToken)) {
51597 fixes.push(fixer.remove(lastValueToken));
51598 }
51599
51600 return fixes;
51601 }
51602
51603 });
51604 }
51605 } else {
51606 if (always || asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression") {
51607 context.report({
51608 node,
51609 loc: arrowBody.loc.start,
51610 messageId: "expectedBlock",
51611
51612 fix(fixer) {
51613 const fixes = [];
51614 const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken);
51615 const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, {
51616 count: 2
51617 });
51618 const lastToken = sourceCode.getLastToken(node);
51619 const isParenthesisedObjectLiteral = astUtils.isOpeningParenToken(firstTokenAfterArrow) && astUtils.isOpeningBraceToken(secondTokenAfterArrow); // If the value is object literal, remove parentheses which were forced by syntax.
51620
51621 if (isParenthesisedObjectLiteral) {
51622 const openingParenToken = firstTokenAfterArrow;
51623 const openingBraceToken = secondTokenAfterArrow;
51624
51625 if (astUtils.isTokenOnSameLine(openingParenToken, openingBraceToken)) {
51626 fixes.push(fixer.replaceText(openingParenToken, "{return "));
51627 } else {
51628 // Avoid ASI
51629 fixes.push(fixer.replaceText(openingParenToken, "{"), fixer.insertTextBefore(openingBraceToken, "return "));
51630 } // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo()
51631
51632
51633 fixes.push(fixer.remove(findClosingParen(openingBraceToken)));
51634 fixes.push(fixer.insertTextAfter(lastToken, "}"));
51635 } else {
51636 fixes.push(fixer.insertTextBefore(firstTokenAfterArrow, "{return "));
51637 fixes.push(fixer.insertTextAfter(lastToken, "}"));
51638 }
51639
51640 return fixes;
51641 }
51642
51643 });
51644 }
51645 }
51646 }
51647
51648 return {
51649 "ArrowFunctionExpression:exit": validate
51650 };
51651 }
51652
51653};
51654
51655/***/ }),
51656/* 436 */
51657/***/ (function(module, exports, __webpack_require__) {
51658
51659"use strict";
51660/**
51661 * @fileoverview Rule to require parens in arrow function arguments.
51662 * @author Jxck
51663 */
51664 //------------------------------------------------------------------------------
51665// Requirements
51666//------------------------------------------------------------------------------
51667
51668const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
51669// Helpers
51670//------------------------------------------------------------------------------
51671
51672/**
51673 * Get location should be reported by AST node.
51674 * @param {ASTNode} node AST Node.
51675 * @returns {Location} Location information.
51676 */
51677
51678
51679function getLocation(node) {
51680 return {
51681 start: node.params[0].loc.start,
51682 end: node.params[node.params.length - 1].loc.end
51683 };
51684} //------------------------------------------------------------------------------
51685// Rule Definition
51686//------------------------------------------------------------------------------
51687
51688
51689module.exports = {
51690 meta: {
51691 type: "layout",
51692 docs: {
51693 description: "require parentheses around arrow function arguments",
51694 category: "ECMAScript 6",
51695 recommended: false,
51696 url: "https://eslint.org/docs/rules/arrow-parens"
51697 },
51698 fixable: "code",
51699 schema: [{
51700 enum: ["always", "as-needed"]
51701 }, {
51702 type: "object",
51703 properties: {
51704 requireForBlockBody: {
51705 type: "boolean",
51706 default: false
51707 }
51708 },
51709 additionalProperties: false
51710 }],
51711 messages: {
51712 unexpectedParens: "Unexpected parentheses around single function argument.",
51713 expectedParens: "Expected parentheses around arrow function argument.",
51714 unexpectedParensInline: "Unexpected parentheses around single function argument having a body with no curly braces.",
51715 expectedParensBlock: "Expected parentheses around arrow function argument having a body with curly braces."
51716 }
51717 },
51718
51719 create(context) {
51720 const asNeeded = context.options[0] === "as-needed";
51721 const requireForBlockBody = asNeeded && context.options[1] && context.options[1].requireForBlockBody === true;
51722 const sourceCode = context.getSourceCode();
51723 /**
51724 * Determines whether a arrow function argument end with `)`
51725 * @param {ASTNode} node The arrow function node.
51726 * @returns {void}
51727 */
51728
51729 function parens(node) {
51730 const isAsync = node.async;
51731 const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0);
51732 /**
51733 * Remove the parenthesis around a parameter
51734 * @param {Fixer} fixer Fixer
51735 * @returns {string} fixed parameter
51736 */
51737
51738 function fixParamsWithParenthesis(fixer) {
51739 const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
51740 /*
51741 * ES8 allows Trailing commas in function parameter lists and calls
51742 * https://github.com/eslint/eslint/issues/8834
51743 */
51744
51745 const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
51746 const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
51747 const shouldAddSpaceForAsync = asyncToken && asyncToken.range[1] === firstTokenOfParam.range[0];
51748 return fixer.replaceTextRange([firstTokenOfParam.range[0], closingParenToken.range[1]], "".concat(shouldAddSpaceForAsync ? " " : "").concat(paramToken.value));
6a5a0f88
TL
51749 }
51750 /**
51751 * Checks whether there are comments inside the params or not.
51752 * @returns {boolean} `true` if there are comments inside of parens, else `false`
51753 */
51754
51755
51756 function hasCommentsInParens() {
51757 if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
51758 const closingParenToken = sourceCode.getTokenAfter(node.params[0], astUtils.isClosingParenToken);
51759 return closingParenToken && sourceCode.commentsExistBetween(firstTokenOfParam, closingParenToken);
51760 }
51761
51762 return false;
51763 }
51764
51765 if (hasCommentsInParens()) {
51766 return;
eb39fafa
DC
51767 } // "as-needed", { "requireForBlockBody": true }: x => x
51768
51769
6a5a0f88 51770 if (requireForBlockBody && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && node.body.type !== "BlockStatement" && !node.returnType) {
eb39fafa
DC
51771 if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
51772 context.report({
51773 node,
51774 messageId: "unexpectedParensInline",
51775 loc: getLocation(node),
51776 fix: fixParamsWithParenthesis
51777 });
51778 }
51779
51780 return;
51781 }
51782
51783 if (requireForBlockBody && node.body.type === "BlockStatement") {
51784 if (!astUtils.isOpeningParenToken(firstTokenOfParam)) {
51785 context.report({
51786 node,
51787 messageId: "expectedParensBlock",
51788 loc: getLocation(node),
51789
51790 fix(fixer) {
51791 return fixer.replaceText(firstTokenOfParam, "(".concat(firstTokenOfParam.value, ")"));
51792 }
51793
51794 });
51795 }
51796
51797 return;
51798 } // "as-needed": x => x
51799
51800
6a5a0f88 51801 if (asNeeded && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.returnType) {
eb39fafa
DC
51802 if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
51803 context.report({
51804 node,
51805 messageId: "unexpectedParens",
51806 loc: getLocation(node),
51807 fix: fixParamsWithParenthesis
51808 });
51809 }
51810
51811 return;
51812 }
51813
51814 if (firstTokenOfParam.type === "Identifier") {
51815 const after = sourceCode.getTokenAfter(firstTokenOfParam); // (x) => x
51816
51817 if (after.value !== ")") {
51818 context.report({
51819 node,
51820 messageId: "expectedParens",
51821 loc: getLocation(node),
51822
51823 fix(fixer) {
51824 return fixer.replaceText(firstTokenOfParam, "(".concat(firstTokenOfParam.value, ")"));
51825 }
51826
51827 });
51828 }
51829 }
51830 }
51831
51832 return {
6a5a0f88 51833 "ArrowFunctionExpression[params.length=1]": parens
eb39fafa
DC
51834 };
51835 }
51836
51837};
51838
51839/***/ }),
51840/* 437 */
51841/***/ (function(module, exports, __webpack_require__) {
51842
51843"use strict";
51844/**
51845 * @fileoverview Rule to define spacing before/after arrow function's arrow.
51846 * @author Jxck
51847 */
51848 //------------------------------------------------------------------------------
51849// Requirements
51850//------------------------------------------------------------------------------
51851
51852const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
51853// Rule Definition
51854//------------------------------------------------------------------------------
51855
51856
51857module.exports = {
51858 meta: {
51859 type: "layout",
51860 docs: {
51861 description: "enforce consistent spacing before and after the arrow in arrow functions",
51862 category: "ECMAScript 6",
51863 recommended: false,
51864 url: "https://eslint.org/docs/rules/arrow-spacing"
51865 },
51866 fixable: "whitespace",
51867 schema: [{
51868 type: "object",
51869 properties: {
51870 before: {
51871 type: "boolean",
51872 default: true
51873 },
51874 after: {
51875 type: "boolean",
51876 default: true
51877 }
51878 },
51879 additionalProperties: false
51880 }],
51881 messages: {
51882 expectedBefore: "Missing space before =>.",
51883 unexpectedBefore: "Unexpected space before =>.",
51884 expectedAfter: "Missing space after =>.",
51885 unexpectedAfter: "Unexpected space after =>."
51886 }
51887 },
51888
51889 create(context) {
51890 // merge rules with default
51891 const rule = Object.assign({}, context.options[0]);
51892 rule.before = rule.before !== false;
51893 rule.after = rule.after !== false;
51894 const sourceCode = context.getSourceCode();
51895 /**
51896 * Get tokens of arrow(`=>`) and before/after arrow.
51897 * @param {ASTNode} node The arrow function node.
51898 * @returns {Object} Tokens of arrow and before/after arrow.
51899 */
51900
51901 function getTokens(node) {
51902 const arrow = sourceCode.getTokenBefore(node.body, astUtils.isArrowToken);
51903 return {
51904 before: sourceCode.getTokenBefore(arrow),
51905 arrow,
51906 after: sourceCode.getTokenAfter(arrow)
51907 };
51908 }
51909 /**
51910 * Count spaces before/after arrow(`=>`) token.
51911 * @param {Object} tokens Tokens before/after arrow.
51912 * @returns {Object} count of space before/after arrow.
51913 */
51914
51915
51916 function countSpaces(tokens) {
51917 const before = tokens.arrow.range[0] - tokens.before.range[1];
51918 const after = tokens.after.range[0] - tokens.arrow.range[1];
51919 return {
51920 before,
51921 after
51922 };
51923 }
51924 /**
51925 * Determines whether space(s) before after arrow(`=>`) is satisfy rule.
51926 * if before/after value is `true`, there should be space(s).
51927 * if before/after value is `false`, there should be no space.
51928 * @param {ASTNode} node The arrow function node.
51929 * @returns {void}
51930 */
51931
51932
51933 function spaces(node) {
51934 const tokens = getTokens(node);
51935 const countSpace = countSpaces(tokens);
51936
51937 if (rule.before) {
51938 // should be space(s) before arrow
51939 if (countSpace.before === 0) {
51940 context.report({
51941 node: tokens.before,
51942 messageId: "expectedBefore",
51943
51944 fix(fixer) {
51945 return fixer.insertTextBefore(tokens.arrow, " ");
51946 }
51947
51948 });
51949 }
51950 } else {
51951 // should be no space before arrow
51952 if (countSpace.before > 0) {
51953 context.report({
51954 node: tokens.before,
51955 messageId: "unexpectedBefore",
51956
51957 fix(fixer) {
51958 return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]);
51959 }
51960
51961 });
51962 }
51963 }
51964
51965 if (rule.after) {
51966 // should be space(s) after arrow
51967 if (countSpace.after === 0) {
51968 context.report({
51969 node: tokens.after,
51970 messageId: "expectedAfter",
51971
51972 fix(fixer) {
51973 return fixer.insertTextAfter(tokens.arrow, " ");
51974 }
51975
51976 });
51977 }
51978 } else {
51979 // should be no space after arrow
51980 if (countSpace.after > 0) {
51981 context.report({
51982 node: tokens.after,
51983 messageId: "unexpectedAfter",
51984
51985 fix(fixer) {
51986 return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]);
51987 }
51988
51989 });
51990 }
51991 }
51992 }
51993
51994 return {
51995 ArrowFunctionExpression: spaces
51996 };
51997 }
51998
51999};
52000
52001/***/ }),
52002/* 438 */
52003/***/ (function(module, exports, __webpack_require__) {
52004
52005"use strict";
52006/**
52007 * @fileoverview Rule to check for "block scoped" variables by binding context
52008 * @author Matt DuVall <http://www.mattduvall.com>
52009 */
52010 //------------------------------------------------------------------------------
52011// Rule Definition
52012//------------------------------------------------------------------------------
52013
52014module.exports = {
52015 meta: {
52016 type: "suggestion",
52017 docs: {
52018 description: "enforce the use of variables within the scope they are defined",
52019 category: "Best Practices",
52020 recommended: false,
52021 url: "https://eslint.org/docs/rules/block-scoped-var"
52022 },
52023 schema: [],
52024 messages: {
52025 outOfScope: "'{{name}}' used outside of binding context."
52026 }
52027 },
52028
52029 create(context) {
52030 let stack = [];
52031 /**
52032 * Makes a block scope.
52033 * @param {ASTNode} node A node of a scope.
52034 * @returns {void}
52035 */
52036
52037 function enterScope(node) {
52038 stack.push(node.range);
52039 }
52040 /**
52041 * Pops the last block scope.
52042 * @returns {void}
52043 */
52044
52045
52046 function exitScope() {
52047 stack.pop();
52048 }
52049 /**
52050 * Reports a given reference.
52051 * @param {eslint-scope.Reference} reference A reference to report.
52052 * @returns {void}
52053 */
52054
52055
52056 function report(reference) {
52057 const identifier = reference.identifier;
52058 context.report({
52059 node: identifier,
52060 messageId: "outOfScope",
52061 data: {
52062 name: identifier.name
52063 }
52064 });
52065 }
52066 /**
52067 * Finds and reports references which are outside of valid scopes.
52068 * @param {ASTNode} node A node to get variables.
52069 * @returns {void}
52070 */
52071
52072
52073 function checkForVariables(node) {
52074 if (node.kind !== "var") {
52075 return;
52076 } // Defines a predicate to check whether or not a given reference is outside of valid scope.
52077
52078
52079 const scopeRange = stack[stack.length - 1];
52080 /**
52081 * Check if a reference is out of scope
52082 * @param {ASTNode} reference node to examine
52083 * @returns {boolean} True is its outside the scope
52084 * @private
52085 */
52086
52087 function isOutsideOfScope(reference) {
52088 const idRange = reference.identifier.range;
52089 return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1];
52090 } // Gets declared variables, and checks its references.
52091
52092
52093 const variables = context.getDeclaredVariables(node);
52094
52095 for (let i = 0; i < variables.length; ++i) {
52096 // Reports.
52097 variables[i].references.filter(isOutsideOfScope).forEach(report);
52098 }
52099 }
52100
52101 return {
52102 Program(node) {
52103 stack = [node.range];
52104 },
52105
52106 // Manages scopes.
52107 BlockStatement: enterScope,
52108 "BlockStatement:exit": exitScope,
52109 ForStatement: enterScope,
52110 "ForStatement:exit": exitScope,
52111 ForInStatement: enterScope,
52112 "ForInStatement:exit": exitScope,
52113 ForOfStatement: enterScope,
52114 "ForOfStatement:exit": exitScope,
52115 SwitchStatement: enterScope,
52116 "SwitchStatement:exit": exitScope,
52117 CatchClause: enterScope,
52118 "CatchClause:exit": exitScope,
52119 // Finds and reports references which are outside of valid scope.
52120 VariableDeclaration: checkForVariables
52121 };
52122 }
52123
52124};
52125
52126/***/ }),
52127/* 439 */
52128/***/ (function(module, exports, __webpack_require__) {
52129
52130"use strict";
52131/**
52132 * @fileoverview A rule to disallow or enforce spaces inside of single line blocks.
52133 * @author Toru Nagashima
52134 */
52135
52136
52137const util = __webpack_require__(426); //------------------------------------------------------------------------------
52138// Rule Definition
52139//------------------------------------------------------------------------------
52140
52141
52142module.exports = {
52143 meta: {
52144 type: "layout",
52145 docs: {
52146 description: "disallow or enforce spaces inside of blocks after opening block and before closing block",
52147 category: "Stylistic Issues",
52148 recommended: false,
52149 url: "https://eslint.org/docs/rules/block-spacing"
52150 },
52151 fixable: "whitespace",
52152 schema: [{
52153 enum: ["always", "never"]
52154 }],
52155 messages: {
52156 missing: "Requires a space {{location}} '{{token}}'.",
52157 extra: "Unexpected space(s) {{location}} '{{token}}'."
52158 }
52159 },
52160
52161 create(context) {
52162 const always = context.options[0] !== "never",
52163 messageId = always ? "missing" : "extra",
52164 sourceCode = context.getSourceCode();
52165 /**
52166 * Gets the open brace token from a given node.
52167 * @param {ASTNode} node A BlockStatement/SwitchStatement node to get.
52168 * @returns {Token} The token of the open brace.
52169 */
52170
52171 function getOpenBrace(node) {
52172 if (node.type === "SwitchStatement") {
52173 if (node.cases.length > 0) {
52174 return sourceCode.getTokenBefore(node.cases[0]);
52175 }
52176
52177 return sourceCode.getLastToken(node, 1);
52178 }
52179
52180 return sourceCode.getFirstToken(node);
52181 }
52182 /**
52183 * Checks whether or not:
52184 * - given tokens are on same line.
52185 * - there is/isn't a space between given tokens.
52186 * @param {Token} left A token to check.
52187 * @param {Token} right The token which is next to `left`.
52188 * @returns {boolean}
52189 * When the option is `"always"`, `true` if there are one or more spaces between given tokens.
52190 * When the option is `"never"`, `true` if there are not any spaces between given tokens.
52191 * If given tokens are not on same line, it's always `true`.
52192 */
52193
52194
52195 function isValid(left, right) {
52196 return !util.isTokenOnSameLine(left, right) || sourceCode.isSpaceBetweenTokens(left, right) === always;
52197 }
52198 /**
52199 * Reports invalid spacing style inside braces.
52200 * @param {ASTNode} node A BlockStatement/SwitchStatement node to get.
52201 * @returns {void}
52202 */
52203
52204
52205 function checkSpacingInsideBraces(node) {
52206 // Gets braces and the first/last token of content.
52207 const openBrace = getOpenBrace(node);
52208 const closeBrace = sourceCode.getLastToken(node);
52209 const firstToken = sourceCode.getTokenAfter(openBrace, {
52210 includeComments: true
52211 });
52212 const lastToken = sourceCode.getTokenBefore(closeBrace, {
52213 includeComments: true
52214 }); // Skip if the node is invalid or empty.
52215
52216 if (openBrace.type !== "Punctuator" || openBrace.value !== "{" || closeBrace.type !== "Punctuator" || closeBrace.value !== "}" || firstToken === closeBrace) {
52217 return;
52218 } // Skip line comments for option never
52219
52220
52221 if (!always && firstToken.type === "Line") {
52222 return;
52223 } // Check.
52224
52225
52226 if (!isValid(openBrace, firstToken)) {
6a5a0f88
TL
52227 let loc = openBrace.loc;
52228
52229 if (messageId === "extra") {
52230 loc = {
52231 start: openBrace.loc.end,
52232 end: firstToken.loc.start
52233 };
52234 }
52235
eb39fafa
DC
52236 context.report({
52237 node,
6a5a0f88 52238 loc,
eb39fafa
DC
52239 messageId,
52240 data: {
52241 location: "after",
52242 token: openBrace.value
52243 },
52244
52245 fix(fixer) {
52246 if (always) {
52247 return fixer.insertTextBefore(firstToken, " ");
52248 }
52249
52250 return fixer.removeRange([openBrace.range[1], firstToken.range[0]]);
52251 }
52252
52253 });
52254 }
52255
52256 if (!isValid(lastToken, closeBrace)) {
6a5a0f88
TL
52257 let loc = closeBrace.loc;
52258
52259 if (messageId === "extra") {
52260 loc = {
52261 start: lastToken.loc.end,
52262 end: closeBrace.loc.start
52263 };
52264 }
52265
eb39fafa
DC
52266 context.report({
52267 node,
6a5a0f88 52268 loc,
eb39fafa
DC
52269 messageId,
52270 data: {
52271 location: "before",
52272 token: closeBrace.value
52273 },
52274
52275 fix(fixer) {
52276 if (always) {
52277 return fixer.insertTextAfter(lastToken, " ");
52278 }
52279
52280 return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]);
52281 }
52282
52283 });
52284 }
52285 }
52286
52287 return {
52288 BlockStatement: checkSpacingInsideBraces,
52289 SwitchStatement: checkSpacingInsideBraces
52290 };
52291 }
52292
52293};
52294
52295/***/ }),
52296/* 440 */
52297/***/ (function(module, exports, __webpack_require__) {
52298
52299"use strict";
52300/**
52301 * @fileoverview Rule to flag block statements that do not use the one true brace style
52302 * @author Ian Christian Myers
52303 */
52304
52305
52306const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
52307// Rule Definition
52308//------------------------------------------------------------------------------
52309
52310
52311module.exports = {
52312 meta: {
52313 type: "layout",
52314 docs: {
52315 description: "enforce consistent brace style for blocks",
52316 category: "Stylistic Issues",
52317 recommended: false,
52318 url: "https://eslint.org/docs/rules/brace-style"
52319 },
52320 schema: [{
52321 enum: ["1tbs", "stroustrup", "allman"]
52322 }, {
52323 type: "object",
52324 properties: {
52325 allowSingleLine: {
52326 type: "boolean",
52327 default: false
52328 }
52329 },
52330 additionalProperties: false
52331 }],
52332 fixable: "whitespace",
52333 messages: {
52334 nextLineOpen: "Opening curly brace does not appear on the same line as controlling statement.",
52335 sameLineOpen: "Opening curly brace appears on the same line as controlling statement.",
52336 blockSameLine: "Statement inside of curly braces should be on next line.",
52337 nextLineClose: "Closing curly brace does not appear on the same line as the subsequent block.",
52338 singleLineClose: "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.",
52339 sameLineClose: "Closing curly brace appears on the same line as the subsequent block."
52340 }
52341 },
52342
52343 create(context) {
52344 const style = context.options[0] || "1tbs",
52345 params = context.options[1] || {},
52346 sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
52347 // Helpers
52348 //--------------------------------------------------------------------------
52349
52350 /**
52351 * Fixes a place where a newline unexpectedly appears
52352 * @param {Token} firstToken The token before the unexpected newline
52353 * @param {Token} secondToken The token after the unexpected newline
52354 * @returns {Function} A fixer function to remove the newlines between the tokens
52355 */
52356
52357 function removeNewlineBetween(firstToken, secondToken) {
52358 const textRange = [firstToken.range[1], secondToken.range[0]];
52359 const textBetween = sourceCode.text.slice(textRange[0], textRange[1]); // Don't do a fix if there is a comment between the tokens
52360
52361 if (textBetween.trim()) {
52362 return null;
52363 }
52364
52365 return fixer => fixer.replaceTextRange(textRange, " ");
52366 }
52367 /**
52368 * Validates a pair of curly brackets based on the user's config
52369 * @param {Token} openingCurly The opening curly bracket
52370 * @param {Token} closingCurly The closing curly bracket
52371 * @returns {void}
52372 */
52373
52374
52375 function validateCurlyPair(openingCurly, closingCurly) {
52376 const tokenBeforeOpeningCurly = sourceCode.getTokenBefore(openingCurly);
52377 const tokenAfterOpeningCurly = sourceCode.getTokenAfter(openingCurly);
52378 const tokenBeforeClosingCurly = sourceCode.getTokenBefore(closingCurly);
52379 const singleLineException = params.allowSingleLine && astUtils.isTokenOnSameLine(openingCurly, closingCurly);
52380
52381 if (style !== "allman" && !astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly)) {
52382 context.report({
52383 node: openingCurly,
52384 messageId: "nextLineOpen",
52385 fix: removeNewlineBetween(tokenBeforeOpeningCurly, openingCurly)
52386 });
52387 }
52388
52389 if (style === "allman" && astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly) && !singleLineException) {
52390 context.report({
52391 node: openingCurly,
52392 messageId: "sameLineOpen",
52393 fix: fixer => fixer.insertTextBefore(openingCurly, "\n")
52394 });
52395 }
52396
52397 if (astUtils.isTokenOnSameLine(openingCurly, tokenAfterOpeningCurly) && tokenAfterOpeningCurly !== closingCurly && !singleLineException) {
52398 context.report({
52399 node: openingCurly,
52400 messageId: "blockSameLine",
52401 fix: fixer => fixer.insertTextAfter(openingCurly, "\n")
52402 });
52403 }
52404
52405 if (tokenBeforeClosingCurly !== openingCurly && !singleLineException && astUtils.isTokenOnSameLine(tokenBeforeClosingCurly, closingCurly)) {
52406 context.report({
52407 node: closingCurly,
52408 messageId: "singleLineClose",
52409 fix: fixer => fixer.insertTextBefore(closingCurly, "\n")
52410 });
52411 }
52412 }
52413 /**
52414 * Validates the location of a token that appears before a keyword (e.g. a newline before `else`)
52415 * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`).
52416 * @returns {void}
52417 */
52418
52419
52420 function validateCurlyBeforeKeyword(curlyToken) {
52421 const keywordToken = sourceCode.getTokenAfter(curlyToken);
52422
52423 if (style === "1tbs" && !astUtils.isTokenOnSameLine(curlyToken, keywordToken)) {
52424 context.report({
52425 node: curlyToken,
52426 messageId: "nextLineClose",
52427 fix: removeNewlineBetween(curlyToken, keywordToken)
52428 });
52429 }
52430
52431 if (style !== "1tbs" && astUtils.isTokenOnSameLine(curlyToken, keywordToken)) {
52432 context.report({
52433 node: curlyToken,
52434 messageId: "sameLineClose",
52435 fix: fixer => fixer.insertTextAfter(curlyToken, "\n")
52436 });
52437 }
52438 } //--------------------------------------------------------------------------
52439 // Public API
52440 //--------------------------------------------------------------------------
52441
52442
52443 return {
52444 BlockStatement(node) {
52445 if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
52446 validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node));
52447 }
52448 },
52449
52450 ClassBody(node) {
52451 validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node));
52452 },
52453
52454 SwitchStatement(node) {
52455 const closingCurly = sourceCode.getLastToken(node);
52456 const openingCurly = sourceCode.getTokenBefore(node.cases.length ? node.cases[0] : closingCurly);
52457 validateCurlyPair(openingCurly, closingCurly);
52458 },
52459
52460 IfStatement(node) {
52461 if (node.consequent.type === "BlockStatement" && node.alternate) {
52462 // Handle the keyword after the `if` block (before `else`)
52463 validateCurlyBeforeKeyword(sourceCode.getLastToken(node.consequent));
52464 }
52465 },
52466
52467 TryStatement(node) {
52468 // Handle the keyword after the `try` block (before `catch` or `finally`)
52469 validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block));
52470
52471 if (node.handler && node.finalizer) {
52472 // Handle the keyword after the `catch` block (before `finally`)
52473 validateCurlyBeforeKeyword(sourceCode.getLastToken(node.handler.body));
52474 }
52475 }
52476
52477 };
52478 }
52479
52480};
52481
52482/***/ }),
52483/* 441 */
52484/***/ (function(module, exports, __webpack_require__) {
52485
52486"use strict";
52487/**
52488 * @fileoverview Enforce return after a callback.
52489 * @author Jamund Ferguson
52490 */
52491 //------------------------------------------------------------------------------
52492// Rule Definition
52493//------------------------------------------------------------------------------
52494
52495module.exports = {
52496 meta: {
56c4a2cb 52497 deprecated: true,
6a5a0f88 52498 replacedBy: [],
eb39fafa
DC
52499 type: "suggestion",
52500 docs: {
52501 description: "require `return` statements after callbacks",
52502 category: "Node.js and CommonJS",
52503 recommended: false,
52504 url: "https://eslint.org/docs/rules/callback-return"
52505 },
52506 schema: [{
52507 type: "array",
52508 items: {
52509 type: "string"
52510 }
52511 }],
52512 messages: {
52513 missingReturn: "Expected return with your callback function."
52514 }
52515 },
52516
52517 create(context) {
52518 const callbacks = context.options[0] || ["callback", "cb", "next"],
52519 sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
52520 // Helpers
52521 //--------------------------------------------------------------------------
52522
52523 /**
52524 * Find the closest parent matching a list of types.
52525 * @param {ASTNode} node The node whose parents we are searching
52526 * @param {Array} types The node types to match
52527 * @returns {ASTNode} The matched node or undefined.
52528 */
52529
52530 function findClosestParentOfType(node, types) {
52531 if (!node.parent) {
52532 return null;
52533 }
52534
52535 if (types.indexOf(node.parent.type) === -1) {
52536 return findClosestParentOfType(node.parent, types);
52537 }
52538
52539 return node.parent;
52540 }
52541 /**
52542 * Check to see if a node contains only identifers
52543 * @param {ASTNode} node The node to check
52544 * @returns {boolean} Whether or not the node contains only identifers
52545 */
52546
52547
52548 function containsOnlyIdentifiers(node) {
52549 if (node.type === "Identifier") {
52550 return true;
52551 }
52552
52553 if (node.type === "MemberExpression") {
52554 if (node.object.type === "Identifier") {
52555 return true;
52556 }
52557
52558 if (node.object.type === "MemberExpression") {
52559 return containsOnlyIdentifiers(node.object);
52560 }
52561 }
52562
52563 return false;
52564 }
52565 /**
52566 * Check to see if a CallExpression is in our callback list.
52567 * @param {ASTNode} node The node to check against our callback names list.
52568 * @returns {boolean} Whether or not this function matches our callback name.
52569 */
52570
52571
52572 function isCallback(node) {
52573 return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1;
52574 }
52575 /**
52576 * Determines whether or not the callback is part of a callback expression.
52577 * @param {ASTNode} node The callback node
52578 * @param {ASTNode} parentNode The expression node
52579 * @returns {boolean} Whether or not this is part of a callback expression
52580 */
52581
52582
52583 function isCallbackExpression(node, parentNode) {
52584 // ensure the parent node exists and is an expression
52585 if (!parentNode || parentNode.type !== "ExpressionStatement") {
52586 return false;
52587 } // cb()
52588
52589
52590 if (parentNode.expression === node) {
52591 return true;
52592 } // special case for cb && cb() and similar
52593
52594
52595 if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") {
52596 if (parentNode.expression.right === node) {
52597 return true;
52598 }
52599 }
52600
52601 return false;
52602 } //--------------------------------------------------------------------------
52603 // Public
52604 //--------------------------------------------------------------------------
52605
52606
52607 return {
52608 CallExpression(node) {
52609 // if we're not a callback we can return
52610 if (!isCallback(node)) {
52611 return;
52612 } // find the closest block, return or loop
52613
52614
52615 const closestBlock = findClosestParentOfType(node, ["BlockStatement", "ReturnStatement", "ArrowFunctionExpression"]) || {}; // if our parent is a return we know we're ok
52616
52617 if (closestBlock.type === "ReturnStatement") {
52618 return;
52619 } // arrow functions don't always have blocks and implicitly return
52620
52621
52622 if (closestBlock.type === "ArrowFunctionExpression") {
52623 return;
52624 } // block statements are part of functions and most if statements
52625
52626
52627 if (closestBlock.type === "BlockStatement") {
52628 // find the last item in the block
52629 const lastItem = closestBlock.body[closestBlock.body.length - 1]; // if the callback is the last thing in a block that might be ok
52630
52631 if (isCallbackExpression(node, lastItem)) {
52632 const parentType = closestBlock.parent.type; // but only if the block is part of a function
52633
52634 if (parentType === "FunctionExpression" || parentType === "FunctionDeclaration" || parentType === "ArrowFunctionExpression") {
52635 return;
52636 }
52637 } // ending a block with a return is also ok
52638
52639
52640 if (lastItem.type === "ReturnStatement") {
52641 // but only if the callback is immediately before
52642 if (isCallbackExpression(node, closestBlock.body[closestBlock.body.length - 2])) {
52643 return;
52644 }
52645 }
52646 } // as long as you're the child of a function at this point you should be asked to return
52647
52648
52649 if (findClosestParentOfType(node, ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"])) {
52650 context.report({
52651 node,
52652 messageId: "missingReturn"
52653 });
52654 }
52655 }
52656
52657 };
52658 }
52659
52660};
52661
52662/***/ }),
52663/* 442 */
52664/***/ (function(module, exports, __webpack_require__) {
52665
52666"use strict";
52667/**
52668 * @fileoverview Rule to flag non-camelcased identifiers
52669 * @author Nicholas C. Zakas
52670 */
52671 //------------------------------------------------------------------------------
52672// Rule Definition
52673//------------------------------------------------------------------------------
52674
52675module.exports = {
52676 meta: {
52677 type: "suggestion",
52678 docs: {
52679 description: "enforce camelcase naming convention",
52680 category: "Stylistic Issues",
52681 recommended: false,
52682 url: "https://eslint.org/docs/rules/camelcase"
52683 },
52684 schema: [{
52685 type: "object",
52686 properties: {
52687 ignoreDestructuring: {
52688 type: "boolean",
52689 default: false
52690 },
52691 ignoreImports: {
52692 type: "boolean",
52693 default: false
52694 },
52695 properties: {
52696 enum: ["always", "never"]
52697 },
52698 allow: {
52699 type: "array",
52700 items: [{
52701 type: "string"
52702 }],
52703 minItems: 0,
52704 uniqueItems: true
52705 }
52706 },
52707 additionalProperties: false
52708 }],
52709 messages: {
52710 notCamelCase: "Identifier '{{name}}' is not in camel case."
52711 }
52712 },
52713
52714 create(context) {
52715 const options = context.options[0] || {};
52716 let properties = options.properties || "";
52717 const ignoreDestructuring = options.ignoreDestructuring;
52718 const ignoreImports = options.ignoreImports;
52719 const allow = options.allow || [];
52720
52721 if (properties !== "always" && properties !== "never") {
52722 properties = "always";
52723 } //--------------------------------------------------------------------------
52724 // Helpers
52725 //--------------------------------------------------------------------------
52726 // contains reported nodes to avoid reporting twice on destructuring with shorthand notation
52727
52728
52729 const reported = [];
52730 const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]);
52731 /**
52732 * Checks if a string contains an underscore and isn't all upper-case
52733 * @param {string} name The string to check.
52734 * @returns {boolean} if the string is underscored
52735 * @private
52736 */
52737
52738 function isUnderscored(name) {
52739 // if there's an underscore, it might be A_CONSTANT, which is okay
52740 return name.includes("_") && name !== name.toUpperCase();
52741 }
52742 /**
52743 * Checks if a string match the ignore list
52744 * @param {string} name The string to check.
52745 * @returns {boolean} if the string is ignored
52746 * @private
52747 */
52748
52749
52750 function isAllowed(name) {
52751 return allow.some(entry => name === entry || name.match(new RegExp(entry, "u")));
52752 }
52753 /**
52754 * Checks if a parent of a node is an ObjectPattern.
52755 * @param {ASTNode} node The node to check.
52756 * @returns {boolean} if the node is inside an ObjectPattern
52757 * @private
52758 */
52759
52760
52761 function isInsideObjectPattern(node) {
52762 let current = node;
52763
52764 while (current) {
52765 const parent = current.parent;
52766
52767 if (parent && parent.type === "Property" && parent.computed && parent.key === current) {
52768 return false;
52769 }
52770
52771 if (current.type === "ObjectPattern") {
52772 return true;
52773 }
52774
52775 current = parent;
52776 }
52777
52778 return false;
52779 }
52780 /**
52781 * Checks whether the given node represents assignment target property in destructuring.
52782 *
52783 * For examples:
52784 * ({a: b.foo} = c); // => true for `foo`
52785 * ([a.foo] = b); // => true for `foo`
52786 * ([a.foo = 1] = b); // => true for `foo`
52787 * ({...a.foo} = b); // => true for `foo`
52788 * @param {ASTNode} node An Identifier node to check
52789 * @returns {boolean} True if the node is an assignment target property in destructuring.
52790 */
52791
52792
52793 function isAssignmentTargetPropertyInDestructuring(node) {
52794 if (node.parent.type === "MemberExpression" && node.parent.property === node && !node.parent.computed) {
52795 const effectiveParent = node.parent.parent;
52796 return effectiveParent.type === "Property" && effectiveParent.value === node.parent && effectiveParent.parent.type === "ObjectPattern" || effectiveParent.type === "ArrayPattern" || effectiveParent.type === "RestElement" || effectiveParent.type === "AssignmentPattern" && effectiveParent.left === node.parent;
52797 }
52798
52799 return false;
52800 }
52801 /**
52802 * Reports an AST node as a rule violation.
52803 * @param {ASTNode} node The node to report.
52804 * @returns {void}
52805 * @private
52806 */
52807
52808
52809 function report(node) {
52810 if (!reported.includes(node)) {
52811 reported.push(node);
52812 context.report({
52813 node,
52814 messageId: "notCamelCase",
52815 data: {
52816 name: node.name
52817 }
52818 });
52819 }
52820 }
52821
52822 return {
52823 Identifier(node) {
52824 /*
52825 * Leading and trailing underscores are commonly used to flag
52826 * private/protected identifiers, strip them before checking if underscored
52827 */
52828 const name = node.name,
52829 nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/gu, "")),
52830 effectiveParent = node.parent.type === "MemberExpression" ? node.parent.parent : node.parent; // First, we ignore the node if it match the ignore list
52831
52832 if (isAllowed(name)) {
52833 return;
52834 } // MemberExpressions get special rules
52835
52836
52837 if (node.parent.type === "MemberExpression") {
52838 // "never" check properties
52839 if (properties === "never") {
52840 return;
52841 } // Always report underscored object names
52842
52843
52844 if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && nameIsUnderscored) {
52845 report(node); // Report AssignmentExpressions only if they are the left side of the assignment
52846 } else if (effectiveParent.type === "AssignmentExpression" && nameIsUnderscored && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) {
52847 report(node);
52848 } else if (isAssignmentTargetPropertyInDestructuring(node) && nameIsUnderscored) {
52849 report(node);
52850 }
52851 /*
52852 * Properties have their own rules, and
52853 * AssignmentPattern nodes can be treated like Properties:
52854 * e.g.: const { no_camelcased = false } = bar;
52855 */
52856
52857 } else if (node.parent.type === "Property" || node.parent.type === "AssignmentPattern") {
52858 if (node.parent.parent && node.parent.parent.type === "ObjectPattern") {
52859 if (node.parent.shorthand && node.parent.value.left && nameIsUnderscored) {
52860 report(node);
52861 }
52862
52863 const assignmentKeyEqualsValue = node.parent.key.name === node.parent.value.name;
52864
52865 if (nameIsUnderscored && node.parent.computed) {
52866 report(node);
52867 } // prevent checking righthand side of destructured object
52868
52869
52870 if (node.parent.key === node && node.parent.value !== node) {
52871 return;
52872 }
52873
52874 const valueIsUnderscored = node.parent.value.name && nameIsUnderscored; // ignore destructuring if the option is set, unless a new identifier is created
52875
52876 if (valueIsUnderscored && !(assignmentKeyEqualsValue && ignoreDestructuring)) {
52877 report(node);
52878 }
52879 } // "never" check properties or always ignore destructuring
52880
52881
52882 if (properties === "never" || ignoreDestructuring && isInsideObjectPattern(node)) {
52883 return;
52884 } // don't check right hand side of AssignmentExpression to prevent duplicate warnings
52885
52886
52887 if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) {
52888 report(node);
52889 } // Check if it's an import specifier
52890
52891 } else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].includes(node.parent.type)) {
52892 if (node.parent.type === "ImportSpecifier" && ignoreImports) {
52893 return;
52894 } // Report only if the local imported identifier is underscored
52895
52896
52897 if (node.parent.local && node.parent.local.name === node.name && nameIsUnderscored) {
52898 report(node);
52899 } // Report anything that is underscored that isn't a CallExpression
52900
52901 } else if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
52902 report(node);
52903 }
52904 }
52905
52906 };
52907 }
52908
52909};
52910
52911/***/ }),
52912/* 443 */
52913/***/ (function(module, exports, __webpack_require__) {
52914
52915"use strict";
52916/**
52917 * @fileoverview enforce or disallow capitalization of the first letter of a comment
52918 * @author Kevin Partington
52919 */
52920 //------------------------------------------------------------------------------
52921// Requirements
52922//------------------------------------------------------------------------------
52923
52924const LETTER_PATTERN = __webpack_require__(444);
52925
52926const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
52927// Helpers
52928//------------------------------------------------------------------------------
52929
52930
52931const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN,
52932 WHITESPACE = /\s/gu,
52933 MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u; // TODO: Combine w/ max-len pattern?
52934
52935/*
52936 * Base schema body for defining the basic capitalization rule, ignorePattern,
52937 * and ignoreInlineComments values.
52938 * This can be used in a few different ways in the actual schema.
52939 */
52940
52941const SCHEMA_BODY = {
52942 type: "object",
52943 properties: {
52944 ignorePattern: {
52945 type: "string"
52946 },
52947 ignoreInlineComments: {
52948 type: "boolean"
52949 },
52950 ignoreConsecutiveComments: {
52951 type: "boolean"
52952 }
52953 },
52954 additionalProperties: false
52955};
52956const DEFAULTS = {
52957 ignorePattern: "",
52958 ignoreInlineComments: false,
52959 ignoreConsecutiveComments: false
52960};
52961/**
52962 * Get normalized options for either block or line comments from the given
52963 * user-provided options.
52964 * - If the user-provided options is just a string, returns a normalized
52965 * set of options using default values for all other options.
52966 * - If the user-provided options is an object, then a normalized option
52967 * set is returned. Options specified in overrides will take priority
52968 * over options specified in the main options object, which will in
52969 * turn take priority over the rule's defaults.
52970 * @param {Object|string} rawOptions The user-provided options.
52971 * @param {string} which Either "line" or "block".
52972 * @returns {Object} The normalized options.
52973 */
52974
52975function getNormalizedOptions(rawOptions, which) {
52976 return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions);
52977}
52978/**
52979 * Get normalized options for block and line comments.
52980 * @param {Object|string} rawOptions The user-provided options.
52981 * @returns {Object} An object with "Line" and "Block" keys and corresponding
52982 * normalized options objects.
52983 */
52984
52985
52986function getAllNormalizedOptions(rawOptions = {}) {
52987 return {
52988 Line: getNormalizedOptions(rawOptions, "line"),
52989 Block: getNormalizedOptions(rawOptions, "block")
52990 };
52991}
52992/**
52993 * Creates a regular expression for each ignorePattern defined in the rule
52994 * options.
52995 *
52996 * This is done in order to avoid invoking the RegExp constructor repeatedly.
52997 * @param {Object} normalizedOptions The normalized rule options.
52998 * @returns {void}
52999 */
53000
53001
53002function createRegExpForIgnorePatterns(normalizedOptions) {
53003 Object.keys(normalizedOptions).forEach(key => {
53004 const ignorePatternStr = normalizedOptions[key].ignorePattern;
53005
53006 if (ignorePatternStr) {
53007 const regExp = RegExp("^\\s*(?:".concat(ignorePatternStr, ")"), "u");
53008 normalizedOptions[key].ignorePatternRegExp = regExp;
53009 }
53010 });
53011} //------------------------------------------------------------------------------
53012// Rule Definition
53013//------------------------------------------------------------------------------
53014
53015
53016module.exports = {
53017 meta: {
53018 type: "suggestion",
53019 docs: {
53020 description: "enforce or disallow capitalization of the first letter of a comment",
53021 category: "Stylistic Issues",
53022 recommended: false,
53023 url: "https://eslint.org/docs/rules/capitalized-comments"
53024 },
53025 fixable: "code",
53026 schema: [{
53027 enum: ["always", "never"]
53028 }, {
53029 oneOf: [SCHEMA_BODY, {
53030 type: "object",
53031 properties: {
53032 line: SCHEMA_BODY,
53033 block: SCHEMA_BODY
53034 },
53035 additionalProperties: false
53036 }]
53037 }],
53038 messages: {
53039 unexpectedLowercaseComment: "Comments should not begin with a lowercase character.",
53040 unexpectedUppercaseComment: "Comments should not begin with an uppercase character."
53041 }
53042 },
53043
53044 create(context) {
53045 const capitalize = context.options[0] || "always",
53046 normalizedOptions = getAllNormalizedOptions(context.options[1]),
53047 sourceCode = context.getSourceCode();
53048 createRegExpForIgnorePatterns(normalizedOptions); //----------------------------------------------------------------------
53049 // Helpers
53050 //----------------------------------------------------------------------
53051
53052 /**
53053 * Checks whether a comment is an inline comment.
53054 *
53055 * For the purpose of this rule, a comment is inline if:
53056 * 1. The comment is preceded by a token on the same line; and
53057 * 2. The command is followed by a token on the same line.
53058 *
53059 * Note that the comment itself need not be single-line!
53060 *
53061 * Also, it follows from this definition that only block comments can
53062 * be considered as possibly inline. This is because line comments
53063 * would consume any following tokens on the same line as the comment.
53064 * @param {ASTNode} comment The comment node to check.
53065 * @returns {boolean} True if the comment is an inline comment, false
53066 * otherwise.
53067 */
53068
53069 function isInlineComment(comment) {
53070 const previousToken = sourceCode.getTokenBefore(comment, {
53071 includeComments: true
53072 }),
53073 nextToken = sourceCode.getTokenAfter(comment, {
53074 includeComments: true
53075 });
53076 return Boolean(previousToken && nextToken && comment.loc.start.line === previousToken.loc.end.line && comment.loc.end.line === nextToken.loc.start.line);
53077 }
53078 /**
53079 * Determine if a comment follows another comment.
53080 * @param {ASTNode} comment The comment to check.
53081 * @returns {boolean} True if the comment follows a valid comment.
53082 */
53083
53084
53085 function isConsecutiveComment(comment) {
53086 const previousTokenOrComment = sourceCode.getTokenBefore(comment, {
53087 includeComments: true
53088 });
53089 return Boolean(previousTokenOrComment && ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1);
53090 }
53091 /**
53092 * Check a comment to determine if it is valid for this rule.
53093 * @param {ASTNode} comment The comment node to process.
53094 * @param {Object} options The options for checking this comment.
53095 * @returns {boolean} True if the comment is valid, false otherwise.
53096 */
53097
53098
53099 function isCommentValid(comment, options) {
53100 // 1. Check for default ignore pattern.
53101 if (DEFAULT_IGNORE_PATTERN.test(comment.value)) {
53102 return true;
53103 } // 2. Check for custom ignore pattern.
53104
53105
53106 const commentWithoutAsterisks = comment.value.replace(/\*/gu, "");
53107
53108 if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) {
53109 return true;
53110 } // 3. Check for inline comments.
53111
53112
53113 if (options.ignoreInlineComments && isInlineComment(comment)) {
53114 return true;
53115 } // 4. Is this a consecutive comment (and are we tolerating those)?
53116
53117
53118 if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) {
53119 return true;
53120 } // 5. Does the comment start with a possible URL?
53121
53122
53123 if (MAYBE_URL.test(commentWithoutAsterisks)) {
53124 return true;
53125 } // 6. Is the initial word character a letter?
53126
53127
53128 const commentWordCharsOnly = commentWithoutAsterisks.replace(WHITESPACE, "");
53129
53130 if (commentWordCharsOnly.length === 0) {
53131 return true;
53132 }
53133
53134 const firstWordChar = commentWordCharsOnly[0];
53135
53136 if (!LETTER_PATTERN.test(firstWordChar)) {
53137 return true;
53138 } // 7. Check the case of the initial word character.
53139
53140
53141 const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(),
53142 isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase();
53143
53144 if (capitalize === "always" && isLowercase) {
53145 return false;
53146 }
53147
53148 if (capitalize === "never" && isUppercase) {
53149 return false;
53150 }
53151
53152 return true;
53153 }
53154 /**
53155 * Process a comment to determine if it needs to be reported.
53156 * @param {ASTNode} comment The comment node to process.
53157 * @returns {void}
53158 */
53159
53160
53161 function processComment(comment) {
53162 const options = normalizedOptions[comment.type],
53163 commentValid = isCommentValid(comment, options);
53164
53165 if (!commentValid) {
53166 const messageId = capitalize === "always" ? "unexpectedLowercaseComment" : "unexpectedUppercaseComment";
53167 context.report({
53168 node: null,
53169 // Intentionally using loc instead
53170 loc: comment.loc,
53171 messageId,
53172
53173 fix(fixer) {
53174 const match = comment.value.match(LETTER_PATTERN);
53175 return fixer.replaceTextRange( // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*)
53176 [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase());
53177 }
53178
53179 });
53180 }
53181 } //----------------------------------------------------------------------
53182 // Public
53183 //----------------------------------------------------------------------
53184
53185
53186 return {
53187 Program() {
53188 const comments = sourceCode.getAllComments();
53189 comments.filter(token => token.type !== "Shebang").forEach(processComment);
53190 }
53191
53192 };
53193 }
53194
53195};
53196
53197/***/ }),
53198/* 444 */
53199/***/ (function(module, exports, __webpack_require__) {
53200
53201"use strict";
53202/**
53203 * @fileoverview Pattern for detecting any letter (even letters outside of ASCII).
53204 * NOTE: This file was generated using this script in JSCS based on the Unicode 7.0.0 standard: https://github.com/jscs-dev/node-jscs/blob/f5ed14427deb7e7aac84f3056a5aab2d9f3e563e/publish/helpers/generate-patterns.js
53205 * Do not edit this file by hand-- please use https://github.com/mathiasbynens/regenerate to regenerate the regular expression exported from this file.
53206 * @author Kevin Partington
53207 * @license MIT License (from JSCS). See below.
53208 */
53209
53210/*
53211 * The MIT License (MIT)
53212 *
53213 * Copyright 2013-2016 Dulin Marat and other contributors
53214 *
53215 * Permission is hereby granted, free of charge, to any person obtaining
53216 * a copy of this software and associated documentation files (the
53217 * "Software"), to deal in the Software without restriction, including
53218 * without limitation the rights to use, copy, modify, merge, publish,
53219 * distribute, sublicense, and/or sell copies of the Software, and to
53220 * permit persons to whom the Software is furnished to do so, subject to
53221 * the following conditions:
53222 *
53223 * The above copyright notice and this permission notice shall be
53224 * included in all copies or substantial portions of the Software.
53225 *
53226 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
53227 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
53228 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
53229 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
53230 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
53231 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
53232 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
53233 */
53234
53235
53236module.exports = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/u;
53237
53238/***/ }),
53239/* 445 */
53240/***/ (function(module, exports, __webpack_require__) {
53241
53242"use strict";
53243/**
53244 * @fileoverview Rule to enforce that all class methods use 'this'.
53245 * @author Patrick Williams
53246 */
53247 //------------------------------------------------------------------------------
53248// Requirements
53249//------------------------------------------------------------------------------
53250
53251const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
53252// Rule Definition
53253//------------------------------------------------------------------------------
53254
53255
53256module.exports = {
53257 meta: {
53258 type: "suggestion",
53259 docs: {
53260 description: "enforce that class methods utilize `this`",
53261 category: "Best Practices",
53262 recommended: false,
53263 url: "https://eslint.org/docs/rules/class-methods-use-this"
53264 },
53265 schema: [{
53266 type: "object",
53267 properties: {
53268 exceptMethods: {
53269 type: "array",
53270 items: {
53271 type: "string"
53272 }
53273 }
53274 },
53275 additionalProperties: false
53276 }],
53277 messages: {
53278 missingThis: "Expected 'this' to be used by class {{name}}."
53279 }
53280 },
53281
53282 create(context) {
53283 const config = Object.assign({}, context.options[0]);
53284 const exceptMethods = new Set(config.exceptMethods || []);
53285 const stack = [];
53286 /**
53287 * Initializes the current context to false and pushes it onto the stack.
53288 * These booleans represent whether 'this' has been used in the context.
53289 * @returns {void}
53290 * @private
53291 */
53292
53293 function enterFunction() {
53294 stack.push(false);
53295 }
53296 /**
53297 * Check if the node is an instance method
53298 * @param {ASTNode} node node to check
53299 * @returns {boolean} True if its an instance method
53300 * @private
53301 */
53302
53303
53304 function isInstanceMethod(node) {
53305 return !node.static && node.kind !== "constructor" && node.type === "MethodDefinition";
53306 }
53307 /**
53308 * Check if the node is an instance method not excluded by config
53309 * @param {ASTNode} node node to check
53310 * @returns {boolean} True if it is an instance method, and not excluded by config
53311 * @private
53312 */
53313
53314
53315 function isIncludedInstanceMethod(node) {
53316 return isInstanceMethod(node) && (node.computed || !exceptMethods.has(node.key.name));
53317 }
53318 /**
53319 * Checks if we are leaving a function that is a method, and reports if 'this' has not been used.
53320 * Static methods and the constructor are exempt.
53321 * Then pops the context off the stack.
53322 * @param {ASTNode} node A function node that was entered.
53323 * @returns {void}
53324 * @private
53325 */
53326
53327
53328 function exitFunction(node) {
53329 const methodUsesThis = stack.pop();
53330
53331 if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) {
53332 context.report({
53333 node,
53334 messageId: "missingThis",
53335 data: {
53336 name: astUtils.getFunctionNameWithKind(node)
53337 }
53338 });
53339 }
53340 }
53341 /**
53342 * Mark the current context as having used 'this'.
53343 * @returns {void}
53344 * @private
53345 */
53346
53347
53348 function markThisUsed() {
53349 if (stack.length) {
53350 stack[stack.length - 1] = true;
53351 }
53352 }
53353
53354 return {
53355 FunctionDeclaration: enterFunction,
53356 "FunctionDeclaration:exit": exitFunction,
53357 FunctionExpression: enterFunction,
53358 "FunctionExpression:exit": exitFunction,
53359 ThisExpression: markThisUsed,
53360 Super: markThisUsed
53361 };
53362 }
53363
53364};
53365
53366/***/ }),
53367/* 446 */
53368/***/ (function(module, exports, __webpack_require__) {
53369
53370"use strict";
53371/**
53372 * @fileoverview Rule to forbid or enforce dangling commas.
53373 * @author Ian Christian Myers
53374 */
53375 //------------------------------------------------------------------------------
53376// Requirements
53377//------------------------------------------------------------------------------
53378
53379const lodash = __webpack_require__(403);
53380
53381const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
53382// Helpers
53383//------------------------------------------------------------------------------
53384
53385
53386const DEFAULT_OPTIONS = Object.freeze({
53387 arrays: "never",
53388 objects: "never",
53389 imports: "never",
53390 exports: "never",
53391 functions: "never"
53392});
53393/**
53394 * Checks whether or not a trailing comma is allowed in a given node.
53395 * If the `lastItem` is `RestElement` or `RestProperty`, it disallows trailing commas.
53396 * @param {ASTNode} lastItem The node of the last element in the given node.
53397 * @returns {boolean} `true` if a trailing comma is allowed.
53398 */
53399
53400function isTrailingCommaAllowed(lastItem) {
53401 return !(lastItem.type === "RestElement" || lastItem.type === "RestProperty" || lastItem.type === "ExperimentalRestProperty");
53402}
53403/**
53404 * Normalize option value.
53405 * @param {string|Object|undefined} optionValue The 1st option value to normalize.
53406 * @param {number} ecmaVersion The normalized ECMAScript version.
53407 * @returns {Object} The normalized option value.
53408 */
53409
53410
53411function normalizeOptions(optionValue, ecmaVersion) {
53412 if (typeof optionValue === "string") {
53413 return {
53414 arrays: optionValue,
53415 objects: optionValue,
53416 imports: optionValue,
53417 exports: optionValue,
53418 functions: !ecmaVersion || ecmaVersion < 8 ? "ignore" : optionValue
53419 };
53420 }
53421
53422 if (typeof optionValue === "object" && optionValue !== null) {
53423 return {
53424 arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays,
53425 objects: optionValue.objects || DEFAULT_OPTIONS.objects,
53426 imports: optionValue.imports || DEFAULT_OPTIONS.imports,
53427 exports: optionValue.exports || DEFAULT_OPTIONS.exports,
53428 functions: optionValue.functions || DEFAULT_OPTIONS.functions
53429 };
53430 }
53431
53432 return DEFAULT_OPTIONS;
53433} //------------------------------------------------------------------------------
53434// Rule Definition
53435//------------------------------------------------------------------------------
53436
53437
53438module.exports = {
53439 meta: {
53440 type: "layout",
53441 docs: {
53442 description: "require or disallow trailing commas",
53443 category: "Stylistic Issues",
53444 recommended: false,
53445 url: "https://eslint.org/docs/rules/comma-dangle"
53446 },
53447 fixable: "code",
53448 schema: {
53449 definitions: {
53450 value: {
53451 enum: ["always-multiline", "always", "never", "only-multiline"]
53452 },
53453 valueWithIgnore: {
53454 enum: ["always-multiline", "always", "ignore", "never", "only-multiline"]
53455 }
53456 },
53457 type: "array",
53458 items: [{
53459 oneOf: [{
53460 $ref: "#/definitions/value"
53461 }, {
53462 type: "object",
53463 properties: {
53464 arrays: {
53465 $ref: "#/definitions/valueWithIgnore"
53466 },
53467 objects: {
53468 $ref: "#/definitions/valueWithIgnore"
53469 },
53470 imports: {
53471 $ref: "#/definitions/valueWithIgnore"
53472 },
53473 exports: {
53474 $ref: "#/definitions/valueWithIgnore"
53475 },
53476 functions: {
53477 $ref: "#/definitions/valueWithIgnore"
53478 }
53479 },
53480 additionalProperties: false
53481 }]
53482 }]
53483 },
53484 messages: {
53485 unexpected: "Unexpected trailing comma.",
53486 missing: "Missing trailing comma."
53487 }
53488 },
53489
53490 create(context) {
53491 const options = normalizeOptions(context.options[0], context.parserOptions.ecmaVersion);
53492 const sourceCode = context.getSourceCode();
53493 /**
53494 * Gets the last item of the given node.
53495 * @param {ASTNode} node The node to get.
53496 * @returns {ASTNode|null} The last node or null.
53497 */
53498
53499 function getLastItem(node) {
53500 switch (node.type) {
53501 case "ObjectExpression":
53502 case "ObjectPattern":
53503 return lodash.last(node.properties);
53504
53505 case "ArrayExpression":
53506 case "ArrayPattern":
53507 return lodash.last(node.elements);
53508
53509 case "ImportDeclaration":
53510 case "ExportNamedDeclaration":
53511 return lodash.last(node.specifiers);
53512
53513 case "FunctionDeclaration":
53514 case "FunctionExpression":
53515 case "ArrowFunctionExpression":
53516 return lodash.last(node.params);
53517
53518 case "CallExpression":
53519 case "NewExpression":
53520 return lodash.last(node.arguments);
53521
53522 default:
53523 return null;
53524 }
53525 }
53526 /**
53527 * Gets the trailing comma token of the given node.
53528 * If the trailing comma does not exist, this returns the token which is
53529 * the insertion point of the trailing comma token.
53530 * @param {ASTNode} node The node to get.
53531 * @param {ASTNode} lastItem The last item of the node.
53532 * @returns {Token} The trailing comma token or the insertion point.
53533 */
53534
53535
53536 function getTrailingToken(node, lastItem) {
53537 switch (node.type) {
53538 case "ObjectExpression":
53539 case "ArrayExpression":
53540 case "CallExpression":
53541 case "NewExpression":
53542 return sourceCode.getLastToken(node, 1);
53543
53544 default:
53545 {
53546 const nextToken = sourceCode.getTokenAfter(lastItem);
53547
53548 if (astUtils.isCommaToken(nextToken)) {
53549 return nextToken;
53550 }
53551
53552 return sourceCode.getLastToken(lastItem);
53553 }
53554 }
53555 }
53556 /**
53557 * Checks whether or not a given node is multiline.
53558 * This rule handles a given node as multiline when the closing parenthesis
53559 * and the last element are not on the same line.
53560 * @param {ASTNode} node A node to check.
53561 * @returns {boolean} `true` if the node is multiline.
53562 */
53563
53564
53565 function isMultiline(node) {
53566 const lastItem = getLastItem(node);
53567
53568 if (!lastItem) {
53569 return false;
53570 }
53571
53572 const penultimateToken = getTrailingToken(node, lastItem);
53573 const lastToken = sourceCode.getTokenAfter(penultimateToken);
53574 return lastToken.loc.end.line !== penultimateToken.loc.end.line;
53575 }
53576 /**
53577 * Reports a trailing comma if it exists.
53578 * @param {ASTNode} node A node to check. Its type is one of
53579 * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern,
53580 * ImportDeclaration, and ExportNamedDeclaration.
53581 * @returns {void}
53582 */
53583
53584
53585 function forbidTrailingComma(node) {
53586 const lastItem = getLastItem(node);
53587
53588 if (!lastItem || node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier") {
53589 return;
53590 }
53591
53592 const trailingToken = getTrailingToken(node, lastItem);
53593
53594 if (astUtils.isCommaToken(trailingToken)) {
53595 context.report({
53596 node: lastItem,
53597 loc: trailingToken.loc,
53598 messageId: "unexpected",
53599
53600 fix(fixer) {
53601 return fixer.remove(trailingToken);
53602 }
53603
53604 });
53605 }
53606 }
53607 /**
53608 * Reports the last element of a given node if it does not have a trailing
53609 * comma.
53610 *
53611 * If a given node is `ArrayPattern` which has `RestElement`, the trailing
53612 * comma is disallowed, so report if it exists.
53613 * @param {ASTNode} node A node to check. Its type is one of
53614 * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern,
53615 * ImportDeclaration, and ExportNamedDeclaration.
53616 * @returns {void}
53617 */
53618
53619
53620 function forceTrailingComma(node) {
53621 const lastItem = getLastItem(node);
53622
53623 if (!lastItem || node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier") {
53624 return;
53625 }
53626
53627 if (!isTrailingCommaAllowed(lastItem)) {
53628 forbidTrailingComma(node);
53629 return;
53630 }
53631
53632 const trailingToken = getTrailingToken(node, lastItem);
53633
53634 if (trailingToken.value !== ",") {
53635 context.report({
53636 node: lastItem,
53637 loc: {
53638 start: trailingToken.loc.end,
53639 end: astUtils.getNextLocation(sourceCode, trailingToken.loc.end)
53640 },
53641 messageId: "missing",
53642
53643 fix(fixer) {
53644 return fixer.insertTextAfter(trailingToken, ",");
53645 }
53646
53647 });
53648 }
53649 }
53650 /**
53651 * If a given node is multiline, reports the last element of a given node
53652 * when it does not have a trailing comma.
53653 * Otherwise, reports a trailing comma if it exists.
53654 * @param {ASTNode} node A node to check. Its type is one of
53655 * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern,
53656 * ImportDeclaration, and ExportNamedDeclaration.
53657 * @returns {void}
53658 */
53659
53660
53661 function forceTrailingCommaIfMultiline(node) {
53662 if (isMultiline(node)) {
53663 forceTrailingComma(node);
53664 } else {
53665 forbidTrailingComma(node);
53666 }
53667 }
53668 /**
53669 * Only if a given node is not multiline, reports the last element of a given node
53670 * when it does not have a trailing comma.
53671 * Otherwise, reports a trailing comma if it exists.
53672 * @param {ASTNode} node A node to check. Its type is one of
53673 * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern,
53674 * ImportDeclaration, and ExportNamedDeclaration.
53675 * @returns {void}
53676 */
53677
53678
53679 function allowTrailingCommaIfMultiline(node) {
53680 if (!isMultiline(node)) {
53681 forbidTrailingComma(node);
53682 }
53683 }
53684
53685 const predicate = {
53686 always: forceTrailingComma,
53687 "always-multiline": forceTrailingCommaIfMultiline,
53688 "only-multiline": allowTrailingCommaIfMultiline,
53689 never: forbidTrailingComma,
53690 ignore: lodash.noop
53691 };
53692 return {
53693 ObjectExpression: predicate[options.objects],
53694 ObjectPattern: predicate[options.objects],
53695 ArrayExpression: predicate[options.arrays],
53696 ArrayPattern: predicate[options.arrays],
53697 ImportDeclaration: predicate[options.imports],
53698 ExportNamedDeclaration: predicate[options.exports],
53699 FunctionDeclaration: predicate[options.functions],
53700 FunctionExpression: predicate[options.functions],
53701 ArrowFunctionExpression: predicate[options.functions],
53702 CallExpression: predicate[options.functions],
53703 NewExpression: predicate[options.functions]
53704 };
53705 }
53706
53707};
53708
53709/***/ }),
53710/* 447 */
53711/***/ (function(module, exports, __webpack_require__) {
53712
53713"use strict";
53714/**
53715 * @fileoverview Comma spacing - validates spacing before and after comma
53716 * @author Vignesh Anand aka vegetableman.
53717 */
53718
53719
53720const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
53721// Rule Definition
53722//------------------------------------------------------------------------------
53723
53724
53725module.exports = {
53726 meta: {
53727 type: "layout",
53728 docs: {
53729 description: "enforce consistent spacing before and after commas",
53730 category: "Stylistic Issues",
53731 recommended: false,
53732 url: "https://eslint.org/docs/rules/comma-spacing"
53733 },
53734 fixable: "whitespace",
53735 schema: [{
53736 type: "object",
53737 properties: {
53738 before: {
53739 type: "boolean",
53740 default: false
53741 },
53742 after: {
53743 type: "boolean",
53744 default: true
53745 }
53746 },
53747 additionalProperties: false
53748 }],
53749 messages: {
53750 missing: "A space is required {{loc}} ','.",
53751 unexpected: "There should be no space {{loc}} ','."
53752 }
53753 },
53754
53755 create(context) {
53756 const sourceCode = context.getSourceCode();
53757 const tokensAndComments = sourceCode.tokensAndComments;
53758 const options = {
53759 before: context.options[0] ? context.options[0].before : false,
53760 after: context.options[0] ? context.options[0].after : true
53761 }; //--------------------------------------------------------------------------
53762 // Helpers
53763 //--------------------------------------------------------------------------
53764 // list of comma tokens to ignore for the check of leading whitespace
53765
53766 const commaTokensToIgnore = [];
53767 /**
53768 * Reports a spacing error with an appropriate message.
53769 * @param {ASTNode} node The binary expression node to report.
53770 * @param {string} loc Is the error "before" or "after" the comma?
53771 * @param {ASTNode} otherNode The node at the left or right of `node`
53772 * @returns {void}
53773 * @private
53774 */
53775
53776 function report(node, loc, otherNode) {
53777 context.report({
53778 node,
53779
53780 fix(fixer) {
53781 if (options[loc]) {
53782 if (loc === "before") {
53783 return fixer.insertTextBefore(node, " ");
53784 }
53785
53786 return fixer.insertTextAfter(node, " ");
53787 }
53788
53789 let start, end;
53790 const newText = "";
53791
53792 if (loc === "before") {
53793 start = otherNode.range[1];
53794 end = node.range[0];
53795 } else {
53796 start = node.range[1];
53797 end = otherNode.range[0];
53798 }
53799
53800 return fixer.replaceTextRange([start, end], newText);
53801 },
53802
53803 messageId: options[loc] ? "missing" : "unexpected",
53804 data: {
53805 loc
53806 }
53807 });
53808 }
53809 /**
53810 * Validates the spacing around a comma token.
53811 * @param {Object} tokens The tokens to be validated.
53812 * @param {Token} tokens.comma The token representing the comma.
53813 * @param {Token} [tokens.left] The last token before the comma.
53814 * @param {Token} [tokens.right] The first token after the comma.
53815 * @param {Token|ASTNode} reportItem The item to use when reporting an error.
53816 * @returns {void}
53817 * @private
53818 */
53819
53820
53821 function validateCommaItemSpacing(tokens, reportItem) {
53822 if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) && options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma)) {
53823 report(reportItem, "before", tokens.left);
53824 }
53825
53826 if (tokens.right && astUtils.isClosingParenToken(tokens.right)) {
53827 return;
53828 }
53829
53830 if (tokens.right && !options.after && tokens.right.type === "Line") {
53831 return;
53832 }
53833
53834 if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) && options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right)) {
53835 report(reportItem, "after", tokens.right);
53836 }
53837 }
53838 /**
53839 * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list.
53840 * @param {ASTNode} node An ArrayExpression or ArrayPattern node.
53841 * @returns {void}
53842 */
53843
53844
53845 function addNullElementsToIgnoreList(node) {
53846 let previousToken = sourceCode.getFirstToken(node);
53847 node.elements.forEach(element => {
53848 let token;
53849
53850 if (element === null) {
53851 token = sourceCode.getTokenAfter(previousToken);
53852
53853 if (astUtils.isCommaToken(token)) {
53854 commaTokensToIgnore.push(token);
53855 }
53856 } else {
53857 token = sourceCode.getTokenAfter(element);
53858 }
53859
53860 previousToken = token;
53861 });
53862 } //--------------------------------------------------------------------------
53863 // Public
53864 //--------------------------------------------------------------------------
53865
53866
53867 return {
53868 "Program:exit"() {
53869 tokensAndComments.forEach((token, i) => {
53870 if (!astUtils.isCommaToken(token)) {
53871 return;
53872 }
53873
53874 if (token && token.type === "JSXText") {
53875 return;
53876 }
53877
53878 const previousToken = tokensAndComments[i - 1];
53879 const nextToken = tokensAndComments[i + 1];
53880 validateCommaItemSpacing({
53881 comma: token,
53882 left: astUtils.isCommaToken(previousToken) || commaTokensToIgnore.indexOf(token) > -1 ? null : previousToken,
53883 right: astUtils.isCommaToken(nextToken) ? null : nextToken
53884 }, token);
53885 });
53886 },
53887
53888 ArrayExpression: addNullElementsToIgnoreList,
53889 ArrayPattern: addNullElementsToIgnoreList
53890 };
53891 }
53892
53893};
53894
53895/***/ }),
53896/* 448 */
53897/***/ (function(module, exports, __webpack_require__) {
53898
53899"use strict";
53900/**
53901 * @fileoverview Comma style - enforces comma styles of two types: last and first
53902 * @author Vignesh Anand aka vegetableman
53903 */
53904
53905
53906const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
53907// Rule Definition
53908//------------------------------------------------------------------------------
53909
53910
53911module.exports = {
53912 meta: {
53913 type: "layout",
53914 docs: {
53915 description: "enforce consistent comma style",
53916 category: "Stylistic Issues",
53917 recommended: false,
53918 url: "https://eslint.org/docs/rules/comma-style"
53919 },
53920 fixable: "code",
53921 schema: [{
53922 enum: ["first", "last"]
53923 }, {
53924 type: "object",
53925 properties: {
53926 exceptions: {
53927 type: "object",
53928 additionalProperties: {
53929 type: "boolean"
53930 }
53931 }
53932 },
53933 additionalProperties: false
53934 }],
53935 messages: {
53936 unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.",
53937 expectedCommaFirst: "',' should be placed first.",
53938 expectedCommaLast: "',' should be placed last."
53939 }
53940 },
53941
53942 create(context) {
53943 const style = context.options[0] || "last",
53944 sourceCode = context.getSourceCode();
53945 const exceptions = {
53946 ArrayPattern: true,
53947 ArrowFunctionExpression: true,
53948 CallExpression: true,
53949 FunctionDeclaration: true,
53950 FunctionExpression: true,
53951 ImportDeclaration: true,
53952 ObjectPattern: true,
53953 NewExpression: true
53954 };
53955
53956 if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) {
53957 const keys = Object.keys(context.options[1].exceptions);
53958
53959 for (let i = 0; i < keys.length; i++) {
53960 exceptions[keys[i]] = context.options[1].exceptions[keys[i]];
53961 }
53962 } //--------------------------------------------------------------------------
53963 // Helpers
53964 //--------------------------------------------------------------------------
53965
53966 /**
53967 * Modified text based on the style
53968 * @param {string} styleType Style type
53969 * @param {string} text Source code text
53970 * @returns {string} modified text
53971 * @private
53972 */
53973
53974
53975 function getReplacedText(styleType, text) {
53976 switch (styleType) {
53977 case "between":
53978 return ",".concat(text.replace(astUtils.LINEBREAK_MATCHER, ""));
53979
53980 case "first":
53981 return "".concat(text, ",");
53982
53983 case "last":
53984 return ",".concat(text);
53985
53986 default:
53987 return "";
53988 }
53989 }
53990 /**
53991 * Determines the fixer function for a given style.
53992 * @param {string} styleType comma style
53993 * @param {ASTNode} previousItemToken The token to check.
53994 * @param {ASTNode} commaToken The token to check.
53995 * @param {ASTNode} currentItemToken The token to check.
53996 * @returns {Function} Fixer function
53997 * @private
53998 */
53999
54000
54001 function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
54002 const text = sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) + sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
54003 const range = [previousItemToken.range[1], currentItemToken.range[0]];
54004 return function (fixer) {
54005 return fixer.replaceTextRange(range, getReplacedText(styleType, text));
54006 };
54007 }
54008 /**
54009 * Validates the spacing around single items in lists.
54010 * @param {Token} previousItemToken The last token from the previous item.
54011 * @param {Token} commaToken The token representing the comma.
54012 * @param {Token} currentItemToken The first token of the current item.
54013 * @param {Token} reportItem The item to use when reporting an error.
54014 * @returns {void}
54015 * @private
54016 */
54017
54018
54019 function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
54020 // if single line
54021 if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) && astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {// do nothing.
54022 } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) && !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
54023 const comment = sourceCode.getCommentsAfter(commaToken)[0];
54024 const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment) ? style : "between"; // lone comma
54025
54026 context.report({
54027 node: reportItem,
56c4a2cb 54028 loc: commaToken.loc,
eb39fafa
DC
54029 messageId: "unexpectedLineBeforeAndAfterComma",
54030 fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
54031 });
54032 } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
54033 context.report({
54034 node: reportItem,
56c4a2cb 54035 loc: commaToken.loc,
eb39fafa
DC
54036 messageId: "expectedCommaFirst",
54037 fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
54038 });
54039 } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
54040 context.report({
54041 node: reportItem,
56c4a2cb 54042 loc: commaToken.loc,
eb39fafa
DC
54043 messageId: "expectedCommaLast",
54044 fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
54045 });
54046 }
54047 }
54048 /**
54049 * Checks the comma placement with regards to a declaration/property/element
54050 * @param {ASTNode} node The binary expression node to check
54051 * @param {string} property The property of the node containing child nodes.
54052 * @private
54053 * @returns {void}
54054 */
54055
54056
54057 function validateComma(node, property) {
54058 const items = node[property],
54059 arrayLiteral = node.type === "ArrayExpression" || node.type === "ArrayPattern";
54060
54061 if (items.length > 1 || arrayLiteral) {
54062 // seed as opening [
54063 let previousItemToken = sourceCode.getFirstToken(node);
54064 items.forEach(item => {
54065 const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken,
54066 currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken),
54067 reportItem = item || currentItemToken;
54068 /*
54069 * This works by comparing three token locations:
54070 * - previousItemToken is the last token of the previous item
54071 * - commaToken is the location of the comma before the current item
54072 * - currentItemToken is the first token of the current item
54073 *
54074 * These values get switched around if item is undefined.
54075 * previousItemToken will refer to the last token not belonging
54076 * to the current item, which could be a comma or an opening
54077 * square bracket. currentItemToken could be a comma.
54078 *
54079 * All comparisons are done based on these tokens directly, so
54080 * they are always valid regardless of an undefined item.
54081 */
54082
54083 if (astUtils.isCommaToken(commaToken)) {
54084 validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem);
54085 }
54086
54087 if (item) {
54088 const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken);
54089 previousItemToken = tokenAfterItem ? sourceCode.getTokenBefore(tokenAfterItem) : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1];
54090 }
54091 });
54092 /*
54093 * Special case for array literals that have empty last items, such
54094 * as [ 1, 2, ]. These arrays only have two items show up in the
54095 * AST, so we need to look at the token to verify that there's no
54096 * dangling comma.
54097 */
54098
54099 if (arrayLiteral) {
54100 const lastToken = sourceCode.getLastToken(node),
54101 nextToLastToken = sourceCode.getTokenBefore(lastToken);
54102
54103 if (astUtils.isCommaToken(nextToLastToken)) {
54104 validateCommaItemSpacing(sourceCode.getTokenBefore(nextToLastToken), nextToLastToken, lastToken, lastToken);
54105 }
54106 }
54107 }
54108 } //--------------------------------------------------------------------------
54109 // Public
54110 //--------------------------------------------------------------------------
54111
54112
54113 const nodes = {};
54114
54115 if (!exceptions.VariableDeclaration) {
54116 nodes.VariableDeclaration = function (node) {
54117 validateComma(node, "declarations");
54118 };
54119 }
54120
54121 if (!exceptions.ObjectExpression) {
54122 nodes.ObjectExpression = function (node) {
54123 validateComma(node, "properties");
54124 };
54125 }
54126
54127 if (!exceptions.ObjectPattern) {
54128 nodes.ObjectPattern = function (node) {
54129 validateComma(node, "properties");
54130 };
54131 }
54132
54133 if (!exceptions.ArrayExpression) {
54134 nodes.ArrayExpression = function (node) {
54135 validateComma(node, "elements");
54136 };
54137 }
54138
54139 if (!exceptions.ArrayPattern) {
54140 nodes.ArrayPattern = function (node) {
54141 validateComma(node, "elements");
54142 };
54143 }
54144
54145 if (!exceptions.FunctionDeclaration) {
54146 nodes.FunctionDeclaration = function (node) {
54147 validateComma(node, "params");
54148 };
54149 }
54150
54151 if (!exceptions.FunctionExpression) {
54152 nodes.FunctionExpression = function (node) {
54153 validateComma(node, "params");
54154 };
54155 }
54156
54157 if (!exceptions.ArrowFunctionExpression) {
54158 nodes.ArrowFunctionExpression = function (node) {
54159 validateComma(node, "params");
54160 };
54161 }
54162
54163 if (!exceptions.CallExpression) {
54164 nodes.CallExpression = function (node) {
54165 validateComma(node, "arguments");
54166 };
54167 }
54168
54169 if (!exceptions.ImportDeclaration) {
54170 nodes.ImportDeclaration = function (node) {
54171 validateComma(node, "specifiers");
54172 };
54173 }
54174
54175 if (!exceptions.NewExpression) {
54176 nodes.NewExpression = function (node) {
54177 validateComma(node, "arguments");
54178 };
54179 }
54180
54181 return nodes;
54182 }
54183
54184};
54185
54186/***/ }),
54187/* 449 */
54188/***/ (function(module, exports, __webpack_require__) {
54189
54190"use strict";
54191/**
54192 * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity.
54193 * Counts the number of if, conditional, for, while, try, switch/case,
54194 * @author Patrick Brosset
54195 */
54196 //------------------------------------------------------------------------------
54197// Requirements
54198//------------------------------------------------------------------------------
54199
54200const lodash = __webpack_require__(403);
54201
54202const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
54203// Rule Definition
54204//------------------------------------------------------------------------------
54205
54206
54207module.exports = {
54208 meta: {
54209 type: "suggestion",
54210 docs: {
54211 description: "enforce a maximum cyclomatic complexity allowed in a program",
54212 category: "Best Practices",
54213 recommended: false,
54214 url: "https://eslint.org/docs/rules/complexity"
54215 },
54216 schema: [{
54217 oneOf: [{
54218 type: "integer",
54219 minimum: 0
54220 }, {
54221 type: "object",
54222 properties: {
54223 maximum: {
54224 type: "integer",
54225 minimum: 0
54226 },
54227 max: {
54228 type: "integer",
54229 minimum: 0
54230 }
54231 },
54232 additionalProperties: false
54233 }]
54234 }],
54235 messages: {
54236 complex: "{{name}} has a complexity of {{complexity}}. Maximum allowed is {{max}}."
54237 }
54238 },
54239
54240 create(context) {
54241 const option = context.options[0];
54242 let THRESHOLD = 20;
54243
54244 if (typeof option === "object" && (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))) {
54245 THRESHOLD = option.maximum || option.max;
54246 } else if (typeof option === "number") {
54247 THRESHOLD = option;
54248 } //--------------------------------------------------------------------------
54249 // Helpers
54250 //--------------------------------------------------------------------------
54251 // Using a stack to store complexity (handling nested functions)
54252
54253
54254 const fns = [];
54255 /**
54256 * When parsing a new function, store it in our function stack
54257 * @returns {void}
54258 * @private
54259 */
54260
54261 function startFunction() {
54262 fns.push(1);
54263 }
54264 /**
54265 * Evaluate the node at the end of function
54266 * @param {ASTNode} node node to evaluate
54267 * @returns {void}
54268 * @private
54269 */
54270
54271
54272 function endFunction(node) {
54273 const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node));
54274 const complexity = fns.pop();
54275
54276 if (complexity > THRESHOLD) {
54277 context.report({
54278 node,
54279 messageId: "complex",
54280 data: {
54281 name,
54282 complexity,
54283 max: THRESHOLD
54284 }
54285 });
54286 }
54287 }
54288 /**
54289 * Increase the complexity of the function in context
54290 * @returns {void}
54291 * @private
54292 */
54293
54294
54295 function increaseComplexity() {
54296 if (fns.length) {
54297 fns[fns.length - 1]++;
54298 }
54299 }
54300 /**
54301 * Increase the switch complexity in context
54302 * @param {ASTNode} node node to evaluate
54303 * @returns {void}
54304 * @private
54305 */
54306
54307
54308 function increaseSwitchComplexity(node) {
54309 // Avoiding `default`
54310 if (node.test) {
54311 increaseComplexity();
54312 }
54313 } //--------------------------------------------------------------------------
54314 // Public API
54315 //--------------------------------------------------------------------------
54316
54317
54318 return {
54319 FunctionDeclaration: startFunction,
54320 FunctionExpression: startFunction,
54321 ArrowFunctionExpression: startFunction,
54322 "FunctionDeclaration:exit": endFunction,
54323 "FunctionExpression:exit": endFunction,
54324 "ArrowFunctionExpression:exit": endFunction,
54325 CatchClause: increaseComplexity,
54326 ConditionalExpression: increaseComplexity,
54327 LogicalExpression: increaseComplexity,
54328 ForStatement: increaseComplexity,
54329 ForInStatement: increaseComplexity,
54330 ForOfStatement: increaseComplexity,
54331 IfStatement: increaseComplexity,
54332 SwitchCase: increaseSwitchComplexity,
54333 WhileStatement: increaseComplexity,
54334 DoWhileStatement: increaseComplexity
54335 };
54336 }
54337
54338};
54339
54340/***/ }),
54341/* 450 */
54342/***/ (function(module, exports, __webpack_require__) {
54343
54344"use strict";
54345/**
54346 * @fileoverview Disallows or enforces spaces inside computed properties.
54347 * @author Jamund Ferguson
54348 */
54349
54350
54351const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
54352// Rule Definition
54353//------------------------------------------------------------------------------
54354
54355
54356module.exports = {
54357 meta: {
54358 type: "layout",
54359 docs: {
54360 description: "enforce consistent spacing inside computed property brackets",
54361 category: "Stylistic Issues",
54362 recommended: false,
54363 url: "https://eslint.org/docs/rules/computed-property-spacing"
54364 },
54365 fixable: "whitespace",
54366 schema: [{
54367 enum: ["always", "never"]
54368 }, {
54369 type: "object",
54370 properties: {
54371 enforceForClassMembers: {
54372 type: "boolean",
54373 default: true
54374 }
54375 },
54376 additionalProperties: false
54377 }],
54378 messages: {
54379 unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.",
54380 unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.",
54381 missingSpaceBefore: "A space is required before '{{tokenValue}}'.",
54382 missingSpaceAfter: "A space is required after '{{tokenValue}}'."
54383 }
54384 },
54385
54386 create(context) {
54387 const sourceCode = context.getSourceCode();
54388 const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never"
54389
54390 const enforceForClassMembers = !context.options[1] || context.options[1].enforceForClassMembers; //--------------------------------------------------------------------------
54391 // Helpers
54392 //--------------------------------------------------------------------------
54393
54394 /**
54395 * Reports that there shouldn't be a space after the first token
54396 * @param {ASTNode} node The node to report in the event of an error.
54397 * @param {Token} token The token to use for the report.
54398 * @param {Token} tokenAfter The token after `token`.
54399 * @returns {void}
54400 */
54401
54402 function reportNoBeginningSpace(node, token, tokenAfter) {
54403 context.report({
54404 node,
54405 loc: {
54406 start: token.loc.end,
54407 end: tokenAfter.loc.start
54408 },
54409 messageId: "unexpectedSpaceAfter",
54410 data: {
54411 tokenValue: token.value
54412 },
54413
54414 fix(fixer) {
54415 return fixer.removeRange([token.range[1], tokenAfter.range[0]]);
54416 }
54417
54418 });
54419 }
54420 /**
54421 * Reports that there shouldn't be a space before the last token
54422 * @param {ASTNode} node The node to report in the event of an error.
54423 * @param {Token} token The token to use for the report.
54424 * @param {Token} tokenBefore The token before `token`.
54425 * @returns {void}
54426 */
54427
54428
54429 function reportNoEndingSpace(node, token, tokenBefore) {
54430 context.report({
54431 node,
54432 loc: {
54433 start: tokenBefore.loc.end,
54434 end: token.loc.start
54435 },
54436 messageId: "unexpectedSpaceBefore",
54437 data: {
54438 tokenValue: token.value
54439 },
54440
54441 fix(fixer) {
54442 return fixer.removeRange([tokenBefore.range[1], token.range[0]]);
54443 }
54444
54445 });
54446 }
54447 /**
54448 * Reports that there should be a space after the first token
54449 * @param {ASTNode} node The node to report in the event of an error.
54450 * @param {Token} token The token to use for the report.
54451 * @returns {void}
54452 */
54453
54454
54455 function reportRequiredBeginningSpace(node, token) {
54456 context.report({
54457 node,
54458 loc: token.loc,
54459 messageId: "missingSpaceAfter",
54460 data: {
54461 tokenValue: token.value
54462 },
54463
54464 fix(fixer) {
54465 return fixer.insertTextAfter(token, " ");
54466 }
54467
54468 });
54469 }
54470 /**
54471 * Reports that there should be a space before the last token
54472 * @param {ASTNode} node The node to report in the event of an error.
54473 * @param {Token} token The token to use for the report.
54474 * @returns {void}
54475 */
54476
54477
54478 function reportRequiredEndingSpace(node, token) {
54479 context.report({
54480 node,
54481 loc: token.loc,
54482 messageId: "missingSpaceBefore",
54483 data: {
54484 tokenValue: token.value
54485 },
54486
54487 fix(fixer) {
54488 return fixer.insertTextBefore(token, " ");
54489 }
54490
54491 });
54492 }
54493 /**
54494 * Returns a function that checks the spacing of a node on the property name
54495 * that was passed in.
54496 * @param {string} propertyName The property on the node to check for spacing
54497 * @returns {Function} A function that will check spacing on a node
54498 */
54499
54500
54501 function checkSpacing(propertyName) {
54502 return function (node) {
54503 if (!node.computed) {
54504 return;
54505 }
54506
54507 const property = node[propertyName];
54508 const before = sourceCode.getTokenBefore(property, astUtils.isOpeningBracketToken),
54509 first = sourceCode.getTokenAfter(before, {
54510 includeComments: true
54511 }),
54512 after = sourceCode.getTokenAfter(property, astUtils.isClosingBracketToken),
54513 last = sourceCode.getTokenBefore(after, {
54514 includeComments: true
54515 });
54516
54517 if (astUtils.isTokenOnSameLine(before, first)) {
54518 if (propertyNameMustBeSpaced) {
54519 if (!sourceCode.isSpaceBetweenTokens(before, first) && astUtils.isTokenOnSameLine(before, first)) {
54520 reportRequiredBeginningSpace(node, before);
54521 }
54522 } else {
54523 if (sourceCode.isSpaceBetweenTokens(before, first)) {
54524 reportNoBeginningSpace(node, before, first);
54525 }
54526 }
54527 }
54528
54529 if (astUtils.isTokenOnSameLine(last, after)) {
54530 if (propertyNameMustBeSpaced) {
54531 if (!sourceCode.isSpaceBetweenTokens(last, after) && astUtils.isTokenOnSameLine(last, after)) {
54532 reportRequiredEndingSpace(node, after);
54533 }
54534 } else {
54535 if (sourceCode.isSpaceBetweenTokens(last, after)) {
54536 reportNoEndingSpace(node, after, last);
54537 }
54538 }
54539 }
54540 };
54541 } //--------------------------------------------------------------------------
54542 // Public
54543 //--------------------------------------------------------------------------
54544
54545
54546 const listeners = {
54547 Property: checkSpacing("key"),
54548 MemberExpression: checkSpacing("property")
54549 };
54550
54551 if (enforceForClassMembers) {
54552 listeners.MethodDefinition = checkSpacing("key");
54553 }
54554
54555 return listeners;
54556 }
54557
54558};
54559
54560/***/ }),
54561/* 451 */
54562/***/ (function(module, exports, __webpack_require__) {
54563
54564"use strict";
54565/**
54566 * @fileoverview Rule to flag consistent return values
54567 * @author Nicholas C. Zakas
54568 */
54569 //------------------------------------------------------------------------------
54570// Requirements
54571//------------------------------------------------------------------------------
54572
54573const lodash = __webpack_require__(403);
54574
54575const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
54576// Helpers
54577//------------------------------------------------------------------------------
54578
54579/**
54580 * Checks whether or not a given node is an `Identifier` node which was named a given name.
54581 * @param {ASTNode} node A node to check.
54582 * @param {string} name An expected name of the node.
54583 * @returns {boolean} `true` if the node is an `Identifier` node which was named as expected.
54584 */
54585
54586
54587function isIdentifier(node, name) {
54588 return node.type === "Identifier" && node.name === name;
54589}
54590/**
54591 * Checks whether or not a given code path segment is unreachable.
54592 * @param {CodePathSegment} segment A CodePathSegment to check.
54593 * @returns {boolean} `true` if the segment is unreachable.
54594 */
54595
54596
54597function isUnreachable(segment) {
54598 return !segment.reachable;
54599}
54600/**
54601 * Checks whether a given node is a `constructor` method in an ES6 class
54602 * @param {ASTNode} node A node to check
54603 * @returns {boolean} `true` if the node is a `constructor` method
54604 */
54605
54606
54607function isClassConstructor(node) {
54608 return node.type === "FunctionExpression" && node.parent && node.parent.type === "MethodDefinition" && node.parent.kind === "constructor";
54609} //------------------------------------------------------------------------------
54610// Rule Definition
54611//------------------------------------------------------------------------------
54612
54613
54614module.exports = {
54615 meta: {
54616 type: "suggestion",
54617 docs: {
54618 description: "require `return` statements to either always or never specify values",
54619 category: "Best Practices",
54620 recommended: false,
54621 url: "https://eslint.org/docs/rules/consistent-return"
54622 },
54623 schema: [{
54624 type: "object",
54625 properties: {
54626 treatUndefinedAsUnspecified: {
54627 type: "boolean",
54628 default: false
54629 }
54630 },
54631 additionalProperties: false
54632 }],
54633 messages: {
54634 missingReturn: "Expected to return a value at the end of {{name}}.",
54635 missingReturnValue: "{{name}} expected a return value.",
54636 unexpectedReturnValue: "{{name}} expected no return value."
54637 }
54638 },
54639
54640 create(context) {
54641 const options = context.options[0] || {};
54642 const treatUndefinedAsUnspecified = options.treatUndefinedAsUnspecified === true;
54643 let funcInfo = null;
54644 /**
54645 * Checks whether of not the implicit returning is consistent if the last
54646 * code path segment is reachable.
54647 * @param {ASTNode} node A program/function node to check.
54648 * @returns {void}
54649 */
54650
54651 function checkLastSegment(node) {
54652 let loc, name;
54653 /*
54654 * Skip if it expected no return value or unreachable.
54655 * When unreachable, all paths are returned or thrown.
54656 */
54657
54658 if (!funcInfo.hasReturnValue || funcInfo.codePath.currentSegments.every(isUnreachable) || astUtils.isES5Constructor(node) || isClassConstructor(node)) {
54659 return;
54660 } // Adjust a location and a message.
54661
54662
54663 if (node.type === "Program") {
54664 // The head of program.
54665 loc = {
54666 line: 1,
54667 column: 0
54668 };
54669 name = "program";
54670 } else if (node.type === "ArrowFunctionExpression") {
54671 // `=>` token
54672 loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start;
54673 } else if (node.parent.type === "MethodDefinition" || node.parent.type === "Property" && node.parent.method) {
54674 // Method name.
54675 loc = node.parent.key.loc.start;
54676 } else {
54677 // Function name or `function` keyword.
54678 loc = (node.id || node).loc.start;
54679 }
54680
54681 if (!name) {
54682 name = astUtils.getFunctionNameWithKind(node);
54683 } // Reports.
54684
54685
54686 context.report({
54687 node,
54688 loc,
54689 messageId: "missingReturn",
54690 data: {
54691 name
54692 }
54693 });
54694 }
54695
54696 return {
54697 // Initializes/Disposes state of each code path.
54698 onCodePathStart(codePath, node) {
54699 funcInfo = {
54700 upper: funcInfo,
54701 codePath,
54702 hasReturn: false,
54703 hasReturnValue: false,
54704 messageId: "",
54705 node
54706 };
54707 },
54708
54709 onCodePathEnd() {
54710 funcInfo = funcInfo.upper;
54711 },
54712
54713 // Reports a given return statement if it's inconsistent.
54714 ReturnStatement(node) {
54715 const argument = node.argument;
54716 let hasReturnValue = Boolean(argument);
54717
54718 if (treatUndefinedAsUnspecified && hasReturnValue) {
54719 hasReturnValue = !isIdentifier(argument, "undefined") && argument.operator !== "void";
54720 }
54721
54722 if (!funcInfo.hasReturn) {
54723 funcInfo.hasReturn = true;
54724 funcInfo.hasReturnValue = hasReturnValue;
54725 funcInfo.messageId = hasReturnValue ? "missingReturnValue" : "unexpectedReturnValue";
54726 funcInfo.data = {
54727 name: funcInfo.node.type === "Program" ? "Program" : lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node))
54728 };
54729 } else if (funcInfo.hasReturnValue !== hasReturnValue) {
54730 context.report({
54731 node,
54732 messageId: funcInfo.messageId,
54733 data: funcInfo.data
54734 });
54735 }
54736 },
54737
54738 // Reports a given program/function if the implicit returning is not consistent.
54739 "Program:exit": checkLastSegment,
54740 "FunctionDeclaration:exit": checkLastSegment,
54741 "FunctionExpression:exit": checkLastSegment,
54742 "ArrowFunctionExpression:exit": checkLastSegment
54743 };
54744 }
54745
54746};
54747
54748/***/ }),
54749/* 452 */
54750/***/ (function(module, exports, __webpack_require__) {
54751
54752"use strict";
54753/**
54754 * @fileoverview Rule to enforce consistent naming of "this" context variables
54755 * @author Raphael Pigulla
54756 */
54757 //------------------------------------------------------------------------------
54758// Rule Definition
54759//------------------------------------------------------------------------------
54760
54761module.exports = {
54762 meta: {
54763 type: "suggestion",
54764 docs: {
54765 description: "enforce consistent naming when capturing the current execution context",
54766 category: "Stylistic Issues",
54767 recommended: false,
54768 url: "https://eslint.org/docs/rules/consistent-this"
54769 },
54770 schema: {
54771 type: "array",
54772 items: {
54773 type: "string",
54774 minLength: 1
54775 },
54776 uniqueItems: true
54777 },
54778 messages: {
54779 aliasNotAssignedToThis: "Designated alias '{{name}}' is not assigned to 'this'.",
54780 unexpectedAlias: "Unexpected alias '{{name}}' for 'this'."
54781 }
54782 },
54783
54784 create(context) {
54785 let aliases = [];
54786
54787 if (context.options.length === 0) {
54788 aliases.push("that");
54789 } else {
54790 aliases = context.options;
54791 }
54792 /**
54793 * Reports that a variable declarator or assignment expression is assigning
54794 * a non-'this' value to the specified alias.
54795 * @param {ASTNode} node The assigning node.
54796 * @param {string} name the name of the alias that was incorrectly used.
54797 * @returns {void}
54798 */
54799
54800
54801 function reportBadAssignment(node, name) {
54802 context.report({
54803 node,
54804 messageId: "aliasNotAssignedToThis",
54805 data: {
54806 name
54807 }
54808 });
54809 }
54810 /**
54811 * Checks that an assignment to an identifier only assigns 'this' to the
54812 * appropriate alias, and the alias is only assigned to 'this'.
54813 * @param {ASTNode} node The assigning node.
54814 * @param {Identifier} name The name of the variable assigned to.
54815 * @param {Expression} value The value of the assignment.
54816 * @returns {void}
54817 */
54818
54819
54820 function checkAssignment(node, name, value) {
54821 const isThis = value.type === "ThisExpression";
54822
54823 if (aliases.indexOf(name) !== -1) {
54824 if (!isThis || node.operator && node.operator !== "=") {
54825 reportBadAssignment(node, name);
54826 }
54827 } else if (isThis) {
54828 context.report({
54829 node,
54830 messageId: "unexpectedAlias",
54831 data: {
54832 name
54833 }
54834 });
54835 }
54836 }
54837 /**
54838 * Ensures that a variable declaration of the alias in a program or function
54839 * is assigned to the correct value.
54840 * @param {string} alias alias the check the assignment of.
54841 * @param {Object} scope scope of the current code we are checking.
54842 * @private
54843 * @returns {void}
54844 */
54845
54846
54847 function checkWasAssigned(alias, scope) {
54848 const variable = scope.set.get(alias);
54849
54850 if (!variable) {
54851 return;
54852 }
54853
54854 if (variable.defs.some(def => def.node.type === "VariableDeclarator" && def.node.init !== null)) {
54855 return;
54856 }
54857 /*
54858 * The alias has been declared and not assigned: check it was
54859 * assigned later in the same scope.
54860 */
54861
54862
54863 if (!variable.references.some(reference => {
54864 const write = reference.writeExpr;
54865 return reference.from === scope && write && write.type === "ThisExpression" && write.parent.operator === "=";
54866 })) {
54867 variable.defs.map(def => def.node).forEach(node => {
54868 reportBadAssignment(node, alias);
54869 });
54870 }
54871 }
54872 /**
54873 * Check each alias to ensure that is was assigned to the correct value.
54874 * @returns {void}
54875 */
54876
54877
54878 function ensureWasAssigned() {
54879 const scope = context.getScope();
54880 aliases.forEach(alias => {
54881 checkWasAssigned(alias, scope);
54882 });
54883 }
54884
54885 return {
54886 "Program:exit": ensureWasAssigned,
54887 "FunctionExpression:exit": ensureWasAssigned,
54888 "FunctionDeclaration:exit": ensureWasAssigned,
54889
54890 VariableDeclarator(node) {
54891 const id = node.id;
54892 const isDestructuring = id.type === "ArrayPattern" || id.type === "ObjectPattern";
54893
54894 if (node.init !== null && !isDestructuring) {
54895 checkAssignment(node, id.name, node.init);
54896 }
54897 },
54898
54899 AssignmentExpression(node) {
54900 if (node.left.type === "Identifier") {
54901 checkAssignment(node, node.left.name, node.right);
54902 }
54903 }
54904
54905 };
54906 }
54907
54908};
54909
54910/***/ }),
54911/* 453 */
54912/***/ (function(module, exports, __webpack_require__) {
54913
54914"use strict";
54915/**
54916 * @fileoverview A rule to verify `super()` callings in constructor.
54917 * @author Toru Nagashima
54918 */
54919 //------------------------------------------------------------------------------
54920// Helpers
54921//------------------------------------------------------------------------------
54922
54923/**
54924 * Checks whether a given code path segment is reachable or not.
54925 * @param {CodePathSegment} segment A code path segment to check.
54926 * @returns {boolean} `true` if the segment is reachable.
54927 */
54928
54929function isReachable(segment) {
54930 return segment.reachable;
54931}
54932/**
54933 * Checks whether or not a given node is a constructor.
54934 * @param {ASTNode} node A node to check. This node type is one of
54935 * `Program`, `FunctionDeclaration`, `FunctionExpression`, and
54936 * `ArrowFunctionExpression`.
54937 * @returns {boolean} `true` if the node is a constructor.
54938 */
54939
54940
54941function isConstructorFunction(node) {
54942 return node.type === "FunctionExpression" && node.parent.type === "MethodDefinition" && node.parent.kind === "constructor";
54943}
54944/**
54945 * Checks whether a given node can be a constructor or not.
54946 * @param {ASTNode} node A node to check.
54947 * @returns {boolean} `true` if the node can be a constructor.
54948 */
54949
54950
54951function isPossibleConstructor(node) {
54952 if (!node) {
54953 return false;
54954 }
54955
54956 switch (node.type) {
54957 case "ClassExpression":
54958 case "FunctionExpression":
54959 case "ThisExpression":
54960 case "MemberExpression":
54961 case "CallExpression":
54962 case "NewExpression":
54963 case "YieldExpression":
54964 case "TaggedTemplateExpression":
54965 case "MetaProperty":
54966 return true;
54967
54968 case "Identifier":
54969 return node.name !== "undefined";
54970
54971 case "AssignmentExpression":
54972 return isPossibleConstructor(node.right);
54973
54974 case "LogicalExpression":
54975 return isPossibleConstructor(node.left) || isPossibleConstructor(node.right);
54976
54977 case "ConditionalExpression":
54978 return isPossibleConstructor(node.alternate) || isPossibleConstructor(node.consequent);
54979
54980 case "SequenceExpression":
54981 {
54982 const lastExpression = node.expressions[node.expressions.length - 1];
54983 return isPossibleConstructor(lastExpression);
54984 }
54985
54986 default:
54987 return false;
54988 }
54989} //------------------------------------------------------------------------------
54990// Rule Definition
54991//------------------------------------------------------------------------------
54992
54993
54994module.exports = {
54995 meta: {
54996 type: "problem",
54997 docs: {
54998 description: "require `super()` calls in constructors",
54999 category: "ECMAScript 6",
55000 recommended: true,
55001 url: "https://eslint.org/docs/rules/constructor-super"
55002 },
55003 schema: [],
55004 messages: {
55005 missingSome: "Lacked a call of 'super()' in some code paths.",
55006 missingAll: "Expected to call 'super()'.",
55007 duplicate: "Unexpected duplicate 'super()'.",
55008 badSuper: "Unexpected 'super()' because 'super' is not a constructor.",
55009 unexpected: "Unexpected 'super()'."
55010 }
55011 },
55012
55013 create(context) {
55014 /*
55015 * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]}
55016 * Information for each constructor.
55017 * - upper: Information of the upper constructor.
55018 * - hasExtends: A flag which shows whether own class has a valid `extends`
55019 * part.
55020 * - scope: The scope of own class.
55021 * - codePath: The code path object of the constructor.
55022 */
55023 let funcInfo = null;
55024 /*
55025 * {Map<string, {calledInSomePaths: boolean, calledInEveryPaths: boolean}>}
55026 * Information for each code path segment.
55027 * - calledInSomePaths: A flag of be called `super()` in some code paths.
55028 * - calledInEveryPaths: A flag of be called `super()` in all code paths.
55029 * - validNodes:
55030 */
55031
55032 let segInfoMap = Object.create(null);
55033 /**
55034 * Gets the flag which shows `super()` is called in some paths.
55035 * @param {CodePathSegment} segment A code path segment to get.
55036 * @returns {boolean} The flag which shows `super()` is called in some paths
55037 */
55038
55039 function isCalledInSomePath(segment) {
55040 return segment.reachable && segInfoMap[segment.id].calledInSomePaths;
55041 }
55042 /**
55043 * Gets the flag which shows `super()` is called in all paths.
55044 * @param {CodePathSegment} segment A code path segment to get.
55045 * @returns {boolean} The flag which shows `super()` is called in all paths.
55046 */
55047
55048
55049 function isCalledInEveryPath(segment) {
55050 /*
55051 * If specific segment is the looped segment of the current segment,
55052 * skip the segment.
55053 * If not skipped, this never becomes true after a loop.
55054 */
55055 if (segment.nextSegments.length === 1 && segment.nextSegments[0].isLoopedPrevSegment(segment)) {
55056 return true;
55057 }
55058
55059 return segment.reachable && segInfoMap[segment.id].calledInEveryPaths;
55060 }
55061
55062 return {
55063 /**
55064 * Stacks a constructor information.
55065 * @param {CodePath} codePath A code path which was started.
55066 * @param {ASTNode} node The current node.
55067 * @returns {void}
55068 */
55069 onCodePathStart(codePath, node) {
55070 if (isConstructorFunction(node)) {
55071 // Class > ClassBody > MethodDefinition > FunctionExpression
55072 const classNode = node.parent.parent.parent;
55073 const superClass = classNode.superClass;
55074 funcInfo = {
55075 upper: funcInfo,
55076 isConstructor: true,
55077 hasExtends: Boolean(superClass),
55078 superIsConstructor: isPossibleConstructor(superClass),
55079 codePath
55080 };
55081 } else {
55082 funcInfo = {
55083 upper: funcInfo,
55084 isConstructor: false,
55085 hasExtends: false,
55086 superIsConstructor: false,
55087 codePath
55088 };
55089 }
55090 },
55091
55092 /**
55093 * Pops a constructor information.
55094 * And reports if `super()` lacked.
55095 * @param {CodePath} codePath A code path which was ended.
55096 * @param {ASTNode} node The current node.
55097 * @returns {void}
55098 */
55099 onCodePathEnd(codePath, node) {
55100 const hasExtends = funcInfo.hasExtends; // Pop.
55101
55102 funcInfo = funcInfo.upper;
55103
55104 if (!hasExtends) {
55105 return;
55106 } // Reports if `super()` lacked.
55107
55108
55109 const segments = codePath.returnedSegments;
55110 const calledInEveryPaths = segments.every(isCalledInEveryPath);
55111 const calledInSomePaths = segments.some(isCalledInSomePath);
55112
55113 if (!calledInEveryPaths) {
55114 context.report({
55115 messageId: calledInSomePaths ? "missingSome" : "missingAll",
55116 node: node.parent
55117 });
55118 }
55119 },
55120
55121 /**
55122 * Initialize information of a given code path segment.
55123 * @param {CodePathSegment} segment A code path segment to initialize.
55124 * @returns {void}
55125 */
55126 onCodePathSegmentStart(segment) {
55127 if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) {
55128 return;
55129 } // Initialize info.
55130
55131
55132 const info = segInfoMap[segment.id] = {
55133 calledInSomePaths: false,
55134 calledInEveryPaths: false,
55135 validNodes: []
55136 }; // When there are previous segments, aggregates these.
55137
55138 const prevSegments = segment.prevSegments;
55139
55140 if (prevSegments.length > 0) {
55141 info.calledInSomePaths = prevSegments.some(isCalledInSomePath);
55142 info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath);
55143 }
55144 },
55145
55146 /**
55147 * Update information of the code path segment when a code path was
55148 * looped.
55149 * @param {CodePathSegment} fromSegment The code path segment of the
55150 * end of a loop.
55151 * @param {CodePathSegment} toSegment A code path segment of the head
55152 * of a loop.
55153 * @returns {void}
55154 */
55155 onCodePathSegmentLoop(fromSegment, toSegment) {
55156 if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) {
55157 return;
55158 } // Update information inside of the loop.
55159
55160
55161 const isRealLoop = toSegment.prevSegments.length >= 2;
55162 funcInfo.codePath.traverseSegments({
55163 first: toSegment,
55164 last: fromSegment
55165 }, segment => {
55166 const info = segInfoMap[segment.id];
55167 const prevSegments = segment.prevSegments; // Updates flags.
55168
55169 info.calledInSomePaths = prevSegments.some(isCalledInSomePath);
55170 info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); // If flags become true anew, reports the valid nodes.
55171
55172 if (info.calledInSomePaths || isRealLoop) {
55173 const nodes = info.validNodes;
55174 info.validNodes = [];
55175
55176 for (let i = 0; i < nodes.length; ++i) {
55177 const node = nodes[i];
55178 context.report({
55179 messageId: "duplicate",
55180 node
55181 });
55182 }
55183 }
55184 });
55185 },
55186
55187 /**
55188 * Checks for a call of `super()`.
55189 * @param {ASTNode} node A CallExpression node to check.
55190 * @returns {void}
55191 */
55192 "CallExpression:exit"(node) {
55193 if (!(funcInfo && funcInfo.isConstructor)) {
55194 return;
55195 } // Skips except `super()`.
55196
55197
55198 if (node.callee.type !== "Super") {
55199 return;
55200 } // Reports if needed.
55201
55202
55203 if (funcInfo.hasExtends) {
55204 const segments = funcInfo.codePath.currentSegments;
55205 let duplicate = false;
55206 let info = null;
55207
55208 for (let i = 0; i < segments.length; ++i) {
55209 const segment = segments[i];
55210
55211 if (segment.reachable) {
55212 info = segInfoMap[segment.id];
55213 duplicate = duplicate || info.calledInSomePaths;
55214 info.calledInSomePaths = info.calledInEveryPaths = true;
55215 }
55216 }
55217
55218 if (info) {
55219 if (duplicate) {
55220 context.report({
55221 messageId: "duplicate",
55222 node
55223 });
55224 } else if (!funcInfo.superIsConstructor) {
55225 context.report({
55226 messageId: "badSuper",
55227 node
55228 });
55229 } else {
55230 info.validNodes.push(node);
55231 }
55232 }
55233 } else if (funcInfo.codePath.currentSegments.some(isReachable)) {
55234 context.report({
55235 messageId: "unexpected",
55236 node
55237 });
55238 }
55239 },
55240
55241 /**
55242 * Set the mark to the returned path as `super()` was called.
55243 * @param {ASTNode} node A ReturnStatement node to check.
55244 * @returns {void}
55245 */
55246 ReturnStatement(node) {
55247 if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) {
55248 return;
55249 } // Skips if no argument.
55250
55251
55252 if (!node.argument) {
55253 return;
55254 } // Returning argument is a substitute of 'super()'.
55255
55256
55257 const segments = funcInfo.codePath.currentSegments;
55258
55259 for (let i = 0; i < segments.length; ++i) {
55260 const segment = segments[i];
55261
55262 if (segment.reachable) {
55263 const info = segInfoMap[segment.id];
55264 info.calledInSomePaths = info.calledInEveryPaths = true;
55265 }
55266 }
55267 },
55268
55269 /**
55270 * Resets state.
55271 * @returns {void}
55272 */
55273 "Program:exit"() {
55274 segInfoMap = Object.create(null);
55275 }
55276
55277 };
55278 }
55279
55280};
55281
55282/***/ }),
55283/* 454 */
55284/***/ (function(module, exports, __webpack_require__) {
55285
55286"use strict";
55287/**
55288 * @fileoverview Rule to flag statements without curly braces
55289 * @author Nicholas C. Zakas
55290 */
55291 //------------------------------------------------------------------------------
55292// Requirements
55293//------------------------------------------------------------------------------
55294
55295const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
55296// Rule Definition
55297//------------------------------------------------------------------------------
55298
55299
55300module.exports = {
55301 meta: {
55302 type: "suggestion",
55303 docs: {
55304 description: "enforce consistent brace style for all control statements",
55305 category: "Best Practices",
55306 recommended: false,
55307 url: "https://eslint.org/docs/rules/curly"
55308 },
55309 schema: {
55310 anyOf: [{
55311 type: "array",
55312 items: [{
55313 enum: ["all"]
55314 }],
55315 minItems: 0,
55316 maxItems: 1
55317 }, {
55318 type: "array",
55319 items: [{
55320 enum: ["multi", "multi-line", "multi-or-nest"]
55321 }, {
55322 enum: ["consistent"]
55323 }],
55324 minItems: 0,
55325 maxItems: 2
55326 }]
55327 },
55328 fixable: "code",
55329 messages: {
55330 missingCurlyAfter: "Expected { after '{{name}}'.",
55331 missingCurlyAfterCondition: "Expected { after '{{name}}' condition.",
55332 unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.",
55333 unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition."
55334 }
55335 },
55336
55337 create(context) {
55338 const multiOnly = context.options[0] === "multi";
55339 const multiLine = context.options[0] === "multi-line";
55340 const multiOrNest = context.options[0] === "multi-or-nest";
55341 const consistent = context.options[1] === "consistent";
55342 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
55343 // Helpers
55344 //--------------------------------------------------------------------------
55345
55346 /**
55347 * Determines if a given node is a one-liner that's on the same line as it's preceding code.
55348 * @param {ASTNode} node The node to check.
55349 * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code.
55350 * @private
55351 */
55352
55353 function isCollapsedOneLiner(node) {
55354 const before = sourceCode.getTokenBefore(node);
55355 const last = sourceCode.getLastToken(node);
55356 const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
55357 return before.loc.start.line === lastExcludingSemicolon.loc.end.line;
55358 }
55359 /**
55360 * Determines if a given node is a one-liner.
55361 * @param {ASTNode} node The node to check.
55362 * @returns {boolean} True if the node is a one-liner.
55363 * @private
55364 */
55365
55366
55367 function isOneLiner(node) {
55368 if (node.type === "EmptyStatement") {
55369 return true;
55370 }
55371
55372 const first = sourceCode.getFirstToken(node);
55373 const last = sourceCode.getLastToken(node);
55374 const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
55375 return first.loc.start.line === lastExcludingSemicolon.loc.end.line;
55376 }
55377 /**
55378 * Determines if the given node is a lexical declaration (let, const, function, or class)
55379 * @param {ASTNode} node The node to check
55380 * @returns {boolean} True if the node is a lexical declaration
55381 * @private
55382 */
55383
55384
55385 function isLexicalDeclaration(node) {
55386 if (node.type === "VariableDeclaration") {
55387 return node.kind === "const" || node.kind === "let";
55388 }
55389
55390 return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration";
55391 }
55392 /**
55393 * Checks if the given token is an `else` token or not.
55394 * @param {Token} token The token to check.
55395 * @returns {boolean} `true` if the token is an `else` token.
55396 */
55397
55398
55399 function isElseKeywordToken(token) {
55400 return token.value === "else" && token.type === "Keyword";
55401 }
55402 /**
55403 * Gets the `else` keyword token of a given `IfStatement` node.
55404 * @param {ASTNode} node A `IfStatement` node to get.
55405 * @returns {Token} The `else` keyword token.
55406 */
55407
55408
55409 function getElseKeyword(node) {
55410 return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
55411 }
55412 /**
55413 * Determines whether the given node has an `else` keyword token as the first token after.
55414 * @param {ASTNode} node The node to check.
55415 * @returns {boolean} `true` if the node is followed by an `else` keyword token.
55416 */
55417
55418
55419 function isFollowedByElseKeyword(node) {
55420 const nextToken = sourceCode.getTokenAfter(node);
55421 return Boolean(nextToken) && isElseKeywordToken(nextToken);
55422 }
55423 /**
55424 * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
55425 * @param {Token} closingBracket The } token
55426 * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
55427 */
55428
55429
55430 function needsSemicolon(closingBracket) {
55431 const tokenBefore = sourceCode.getTokenBefore(closingBracket);
55432 const tokenAfter = sourceCode.getTokenAfter(closingBracket);
55433 const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
55434
55435 if (astUtils.isSemicolonToken(tokenBefore)) {
55436 // If the last statement already has a semicolon, don't add another one.
55437 return false;
55438 }
55439
55440 if (!tokenAfter) {
55441 // If there are no statements after this block, there is no need to add a semicolon.
55442 return false;
55443 }
55444
55445 if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
55446 /*
55447 * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
55448 * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
55449 * a SyntaxError if it was followed by `else`.
55450 */
55451 return false;
55452 }
55453
55454 if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
55455 // If the next token is on the same line, insert a semicolon.
55456 return true;
55457 }
55458
55459 if (/^[([/`+-]/u.test(tokenAfter.value)) {
55460 // If the next token starts with a character that would disrupt ASI, insert a semicolon.
55461 return true;
55462 }
55463
55464 if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
55465 // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
55466 return true;
55467 } // Otherwise, do not insert a semicolon.
55468
55469
55470 return false;
55471 }
55472 /**
55473 * Determines whether the code represented by the given node contains an `if` statement
55474 * that would become associated with an `else` keyword directly appended to that code.
55475 *
55476 * Examples where it returns `true`:
55477 *
55478 * if (a)
55479 * foo();
55480 *
55481 * if (a) {
55482 * foo();
55483 * }
55484 *
55485 * if (a)
55486 * foo();
55487 * else if (b)
55488 * bar();
55489 *
55490 * while (a)
55491 * if (b)
55492 * if(c)
55493 * foo();
55494 * else
55495 * bar();
55496 *
55497 * Examples where it returns `false`:
55498 *
55499 * if (a)
55500 * foo();
55501 * else
55502 * bar();
55503 *
55504 * while (a) {
55505 * if (b)
55506 * if(c)
55507 * foo();
55508 * else
55509 * bar();
55510 * }
55511 *
55512 * while (a)
55513 * if (b) {
55514 * if(c)
55515 * foo();
55516 * }
55517 * else
55518 * bar();
55519 * @param {ASTNode} node Node representing the code to check.
55520 * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
55521 */
55522
55523
55524 function hasUnsafeIf(node) {
55525 switch (node.type) {
55526 case "IfStatement":
55527 if (!node.alternate) {
55528 return true;
55529 }
55530
55531 return hasUnsafeIf(node.alternate);
55532
55533 case "ForStatement":
55534 case "ForInStatement":
55535 case "ForOfStatement":
55536 case "LabeledStatement":
55537 case "WithStatement":
55538 case "WhileStatement":
55539 return hasUnsafeIf(node.body);
55540
55541 default:
55542 return false;
55543 }
55544 }
55545 /**
55546 * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
55547 * The braces, which make the given block body, are necessary in either of the following situations:
55548 *
55549 * 1. The statement is a lexical declaration.
55550 * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
55551 *
55552 * if (a) {
55553 * if (b)
55554 * foo();
55555 * }
55556 * else
55557 * bar();
55558 *
55559 * if (a)
55560 * while (b)
55561 * while (c) {
55562 * while (d)
55563 * if (e)
55564 * while(f)
55565 * foo();
55566 * }
55567 * else
55568 * bar();
55569 * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
55570 * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
55571 * would change the semantics of the code or produce a syntax error.
55572 */
55573
55574
55575 function areBracesNecessary(node) {
55576 const statement = node.body[0];
55577 return isLexicalDeclaration(statement) || hasUnsafeIf(statement) && isFollowedByElseKeyword(node);
55578 }
55579 /**
55580 * Prepares to check the body of a node to see if it's a block statement.
55581 * @param {ASTNode} node The node to report if there's a problem.
55582 * @param {ASTNode} body The body node to check for blocks.
55583 * @param {string} name The name to report if there's a problem.
55584 * @param {{ condition: boolean }} opts Options to pass to the report functions
55585 * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
55586 * "actual" will be `true` or `false` whether the body is already a block statement.
55587 * "expected" will be `true` or `false` if the body should be a block statement or not, or
55588 * `null` if it doesn't matter, depending on the rule options. It can be modified to change
55589 * the final behavior of "check".
55590 * "check" will be a function reporting appropriate problems depending on the other
55591 * properties.
55592 */
55593
55594
55595 function prepareCheck(node, body, name, opts) {
55596 const hasBlock = body.type === "BlockStatement";
55597 let expected = null;
55598
55599 if (hasBlock && (body.body.length !== 1 || areBracesNecessary(body))) {
55600 expected = true;
55601 } else if (multiOnly) {
55602 expected = false;
55603 } else if (multiLine) {
55604 if (!isCollapsedOneLiner(body)) {
55605 expected = true;
55606 } // otherwise, the body is allowed to have braces or not to have braces
55607
55608 } else if (multiOrNest) {
55609 if (hasBlock) {
55610 const statement = body.body[0];
55611 const leadingCommentsInBlock = sourceCode.getCommentsBefore(statement);
55612 expected = !isOneLiner(statement) || leadingCommentsInBlock.length > 0;
55613 } else {
55614 expected = !isOneLiner(body);
55615 }
55616 } else {
55617 // default "all"
55618 expected = true;
55619 }
55620
55621 return {
55622 actual: hasBlock,
55623 expected,
55624
55625 check() {
55626 if (this.expected !== null && this.expected !== this.actual) {
55627 if (this.expected) {
55628 context.report({
55629 node,
55630 loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
55631 messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
55632 data: {
55633 name
55634 },
55635 fix: fixer => fixer.replaceText(body, "{".concat(sourceCode.getText(body), "}"))
55636 });
55637 } else {
55638 context.report({
55639 node,
55640 loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
55641 messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
55642 data: {
55643 name
55644 },
55645
55646 fix(fixer) {
55647 /*
55648 * `do while` expressions sometimes need a space to be inserted after `do`.
55649 * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
55650 */
55651 const needsPrecedingSpace = node.type === "DoWhileStatement" && sourceCode.getTokenBefore(body).range[1] === body.range[0] && !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, {
55652 skip: 1
55653 }));
55654 const openingBracket = sourceCode.getFirstToken(body);
55655 const closingBracket = sourceCode.getLastToken(body);
55656 const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
55657
55658 if (needsSemicolon(closingBracket)) {
55659 /*
55660 * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
55661 * change the semantics of the code due to ASI), don't perform a fix.
55662 */
55663 return null;
55664 }
55665
55666 const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) + sourceCode.getText(lastTokenInBlock) + sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
55667 return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
55668 }
55669
55670 });
55671 }
55672 }
55673 }
55674
55675 };
55676 }
55677 /**
55678 * Prepares to check the bodies of a "if", "else if" and "else" chain.
55679 * @param {ASTNode} node The first IfStatement node of the chain.
55680 * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
55681 * information.
55682 */
55683
55684
55685 function prepareIfChecks(node) {
55686 const preparedChecks = [];
55687
55688 for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
55689 preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", {
55690 condition: true
55691 }));
55692
55693 if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
55694 preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
55695 break;
55696 }
55697 }
55698
55699 if (consistent) {
55700 /*
55701 * If any node should have or already have braces, make sure they
55702 * all have braces.
55703 * If all nodes shouldn't have braces, make sure they don't.
55704 */
55705 const expected = preparedChecks.some(preparedCheck => {
55706 if (preparedCheck.expected !== null) {
55707 return preparedCheck.expected;
55708 }
55709
55710 return preparedCheck.actual;
55711 });
55712 preparedChecks.forEach(preparedCheck => {
55713 preparedCheck.expected = expected;
55714 });
55715 }
55716
55717 return preparedChecks;
55718 } //--------------------------------------------------------------------------
55719 // Public
55720 //--------------------------------------------------------------------------
55721
55722
55723 return {
55724 IfStatement(node) {
55725 if (node.parent.type !== "IfStatement") {
55726 prepareIfChecks(node).forEach(preparedCheck => {
55727 preparedCheck.check();
55728 });
55729 }
55730 },
55731
55732 WhileStatement(node) {
55733 prepareCheck(node, node.body, "while", {
55734 condition: true
55735 }).check();
55736 },
55737
55738 DoWhileStatement(node) {
55739 prepareCheck(node, node.body, "do").check();
55740 },
55741
55742 ForStatement(node) {
55743 prepareCheck(node, node.body, "for", {
55744 condition: true
55745 }).check();
55746 },
55747
55748 ForInStatement(node) {
55749 prepareCheck(node, node.body, "for-in").check();
55750 },
55751
55752 ForOfStatement(node) {
55753 prepareCheck(node, node.body, "for-of").check();
55754 }
55755
55756 };
55757 }
55758
55759};
55760
55761/***/ }),
55762/* 455 */
55763/***/ (function(module, exports, __webpack_require__) {
55764
55765"use strict";
55766/**
55767 * @fileoverview require default case in switch statements
55768 * @author Aliaksei Shytkin
55769 */
55770
55771
55772const DEFAULT_COMMENT_PATTERN = /^no default$/iu; //------------------------------------------------------------------------------
55773// Rule Definition
55774//------------------------------------------------------------------------------
55775
55776module.exports = {
55777 meta: {
55778 type: "suggestion",
55779 docs: {
55780 description: "require `default` cases in `switch` statements",
55781 category: "Best Practices",
55782 recommended: false,
55783 url: "https://eslint.org/docs/rules/default-case"
55784 },
55785 schema: [{
55786 type: "object",
55787 properties: {
55788 commentPattern: {
55789 type: "string"
55790 }
55791 },
55792 additionalProperties: false
55793 }],
55794 messages: {
55795 missingDefaultCase: "Expected a default case."
55796 }
55797 },
55798
55799 create(context) {
55800 const options = context.options[0] || {};
55801 const commentPattern = options.commentPattern ? new RegExp(options.commentPattern, "u") : DEFAULT_COMMENT_PATTERN;
55802 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
55803 // Helpers
55804 //--------------------------------------------------------------------------
55805
55806 /**
55807 * Shortcut to get last element of array
55808 * @param {*[]} collection Array
55809 * @returns {*} Last element
55810 */
55811
55812 function last(collection) {
55813 return collection[collection.length - 1];
55814 } //--------------------------------------------------------------------------
55815 // Public
55816 //--------------------------------------------------------------------------
55817
55818
55819 return {
55820 SwitchStatement(node) {
55821 if (!node.cases.length) {
55822 /*
55823 * skip check of empty switch because there is no easy way
55824 * to extract comments inside it now
55825 */
55826 return;
55827 }
55828
55829 const hasDefault = node.cases.some(v => v.test === null);
55830
55831 if (!hasDefault) {
55832 let comment;
55833 const lastCase = last(node.cases);
55834 const comments = sourceCode.getCommentsAfter(lastCase);
55835
55836 if (comments.length) {
55837 comment = last(comments);
55838 }
55839
55840 if (!comment || !commentPattern.test(comment.value.trim())) {
55841 context.report({
55842 node,
55843 messageId: "missingDefaultCase"
55844 });
55845 }
55846 }
55847 }
55848
55849 };
55850 }
55851
55852};
55853
55854/***/ }),
55855/* 456 */
55856/***/ (function(module, exports, __webpack_require__) {
55857
55858"use strict";
55859/**
55860 * @fileoverview Rule to enforce default clauses in switch statements to be last
55861 * @author Milos Djermanovic
55862 */
55863 //------------------------------------------------------------------------------
55864// Rule Definition
55865//------------------------------------------------------------------------------
55866
55867module.exports = {
55868 meta: {
55869 type: "suggestion",
55870 docs: {
55871 description: "enforce default clauses in switch statements to be last",
55872 category: "Best Practices",
55873 recommended: false,
55874 url: "https://eslint.org/docs/rules/default-case-last"
55875 },
55876 schema: [],
55877 messages: {
55878 notLast: "Default clause should be the last clause."
55879 }
55880 },
55881
55882 create(context) {
55883 return {
55884 SwitchStatement(node) {
55885 const cases = node.cases,
55886 indexOfDefault = cases.findIndex(c => c.test === null);
55887
55888 if (indexOfDefault !== -1 && indexOfDefault !== cases.length - 1) {
55889 const defaultClause = cases[indexOfDefault];
55890 context.report({
55891 node: defaultClause,
55892 messageId: "notLast"
55893 });
55894 }
55895 }
55896
55897 };
55898 }
55899
55900};
55901
55902/***/ }),
55903/* 457 */
55904/***/ (function(module, exports, __webpack_require__) {
55905
55906"use strict";
55907/**
55908 * @fileoverview enforce default parameters to be last
55909 * @author Chiawen Chen
55910 */
55911
55912
55913module.exports = {
55914 meta: {
55915 type: "suggestion",
55916 docs: {
55917 description: "enforce default parameters to be last",
55918 category: "Best Practices",
55919 recommended: false,
55920 url: "https://eslint.org/docs/rules/default-param-last"
55921 },
55922 schema: [],
55923 messages: {
55924 shouldBeLast: "Default parameters should be last."
55925 }
55926 },
55927
55928 create(context) {
55929 // eslint-disable-next-line jsdoc/require-description
55930
55931 /**
55932 * @param {ASTNode} node function node
55933 * @returns {void}
55934 */
55935 function handleFunction(node) {
55936 let hasSeenPlainParam = false;
55937
55938 for (let i = node.params.length - 1; i >= 0; i -= 1) {
55939 const param = node.params[i];
55940
55941 if (param.type !== "AssignmentPattern" && param.type !== "RestElement") {
55942 hasSeenPlainParam = true;
55943 continue;
55944 }
55945
55946 if (hasSeenPlainParam && param.type === "AssignmentPattern") {
55947 context.report({
55948 node: param,
55949 messageId: "shouldBeLast"
55950 });
55951 }
55952 }
55953 }
55954
55955 return {
55956 FunctionDeclaration: handleFunction,
55957 FunctionExpression: handleFunction,
55958 ArrowFunctionExpression: handleFunction
55959 };
55960 }
55961
55962};
55963
55964/***/ }),
55965/* 458 */
55966/***/ (function(module, exports, __webpack_require__) {
55967
55968"use strict";
55969/**
55970 * @fileoverview Validates newlines before and after dots
55971 * @author Greg Cochard
55972 */
55973
55974
55975const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
55976// Rule Definition
55977//------------------------------------------------------------------------------
55978
55979
55980module.exports = {
55981 meta: {
55982 type: "layout",
55983 docs: {
55984 description: "enforce consistent newlines before and after dots",
55985 category: "Best Practices",
55986 recommended: false,
55987 url: "https://eslint.org/docs/rules/dot-location"
55988 },
55989 schema: [{
55990 enum: ["object", "property"]
55991 }],
55992 fixable: "code",
55993 messages: {
55994 expectedDotAfterObject: "Expected dot to be on same line as object.",
55995 expectedDotBeforeProperty: "Expected dot to be on same line as property."
55996 }
55997 },
55998
55999 create(context) {
56000 const config = context.options[0]; // default to onObject if no preference is passed
56001
56002 const onObject = config === "object" || !config;
56003 const sourceCode = context.getSourceCode();
56004 /**
56005 * Reports if the dot between object and property is on the correct loccation.
56006 * @param {ASTNode} node The `MemberExpression` node.
56007 * @returns {void}
56008 */
56009
56010 function checkDotLocation(node) {
56011 const property = node.property;
56012 const dot = sourceCode.getTokenBefore(property); // `obj` expression can be parenthesized, but those paren tokens are not a part of the `obj` node.
56013
56014 const tokenBeforeDot = sourceCode.getTokenBefore(dot);
56015 const textBeforeDot = sourceCode.getText().slice(tokenBeforeDot.range[1], dot.range[0]);
56016 const textAfterDot = sourceCode.getText().slice(dot.range[1], property.range[0]);
56017
56018 if (onObject) {
56019 if (!astUtils.isTokenOnSameLine(tokenBeforeDot, dot)) {
56020 const neededTextAfterToken = astUtils.isDecimalIntegerNumericToken(tokenBeforeDot) ? " " : "";
56021 context.report({
56022 node,
56023 loc: dot.loc,
56024 messageId: "expectedDotAfterObject",
56025 fix: fixer => fixer.replaceTextRange([tokenBeforeDot.range[1], property.range[0]], "".concat(neededTextAfterToken, ".").concat(textBeforeDot).concat(textAfterDot))
56026 });
56027 }
56028 } else if (!astUtils.isTokenOnSameLine(dot, property)) {
56029 context.report({
56030 node,
56031 loc: dot.loc,
56032 messageId: "expectedDotBeforeProperty",
56033 fix: fixer => fixer.replaceTextRange([tokenBeforeDot.range[1], property.range[0]], "".concat(textBeforeDot).concat(textAfterDot, "."))
56034 });
56035 }
56036 }
56037 /**
56038 * Checks the spacing of the dot within a member expression.
56039 * @param {ASTNode} node The node to check.
56040 * @returns {void}
56041 */
56042
56043
56044 function checkNode(node) {
56045 if (!node.computed) {
56046 checkDotLocation(node);
56047 }
56048 }
56049
56050 return {
56051 MemberExpression: checkNode
56052 };
56053 }
56054
56055};
56056
56057/***/ }),
56058/* 459 */
56059/***/ (function(module, exports, __webpack_require__) {
56060
56061"use strict";
56062/**
56063 * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
56064 * @author Josh Perez
56065 */
56066 //------------------------------------------------------------------------------
56067// Requirements
56068//------------------------------------------------------------------------------
56069
56070const astUtils = __webpack_require__(426);
56071
56072const keywords = __webpack_require__(460); //------------------------------------------------------------------------------
56073// Rule Definition
56074//------------------------------------------------------------------------------
56075
56076
56077const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u; // `null` literal must be handled separately.
56078
56079const literalTypesToCheck = new Set(["string", "boolean"]);
56080module.exports = {
56081 meta: {
56082 type: "suggestion",
56083 docs: {
56084 description: "enforce dot notation whenever possible",
56085 category: "Best Practices",
56086 recommended: false,
56087 url: "https://eslint.org/docs/rules/dot-notation"
56088 },
56089 schema: [{
56090 type: "object",
56091 properties: {
56092 allowKeywords: {
56093 type: "boolean",
56094 default: true
56095 },
56096 allowPattern: {
56097 type: "string",
56098 default: ""
56099 }
56100 },
56101 additionalProperties: false
56102 }],
56103 fixable: "code",
56104 messages: {
56105 useDot: "[{{key}}] is better written in dot notation.",
56106 useBrackets: ".{{key}} is a syntax error."
56107 }
56108 },
56109
56110 create(context) {
56111 const options = context.options[0] || {};
56112 const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords;
56113 const sourceCode = context.getSourceCode();
56114 let allowPattern;
56115
56116 if (options.allowPattern) {
56117 allowPattern = new RegExp(options.allowPattern, "u");
56118 }
56119 /**
56120 * Check if the property is valid dot notation
56121 * @param {ASTNode} node The dot notation node
56122 * @param {string} value Value which is to be checked
56123 * @returns {void}
56124 */
56125
56126
56127 function checkComputedProperty(node, value) {
56128 if (validIdentifier.test(value) && (allowKeywords || keywords.indexOf(String(value)) === -1) && !(allowPattern && allowPattern.test(value))) {
56129 const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : "`".concat(value, "`");
56130 context.report({
56131 node: node.property,
56132 messageId: "useDot",
56133 data: {
56134 key: formattedValue
56135 },
56136
56137 fix(fixer) {
56138 const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
56139 const rightBracket = sourceCode.getLastToken(node);
56140
56141 if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, {
56142 includeComments: true,
56143 filter: astUtils.isCommentToken
56144 })) {
56145 // Don't perform any fixes if there are comments inside the brackets.
56146 return null;
56147 }
56148
56149 const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
56150 const needsSpaceAfterProperty = tokenAfterProperty && rightBracket.range[1] === tokenAfterProperty.range[0] && !astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
56151 const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
56152 const textAfterProperty = needsSpaceAfterProperty ? " " : "";
56153 return fixer.replaceTextRange([leftBracket.range[0], rightBracket.range[1]], "".concat(textBeforeDot, ".").concat(value).concat(textAfterProperty));
56154 }
56155
56156 });
56157 }
56158 }
56159
56160 return {
56161 MemberExpression(node) {
56162 if (node.computed && node.property.type === "Literal" && (literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property))) {
56163 checkComputedProperty(node, node.property.value);
56164 }
56165
56166 if (node.computed && node.property.type === "TemplateLiteral" && node.property.expressions.length === 0) {
56167 checkComputedProperty(node, node.property.quasis[0].value.cooked);
56168 }
56169
56170 if (!allowKeywords && !node.computed && keywords.indexOf(String(node.property.name)) !== -1) {
56171 context.report({
56172 node: node.property,
56173 messageId: "useBrackets",
56174 data: {
56175 key: node.property.name
56176 },
56177
56178 fix(fixer) {
56179 const dot = sourceCode.getTokenBefore(node.property);
56180 const textAfterDot = sourceCode.text.slice(dot.range[1], node.property.range[0]);
56181
56182 if (textAfterDot.trim()) {
56183 // Don't perform any fixes if there are comments between the dot and the property name.
56184 return null;
56185 }
56186
56187 if (node.object.type === "Identifier" && node.object.name === "let") {
56188 /*
56189 * A statement that starts with `let[` is parsed as a destructuring variable declaration, not
56190 * a MemberExpression.
56191 */
56192 return null;
56193 }
56194
56195 return fixer.replaceTextRange([dot.range[0], node.property.range[1]], "[".concat(textAfterDot, "\"").concat(node.property.name, "\"]"));
56196 }
56197
56198 });
56199 }
56200 }
56201
56202 };
56203 }
56204
56205};
56206
56207/***/ }),
56208/* 460 */
56209/***/ (function(module, exports, __webpack_require__) {
56210
56211"use strict";
56212/**
56213 * @fileoverview A shared list of ES3 keywords.
56214 * @author Josh Perez
56215 */
56216
56217
56218module.exports = ["abstract", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with"];
56219
56220/***/ }),
56221/* 461 */
56222/***/ (function(module, exports, __webpack_require__) {
56223
56224"use strict";
56225/**
56226 * @fileoverview Require or disallow newline at the end of files
56227 * @author Nodeca Team <https://github.com/nodeca>
56228 */
56229 //------------------------------------------------------------------------------
56230// Requirements
56231//------------------------------------------------------------------------------
56232
56233const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
56234// Rule Definition
56235//------------------------------------------------------------------------------
56236
56237
56238module.exports = {
56239 meta: {
56240 type: "layout",
56241 docs: {
56242 description: "require or disallow newline at the end of files",
56243 category: "Stylistic Issues",
56244 recommended: false,
56245 url: "https://eslint.org/docs/rules/eol-last"
56246 },
56247 fixable: "whitespace",
56248 schema: [{
56249 enum: ["always", "never", "unix", "windows"]
56250 }],
56251 messages: {
56252 missing: "Newline required at end of file but not found.",
56253 unexpected: "Newline not allowed at end of file."
56254 }
56255 },
56256
56257 create(context) {
56258 //--------------------------------------------------------------------------
56259 // Public
56260 //--------------------------------------------------------------------------
56261 return {
56262 Program: function checkBadEOF(node) {
56263 const sourceCode = context.getSourceCode(),
56264 src = sourceCode.getText(),
56265 location = {
56266 column: lodash.last(sourceCode.lines).length,
56267 line: sourceCode.lines.length
56268 },
56269 LF = "\n",
56270 CRLF = "\r".concat(LF),
56271 endsWithNewline = lodash.endsWith(src, LF);
56272 /*
56273 * Empty source is always valid: No content in file so we don't
56274 * need to lint for a newline on the last line of content.
56275 */
56276
56277 if (!src.length) {
56278 return;
56279 }
56280
56281 let mode = context.options[0] || "always",
56282 appendCRLF = false;
56283
56284 if (mode === "unix") {
56285 // `"unix"` should behave exactly as `"always"`
56286 mode = "always";
56287 }
56288
56289 if (mode === "windows") {
56290 // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility
56291 mode = "always";
56292 appendCRLF = true;
56293 }
56294
56295 if (mode === "always" && !endsWithNewline) {
56296 // File is not newline-terminated, but should be
56297 context.report({
56298 node,
56299 loc: location,
56300 messageId: "missing",
56301
56302 fix(fixer) {
56303 return fixer.insertTextAfterRange([0, src.length], appendCRLF ? CRLF : LF);
56304 }
56305
56306 });
56307 } else if (mode === "never" && endsWithNewline) {
56308 // File is newline-terminated, but shouldn't be
56309 context.report({
56310 node,
56311 loc: location,
56312 messageId: "unexpected",
56313
56314 fix(fixer) {
56315 const finalEOLs = /(?:\r?\n)+$/u,
56316 match = finalEOLs.exec(sourceCode.text),
56317 start = match.index,
56318 end = sourceCode.text.length;
56319 return fixer.replaceTextRange([start, end], "");
56320 }
56321
56322 });
56323 }
56324 }
56325 };
56326 }
56327
56328};
56329
56330/***/ }),
56331/* 462 */
56332/***/ (function(module, exports, __webpack_require__) {
56333
56334"use strict";
56335/**
56336 * @fileoverview Rule to flag statements that use != and == instead of !== and ===
56337 * @author Nicholas C. Zakas
56338 */
56339 //------------------------------------------------------------------------------
56340// Requirements
56341//------------------------------------------------------------------------------
56342
56343const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
56344// Rule Definition
56345//------------------------------------------------------------------------------
56346
56347
56348module.exports = {
56349 meta: {
56350 type: "suggestion",
56351 docs: {
56352 description: "require the use of `===` and `!==`",
56353 category: "Best Practices",
56354 recommended: false,
56355 url: "https://eslint.org/docs/rules/eqeqeq"
56356 },
56357 schema: {
56358 anyOf: [{
56359 type: "array",
56360 items: [{
56361 enum: ["always"]
56362 }, {
56363 type: "object",
56364 properties: {
56365 null: {
56366 enum: ["always", "never", "ignore"]
56367 }
56368 },
56369 additionalProperties: false
56370 }],
56371 additionalItems: false
56372 }, {
56373 type: "array",
56374 items: [{
56375 enum: ["smart", "allow-null"]
56376 }],
56377 additionalItems: false
56378 }]
56379 },
56380 fixable: "code",
56381 messages: {
56382 unexpected: "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'."
56383 }
56384 },
56385
56386 create(context) {
56387 const config = context.options[0] || "always";
56388 const options = context.options[1] || {};
56389 const sourceCode = context.getSourceCode();
56390 const nullOption = config === "always" ? options.null || "always" : "ignore";
56391 const enforceRuleForNull = nullOption === "always";
56392 const enforceInverseRuleForNull = nullOption === "never";
56393 /**
56394 * Checks if an expression is a typeof expression
56395 * @param {ASTNode} node The node to check
56396 * @returns {boolean} if the node is a typeof expression
56397 */
56398
56399 function isTypeOf(node) {
56400 return node.type === "UnaryExpression" && node.operator === "typeof";
56401 }
56402 /**
56403 * Checks if either operand of a binary expression is a typeof operation
56404 * @param {ASTNode} node The node to check
56405 * @returns {boolean} if one of the operands is typeof
56406 * @private
56407 */
56408
56409
56410 function isTypeOfBinary(node) {
56411 return isTypeOf(node.left) || isTypeOf(node.right);
56412 }
56413 /**
56414 * Checks if operands are literals of the same type (via typeof)
56415 * @param {ASTNode} node The node to check
56416 * @returns {boolean} if operands are of same type
56417 * @private
56418 */
56419
56420
56421 function areLiteralsAndSameType(node) {
56422 return node.left.type === "Literal" && node.right.type === "Literal" && typeof node.left.value === typeof node.right.value;
56423 }
56424 /**
56425 * Checks if one of the operands is a literal null
56426 * @param {ASTNode} node The node to check
56427 * @returns {boolean} if operands are null
56428 * @private
56429 */
56430
56431
56432 function isNullCheck(node) {
56433 return astUtils.isNullLiteral(node.right) || astUtils.isNullLiteral(node.left);
56434 }
56435 /**
56436 * Reports a message for this rule.
56437 * @param {ASTNode} node The binary expression node that was checked
56438 * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==')
56439 * @returns {void}
56440 * @private
56441 */
56442
56443
56444 function report(node, expectedOperator) {
56445 const operatorToken = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
56446 context.report({
56447 node,
56448 loc: operatorToken.loc,
56449 messageId: "unexpected",
56450 data: {
56451 expectedOperator,
56452 actualOperator: node.operator
56453 },
56454
56455 fix(fixer) {
56456 // If the comparison is a `typeof` comparison or both sides are literals with the same type, then it's safe to fix.
56457 if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) {
56458 return fixer.replaceText(operatorToken, expectedOperator);
56459 }
56460
56461 return null;
56462 }
56463
56464 });
56465 }
56466
56467 return {
56468 BinaryExpression(node) {
56469 const isNull = isNullCheck(node);
56470
56471 if (node.operator !== "==" && node.operator !== "!=") {
56472 if (enforceInverseRuleForNull && isNull) {
56473 report(node, node.operator.slice(0, -1));
56474 }
56475
56476 return;
56477 }
56478
56479 if (config === "smart" && (isTypeOfBinary(node) || areLiteralsAndSameType(node) || isNull)) {
56480 return;
56481 }
56482
56483 if (!enforceRuleForNull && isNull) {
56484 return;
56485 }
56486
56487 report(node, "".concat(node.operator, "="));
56488 }
56489
56490 };
56491 }
56492
56493};
56494
56495/***/ }),
56496/* 463 */
56497/***/ (function(module, exports, __webpack_require__) {
56498
56499"use strict";
56500/**
56501 * @fileoverview enforce "for" loop update clause moving the counter in the right direction.(for-direction)
56502 * @author Aladdin-ADD<hh_2013@foxmail.com>
56503 */
56504 //------------------------------------------------------------------------------
56505// Rule Definition
56506//------------------------------------------------------------------------------
56507
56508module.exports = {
56509 meta: {
56510 type: "problem",
56511 docs: {
56512 description: "enforce \"for\" loop update clause moving the counter in the right direction.",
56513 category: "Possible Errors",
56514 recommended: true,
56515 url: "https://eslint.org/docs/rules/for-direction"
56516 },
56517 fixable: null,
56518 schema: [],
56519 messages: {
56520 incorrectDirection: "The update clause in this loop moves the variable in the wrong direction."
56521 }
56522 },
56523
56524 create(context) {
56525 /**
56526 * report an error.
56527 * @param {ASTNode} node the node to report.
56528 * @returns {void}
56529 */
56530 function report(node) {
56531 context.report({
56532 node,
56533 messageId: "incorrectDirection"
56534 });
56535 }
56536 /**
56537 * check the right side of the assignment
56538 * @param {ASTNode} update UpdateExpression to check
56539 * @param {int} dir expected direction that could either be turned around or invalidated
56540 * @returns {int} return dir, the negated dir or zero if it's not clear for identifiers
56541 */
56542
56543
56544 function getRightDirection(update, dir) {
56545 if (update.right.type === "UnaryExpression") {
56546 if (update.right.operator === "-") {
56547 return -dir;
56548 }
56549 } else if (update.right.type === "Identifier") {
56550 return 0;
56551 }
56552
56553 return dir;
56554 }
56555 /**
56556 * check UpdateExpression add/sub the counter
56557 * @param {ASTNode} update UpdateExpression to check
56558 * @param {string} counter variable name to check
56559 * @returns {int} if add return 1, if sub return -1, if nochange, return 0
56560 */
56561
56562
56563 function getUpdateDirection(update, counter) {
56564 if (update.argument.type === "Identifier" && update.argument.name === counter) {
56565 if (update.operator === "++") {
56566 return 1;
56567 }
56568
56569 if (update.operator === "--") {
56570 return -1;
56571 }
56572 }
56573
56574 return 0;
56575 }
56576 /**
56577 * check AssignmentExpression add/sub the counter
56578 * @param {ASTNode} update AssignmentExpression to check
56579 * @param {string} counter variable name to check
56580 * @returns {int} if add return 1, if sub return -1, if nochange, return 0
56581 */
56582
56583
56584 function getAssignmentDirection(update, counter) {
56585 if (update.left.name === counter) {
56586 if (update.operator === "+=") {
56587 return getRightDirection(update, 1);
56588 }
56589
56590 if (update.operator === "-=") {
56591 return getRightDirection(update, -1);
56592 }
56593 }
56594
56595 return 0;
56596 }
56597
56598 return {
56599 ForStatement(node) {
56600 if (node.test && node.test.type === "BinaryExpression" && node.test.left.type === "Identifier" && node.update) {
56601 const counter = node.test.left.name;
56602 const operator = node.test.operator;
56603 const update = node.update;
56604 let wrongDirection;
56605
56606 if (operator === "<" || operator === "<=") {
56607 wrongDirection = -1;
56608 } else if (operator === ">" || operator === ">=") {
56609 wrongDirection = 1;
56610 } else {
56611 return;
56612 }
56613
56614 if (update.type === "UpdateExpression") {
56615 if (getUpdateDirection(update, counter) === wrongDirection) {
56616 report(node);
56617 }
56618 } else if (update.type === "AssignmentExpression" && getAssignmentDirection(update, counter) === wrongDirection) {
56619 report(node);
56620 }
56621 }
56622 }
56623
56624 };
56625 }
56626
56627};
56628
56629/***/ }),
56630/* 464 */
56631/***/ (function(module, exports, __webpack_require__) {
56632
56633"use strict";
56634/**
56635 * @fileoverview Rule to control spacing within function calls
56636 * @author Matt DuVall <http://www.mattduvall.com>
56637 */
56638 //------------------------------------------------------------------------------
56639// Requirements
56640//------------------------------------------------------------------------------
56641
56642const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
56643// Rule Definition
56644//------------------------------------------------------------------------------
56645
56646
56647module.exports = {
56648 meta: {
56649 type: "layout",
56650 docs: {
56651 description: "require or disallow spacing between function identifiers and their invocations",
56652 category: "Stylistic Issues",
56653 recommended: false,
56654 url: "https://eslint.org/docs/rules/func-call-spacing"
56655 },
56656 fixable: "whitespace",
56657 schema: {
56658 anyOf: [{
56659 type: "array",
56660 items: [{
56661 enum: ["never"]
56662 }],
56663 minItems: 0,
56664 maxItems: 1
56665 }, {
56666 type: "array",
56667 items: [{
56668 enum: ["always"]
56669 }, {
56670 type: "object",
56671 properties: {
56672 allowNewlines: {
56673 type: "boolean"
56674 }
56675 },
56676 additionalProperties: false
56677 }],
56678 minItems: 0,
56679 maxItems: 2
56680 }]
56681 },
56682 messages: {
56c4a2cb
DC
56683 unexpectedWhitespace: "Unexpected whitespace between function name and paren.",
56684 unexpectedNewline: "Unexpected newline between function name and paren.",
eb39fafa
DC
56685 missing: "Missing space between function name and paren."
56686 }
56687 },
56688
56689 create(context) {
56690 const never = context.options[0] !== "always";
56691 const allowNewlines = !never && context.options[1] && context.options[1].allowNewlines;
56692 const sourceCode = context.getSourceCode();
56693 const text = sourceCode.getText();
56694 /**
56695 * Check if open space is present in a function name
56696 * @param {ASTNode} node node to evaluate
56697 * @param {Token} leftToken The last token of the callee. This may be the closing parenthesis that encloses the callee.
56698 * @param {Token} rightToken Tha first token of the arguments. this is the opening parenthesis that encloses the arguments.
56699 * @returns {void}
56700 * @private
56701 */
56702
56703 function checkSpacing(node, leftToken, rightToken) {
56704 const textBetweenTokens = text.slice(leftToken.range[1], rightToken.range[0]).replace(/\/\*.*?\*\//gu, "");
56705 const hasWhitespace = /\s/u.test(textBetweenTokens);
56706 const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens);
56707 /*
56708 * never allowNewlines hasWhitespace hasNewline message
56709 * F F F F Missing space between function name and paren.
56710 * F F F T (Invalid `!hasWhitespace && hasNewline`)
56711 * F F T T Unexpected newline between function name and paren.
56712 * F F T F (OK)
56713 * F T T F (OK)
56714 * F T T T (OK)
56715 * F T F T (Invalid `!hasWhitespace && hasNewline`)
56716 * F T F F Missing space between function name and paren.
56717 * T T F F (Invalid `never && allowNewlines`)
56718 * T T F T (Invalid `!hasWhitespace && hasNewline`)
56719 * T T T T (Invalid `never && allowNewlines`)
56720 * T T T F (Invalid `never && allowNewlines`)
56721 * T F T F Unexpected space between function name and paren.
56722 * T F T T Unexpected space between function name and paren.
56723 * T F F T (Invalid `!hasWhitespace && hasNewline`)
56724 * T F F F (OK)
56725 *
56726 * T T Unexpected space between function name and paren.
56727 * F F Missing space between function name and paren.
56728 * F F T Unexpected newline between function name and paren.
56729 */
56730
56731 if (never && hasWhitespace) {
56732 context.report({
56733 node,
56734 loc: leftToken.loc.start,
56c4a2cb 56735 messageId: "unexpectedWhitespace",
eb39fafa
DC
56736
56737 fix(fixer) {
56738 /*
56739 * Only autofix if there is no newline
56740 * https://github.com/eslint/eslint/issues/7787
56741 */
56742 if (!hasNewline) {
56743 return fixer.removeRange([leftToken.range[1], rightToken.range[0]]);
56744 }
56745
56746 return null;
56747 }
56748
56749 });
56750 } else if (!never && !hasWhitespace) {
56751 context.report({
56752 node,
56753 loc: leftToken.loc.start,
56754 messageId: "missing",
56755
56756 fix(fixer) {
56757 return fixer.insertTextBefore(rightToken, " ");
56758 }
56759
56760 });
56761 } else if (!never && !allowNewlines && hasNewline) {
56762 context.report({
56763 node,
56764 loc: leftToken.loc.start,
56c4a2cb 56765 messageId: "unexpectedNewline",
eb39fafa
DC
56766
56767 fix(fixer) {
56768 return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ");
56769 }
56770
56771 });
56772 }
56773 }
56774
56775 return {
56776 "CallExpression, NewExpression"(node) {
56777 const lastToken = sourceCode.getLastToken(node);
56778 const lastCalleeToken = sourceCode.getLastToken(node.callee);
56779 const parenToken = sourceCode.getFirstTokenBetween(lastCalleeToken, lastToken, astUtils.isOpeningParenToken);
56780 const prevToken = parenToken && sourceCode.getTokenBefore(parenToken); // Parens in NewExpression are optional
56781
56782 if (!(parenToken && parenToken.range[1] < node.range[1])) {
56783 return;
56784 }
56785
56786 checkSpacing(node, prevToken, parenToken);
56787 },
56788
56789 ImportExpression(node) {
56790 const leftToken = sourceCode.getFirstToken(node);
56791 const rightToken = sourceCode.getTokenAfter(leftToken);
56792 checkSpacing(node, leftToken, rightToken);
56793 }
56794
56795 };
56796 }
56797
56798};
56799
56800/***/ }),
56801/* 465 */
56802/***/ (function(module, exports, __webpack_require__) {
56803
56804"use strict";
56805/**
56806 * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned.
56807 * @author Annie Zhang, Pavel Strashkin
56808 */
56809 //--------------------------------------------------------------------------
56810// Requirements
56811//--------------------------------------------------------------------------
56812
56813const astUtils = __webpack_require__(426);
56814
56815const esutils = __webpack_require__(427); //--------------------------------------------------------------------------
56816// Helpers
56817//--------------------------------------------------------------------------
56818
56819/**
56820 * Determines if a pattern is `module.exports` or `module["exports"]`
56821 * @param {ASTNode} pattern The left side of the AssignmentExpression
56822 * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]`
56823 */
56824
56825
56826function isModuleExports(pattern) {
56827 if (pattern.type === "MemberExpression" && pattern.object.type === "Identifier" && pattern.object.name === "module") {
56828 // module.exports
56829 if (pattern.property.type === "Identifier" && pattern.property.name === "exports") {
56830 return true;
56831 } // module["exports"]
56832
56833
56834 if (pattern.property.type === "Literal" && pattern.property.value === "exports") {
56835 return true;
56836 }
56837 }
56838
56839 return false;
56840}
56841/**
56842 * Determines if a string name is a valid identifier
56843 * @param {string} name The string to be checked
56844 * @param {int} ecmaVersion The ECMAScript version if specified in the parserOptions config
56845 * @returns {boolean} True if the string is a valid identifier
56846 */
56847
56848
56849function isIdentifier(name, ecmaVersion) {
56850 if (ecmaVersion >= 6) {
56851 return esutils.keyword.isIdentifierES6(name);
56852 }
56853
56854 return esutils.keyword.isIdentifierES5(name);
56855} //------------------------------------------------------------------------------
56856// Rule Definition
56857//------------------------------------------------------------------------------
56858
56859
56860const alwaysOrNever = {
56861 enum: ["always", "never"]
56862};
56863const optionsObject = {
56864 type: "object",
56865 properties: {
56866 considerPropertyDescriptor: {
56867 type: "boolean"
56868 },
56869 includeCommonJSModuleExports: {
56870 type: "boolean"
56871 }
56872 },
56873 additionalProperties: false
56874};
56875module.exports = {
56876 meta: {
56877 type: "suggestion",
56878 docs: {
56879 description: "require function names to match the name of the variable or property to which they are assigned",
56880 category: "Stylistic Issues",
56881 recommended: false,
56882 url: "https://eslint.org/docs/rules/func-name-matching"
56883 },
56884 schema: {
56885 anyOf: [{
56886 type: "array",
56887 additionalItems: false,
56888 items: [alwaysOrNever, optionsObject]
56889 }, {
56890 type: "array",
56891 additionalItems: false,
56892 items: [optionsObject]
56893 }]
56894 },
56895 messages: {
56896 matchProperty: "Function name `{{funcName}}` should match property name `{{name}}`.",
56897 matchVariable: "Function name `{{funcName}}` should match variable name `{{name}}`.",
56898 notMatchProperty: "Function name `{{funcName}}` should not match property name `{{name}}`.",
56899 notMatchVariable: "Function name `{{funcName}}` should not match variable name `{{name}}`."
56900 }
56901 },
56902
56903 create(context) {
56904 const options = (typeof context.options[0] === "object" ? context.options[0] : context.options[1]) || {};
56905 const nameMatches = typeof context.options[0] === "string" ? context.options[0] : "always";
56906 const considerPropertyDescriptor = options.considerPropertyDescriptor;
56907 const includeModuleExports = options.includeCommonJSModuleExports;
56908 const ecmaVersion = context.parserOptions && context.parserOptions.ecmaVersion ? context.parserOptions.ecmaVersion : 5;
56909 /**
56910 * Check whether node is a certain CallExpression.
56911 * @param {string} objName object name
56912 * @param {string} funcName function name
56913 * @param {ASTNode} node The node to check
56914 * @returns {boolean} `true` if node matches CallExpression
56915 */
56916
56917 function isPropertyCall(objName, funcName, node) {
56918 if (!node) {
56919 return false;
56920 }
56921
56922 return node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.name === objName && node.callee.property.name === funcName;
56923 }
56924 /**
56925 * Compares identifiers based on the nameMatches option
56926 * @param {string} x the first identifier
56927 * @param {string} y the second identifier
56928 * @returns {boolean} whether the two identifiers should warn.
56929 */
56930
56931
56932 function shouldWarn(x, y) {
56933 return nameMatches === "always" && x !== y || nameMatches === "never" && x === y;
56934 }
56935 /**
56936 * Reports
56937 * @param {ASTNode} node The node to report
56938 * @param {string} name The variable or property name
56939 * @param {string} funcName The function name
56940 * @param {boolean} isProp True if the reported node is a property assignment
56941 * @returns {void}
56942 */
56943
56944
56945 function report(node, name, funcName, isProp) {
56946 let messageId;
56947
56948 if (nameMatches === "always" && isProp) {
56949 messageId = "matchProperty";
56950 } else if (nameMatches === "always") {
56951 messageId = "matchVariable";
56952 } else if (isProp) {
56953 messageId = "notMatchProperty";
56954 } else {
56955 messageId = "notMatchVariable";
56956 }
56957
56958 context.report({
56959 node,
56960 messageId,
56961 data: {
56962 name,
56963 funcName
56964 }
56965 });
56966 }
56967 /**
56968 * Determines whether a given node is a string literal
56969 * @param {ASTNode} node The node to check
56970 * @returns {boolean} `true` if the node is a string literal
56971 */
56972
56973
56974 function isStringLiteral(node) {
56975 return node.type === "Literal" && typeof node.value === "string";
56976 } //--------------------------------------------------------------------------
56977 // Public
56978 //--------------------------------------------------------------------------
56979
56980
56981 return {
56982 VariableDeclarator(node) {
56983 if (!node.init || node.init.type !== "FunctionExpression" || node.id.type !== "Identifier") {
56984 return;
56985 }
56986
56987 if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) {
56988 report(node, node.id.name, node.init.id.name, false);
56989 }
56990 },
56991
56992 AssignmentExpression(node) {
56993 if (node.right.type !== "FunctionExpression" || node.left.computed && node.left.property.type !== "Literal" || !includeModuleExports && isModuleExports(node.left) || node.left.type !== "Identifier" && node.left.type !== "MemberExpression") {
56994 return;
56995 }
56996
56997 const isProp = node.left.type === "MemberExpression";
56998 const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name;
56999
57000 if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) {
57001 report(node, name, node.right.id.name, isProp);
57002 }
57003 },
57004
57005 Property(node) {
57006 if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && !isStringLiteral(node.key)) {
57007 return;
57008 }
57009
57010 if (node.key.type === "Identifier") {
57011 const functionName = node.value.id.name;
57012 let propertyName = node.key.name;
57013
57014 if (considerPropertyDescriptor && propertyName === "value") {
57015 if (isPropertyCall("Object", "defineProperty", node.parent.parent) || isPropertyCall("Reflect", "defineProperty", node.parent.parent)) {
57016 const property = node.parent.parent.arguments[1];
57017
57018 if (isStringLiteral(property) && shouldWarn(property.value, functionName)) {
57019 report(node, property.value, functionName, true);
57020 }
57021 } else if (isPropertyCall("Object", "defineProperties", node.parent.parent.parent.parent)) {
57022 propertyName = node.parent.parent.key.name;
57023
57024 if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) {
57025 report(node, propertyName, functionName, true);
57026 }
57027 } else if (isPropertyCall("Object", "create", node.parent.parent.parent.parent)) {
57028 propertyName = node.parent.parent.key.name;
57029
57030 if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) {
57031 report(node, propertyName, functionName, true);
57032 }
57033 } else if (shouldWarn(propertyName, functionName)) {
57034 report(node, propertyName, functionName, true);
57035 }
57036 } else if (shouldWarn(propertyName, functionName)) {
57037 report(node, propertyName, functionName, true);
57038 }
57039
57040 return;
57041 }
57042
57043 if (isStringLiteral(node.key) && isIdentifier(node.key.value, ecmaVersion) && shouldWarn(node.key.value, node.value.id.name)) {
57044 report(node, node.key.value, node.value.id.name, true);
57045 }
57046 }
57047
57048 };
57049 }
57050
57051};
57052
57053/***/ }),
57054/* 466 */
57055/***/ (function(module, exports, __webpack_require__) {
57056
57057"use strict";
57058/**
57059 * @fileoverview Rule to warn when a function expression does not have a name.
57060 * @author Kyle T. Nunery
57061 */
57062 //------------------------------------------------------------------------------
57063// Requirements
57064//------------------------------------------------------------------------------
57065
57066const astUtils = __webpack_require__(426);
57067/**
57068 * Checks whether or not a given variable is a function name.
57069 * @param {eslint-scope.Variable} variable A variable to check.
57070 * @returns {boolean} `true` if the variable is a function name.
57071 */
57072
57073
57074function isFunctionName(variable) {
57075 return variable && variable.defs[0].type === "FunctionName";
57076} //------------------------------------------------------------------------------
57077// Rule Definition
57078//------------------------------------------------------------------------------
57079
57080
57081module.exports = {
57082 meta: {
57083 type: "suggestion",
57084 docs: {
57085 description: "require or disallow named `function` expressions",
57086 category: "Stylistic Issues",
57087 recommended: false,
57088 url: "https://eslint.org/docs/rules/func-names"
57089 },
57090 schema: {
57091 definitions: {
57092 value: {
57093 enum: ["always", "as-needed", "never"]
57094 }
57095 },
57096 items: [{
57097 $ref: "#/definitions/value"
57098 }, {
57099 type: "object",
57100 properties: {
57101 generators: {
57102 $ref: "#/definitions/value"
57103 }
57104 },
57105 additionalProperties: false
57106 }]
57107 },
57108 messages: {
57109 unnamed: "Unexpected unnamed {{name}}.",
57110 named: "Unexpected named {{name}}."
57111 }
57112 },
57113
57114 create(context) {
57115 const sourceCode = context.getSourceCode();
57116 /**
57117 * Returns the config option for the given node.
57118 * @param {ASTNode} node A node to get the config for.
57119 * @returns {string} The config option.
57120 */
57121
57122 function getConfigForNode(node) {
57123 if (node.generator && context.options.length > 1 && context.options[1].generators) {
57124 return context.options[1].generators;
57125 }
57126
57127 return context.options[0] || "always";
57128 }
57129 /**
57130 * Determines whether the current FunctionExpression node is a get, set, or
57131 * shorthand method in an object literal or a class.
57132 * @param {ASTNode} node A node to check.
57133 * @returns {boolean} True if the node is a get, set, or shorthand method.
57134 */
57135
57136
57137 function isObjectOrClassMethod(node) {
57138 const parent = node.parent;
57139 return parent.type === "MethodDefinition" || parent.type === "Property" && (parent.method || parent.kind === "get" || parent.kind === "set");
57140 }
57141 /**
57142 * Determines whether the current FunctionExpression node has a name that would be
57143 * inferred from context in a conforming ES6 environment.
57144 * @param {ASTNode} node A node to check.
57145 * @returns {boolean} True if the node would have a name assigned automatically.
57146 */
57147
57148
57149 function hasInferredName(node) {
57150 const parent = node.parent;
57151 return isObjectOrClassMethod(node) || parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node || parent.type === "Property" && parent.value === node || parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node || parent.type === "AssignmentPattern" && parent.left.type === "Identifier" && parent.right === node;
57152 }
57153 /**
57154 * Reports that an unnamed function should be named
57155 * @param {ASTNode} node The node to report in the event of an error.
57156 * @returns {void}
57157 */
57158
57159
57160 function reportUnexpectedUnnamedFunction(node) {
57161 context.report({
57162 node,
57163 messageId: "unnamed",
57164 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
57165 data: {
57166 name: astUtils.getFunctionNameWithKind(node)
57167 }
57168 });
57169 }
57170 /**
57171 * Reports that a named function should be unnamed
57172 * @param {ASTNode} node The node to report in the event of an error.
57173 * @returns {void}
57174 */
57175
57176
57177 function reportUnexpectedNamedFunction(node) {
57178 context.report({
57179 node,
57180 messageId: "named",
57181 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
57182 data: {
57183 name: astUtils.getFunctionNameWithKind(node)
57184 }
57185 });
57186 }
57187 /**
57188 * The listener for function nodes.
57189 * @param {ASTNode} node function node
57190 * @returns {void}
57191 */
57192
57193
57194 function handleFunction(node) {
57195 // Skip recursive functions.
57196 const nameVar = context.getDeclaredVariables(node)[0];
57197
57198 if (isFunctionName(nameVar) && nameVar.references.length > 0) {
57199 return;
57200 }
57201
57202 const hasName = Boolean(node.id && node.id.name);
57203 const config = getConfigForNode(node);
57204
57205 if (config === "never") {
57206 if (hasName && node.type !== "FunctionDeclaration") {
57207 reportUnexpectedNamedFunction(node);
57208 }
57209 } else if (config === "as-needed") {
57210 if (!hasName && !hasInferredName(node)) {
57211 reportUnexpectedUnnamedFunction(node);
57212 }
57213 } else {
57214 if (!hasName && !isObjectOrClassMethod(node)) {
57215 reportUnexpectedUnnamedFunction(node);
57216 }
57217 }
57218 }
57219
57220 return {
57221 "FunctionExpression:exit": handleFunction,
57222 "ExportDefaultDeclaration > FunctionDeclaration": handleFunction
57223 };
57224 }
57225
57226};
57227
57228/***/ }),
57229/* 467 */
57230/***/ (function(module, exports, __webpack_require__) {
57231
57232"use strict";
57233/**
57234 * @fileoverview Rule to enforce a particular function style
57235 * @author Nicholas C. Zakas
57236 */
57237 //------------------------------------------------------------------------------
57238// Rule Definition
57239//------------------------------------------------------------------------------
57240
57241module.exports = {
57242 meta: {
57243 type: "suggestion",
57244 docs: {
57245 description: "enforce the consistent use of either `function` declarations or expressions",
57246 category: "Stylistic Issues",
57247 recommended: false,
57248 url: "https://eslint.org/docs/rules/func-style"
57249 },
57250 schema: [{
57251 enum: ["declaration", "expression"]
57252 }, {
57253 type: "object",
57254 properties: {
57255 allowArrowFunctions: {
57256 type: "boolean",
57257 default: false
57258 }
57259 },
57260 additionalProperties: false
57261 }],
57262 messages: {
57263 expression: "Expected a function expression.",
57264 declaration: "Expected a function declaration."
57265 }
57266 },
57267
57268 create(context) {
57269 const style = context.options[0],
57270 allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions,
57271 enforceDeclarations = style === "declaration",
57272 stack = [];
57273 const nodesToCheck = {
57274 FunctionDeclaration(node) {
57275 stack.push(false);
57276
57277 if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") {
57278 context.report({
57279 node,
57280 messageId: "expression"
57281 });
57282 }
57283 },
57284
57285 "FunctionDeclaration:exit"() {
57286 stack.pop();
57287 },
57288
57289 FunctionExpression(node) {
57290 stack.push(false);
57291
57292 if (enforceDeclarations && node.parent.type === "VariableDeclarator") {
57293 context.report({
57294 node: node.parent,
57295 messageId: "declaration"
57296 });
57297 }
57298 },
57299
57300 "FunctionExpression:exit"() {
57301 stack.pop();
57302 },
57303
57304 ThisExpression() {
57305 if (stack.length > 0) {
57306 stack[stack.length - 1] = true;
57307 }
57308 }
57309
57310 };
57311
57312 if (!allowArrowFunctions) {
57313 nodesToCheck.ArrowFunctionExpression = function () {
57314 stack.push(false);
57315 };
57316
57317 nodesToCheck["ArrowFunctionExpression:exit"] = function (node) {
57318 const hasThisExpr = stack.pop();
57319
57320 if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") {
57321 context.report({
57322 node: node.parent,
57323 messageId: "declaration"
57324 });
57325 }
57326 };
57327 }
57328
57329 return nodesToCheck;
57330 }
57331
57332};
57333
57334/***/ }),
57335/* 468 */
57336/***/ (function(module, exports, __webpack_require__) {
57337
57338"use strict";
57339/**
57340 * @fileoverview Rule to enforce line breaks between arguments of a function call
57341 * @author Alexey Gonchar <https://github.com/finico>
57342 */
57343 //------------------------------------------------------------------------------
57344// Rule Definition
57345//------------------------------------------------------------------------------
57346
57347module.exports = {
57348 meta: {
57349 type: "layout",
57350 docs: {
57351 description: "enforce line breaks between arguments of a function call",
57352 category: "Stylistic Issues",
57353 recommended: false,
57354 url: "https://eslint.org/docs/rules/function-call-argument-newline"
57355 },
57356 fixable: "whitespace",
57357 schema: [{
57358 enum: ["always", "never", "consistent"]
57359 }],
57360 messages: {
57361 unexpectedLineBreak: "There should be no line break here.",
57362 missingLineBreak: "There should be a line break after this argument."
57363 }
57364 },
57365
57366 create(context) {
57367 const sourceCode = context.getSourceCode();
57368 const checkers = {
57369 unexpected: {
57370 messageId: "unexpectedLineBreak",
57371 check: (prevToken, currentToken) => prevToken.loc.end.line !== currentToken.loc.start.line,
57372 createFix: (token, tokenBefore) => fixer => fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ")
57373 },
57374 missing: {
57375 messageId: "missingLineBreak",
57376 check: (prevToken, currentToken) => prevToken.loc.end.line === currentToken.loc.start.line,
57377 createFix: (token, tokenBefore) => fixer => fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n")
57378 }
57379 };
57380 /**
57381 * Check all arguments for line breaks in the CallExpression
57382 * @param {CallExpression} node node to evaluate
57383 * @param {{ messageId: string, check: Function }} checker selected checker
57384 * @returns {void}
57385 * @private
57386 */
57387
57388 function checkArguments(node, checker) {
57389 for (let i = 1; i < node.arguments.length; i++) {
57390 const prevArgToken = sourceCode.getLastToken(node.arguments[i - 1]);
57391 const currentArgToken = sourceCode.getFirstToken(node.arguments[i]);
57392
57393 if (checker.check(prevArgToken, currentArgToken)) {
57394 const tokenBefore = sourceCode.getTokenBefore(currentArgToken, {
57395 includeComments: true
57396 });
57397 const hasLineCommentBefore = tokenBefore.type === "Line";
57398 context.report({
57399 node,
57400 loc: {
57401 start: tokenBefore.loc.end,
57402 end: currentArgToken.loc.start
57403 },
57404 messageId: checker.messageId,
57405 fix: hasLineCommentBefore ? null : checker.createFix(currentArgToken, tokenBefore)
57406 });
57407 }
57408 }
57409 }
57410 /**
57411 * Check if open space is present in a function name
57412 * @param {CallExpression} node node to evaluate
57413 * @returns {void}
57414 * @private
57415 */
57416
57417
57418 function check(node) {
57419 if (node.arguments.length < 2) {
57420 return;
57421 }
57422
57423 const option = context.options[0] || "always";
57424
57425 if (option === "never") {
57426 checkArguments(node, checkers.unexpected);
57427 } else if (option === "always") {
57428 checkArguments(node, checkers.missing);
57429 } else if (option === "consistent") {
57430 const firstArgToken = sourceCode.getLastToken(node.arguments[0]);
57431 const secondArgToken = sourceCode.getFirstToken(node.arguments[1]);
57432
57433 if (firstArgToken.loc.end.line === secondArgToken.loc.start.line) {
57434 checkArguments(node, checkers.unexpected);
57435 } else {
57436 checkArguments(node, checkers.missing);
57437 }
57438 }
57439 }
57440
57441 return {
57442 CallExpression: check,
57443 NewExpression: check
57444 };
57445 }
57446
57447};
57448
57449/***/ }),
57450/* 469 */
57451/***/ (function(module, exports, __webpack_require__) {
57452
57453"use strict";
57454/**
57455 * @fileoverview enforce consistent line breaks inside function parentheses
57456 * @author Teddy Katz
57457 */
57458 //------------------------------------------------------------------------------
57459// Requirements
57460//------------------------------------------------------------------------------
57461
57462const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
57463// Rule Definition
57464//------------------------------------------------------------------------------
57465
57466
57467module.exports = {
57468 meta: {
57469 type: "layout",
57470 docs: {
57471 description: "enforce consistent line breaks inside function parentheses",
57472 category: "Stylistic Issues",
57473 recommended: false,
57474 url: "https://eslint.org/docs/rules/function-paren-newline"
57475 },
57476 fixable: "whitespace",
57477 schema: [{
57478 oneOf: [{
57479 enum: ["always", "never", "consistent", "multiline", "multiline-arguments"]
57480 }, {
57481 type: "object",
57482 properties: {
57483 minItems: {
57484 type: "integer",
57485 minimum: 0
57486 }
57487 },
57488 additionalProperties: false
57489 }]
57490 }],
57491 messages: {
57492 expectedBefore: "Expected newline before ')'.",
57493 expectedAfter: "Expected newline after '('.",
57494 expectedBetween: "Expected newline between arguments/params.",
57495 unexpectedBefore: "Unexpected newline before ')'.",
57496 unexpectedAfter: "Unexpected newline after '('."
57497 }
57498 },
57499
57500 create(context) {
57501 const sourceCode = context.getSourceCode();
57502 const rawOption = context.options[0] || "multiline";
57503 const multilineOption = rawOption === "multiline";
57504 const multilineArgumentsOption = rawOption === "multiline-arguments";
57505 const consistentOption = rawOption === "consistent";
57506 let minItems;
57507
57508 if (typeof rawOption === "object") {
57509 minItems = rawOption.minItems;
57510 } else if (rawOption === "always") {
57511 minItems = 0;
57512 } else if (rawOption === "never") {
57513 minItems = Infinity;
57514 } else {
57515 minItems = null;
57516 } //----------------------------------------------------------------------
57517 // Helpers
57518 //----------------------------------------------------------------------
57519
57520 /**
57521 * Determines whether there should be newlines inside function parens
57522 * @param {ASTNode[]} elements The arguments or parameters in the list
57523 * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code.
57524 * @returns {boolean} `true` if there should be newlines inside the function parens
57525 */
57526
57527
57528 function shouldHaveNewlines(elements, hasLeftNewline) {
57529 if (multilineArgumentsOption && elements.length === 1) {
57530 return hasLeftNewline;
57531 }
57532
57533 if (multilineOption || multilineArgumentsOption) {
57534 return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line);
57535 }
57536
57537 if (consistentOption) {
57538 return hasLeftNewline;
57539 }
57540
57541 return elements.length >= minItems;
57542 }
57543 /**
57544 * Validates parens
57545 * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
57546 * @param {ASTNode[]} elements The arguments or parameters in the list
57547 * @returns {void}
57548 */
57549
57550
57551 function validateParens(parens, elements) {
57552 const leftParen = parens.leftParen;
57553 const rightParen = parens.rightParen;
57554 const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
57555 const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen);
57556 const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
57557 const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen);
57558 const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
57559
57560 if (hasLeftNewline && !needsNewlines) {
57561 context.report({
57562 node: leftParen,
57563 messageId: "unexpectedAfter",
57564
57565 fix(fixer) {
57566 return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim() // If there is a comment between the ( and the first element, don't do a fix.
57567 ? null : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]);
57568 }
57569
57570 });
57571 } else if (!hasLeftNewline && needsNewlines) {
57572 context.report({
57573 node: leftParen,
57574 messageId: "expectedAfter",
57575 fix: fixer => fixer.insertTextAfter(leftParen, "\n")
57576 });
57577 }
57578
57579 if (hasRightNewline && !needsNewlines) {
57580 context.report({
57581 node: rightParen,
57582 messageId: "unexpectedBefore",
57583
57584 fix(fixer) {
57585 return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim() // If there is a comment between the last element and the ), don't do a fix.
57586 ? null : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]);
57587 }
57588
57589 });
57590 } else if (!hasRightNewline && needsNewlines) {
57591 context.report({
57592 node: rightParen,
57593 messageId: "expectedBefore",
57594 fix: fixer => fixer.insertTextBefore(rightParen, "\n")
57595 });
57596 }
57597 }
57598 /**
57599 * Validates a list of arguments or parameters
57600 * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
57601 * @param {ASTNode[]} elements The arguments or parameters in the list
57602 * @returns {void}
57603 */
57604
57605
57606 function validateArguments(parens, elements) {
57607 const leftParen = parens.leftParen;
57608 const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
57609 const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
57610 const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
57611
57612 for (let i = 0; i <= elements.length - 2; i++) {
57613 const currentElement = elements[i];
57614 const nextElement = elements[i + 1];
57615 const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line;
57616
57617 if (!hasNewLine && needsNewlines) {
57618 context.report({
57619 node: currentElement,
57620 messageId: "expectedBetween",
57621 fix: fixer => fixer.insertTextBefore(nextElement, "\n")
57622 });
57623 }
57624 }
57625 }
57626 /**
57627 * Gets the left paren and right paren tokens of a node.
57628 * @param {ASTNode} node The node with parens
57629 * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
57630 * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
57631 * with a single parameter)
57632 */
57633
57634
57635 function getParenTokens(node) {
57636 switch (node.type) {
57637 case "NewExpression":
57638 if (!node.arguments.length && !(astUtils.isOpeningParenToken(sourceCode.getLastToken(node, {
57639 skip: 1
57640 })) && astUtils.isClosingParenToken(sourceCode.getLastToken(node)))) {
57641 // If the NewExpression does not have parens (e.g. `new Foo`), return null.
57642 return null;
57643 }
57644
57645 // falls through
57646
57647 case "CallExpression":
57648 return {
57649 leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
57650 rightParen: sourceCode.getLastToken(node)
57651 };
57652
57653 case "FunctionDeclaration":
57654 case "FunctionExpression":
57655 {
57656 const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
57657 const rightParen = node.params.length ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) : sourceCode.getTokenAfter(leftParen);
57658 return {
57659 leftParen,
57660 rightParen
57661 };
57662 }
57663
57664 case "ArrowFunctionExpression":
57665 {
57666 const firstToken = sourceCode.getFirstToken(node);
57667
57668 if (!astUtils.isOpeningParenToken(firstToken)) {
57669 // If the ArrowFunctionExpression has a single param without parens, return null.
57670 return null;
57671 }
57672
57673 return {
57674 leftParen: firstToken,
57675 rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken)
57676 };
57677 }
57678
57679 case "ImportExpression":
57680 {
57681 const leftParen = sourceCode.getFirstToken(node, 1);
57682 const rightParen = sourceCode.getLastToken(node);
57683 return {
57684 leftParen,
57685 rightParen
57686 };
57687 }
57688
57689 default:
57690 throw new TypeError("unexpected node with type ".concat(node.type));
57691 }
57692 } //----------------------------------------------------------------------
57693 // Public
57694 //----------------------------------------------------------------------
57695
57696
57697 return {
57698 [["ArrowFunctionExpression", "CallExpression", "FunctionDeclaration", "FunctionExpression", "ImportExpression", "NewExpression"]](node) {
57699 const parens = getParenTokens(node);
57700 let params;
57701
57702 if (node.type === "ImportExpression") {
57703 params = [node.source];
57704 } else if (astUtils.isFunction(node)) {
57705 params = node.params;
57706 } else {
57707 params = node.arguments;
57708 }
57709
57710 if (parens) {
57711 validateParens(parens, params);
57712
57713 if (multilineArgumentsOption) {
57714 validateArguments(parens, params);
57715 }
57716 }
57717 }
57718
57719 };
57720 }
57721
57722};
57723
57724/***/ }),
57725/* 470 */
57726/***/ (function(module, exports, __webpack_require__) {
57727
57728"use strict";
57729/**
57730 * @fileoverview Rule to check the spacing around the * in generator functions.
57731 * @author Jamund Ferguson
57732 */
57733 //------------------------------------------------------------------------------
57734// Rule Definition
57735//------------------------------------------------------------------------------
57736
57737const OVERRIDE_SCHEMA = {
57738 oneOf: [{
57739 enum: ["before", "after", "both", "neither"]
57740 }, {
57741 type: "object",
57742 properties: {
57743 before: {
57744 type: "boolean"
57745 },
57746 after: {
57747 type: "boolean"
57748 }
57749 },
57750 additionalProperties: false
57751 }]
57752};
57753module.exports = {
57754 meta: {
57755 type: "layout",
57756 docs: {
57757 description: "enforce consistent spacing around `*` operators in generator functions",
57758 category: "ECMAScript 6",
57759 recommended: false,
57760 url: "https://eslint.org/docs/rules/generator-star-spacing"
57761 },
57762 fixable: "whitespace",
57763 schema: [{
57764 oneOf: [{
57765 enum: ["before", "after", "both", "neither"]
57766 }, {
57767 type: "object",
57768 properties: {
57769 before: {
57770 type: "boolean"
57771 },
57772 after: {
57773 type: "boolean"
57774 },
57775 named: OVERRIDE_SCHEMA,
57776 anonymous: OVERRIDE_SCHEMA,
57777 method: OVERRIDE_SCHEMA
57778 },
57779 additionalProperties: false
57780 }]
57781 }],
57782 messages: {
57783 missingBefore: "Missing space before *.",
57784 missingAfter: "Missing space after *.",
57785 unexpectedBefore: "Unexpected space before *.",
57786 unexpectedAfter: "Unexpected space after *."
57787 }
57788 },
57789
57790 create(context) {
57791 const optionDefinitions = {
57792 before: {
57793 before: true,
57794 after: false
57795 },
57796 after: {
57797 before: false,
57798 after: true
57799 },
57800 both: {
57801 before: true,
57802 after: true
57803 },
57804 neither: {
57805 before: false,
57806 after: false
57807 }
57808 };
57809 /**
57810 * Returns resolved option definitions based on an option and defaults
57811 * @param {any} option The option object or string value
57812 * @param {Object} defaults The defaults to use if options are not present
57813 * @returns {Object} the resolved object definition
57814 */
57815
57816 function optionToDefinition(option, defaults) {
57817 if (!option) {
57818 return defaults;
57819 }
57820
57821 return typeof option === "string" ? optionDefinitions[option] : Object.assign({}, defaults, option);
57822 }
57823
57824 const modes = function (option) {
57825 const defaults = optionToDefinition(option, optionDefinitions.before);
57826 return {
57827 named: optionToDefinition(option.named, defaults),
57828 anonymous: optionToDefinition(option.anonymous, defaults),
57829 method: optionToDefinition(option.method, defaults)
57830 };
57831 }(context.options[0] || {});
57832
57833 const sourceCode = context.getSourceCode();
57834 /**
57835 * Checks if the given token is a star token or not.
57836 * @param {Token} token The token to check.
57837 * @returns {boolean} `true` if the token is a star token.
57838 */
57839
57840 function isStarToken(token) {
57841 return token.value === "*" && token.type === "Punctuator";
57842 }
57843 /**
57844 * Gets the generator star token of the given function node.
57845 * @param {ASTNode} node The function node to get.
57846 * @returns {Token} Found star token.
57847 */
57848
57849
57850 function getStarToken(node) {
57851 return sourceCode.getFirstToken(node.parent.method || node.parent.type === "MethodDefinition" ? node.parent : node, isStarToken);
57852 }
57853 /**
57854 * capitalize a given string.
57855 * @param {string} str the given string.
57856 * @returns {string} the capitalized string.
57857 */
57858
57859
57860 function capitalize(str) {
57861 return str[0].toUpperCase() + str.slice(1);
57862 }
57863 /**
57864 * Checks the spacing between two tokens before or after the star token.
57865 * @param {string} kind Either "named", "anonymous", or "method"
57866 * @param {string} side Either "before" or "after".
57867 * @param {Token} leftToken `function` keyword token if side is "before", or
57868 * star token if side is "after".
57869 * @param {Token} rightToken Star token if side is "before", or identifier
57870 * token if side is "after".
57871 * @returns {void}
57872 */
57873
57874
57875 function checkSpacing(kind, side, leftToken, rightToken) {
57876 if (!!(rightToken.range[0] - leftToken.range[1]) !== modes[kind][side]) {
57877 const after = leftToken.value === "*";
57878 const spaceRequired = modes[kind][side];
57879 const node = after ? leftToken : rightToken;
57880 const messageId = "".concat(spaceRequired ? "missing" : "unexpected").concat(capitalize(side));
57881 context.report({
57882 node,
57883 messageId,
57884
57885 fix(fixer) {
57886 if (spaceRequired) {
57887 if (after) {
57888 return fixer.insertTextAfter(node, " ");
57889 }
57890
57891 return fixer.insertTextBefore(node, " ");
57892 }
57893
57894 return fixer.removeRange([leftToken.range[1], rightToken.range[0]]);
57895 }
57896
57897 });
57898 }
57899 }
57900 /**
57901 * Enforces the spacing around the star if node is a generator function.
57902 * @param {ASTNode} node A function expression or declaration node.
57903 * @returns {void}
57904 */
57905
57906
57907 function checkFunction(node) {
57908 if (!node.generator) {
57909 return;
57910 }
57911
57912 const starToken = getStarToken(node);
57913 const prevToken = sourceCode.getTokenBefore(starToken);
57914 const nextToken = sourceCode.getTokenAfter(starToken);
57915 let kind = "named";
57916
57917 if (node.parent.type === "MethodDefinition" || node.parent.type === "Property" && node.parent.method) {
57918 kind = "method";
57919 } else if (!node.id) {
57920 kind = "anonymous";
57921 } // Only check before when preceded by `function`|`static` keyword
57922
57923
57924 if (!(kind === "method" && starToken === sourceCode.getFirstToken(node.parent))) {
57925 checkSpacing(kind, "before", prevToken, starToken);
57926 }
57927
57928 checkSpacing(kind, "after", starToken, nextToken);
57929 }
57930
57931 return {
57932 FunctionDeclaration: checkFunction,
57933 FunctionExpression: checkFunction
57934 };
57935 }
57936
57937};
57938
57939/***/ }),
57940/* 471 */
57941/***/ (function(module, exports, __webpack_require__) {
57942
57943"use strict";
57944/**
57945 * @fileoverview Enforces that a return statement is present in property getters.
57946 * @author Aladdin-ADD(hh_2013@foxmail.com)
57947 */
57948 //------------------------------------------------------------------------------
57949// Requirements
57950//------------------------------------------------------------------------------
57951
57952const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
57953// Helpers
57954//------------------------------------------------------------------------------
57955
57956
57957const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
57958/**
57959 * Checks a given code path segment is reachable.
57960 * @param {CodePathSegment} segment A segment to check.
57961 * @returns {boolean} `true` if the segment is reachable.
57962 */
57963
57964function isReachable(segment) {
57965 return segment.reachable;
eb39fafa
DC
57966} //------------------------------------------------------------------------------
57967// Rule Definition
57968//------------------------------------------------------------------------------
57969
57970
57971module.exports = {
57972 meta: {
57973 type: "problem",
57974 docs: {
57975 description: "enforce `return` statements in getters",
57976 category: "Possible Errors",
57977 recommended: true,
57978 url: "https://eslint.org/docs/rules/getter-return"
57979 },
57980 fixable: null,
57981 schema: [{
57982 type: "object",
57983 properties: {
57984 allowImplicit: {
57985 type: "boolean",
57986 default: false
57987 }
57988 },
57989 additionalProperties: false
57990 }],
57991 messages: {
57992 expected: "Expected to return a value in {{name}}.",
57993 expectedAlways: "Expected {{name}} to always return a value."
57994 }
57995 },
57996
57997 create(context) {
57998 const options = context.options[0] || {
57999 allowImplicit: false
58000 };
56c4a2cb 58001 const sourceCode = context.getSourceCode();
eb39fafa
DC
58002 let funcInfo = {
58003 upper: null,
58004 codePath: null,
58005 hasReturn: false,
58006 shouldCheck: false,
58007 node: null
58008 };
58009 /**
58010 * Checks whether or not the last code path segment is reachable.
58011 * Then reports this function if the segment is reachable.
58012 *
58013 * If the last code path segment is reachable, there are paths which are not
58014 * returned or thrown.
58015 * @param {ASTNode} node A node to check.
58016 * @returns {void}
58017 */
58018
58019 function checkLastSegment(node) {
58020 if (funcInfo.shouldCheck && funcInfo.codePath.currentSegments.some(isReachable)) {
58021 context.report({
58022 node,
56c4a2cb 58023 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
eb39fafa
DC
58024 messageId: funcInfo.hasReturn ? "expectedAlways" : "expected",
58025 data: {
58026 name: astUtils.getFunctionNameWithKind(funcInfo.node)
58027 }
58028 });
58029 }
58030 }
58031 /**
58032 * Checks whether a node means a getter function.
58033 * @param {ASTNode} node a node to check.
58034 * @returns {boolean} if node means a getter, return true; else return false.
58035 */
58036
58037
58038 function isGetter(node) {
58039 const parent = node.parent;
58040
58041 if (TARGET_NODE_TYPE.test(node.type) && node.body.type === "BlockStatement") {
58042 if (parent.kind === "get") {
58043 return true;
58044 }
58045
58046 if (parent.type === "Property" && astUtils.getStaticPropertyName(parent) === "get" && parent.parent.type === "ObjectExpression") {
58047 // Object.defineProperty()
58048 if (parent.parent.parent.type === "CallExpression" && astUtils.getStaticPropertyName(parent.parent.parent.callee) === "defineProperty") {
58049 return true;
58050 } // Object.defineProperties()
58051
58052
58053 if (parent.parent.parent.type === "Property" && parent.parent.parent.parent.type === "ObjectExpression" && parent.parent.parent.parent.parent.type === "CallExpression" && astUtils.getStaticPropertyName(parent.parent.parent.parent.parent.callee) === "defineProperties") {
58054 return true;
58055 }
58056 }
58057 }
58058
58059 return false;
58060 }
58061
58062 return {
58063 // Stacks this function's information.
58064 onCodePathStart(codePath, node) {
58065 funcInfo = {
58066 upper: funcInfo,
58067 codePath,
58068 hasReturn: false,
58069 shouldCheck: isGetter(node),
58070 node
58071 };
58072 },
58073
58074 // Pops this function's information.
58075 onCodePathEnd() {
58076 funcInfo = funcInfo.upper;
58077 },
58078
58079 // Checks the return statement is valid.
58080 ReturnStatement(node) {
58081 if (funcInfo.shouldCheck) {
58082 funcInfo.hasReturn = true; // if allowImplicit: false, should also check node.argument
58083
58084 if (!options.allowImplicit && !node.argument) {
58085 context.report({
58086 node,
58087 messageId: "expected",
58088 data: {
58089 name: astUtils.getFunctionNameWithKind(funcInfo.node)
58090 }
58091 });
58092 }
58093 }
58094 },
58095
58096 // Reports a given function if the last path is reachable.
58097 "FunctionExpression:exit": checkLastSegment,
58098 "ArrowFunctionExpression:exit": checkLastSegment
58099 };
58100 }
58101
58102};
58103
58104/***/ }),
58105/* 472 */
58106/***/ (function(module, exports, __webpack_require__) {
58107
58108"use strict";
58109/**
58110 * @fileoverview Rule for disallowing require() outside of the top-level module context
58111 * @author Jamund Ferguson
58112 */
58113
58114
58115const ACCEPTABLE_PARENTS = ["AssignmentExpression", "VariableDeclarator", "MemberExpression", "ExpressionStatement", "CallExpression", "ConditionalExpression", "Program", "VariableDeclaration"];
58116/**
58117 * Finds the eslint-scope reference in the given scope.
58118 * @param {Object} scope The scope to search.
58119 * @param {ASTNode} node The identifier node.
58120 * @returns {Reference|null} Returns the found reference or null if none were found.
58121 */
58122
58123function findReference(scope, node) {
58124 const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && reference.identifier.range[1] === node.range[1]);
58125 /* istanbul ignore else: correctly returns null */
58126
58127 if (references.length === 1) {
58128 return references[0];
58129 }
58130
58131 return null;
58132}
58133/**
58134 * Checks if the given identifier node is shadowed in the given scope.
58135 * @param {Object} scope The current scope.
58136 * @param {ASTNode} node The identifier node to check.
58137 * @returns {boolean} Whether or not the name is shadowed.
58138 */
58139
58140
58141function isShadowed(scope, node) {
58142 const reference = findReference(scope, node);
58143 return reference && reference.resolved && reference.resolved.defs.length > 0;
58144}
58145
58146module.exports = {
58147 meta: {
56c4a2cb 58148 deprecated: true,
6a5a0f88 58149 replacedBy: [],
eb39fafa
DC
58150 type: "suggestion",
58151 docs: {
58152 description: "require `require()` calls to be placed at top-level module scope",
58153 category: "Node.js and CommonJS",
58154 recommended: false,
58155 url: "https://eslint.org/docs/rules/global-require"
58156 },
58157 schema: [],
58158 messages: {
58159 unexpected: "Unexpected require()."
58160 }
58161 },
58162
58163 create(context) {
58164 return {
58165 CallExpression(node) {
58166 const currentScope = context.getScope();
58167
58168 if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
58169 const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
58170
58171 if (!isGoodRequire) {
58172 context.report({
58173 node,
58174 messageId: "unexpected"
58175 });
58176 }
58177 }
58178 }
58179
58180 };
58181 }
58182
58183};
58184
58185/***/ }),
58186/* 473 */
58187/***/ (function(module, exports, __webpack_require__) {
58188
58189"use strict";
58190/**
58191 * @fileoverview Rule to require grouped accessor pairs in object literals and classes
58192 * @author Milos Djermanovic
58193 */
58194 //------------------------------------------------------------------------------
58195// Requirements
58196//------------------------------------------------------------------------------
58197
58198const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
58199// Typedefs
58200//------------------------------------------------------------------------------
58201
58202/**
58203 * Property name if it can be computed statically, otherwise the list of the tokens of the key node.
58204 * @typedef {string|Token[]} Key
58205 */
58206
58207/**
58208 * Accessor nodes with the same key.
58209 * @typedef {Object} AccessorData
58210 * @property {Key} key Accessor's key
58211 * @property {ASTNode[]} getters List of getter nodes.
58212 * @property {ASTNode[]} setters List of setter nodes.
58213 */
58214//------------------------------------------------------------------------------
58215// Helpers
58216//------------------------------------------------------------------------------
58217
58218/**
58219 * Checks whether or not the given lists represent the equal tokens in the same order.
58220 * Tokens are compared by their properties, not by instance.
58221 * @param {Token[]} left First list of tokens.
58222 * @param {Token[]} right Second list of tokens.
58223 * @returns {boolean} `true` if the lists have same tokens.
58224 */
58225
58226
58227function areEqualTokenLists(left, right) {
58228 if (left.length !== right.length) {
58229 return false;
58230 }
58231
58232 for (let i = 0; i < left.length; i++) {
58233 const leftToken = left[i],
58234 rightToken = right[i];
58235
58236 if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) {
58237 return false;
58238 }
58239 }
58240
58241 return true;
58242}
58243/**
58244 * Checks whether or not the given keys are equal.
58245 * @param {Key} left First key.
58246 * @param {Key} right Second key.
58247 * @returns {boolean} `true` if the keys are equal.
58248 */
58249
58250
58251function areEqualKeys(left, right) {
58252 if (typeof left === "string" && typeof right === "string") {
58253 // Statically computed names.
58254 return left === right;
58255 }
58256
58257 if (Array.isArray(left) && Array.isArray(right)) {
58258 // Token lists.
58259 return areEqualTokenLists(left, right);
58260 }
58261
58262 return false;
58263}
58264/**
58265 * Checks whether or not a given node is of an accessor kind ('get' or 'set').
58266 * @param {ASTNode} node A node to check.
58267 * @returns {boolean} `true` if the node is of an accessor kind.
58268 */
58269
58270
58271function isAccessorKind(node) {
58272 return node.kind === "get" || node.kind === "set";
58273} //------------------------------------------------------------------------------
58274// Rule Definition
58275//------------------------------------------------------------------------------
58276
58277
58278module.exports = {
58279 meta: {
58280 type: "suggestion",
58281 docs: {
58282 description: "require grouped accessor pairs in object literals and classes",
58283 category: "Best Practices",
58284 recommended: false,
58285 url: "https://eslint.org/docs/rules/grouped-accessor-pairs"
58286 },
58287 schema: [{
58288 enum: ["anyOrder", "getBeforeSet", "setBeforeGet"]
58289 }],
58290 messages: {
58291 notGrouped: "Accessor pair {{ formerName }} and {{ latterName }} should be grouped.",
58292 invalidOrder: "Expected {{ latterName }} to be before {{ formerName }}."
58293 }
58294 },
58295
58296 create(context) {
58297 const order = context.options[0] || "anyOrder";
58298 const sourceCode = context.getSourceCode();
58299 /**
58300 * Reports the given accessor pair.
58301 * @param {string} messageId messageId to report.
58302 * @param {ASTNode} formerNode getter/setter node that is defined before `latterNode`.
58303 * @param {ASTNode} latterNode getter/setter node that is defined after `formerNode`.
58304 * @returns {void}
58305 * @private
58306 */
58307
58308 function report(messageId, formerNode, latterNode) {
58309 context.report({
58310 node: latterNode,
58311 messageId,
58312 loc: astUtils.getFunctionHeadLoc(latterNode.value, sourceCode),
58313 data: {
58314 formerName: astUtils.getFunctionNameWithKind(formerNode.value),
58315 latterName: astUtils.getFunctionNameWithKind(latterNode.value)
58316 }
58317 });
58318 }
58319 /**
58320 * Creates a new `AccessorData` object for the given getter or setter node.
58321 * @param {ASTNode} node A getter or setter node.
58322 * @returns {AccessorData} New `AccessorData` object that contains the given node.
58323 * @private
58324 */
58325
58326
58327 function createAccessorData(node) {
58328 const name = astUtils.getStaticPropertyName(node);
58329 const key = name !== null ? name : sourceCode.getTokens(node.key);
58330 return {
58331 key,
58332 getters: node.kind === "get" ? [node] : [],
58333 setters: node.kind === "set" ? [node] : []
58334 };
58335 }
58336 /**
58337 * Merges the given `AccessorData` object into the given accessors list.
58338 * @param {AccessorData[]} accessors The list to merge into.
58339 * @param {AccessorData} accessorData The object to merge.
58340 * @returns {AccessorData[]} The same instance with the merged object.
58341 * @private
58342 */
58343
58344
58345 function mergeAccessorData(accessors, accessorData) {
58346 const equalKeyElement = accessors.find(a => areEqualKeys(a.key, accessorData.key));
58347
58348 if (equalKeyElement) {
58349 equalKeyElement.getters.push(...accessorData.getters);
58350 equalKeyElement.setters.push(...accessorData.setters);
58351 } else {
58352 accessors.push(accessorData);
58353 }
58354
58355 return accessors;
58356 }
58357 /**
58358 * Checks accessor pairs in the given list of nodes.
58359 * @param {ASTNode[]} nodes The list to check.
58360 * @param {Function} shouldCheck – Predicate that returns `true` if the node should be checked.
58361 * @returns {void}
58362 * @private
58363 */
58364
58365
58366 function checkList(nodes, shouldCheck) {
58367 const accessors = nodes.filter(shouldCheck).filter(isAccessorKind).map(createAccessorData).reduce(mergeAccessorData, []);
58368
58369 for (const {
58370 getters,
58371 setters
58372 } of accessors) {
58373 // Don't report accessor properties that have duplicate getters or setters.
58374 if (getters.length === 1 && setters.length === 1) {
58375 const [getter] = getters,
58376 [setter] = setters,
58377 getterIndex = nodes.indexOf(getter),
58378 setterIndex = nodes.indexOf(setter),
58379 formerNode = getterIndex < setterIndex ? getter : setter,
58380 latterNode = getterIndex < setterIndex ? setter : getter;
58381
58382 if (Math.abs(getterIndex - setterIndex) > 1) {
58383 report("notGrouped", formerNode, latterNode);
58384 } else if (order === "getBeforeSet" && getterIndex > setterIndex || order === "setBeforeGet" && getterIndex < setterIndex) {
58385 report("invalidOrder", formerNode, latterNode);
58386 }
58387 }
58388 }
58389 }
58390
58391 return {
58392 ObjectExpression(node) {
58393 checkList(node.properties, n => n.type === "Property");
58394 },
58395
58396 ClassBody(node) {
58397 checkList(node.body, n => n.type === "MethodDefinition" && !n.static);
58398 checkList(node.body, n => n.type === "MethodDefinition" && n.static);
58399 }
58400
58401 };
58402 }
58403
58404};
58405
58406/***/ }),
58407/* 474 */
58408/***/ (function(module, exports, __webpack_require__) {
58409
58410"use strict";
58411/**
58412 * @fileoverview Rule to flag for-in loops without if statements inside
58413 * @author Nicholas C. Zakas
58414 */
58415 //------------------------------------------------------------------------------
58416// Rule Definition
58417//------------------------------------------------------------------------------
58418
58419module.exports = {
58420 meta: {
58421 type: "suggestion",
58422 docs: {
58423 description: "require `for-in` loops to include an `if` statement",
58424 category: "Best Practices",
58425 recommended: false,
58426 url: "https://eslint.org/docs/rules/guard-for-in"
58427 },
58428 schema: [],
58429 messages: {
58430 wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."
58431 }
58432 },
58433
58434 create(context) {
58435 return {
58436 ForInStatement(node) {
58437 const body = node.body; // empty statement
58438
58439 if (body.type === "EmptyStatement") {
58440 return;
58441 } // if statement
58442
58443
58444 if (body.type === "IfStatement") {
58445 return;
58446 } // empty block
58447
58448
58449 if (body.type === "BlockStatement" && body.body.length === 0) {
58450 return;
58451 } // block with just if statement
58452
58453
58454 if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
58455 return;
58456 } // block that starts with if statement
58457
58458
58459 if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
58460 const i = body.body[0]; // ... whose consequent is a continue
58461
58462 if (i.consequent.type === "ContinueStatement") {
58463 return;
58464 } // ... whose consequent is a block that contains only a continue
58465
58466
58467 if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
58468 return;
58469 }
58470 }
58471
58472 context.report({
58473 node,
58474 messageId: "wrap"
58475 });
58476 }
58477
58478 };
58479 }
58480
58481};
58482
58483/***/ }),
58484/* 475 */
58485/***/ (function(module, exports, __webpack_require__) {
58486
58487"use strict";
58488/**
58489 * @fileoverview Ensure handling of errors when we know they exist.
58490 * @author Jamund Ferguson
58491 */
58492 //------------------------------------------------------------------------------
58493// Rule Definition
58494//------------------------------------------------------------------------------
58495
58496module.exports = {
58497 meta: {
56c4a2cb 58498 deprecated: true,
6a5a0f88 58499 replacedBy: [],
eb39fafa
DC
58500 type: "suggestion",
58501 docs: {
58502 description: "require error handling in callbacks",
58503 category: "Node.js and CommonJS",
58504 recommended: false,
58505 url: "https://eslint.org/docs/rules/handle-callback-err"
58506 },
58507 schema: [{
58508 type: "string"
58509 }],
58510 messages: {
58511 expected: "Expected error to be handled."
58512 }
58513 },
58514
58515 create(context) {
58516 const errorArgument = context.options[0] || "err";
58517 /**
58518 * Checks if the given argument should be interpreted as a regexp pattern.
58519 * @param {string} stringToCheck The string which should be checked.
58520 * @returns {boolean} Whether or not the string should be interpreted as a pattern.
58521 */
58522
58523 function isPattern(stringToCheck) {
58524 const firstChar = stringToCheck[0];
58525 return firstChar === "^";
58526 }
58527 /**
58528 * Checks if the given name matches the configured error argument.
58529 * @param {string} name The name which should be compared.
58530 * @returns {boolean} Whether or not the given name matches the configured error variable name.
58531 */
58532
58533
58534 function matchesConfiguredErrorName(name) {
58535 if (isPattern(errorArgument)) {
58536 const regexp = new RegExp(errorArgument, "u");
58537 return regexp.test(name);
58538 }
58539
58540 return name === errorArgument;
58541 }
58542 /**
58543 * Get the parameters of a given function scope.
58544 * @param {Object} scope The function scope.
58545 * @returns {Array} All parameters of the given scope.
58546 */
58547
58548
58549 function getParameters(scope) {
58550 return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter");
58551 }
58552 /**
58553 * Check to see if we're handling the error object properly.
58554 * @param {ASTNode} node The AST node to check.
58555 * @returns {void}
58556 */
58557
58558
58559 function checkForError(node) {
58560 const scope = context.getScope(),
58561 parameters = getParameters(scope),
58562 firstParameter = parameters[0];
58563
58564 if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
58565 if (firstParameter.references.length === 0) {
58566 context.report({
58567 node,
58568 messageId: "expected"
58569 });
58570 }
58571 }
58572 }
58573
58574 return {
58575 FunctionDeclaration: checkForError,
58576 FunctionExpression: checkForError,
58577 ArrowFunctionExpression: checkForError
58578 };
58579 }
58580
58581};
58582
58583/***/ }),
58584/* 476 */
58585/***/ (function(module, exports, __webpack_require__) {
58586
58587"use strict";
58588/**
58589 * @fileoverview Rule that warns when identifier names that are
58590 * blacklisted in the configuration are used.
58591 * @author Keith Cirkel (http://keithcirkel.co.uk)
58592 */
58593 //------------------------------------------------------------------------------
58594// Helpers
58595//------------------------------------------------------------------------------
58596
58597/**
58598 * Checks whether the given node represents assignment target in a normal assignment or destructuring.
58599 * @param {ASTNode} node The node to check.
58600 * @returns {boolean} `true` if the node is assignment target.
58601 */
58602
58603function isAssignmentTarget(node) {
58604 const parent = node.parent;
58605 return (// normal assignment
58606 parent.type === "AssignmentExpression" && parent.left === node || // destructuring
58607 parent.type === "ArrayPattern" || parent.type === "RestElement" || parent.type === "Property" && parent.value === node && parent.parent.type === "ObjectPattern" || parent.type === "AssignmentPattern" && parent.left === node
58608 );
58609}
58610/**
58611 * Checks whether the given node represents an imported name that is renamed in the same import/export specifier.
58612 *
58613 * Examples:
58614 * import { a as b } from 'mod'; // node `a` is renamed import
58615 * export { a as b } from 'mod'; // node `a` is renamed import
58616 * @param {ASTNode} node `Identifier` node to check.
58617 * @returns {boolean} `true` if the node is a renamed import.
58618 */
58619
58620
58621function isRenamedImport(node) {
58622 const parent = node.parent;
58623 return parent.type === "ImportSpecifier" && parent.imported !== parent.local && parent.imported === node || parent.type === "ExportSpecifier" && parent.parent.source && // re-export
58624 parent.local !== parent.exported && parent.local === node;
58625}
58626/**
58627 * Checks whether the given node is a renamed identifier node in an ObjectPattern destructuring.
58628 *
58629 * Examples:
58630 * const { a : b } = foo; // node `a` is renamed node.
58631 * @param {ASTNode} node `Identifier` node to check.
58632 * @returns {boolean} `true` if the node is a renamed node in an ObjectPattern destructuring.
58633 */
58634
58635
58636function isRenamedInDestructuring(node) {
58637 const parent = node.parent;
58638 return !parent.computed && parent.type === "Property" && parent.parent.type === "ObjectPattern" && parent.value !== node && parent.key === node;
58639}
58640/**
58641 * Checks whether the given node represents shorthand definition of a property in an object literal.
58642 * @param {ASTNode} node `Identifier` node to check.
58643 * @returns {boolean} `true` if the node is a shorthand property definition.
58644 */
58645
58646
58647function isShorthandPropertyDefinition(node) {
58648 const parent = node.parent;
58649 return parent.type === "Property" && parent.parent.type === "ObjectExpression" && parent.shorthand;
58650} //------------------------------------------------------------------------------
58651// Rule Definition
58652//------------------------------------------------------------------------------
58653
58654
58655module.exports = {
58656 meta: {
58657 type: "suggestion",
58658 docs: {
58659 description: "disallow specified identifiers",
58660 category: "Stylistic Issues",
58661 recommended: false,
58662 url: "https://eslint.org/docs/rules/id-blacklist"
58663 },
58664 schema: {
58665 type: "array",
58666 items: {
58667 type: "string"
58668 },
58669 uniqueItems: true
58670 },
58671 messages: {
58672 blacklisted: "Identifier '{{name}}' is blacklisted."
58673 }
58674 },
58675
58676 create(context) {
58677 const blacklist = new Set(context.options);
58678 const reportedNodes = new Set();
58679 let globalScope;
58680 /**
58681 * Checks whether the given name is blacklisted.
58682 * @param {string} name The name to check.
58683 * @returns {boolean} `true` if the name is blacklisted.
58684 * @private
58685 */
58686
58687 function isBlacklisted(name) {
58688 return blacklist.has(name);
58689 }
58690 /**
58691 * Checks whether the given node represents a reference to a global variable that is not declared in the source code.
58692 * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
58693 * @param {ASTNode} node `Identifier` node to check.
58694 * @returns {boolean} `true` if the node is a reference to a global variable.
58695 */
58696
58697
58698 function isReferenceToGlobalVariable(node) {
58699 const variable = globalScope.set.get(node.name);
58700 return variable && variable.defs.length === 0 && variable.references.some(ref => ref.identifier === node);
58701 }
58702 /**
58703 * Determines whether the given node should be checked.
58704 * @param {ASTNode} node `Identifier` node.
58705 * @returns {boolean} `true` if the node should be checked.
58706 */
58707
58708
58709 function shouldCheck(node) {
58710 const parent = node.parent;
58711 /*
58712 * Member access has special rules for checking property names.
58713 * Read access to a property with a blacklisted name is allowed, because it can be on an object that user has no control over.
58714 * Write access isn't allowed, because it potentially creates a new property with a blacklisted name.
58715 */
58716
58717 if (parent.type === "MemberExpression" && parent.property === node && !parent.computed) {
58718 return isAssignmentTarget(parent);
58719 }
58720
58721 return parent.type !== "CallExpression" && parent.type !== "NewExpression" && !isRenamedImport(node) && !isRenamedInDestructuring(node) && !(isReferenceToGlobalVariable(node) && !isShorthandPropertyDefinition(node));
58722 }
58723 /**
58724 * Reports an AST node as a rule violation.
58725 * @param {ASTNode} node The node to report.
58726 * @returns {void}
58727 * @private
58728 */
58729
58730
58731 function report(node) {
58732 if (!reportedNodes.has(node)) {
58733 context.report({
58734 node,
58735 messageId: "blacklisted",
58736 data: {
58737 name: node.name
58738 }
58739 });
58740 reportedNodes.add(node);
58741 }
58742 }
58743
58744 return {
58745 Program() {
58746 globalScope = context.getScope();
58747 },
58748
58749 Identifier(node) {
58750 if (isBlacklisted(node.name) && shouldCheck(node)) {
58751 report(node);
58752 }
58753 }
58754
58755 };
58756 }
58757
58758};
58759
58760/***/ }),
58761/* 477 */
58762/***/ (function(module, exports, __webpack_require__) {
58763
58764"use strict";
58765/**
58766 * @fileoverview Rule that warns when identifier names are shorter or longer
58767 * than the values provided in configuration.
58768 * @author Burak Yigit Kaya aka BYK
58769 */
58770 //------------------------------------------------------------------------------
58771// Rule Definition
58772//------------------------------------------------------------------------------
58773
58774module.exports = {
58775 meta: {
58776 type: "suggestion",
58777 docs: {
58778 description: "enforce minimum and maximum identifier lengths",
58779 category: "Stylistic Issues",
58780 recommended: false,
58781 url: "https://eslint.org/docs/rules/id-length"
58782 },
58783 schema: [{
58784 type: "object",
58785 properties: {
58786 min: {
58787 type: "integer",
58788 default: 2
58789 },
58790 max: {
58791 type: "integer"
58792 },
58793 exceptions: {
58794 type: "array",
58795 uniqueItems: true,
58796 items: {
58797 type: "string"
58798 }
58799 },
58800 properties: {
58801 enum: ["always", "never"]
58802 }
58803 },
58804 additionalProperties: false
58805 }],
58806 messages: {
58807 tooShort: "Identifier name '{{name}}' is too short (< {{min}}).",
58808 tooLong: "Identifier name '{{name}}' is too long (> {{max}})."
58809 }
58810 },
58811
58812 create(context) {
58813 const options = context.options[0] || {};
58814 const minLength = typeof options.min !== "undefined" ? options.min : 2;
58815 const maxLength = typeof options.max !== "undefined" ? options.max : Infinity;
58816 const properties = options.properties !== "never";
58817 const exceptions = (options.exceptions ? options.exceptions : []).reduce((obj, item) => {
58818 obj[item] = true;
58819 return obj;
58820 }, {});
58821 const reportedNode = new Set();
58822 const SUPPORTED_EXPRESSIONS = {
58823 MemberExpression: properties && function (parent) {
58824 return !parent.computed && ( // regular property assignment
58825 parent.parent.left === parent && parent.parent.type === "AssignmentExpression" || // or the last identifier in an ObjectPattern destructuring
58826 parent.parent.type === "Property" && parent.parent.value === parent && parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent);
58827 },
58828
58829 AssignmentPattern(parent, node) {
58830 return parent.left === node;
58831 },
58832
58833 VariableDeclarator(parent, node) {
58834 return parent.id === node;
58835 },
58836
58837 Property(parent, node) {
58838 if (parent.parent.type === "ObjectPattern") {
58839 return parent.value !== parent.key && parent.value === node || parent.value === parent.key && parent.key === node && properties;
58840 }
58841
58842 return properties && !parent.computed && parent.key === node;
58843 },
58844
58845 ImportDefaultSpecifier: true,
58846 RestElement: true,
58847 FunctionExpression: true,
58848 ArrowFunctionExpression: true,
58849 ClassDeclaration: true,
58850 FunctionDeclaration: true,
58851 MethodDefinition: true,
58852 CatchClause: true,
58853 ArrayPattern: true
58854 };
58855 return {
58856 Identifier(node) {
58857 const name = node.name;
58858 const parent = node.parent;
58859 const isShort = name.length < minLength;
58860 const isLong = name.length > maxLength;
58861
58862 if (!(isShort || isLong) || exceptions[name]) {
58863 return; // Nothing to report
58864 }
58865
58866 const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];
58867
58868 if (isValidExpression && !reportedNode.has(node) && (isValidExpression === true || isValidExpression(parent, node))) {
58869 reportedNode.add(node);
58870 context.report({
58871 node,
58872 messageId: isShort ? "tooShort" : "tooLong",
58873 data: {
58874 name,
58875 min: minLength,
58876 max: maxLength
58877 }
58878 });
58879 }
58880 }
58881
58882 };
58883 }
58884
58885};
58886
58887/***/ }),
58888/* 478 */
58889/***/ (function(module, exports, __webpack_require__) {
58890
58891"use strict";
58892/**
58893 * @fileoverview Rule to flag non-matching identifiers
58894 * @author Matthieu Larcher
58895 */
58896 //------------------------------------------------------------------------------
58897// Rule Definition
58898//------------------------------------------------------------------------------
58899
58900module.exports = {
58901 meta: {
58902 type: "suggestion",
58903 docs: {
58904 description: "require identifiers to match a specified regular expression",
58905 category: "Stylistic Issues",
58906 recommended: false,
58907 url: "https://eslint.org/docs/rules/id-match"
58908 },
58909 schema: [{
58910 type: "string"
58911 }, {
58912 type: "object",
58913 properties: {
58914 properties: {
58915 type: "boolean",
58916 default: false
58917 },
58918 onlyDeclarations: {
58919 type: "boolean",
58920 default: false
58921 },
58922 ignoreDestructuring: {
58923 type: "boolean",
58924 default: false
58925 }
58926 }
58927 }],
58928 messages: {
58929 notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'."
58930 }
58931 },
58932
58933 create(context) {
58934 //--------------------------------------------------------------------------
58935 // Options
58936 //--------------------------------------------------------------------------
58937 const pattern = context.options[0] || "^.+$",
58938 regexp = new RegExp(pattern, "u");
58939 const options = context.options[1] || {},
58940 properties = !!options.properties,
58941 onlyDeclarations = !!options.onlyDeclarations,
58942 ignoreDestructuring = !!options.ignoreDestructuring; //--------------------------------------------------------------------------
58943 // Helpers
58944 //--------------------------------------------------------------------------
58945 // contains reported nodes to avoid reporting twice on destructuring with shorthand notation
58946
58947 const reported = new Map();
58948 const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]);
58949 const DECLARATION_TYPES = new Set(["FunctionDeclaration", "VariableDeclarator"]);
58950 const IMPORT_TYPES = new Set(["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"]);
58951 /**
58952 * Checks if a string matches the provided pattern
58953 * @param {string} name The string to check.
58954 * @returns {boolean} if the string is a match
58955 * @private
58956 */
58957
58958 function isInvalid(name) {
58959 return !regexp.test(name);
58960 }
58961 /**
58962 * Checks if a parent of a node is an ObjectPattern.
58963 * @param {ASTNode} node The node to check.
58964 * @returns {boolean} if the node is inside an ObjectPattern
58965 * @private
58966 */
58967
58968
58969 function isInsideObjectPattern(node) {
58970 let {
58971 parent
58972 } = node;
58973
58974 while (parent) {
58975 if (parent.type === "ObjectPattern") {
58976 return true;
58977 }
58978
58979 parent = parent.parent;
58980 }
58981
58982 return false;
58983 }
58984 /**
58985 * Verifies if we should report an error or not based on the effective
58986 * parent node and the identifier name.
58987 * @param {ASTNode} effectiveParent The effective parent node of the node to be reported
58988 * @param {string} name The identifier name of the identifier node
58989 * @returns {boolean} whether an error should be reported or not
58990 */
58991
58992
58993 function shouldReport(effectiveParent, name) {
58994 return (!onlyDeclarations || DECLARATION_TYPES.has(effectiveParent.type)) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && isInvalid(name);
58995 }
58996 /**
58997 * Reports an AST node as a rule violation.
58998 * @param {ASTNode} node The node to report.
58999 * @returns {void}
59000 * @private
59001 */
59002
59003
59004 function report(node) {
59005 if (!reported.has(node)) {
59006 context.report({
59007 node,
59008 messageId: "notMatch",
59009 data: {
59010 name: node.name,
59011 pattern
59012 }
59013 });
59014 reported.set(node, true);
59015 }
59016 }
59017
59018 return {
59019 Identifier(node) {
59020 const name = node.name,
59021 parent = node.parent,
59022 effectiveParent = parent.type === "MemberExpression" ? parent.parent : parent;
59023
59024 if (parent.type === "MemberExpression") {
59025 if (!properties) {
59026 return;
59027 } // Always check object names
59028
59029
59030 if (parent.object.type === "Identifier" && parent.object.name === name) {
59031 if (isInvalid(name)) {
59032 report(node);
59033 } // Report AssignmentExpressions left side's assigned variable id
59034
59035 } else if (effectiveParent.type === "AssignmentExpression" && effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name) {
59036 if (isInvalid(name)) {
59037 report(node);
59038 } // Report AssignmentExpressions only if they are the left side of the assignment
59039
59040 } else if (effectiveParent.type === "AssignmentExpression" && effectiveParent.right.type !== "MemberExpression") {
59041 if (isInvalid(name)) {
59042 report(node);
59043 }
59044 }
59045 /*
59046 * Properties have their own rules, and
59047 * AssignmentPattern nodes can be treated like Properties:
59048 * e.g.: const { no_camelcased = false } = bar;
59049 */
59050
59051 } else if (parent.type === "Property" || parent.type === "AssignmentPattern") {
59052 if (parent.parent && parent.parent.type === "ObjectPattern") {
59053 if (parent.shorthand && parent.value.left && isInvalid(name)) {
59054 report(node);
59055 }
59056
59057 const assignmentKeyEqualsValue = parent.key.name === parent.value.name; // prevent checking righthand side of destructured object
59058
59059 if (!assignmentKeyEqualsValue && parent.key === node) {
59060 return;
59061 }
59062
59063 const valueIsInvalid = parent.value.name && isInvalid(name); // ignore destructuring if the option is set, unless a new identifier is created
59064
59065 if (valueIsInvalid && !(assignmentKeyEqualsValue && ignoreDestructuring)) {
59066 report(node);
59067 }
59068 } // never check properties or always ignore destructuring
59069
59070
59071 if (!properties || ignoreDestructuring && isInsideObjectPattern(node)) {
59072 return;
59073 } // don't check right hand side of AssignmentExpression to prevent duplicate warnings
59074
59075
59076 if (parent.right !== node && shouldReport(effectiveParent, name)) {
59077 report(node);
59078 } // Check if it's an import specifier
59079
59080 } else if (IMPORT_TYPES.has(parent.type)) {
59081 // Report only if the local imported identifier is invalid
59082 if (parent.local && parent.local.name === node.name && isInvalid(name)) {
59083 report(node);
59084 } // Report anything that is invalid that isn't a CallExpression
59085
59086 } else if (shouldReport(effectiveParent, name)) {
59087 report(node);
59088 }
59089 }
59090
59091 };
59092 }
59093
59094};
59095
59096/***/ }),
59097/* 479 */
59098/***/ (function(module, exports, __webpack_require__) {
59099
59100"use strict";
59101/**
59102 * @fileoverview enforce the location of arrow function bodies
59103 * @author Sharmila Jesupaul
59104 */
59105
59106
59107const {
59108 isCommentToken,
59109 isNotOpeningParenToken
59110} = __webpack_require__(426); //------------------------------------------------------------------------------
59111// Rule Definition
59112//------------------------------------------------------------------------------
59113
59114
59115module.exports = {
59116 meta: {
59117 type: "layout",
59118 docs: {
59119 description: "enforce the location of arrow function bodies",
59120 category: "Stylistic Issues",
59121 recommended: false,
59122 url: "https://eslint.org/docs/rules/implicit-arrow-linebreak"
59123 },
59124 fixable: "whitespace",
59125 schema: [{
59126 enum: ["beside", "below"]
59127 }],
59128 messages: {
59129 expected: "Expected a linebreak before this expression.",
59130 unexpected: "Expected no linebreak before this expression."
59131 }
59132 },
59133
59134 create(context) {
59135 const sourceCode = context.getSourceCode();
59136 const option = context.options[0] || "beside";
59137 /**
59138 * Validates the location of an arrow function body
59139 * @param {ASTNode} node The arrow function body
59140 * @returns {void}
59141 */
59142
59143 function validateExpression(node) {
59144 if (node.body.type === "BlockStatement") {
59145 return;
59146 }
59147
59148 const arrowToken = sourceCode.getTokenBefore(node.body, isNotOpeningParenToken);
59149 const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken);
59150
59151 if (arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && option === "below") {
59152 context.report({
59153 node: firstTokenOfBody,
59154 messageId: "expected",
59155 fix: fixer => fixer.insertTextBefore(firstTokenOfBody, "\n")
59156 });
59157 } else if (arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && option === "beside") {
59158 context.report({
59159 node: firstTokenOfBody,
59160 messageId: "unexpected",
59161
59162 fix(fixer) {
59163 if (sourceCode.getFirstTokenBetween(arrowToken, firstTokenOfBody, {
59164 includeComments: true,
59165 filter: isCommentToken
59166 })) {
59167 return null;
59168 }
59169
59170 return fixer.replaceTextRange([arrowToken.range[1], firstTokenOfBody.range[0]], " ");
59171 }
59172
59173 });
59174 }
59175 } //----------------------------------------------------------------------
59176 // Public
59177 //----------------------------------------------------------------------
59178
59179
59180 return {
59181 ArrowFunctionExpression: node => validateExpression(node)
59182 };
59183 }
59184
59185};
59186
59187/***/ }),
59188/* 480 */
59189/***/ (function(module, exports, __webpack_require__) {
59190
59191"use strict";
59192/**
59193 * @fileoverview This rule sets a specific indentation style and width for your code
59194 *
59195 * @author Teddy Katz
59196 * @author Vitaly Puzrin
59197 * @author Gyandeep Singh
59198 */
59199 //------------------------------------------------------------------------------
59200// Requirements
59201//------------------------------------------------------------------------------
59202
59203const lodash = __webpack_require__(403);
59204
59205const astUtils = __webpack_require__(426);
59206
59207const createTree = __webpack_require__(481); //------------------------------------------------------------------------------
59208// Rule Definition
59209//------------------------------------------------------------------------------
59210
59211
59212const KNOWN_NODES = new Set(["AssignmentExpression", "AssignmentPattern", "ArrayExpression", "ArrayPattern", "ArrowFunctionExpression", "AwaitExpression", "BlockStatement", "BinaryExpression", "BreakStatement", "CallExpression", "CatchClause", "ClassBody", "ClassDeclaration", "ClassExpression", "ConditionalExpression", "ContinueStatement", "DoWhileStatement", "DebuggerStatement", "EmptyStatement", "ExperimentalRestProperty", "ExperimentalSpreadProperty", "ExpressionStatement", "ForStatement", "ForInStatement", "ForOfStatement", "FunctionDeclaration", "FunctionExpression", "Identifier", "IfStatement", "Literal", "LabeledStatement", "LogicalExpression", "MemberExpression", "MetaProperty", "MethodDefinition", "NewExpression", "ObjectExpression", "ObjectPattern", "Program", "Property", "RestElement", "ReturnStatement", "SequenceExpression", "SpreadElement", "Super", "SwitchCase", "SwitchStatement", "TaggedTemplateExpression", "TemplateElement", "TemplateLiteral", "ThisExpression", "ThrowStatement", "TryStatement", "UnaryExpression", "UpdateExpression", "VariableDeclaration", "VariableDeclarator", "WhileStatement", "WithStatement", "YieldExpression", "JSXFragment", "JSXOpeningFragment", "JSXClosingFragment", "JSXIdentifier", "JSXNamespacedName", "JSXMemberExpression", "JSXEmptyExpression", "JSXExpressionContainer", "JSXElement", "JSXClosingElement", "JSXOpeningElement", "JSXAttribute", "JSXSpreadAttribute", "JSXText", "ExportDefaultDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration", "ExportSpecifier", "ImportDeclaration", "ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier", "ImportExpression"]);
59213/*
59214 * General rule strategy:
59215 * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another
59216 * specified token or to the first column.
59217 * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a
59218 * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly
59219 * brace of the BlockStatement.
59220 * 3. After traversing the AST, calculate the expected indentation levels of every token according to the
59221 * OffsetStorage container.
59222 * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file,
59223 * and report the token if the two values are not equal.
59224 */
59225
59226/**
59227 * A mutable balanced binary search tree that stores (key, value) pairs. The keys are numeric, and must be unique.
59228 * This is intended to be a generic wrapper around a balanced binary search tree library, so that the underlying implementation
59229 * can easily be swapped out.
59230 */
59231
59232class BinarySearchTree {
59233 /**
59234 * Creates an empty tree
59235 */
59236 constructor() {
59237 this._rbTree = createTree();
59238 }
59239 /**
59240 * Inserts an entry into the tree.
59241 * @param {number} key The entry's key
59242 * @param {*} value The entry's value
59243 * @returns {void}
59244 */
59245
59246
59247 insert(key, value) {
59248 const iterator = this._rbTree.find(key);
59249
59250 if (iterator.valid) {
59251 this._rbTree = iterator.update(value);
59252 } else {
59253 this._rbTree = this._rbTree.insert(key, value);
59254 }
59255 }
59256 /**
59257 * Finds the entry with the largest key less than or equal to the provided key
59258 * @param {number} key The provided key
59259 * @returns {{key: number, value: *}|null} The found entry, or null if no such entry exists.
59260 */
59261
59262
59263 findLe(key) {
59264 const iterator = this._rbTree.le(key);
59265
59266 return iterator && {
59267 key: iterator.key,
59268 value: iterator.value
59269 };
59270 }
59271 /**
59272 * Deletes all of the keys in the interval [start, end)
59273 * @param {number} start The start of the range
59274 * @param {number} end The end of the range
59275 * @returns {void}
59276 */
59277
59278
59279 deleteRange(start, end) {
59280 // Exit without traversing the tree if the range has zero size.
59281 if (start === end) {
59282 return;
59283 }
59284
59285 const iterator = this._rbTree.ge(start);
59286
59287 while (iterator.valid && iterator.key < end) {
59288 this._rbTree = this._rbTree.remove(iterator.key);
59289 iterator.next();
59290 }
59291 }
59292
59293}
59294/**
59295 * A helper class to get token-based info related to indentation
59296 */
59297
59298
59299class TokenInfo {
59300 // eslint-disable-next-line jsdoc/require-description
59301
59302 /**
59303 * @param {SourceCode} sourceCode A SourceCode object
59304 */
59305 constructor(sourceCode) {
59306 this.sourceCode = sourceCode;
59307 this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce((map, token) => {
59308 if (!map.has(token.loc.start.line)) {
59309 map.set(token.loc.start.line, token);
59310 }
59311
59312 if (!map.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) {
59313 map.set(token.loc.end.line, token);
59314 }
59315
59316 return map;
59317 }, new Map());
59318 }
59319 /**
59320 * Gets the first token on a given token's line
59321 * @param {Token|ASTNode} token a node or token
59322 * @returns {Token} The first token on the given line
59323 */
59324
59325
59326 getFirstTokenOfLine(token) {
59327 return this.firstTokensByLineNumber.get(token.loc.start.line);
59328 }
59329 /**
59330 * Determines whether a token is the first token in its line
59331 * @param {Token} token The token
59332 * @returns {boolean} `true` if the token is the first on its line
59333 */
59334
59335
59336 isFirstTokenOfLine(token) {
59337 return this.getFirstTokenOfLine(token) === token;
59338 }
59339 /**
59340 * Get the actual indent of a token
59341 * @param {Token} token Token to examine. This should be the first token on its line.
59342 * @returns {string} The indentation characters that precede the token
59343 */
59344
59345
59346 getTokenIndent(token) {
59347 return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]);
59348 }
59349
59350}
59351/**
59352 * A class to store information on desired offsets of tokens from each other
59353 */
59354
59355
59356class OffsetStorage {
59357 // eslint-disable-next-line jsdoc/require-description
59358
59359 /**
59360 * @param {TokenInfo} tokenInfo a TokenInfo instance
59361 * @param {number} indentSize The desired size of each indentation level
59362 * @param {string} indentType The indentation character
59363 */
59364 constructor(tokenInfo, indentSize, indentType) {
59365 this._tokenInfo = tokenInfo;
59366 this._indentSize = indentSize;
59367 this._indentType = indentType;
59368 this._tree = new BinarySearchTree();
59369
59370 this._tree.insert(0, {
59371 offset: 0,
59372 from: null,
59373 force: false
59374 });
59375
59376 this._lockedFirstTokens = new WeakMap();
59377 this._desiredIndentCache = new WeakMap();
59378 this._ignoredTokens = new WeakSet();
59379 }
59380
59381 _getOffsetDescriptor(token) {
59382 return this._tree.findLe(token.range[0]).value;
59383 }
59384 /**
59385 * Sets the offset column of token B to match the offset column of token A.
59386 * **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
59387 * most cases, `setDesiredOffset` should be used instead.
59388 * @param {Token} baseToken The first token
59389 * @param {Token} offsetToken The second token, whose offset should be matched to the first token
59390 * @returns {void}
59391 */
59392
59393
59394 matchOffsetOf(baseToken, offsetToken) {
59395 /*
59396 * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
59397 * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
59398 * token of each element in the array after the first will be mapped to the first token of the first
59399 * element. The desired indentation of each of these tokens is computed based on the desired indentation
59400 * of the "first" element, rather than through the normal offset mechanism.
59401 */
59402 this._lockedFirstTokens.set(offsetToken, baseToken);
59403 }
59404 /**
59405 * Sets the desired offset of a token.
59406 *
59407 * This uses a line-based offset collapsing behavior to handle tokens on the same line.
59408 * For example, consider the following two cases:
59409 *
59410 * (
59411 * [
59412 * bar
59413 * ]
59414 * )
59415 *
59416 * ([
59417 * bar
59418 * ])
59419 *
59420 * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
59421 * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
59422 * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
59423 * from the start of its line.
59424 *
59425 * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
59426 * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
59427 * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
59428 * by 1 indent level from the start of the line.
59429 *
59430 * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
59431 * without needing to check which lines those tokens are on.
59432 *
59433 * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
59434 * behavior can occur. For example, consider the following cases:
59435 *
59436 * foo(
59437 * ).
59438 * bar(
59439 * baz
59440 * )
59441 *
59442 * foo(
59443 * ).bar(
59444 * baz
59445 * )
59446 *
59447 * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
59448 * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
59449 * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
59450 * collapsing would occur).
59451 *
59452 * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
59453 * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
59454 * in the second case.
59455 * @param {Token} token The token
59456 * @param {Token} fromToken The token that `token` should be offset from
59457 * @param {number} offset The desired indent level
59458 * @returns {void}
59459 */
59460
59461
59462 setDesiredOffset(token, fromToken, offset) {
59463 return this.setDesiredOffsets(token.range, fromToken, offset);
59464 }
59465 /**
59466 * Sets the desired offset of all tokens in a range
59467 * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens.
59468 * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains
59469 * it). This means that the offset of each token is updated O(AST depth) times.
59470 * It would not be performant to store and update the offsets for each token independently, because the rule would end
59471 * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files.
59472 *
59473 * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
59474 * list could represent the state of the offset tree at a given point:
59475 *
59476 * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file
59477 * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
59478 * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
59479 * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
59480 * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
59481 *
59482 * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
59483 * `setDesiredOffsets([30, 43], fooToken, 1);`
59484 * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
59485 * @param {Token} fromToken The token that this is offset from
59486 * @param {number} offset The desired indent level
59487 * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
59488 * @returns {void}
59489 */
59490
59491
59492 setDesiredOffsets(range, fromToken, offset, force) {
59493 /*
59494 * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
59495 * descriptor. The tree for the example above would have the following nodes:
59496 *
59497 * * key: 0, value: { offset: 0, from: null }
59498 * * key: 15, value: { offset: 1, from: barToken }
59499 * * key: 30, value: { offset: 1, from: fooToken }
59500 * * key: 43, value: { offset: 2, from: barToken }
59501 * * key: 820, value: { offset: 1, from: bazToken }
59502 *
59503 * To find the offset descriptor for any given token, one needs to find the node with the largest key
59504 * which is <= token.start. To make this operation fast, the nodes are stored in a balanced binary
59505 * search tree indexed by key.
59506 */
59507 const descriptorToInsert = {
59508 offset,
59509 from: fromToken,
59510 force
59511 };
59512
59513 const descriptorAfterRange = this._tree.findLe(range[1]).value;
59514
59515 const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
59516
59517 const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken); // First, remove any existing nodes in the range from the tree.
59518
59519
59520 this._tree.deleteRange(range[0] + 1, range[1]); // Insert a new node into the tree for this range
59521
59522
59523 this._tree.insert(range[0], descriptorToInsert);
59524 /*
59525 * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
59526 * even if it's in the current range.
59527 */
59528
59529
59530 if (fromTokenIsInRange) {
59531 this._tree.insert(fromToken.range[0], fromTokenDescriptor);
59532
59533 this._tree.insert(fromToken.range[1], descriptorToInsert);
59534 }
59535 /*
59536 * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
59537 * tokens the same as it was before.
59538 */
59539
59540
59541 this._tree.insert(range[1], descriptorAfterRange);
59542 }
59543 /**
59544 * Gets the desired indent of a token
59545 * @param {Token} token The token
59546 * @returns {string} The desired indent of the token
59547 */
59548
59549
59550 getDesiredIndent(token) {
59551 if (!this._desiredIndentCache.has(token)) {
59552 if (this._ignoredTokens.has(token)) {
59553 /*
59554 * If the token is ignored, use the actual indent of the token as the desired indent.
59555 * This ensures that no errors are reported for this token.
59556 */
59557 this._desiredIndentCache.set(token, this._tokenInfo.getTokenIndent(token));
59558 } else if (this._lockedFirstTokens.has(token)) {
59559 const firstToken = this._lockedFirstTokens.get(token);
59560
59561 this._desiredIndentCache.set(token, // (indentation for the first element's line)
59562 this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) + // (space between the start of the first element's line and the first element)
59563 this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column));
59564 } else {
59565 const offsetInfo = this._getOffsetDescriptor(token);
59566
59567 const offset = offsetInfo.from && offsetInfo.from.loc.start.line === token.loc.start.line && !/^\s*?\n/u.test(token.value) && !offsetInfo.force ? 0 : offsetInfo.offset * this._indentSize;
59568
59569 this._desiredIndentCache.set(token, (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset));
59570 }
59571 }
59572
59573 return this._desiredIndentCache.get(token);
59574 }
59575 /**
59576 * Ignores a token, preventing it from being reported.
59577 * @param {Token} token The token
59578 * @returns {void}
59579 */
59580
59581
59582 ignoreToken(token) {
59583 if (this._tokenInfo.isFirstTokenOfLine(token)) {
59584 this._ignoredTokens.add(token);
59585 }
59586 }
59587 /**
59588 * Gets the first token that the given token's indentation is dependent on
59589 * @param {Token} token The token
59590 * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
59591 */
59592
59593
59594 getFirstDependency(token) {
59595 return this._getOffsetDescriptor(token).from;
59596 }
59597
59598}
59599
59600const ELEMENT_LIST_SCHEMA = {
59601 oneOf: [{
59602 type: "integer",
59603 minimum: 0
59604 }, {
59605 enum: ["first", "off"]
59606 }]
59607};
59608module.exports = {
59609 meta: {
59610 type: "layout",
59611 docs: {
59612 description: "enforce consistent indentation",
59613 category: "Stylistic Issues",
59614 recommended: false,
59615 url: "https://eslint.org/docs/rules/indent"
59616 },
59617 fixable: "whitespace",
59618 schema: [{
59619 oneOf: [{
59620 enum: ["tab"]
59621 }, {
59622 type: "integer",
59623 minimum: 0
59624 }]
59625 }, {
59626 type: "object",
59627 properties: {
59628 SwitchCase: {
59629 type: "integer",
59630 minimum: 0,
59631 default: 0
59632 },
59633 VariableDeclarator: {
59634 oneOf: [ELEMENT_LIST_SCHEMA, {
59635 type: "object",
59636 properties: {
59637 var: ELEMENT_LIST_SCHEMA,
59638 let: ELEMENT_LIST_SCHEMA,
59639 const: ELEMENT_LIST_SCHEMA
59640 },
59641 additionalProperties: false
59642 }]
59643 },
59644 outerIIFEBody: {
59645 oneOf: [{
59646 type: "integer",
59647 minimum: 0
59648 }, {
59649 enum: ["off"]
59650 }]
59651 },
59652 MemberExpression: {
59653 oneOf: [{
59654 type: "integer",
59655 minimum: 0
59656 }, {
59657 enum: ["off"]
59658 }]
59659 },
59660 FunctionDeclaration: {
59661 type: "object",
59662 properties: {
59663 parameters: ELEMENT_LIST_SCHEMA,
59664 body: {
59665 type: "integer",
59666 minimum: 0
59667 }
59668 },
59669 additionalProperties: false
59670 },
59671 FunctionExpression: {
59672 type: "object",
59673 properties: {
59674 parameters: ELEMENT_LIST_SCHEMA,
59675 body: {
59676 type: "integer",
59677 minimum: 0
59678 }
59679 },
59680 additionalProperties: false
59681 },
59682 CallExpression: {
59683 type: "object",
59684 properties: {
59685 arguments: ELEMENT_LIST_SCHEMA
59686 },
59687 additionalProperties: false
59688 },
59689 ArrayExpression: ELEMENT_LIST_SCHEMA,
59690 ObjectExpression: ELEMENT_LIST_SCHEMA,
59691 ImportDeclaration: ELEMENT_LIST_SCHEMA,
59692 flatTernaryExpressions: {
59693 type: "boolean",
59694 default: false
59695 },
59696 offsetTernaryExpressions: {
59697 type: "boolean",
59698 default: false
59699 },
59700 ignoredNodes: {
59701 type: "array",
59702 items: {
59703 type: "string",
59704 not: {
59705 pattern: ":exit$"
59706 }
59707 }
59708 },
59709 ignoreComments: {
59710 type: "boolean",
59711 default: false
59712 }
59713 },
59714 additionalProperties: false
59715 }],
59716 messages: {
59717 wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}."
59718 }
59719 },
59720
59721 create(context) {
59722 const DEFAULT_VARIABLE_INDENT = 1;
59723 const DEFAULT_PARAMETER_INDENT = 1;
59724 const DEFAULT_FUNCTION_BODY_INDENT = 1;
59725 let indentType = "space";
59726 let indentSize = 4;
59727 const options = {
59728 SwitchCase: 0,
59729 VariableDeclarator: {
59730 var: DEFAULT_VARIABLE_INDENT,
59731 let: DEFAULT_VARIABLE_INDENT,
59732 const: DEFAULT_VARIABLE_INDENT
59733 },
59734 outerIIFEBody: 1,
59735 FunctionDeclaration: {
59736 parameters: DEFAULT_PARAMETER_INDENT,
59737 body: DEFAULT_FUNCTION_BODY_INDENT
59738 },
59739 FunctionExpression: {
59740 parameters: DEFAULT_PARAMETER_INDENT,
59741 body: DEFAULT_FUNCTION_BODY_INDENT
59742 },
59743 CallExpression: {
59744 arguments: DEFAULT_PARAMETER_INDENT
59745 },
59746 MemberExpression: 1,
59747 ArrayExpression: 1,
59748 ObjectExpression: 1,
59749 ImportDeclaration: 1,
59750 flatTernaryExpressions: false,
59751 ignoredNodes: [],
59752 ignoreComments: false
59753 };
59754
59755 if (context.options.length) {
59756 if (context.options[0] === "tab") {
59757 indentSize = 1;
59758 indentType = "tab";
59759 } else {
59760 indentSize = context.options[0];
59761 indentType = "space";
59762 }
59763
59764 if (context.options[1]) {
59765 Object.assign(options, context.options[1]);
59766
59767 if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") {
59768 options.VariableDeclarator = {
59769 var: options.VariableDeclarator,
59770 let: options.VariableDeclarator,
59771 const: options.VariableDeclarator
59772 };
59773 }
59774 }
59775 }
59776
59777 const sourceCode = context.getSourceCode();
59778 const tokenInfo = new TokenInfo(sourceCode);
59779 const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t");
59780 const parameterParens = new WeakSet();
59781 /**
59782 * Creates an error message for a line, given the expected/actual indentation.
59783 * @param {int} expectedAmount The expected amount of indentation characters for this line
59784 * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
59785 * @param {int} actualTabs The actual number of indentation tabs that were found on this line
59786 * @returns {string} An error message for this line
59787 */
59788
59789 function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
59790 const expectedStatement = "".concat(expectedAmount, " ").concat(indentType).concat(expectedAmount === 1 ? "" : "s"); // e.g. "2 tabs"
59791
59792 const foundSpacesWord = "space".concat(actualSpaces === 1 ? "" : "s"); // e.g. "space"
59793
59794 const foundTabsWord = "tab".concat(actualTabs === 1 ? "" : "s"); // e.g. "tabs"
59795
59796 let foundStatement;
59797
59798 if (actualSpaces > 0) {
59799 /*
59800 * Abbreviate the message if the expected indentation is also spaces.
59801 * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
59802 */
59803 foundStatement = indentType === "space" ? actualSpaces : "".concat(actualSpaces, " ").concat(foundSpacesWord);
59804 } else if (actualTabs > 0) {
59805 foundStatement = indentType === "tab" ? actualTabs : "".concat(actualTabs, " ").concat(foundTabsWord);
59806 } else {
59807 foundStatement = "0";
59808 }
59809
59810 return {
59811 expected: expectedStatement,
59812 actual: foundStatement
59813 };
59814 }
59815 /**
59816 * Reports a given indent violation
59817 * @param {Token} token Token violating the indent rule
59818 * @param {string} neededIndent Expected indentation string
59819 * @returns {void}
59820 */
59821
59822
59823 function report(token, neededIndent) {
59824 const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
59825 const numSpaces = actualIndent.filter(char => char === " ").length;
59826 const numTabs = actualIndent.filter(char => char === "\t").length;
59827 context.report({
59828 node: token,
59829 messageId: "wrongIndentation",
59830 data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
59831 loc: {
59832 start: {
59833 line: token.loc.start.line,
59834 column: 0
59835 },
59836 end: {
59837 line: token.loc.start.line,
59838 column: token.loc.start.column
59839 }
59840 },
59841
59842 fix(fixer) {
59843 const range = [token.range[0] - token.loc.start.column, token.range[0]];
59844 const newText = neededIndent;
59845 return fixer.replaceTextRange(range, newText);
59846 }
59847
59848 });
59849 }
59850 /**
59851 * Checks if a token's indentation is correct
59852 * @param {Token} token Token to examine
59853 * @param {string} desiredIndent Desired indentation of the string
59854 * @returns {boolean} `true` if the token's indentation is correct
59855 */
59856
59857
59858 function validateTokenIndent(token, desiredIndent) {
59859 const indentation = tokenInfo.getTokenIndent(token);
59860 return indentation === desiredIndent || // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
59861 indentation.includes(" ") && indentation.includes("\t");
59862 }
59863 /**
59864 * Check to see if the node is a file level IIFE
59865 * @param {ASTNode} node The function node to check.
59866 * @returns {boolean} True if the node is the outer IIFE
59867 */
59868
59869
59870 function isOuterIIFE(node) {
59871 /*
59872 * Verify that the node is an IIFE
59873 */
59874 if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
59875 return false;
59876 }
59877 /*
59878 * Navigate legal ancestors to determine whether this IIFE is outer.
59879 * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
59880 * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
59881 */
59882
59883
59884 let statement = node.parent && node.parent.parent;
59885
59886 while (statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 || statement.type === "AssignmentExpression" || statement.type === "LogicalExpression" || statement.type === "SequenceExpression" || statement.type === "VariableDeclarator") {
59887 statement = statement.parent;
59888 }
59889
59890 return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
59891 }
59892 /**
59893 * Counts the number of linebreaks that follow the last non-whitespace character in a string
59894 * @param {string} string The string to check
59895 * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
59896 * or the total number of linebreaks if the string is all whitespace.
59897 */
59898
59899
59900 function countTrailingLinebreaks(string) {
59901 const trailingWhitespace = string.match(/\s*$/u)[0];
59902 const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
59903 return linebreakMatches === null ? 0 : linebreakMatches.length;
59904 }
59905 /**
59906 * Check indentation for lists of elements (arrays, objects, function params)
59907 * @param {ASTNode[]} elements List of elements that should be offset
59908 * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
59909 * @param {Token} endToken The end token of the list, e.g. ']'
59910 * @param {number|string} offset The amount that the elements should be offset
59911 * @returns {void}
59912 */
59913
59914
59915 function addElementListIndent(elements, startToken, endToken, offset) {
59916 /**
59917 * Gets the first token of a given element, including surrounding parentheses.
59918 * @param {ASTNode} element A node in the `elements` list
59919 * @returns {Token} The first token of this element
59920 */
59921 function getFirstToken(element) {
59922 let token = sourceCode.getTokenBefore(element);
59923
59924 while (astUtils.isOpeningParenToken(token) && token !== startToken) {
59925 token = sourceCode.getTokenBefore(token);
59926 }
59927
59928 return sourceCode.getTokenAfter(token);
59929 } // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
59930
59931
59932 offsets.setDesiredOffsets([startToken.range[1], endToken.range[0]], startToken, typeof offset === "number" ? offset : 1);
59933 offsets.setDesiredOffset(endToken, startToken, 0); // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
59934
59935 if (offset === "first" && elements.length && !elements[0]) {
59936 return;
59937 }
59938
59939 elements.forEach((element, index) => {
59940 if (!element) {
59941 // Skip holes in arrays
59942 return;
59943 }
59944
59945 if (offset === "off") {
59946 // Ignore the first token of every element if the "off" option is used
59947 offsets.ignoreToken(getFirstToken(element));
59948 } // Offset the following elements correctly relative to the first element
59949
59950
59951 if (index === 0) {
59952 return;
59953 }
59954
59955 if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
59956 offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
59957 } else {
59958 const previousElement = elements[index - 1];
59959 const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
59960 const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
59961
59962 if (previousElement && previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line) {
59963 offsets.setDesiredOffsets([previousElement.range[1], element.range[1]], firstTokenOfPreviousElement, 0);
59964 }
59965 }
59966 });
59967 }
59968 /**
59969 * Check and decide whether to check for indentation for blockless nodes
59970 * Scenarios are for or while statements without braces around them
59971 * @param {ASTNode} node node to examine
59972 * @returns {void}
59973 */
59974
59975
59976 function addBlocklessNodeIndent(node) {
59977 if (node.type !== "BlockStatement") {
59978 const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
59979 let firstBodyToken = sourceCode.getFirstToken(node);
59980 let lastBodyToken = sourceCode.getLastToken(node);
59981
59982 while (astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) && astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))) {
59983 firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
59984 lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
59985 }
59986
59987 offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
59988 /*
59989 * For blockless nodes with semicolon-first style, don't indent the semicolon.
59990 * e.g.
59991 * if (foo) bar()
59992 * ; [1, 2, 3].map(foo)
59993 */
59994
59995 const lastToken = sourceCode.getLastToken(node);
59996
59997 if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
59998 offsets.setDesiredOffset(lastToken, lastParentToken, 0);
59999 }
60000 }
60001 }
60002 /**
60003 * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
60004 * @param {ASTNode} node A CallExpression or NewExpression node
60005 * @returns {void}
60006 */
60007
60008
60009 function addFunctionCallIndent(node) {
60010 let openingParen;
60011
60012 if (node.arguments.length) {
60013 openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
60014 } else {
60015 openingParen = sourceCode.getLastToken(node, 1);
60016 }
60017
60018 const closingParen = sourceCode.getLastToken(node);
60019 parameterParens.add(openingParen);
60020 parameterParens.add(closingParen);
60021 const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen;
60022 const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
60023 offsets.setDesiredOffset(openingParen, offsetToken, 0);
60024 addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
60025 }
60026 /**
60027 * Checks the indentation of parenthesized values, given a list of tokens in a program
60028 * @param {Token[]} tokens A list of tokens
60029 * @returns {void}
60030 */
60031
60032
60033 function addParensIndent(tokens) {
60034 const parenStack = [];
60035 const parenPairs = [];
60036 tokens.forEach(nextToken => {
60037 // Accumulate a list of parenthesis pairs
60038 if (astUtils.isOpeningParenToken(nextToken)) {
60039 parenStack.push(nextToken);
60040 } else if (astUtils.isClosingParenToken(nextToken)) {
60041 parenPairs.unshift({
60042 left: parenStack.pop(),
60043 right: nextToken
60044 });
60045 }
60046 });
60047 parenPairs.forEach(pair => {
60048 const leftParen = pair.left;
60049 const rightParen = pair.right; // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
60050
60051 if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
60052 const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
60053 parenthesizedTokens.forEach(token => {
60054 if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
60055 offsets.setDesiredOffset(token, leftParen, 1);
60056 }
60057 });
60058 }
60059
60060 offsets.setDesiredOffset(rightParen, leftParen, 0);
60061 });
60062 }
60063 /**
60064 * Ignore all tokens within an unknown node whose offset do not depend
60065 * on another token's offset within the unknown node
60066 * @param {ASTNode} node Unknown Node
60067 * @returns {void}
60068 */
60069
60070
60071 function ignoreNode(node) {
60072 const unknownNodeTokens = new Set(sourceCode.getTokens(node, {
60073 includeComments: true
60074 }));
60075 unknownNodeTokens.forEach(token => {
60076 if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
60077 const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
60078
60079 if (token === firstTokenOfLine) {
60080 offsets.ignoreToken(token);
60081 } else {
60082 offsets.setDesiredOffset(token, firstTokenOfLine, 0);
60083 }
60084 }
60085 });
60086 }
60087 /**
60088 * Check whether the given token is on the first line of a statement.
60089 * @param {Token} token The token to check.
60090 * @param {ASTNode} leafNode The expression node that the token belongs directly.
60091 * @returns {boolean} `true` if the token is on the first line of a statement.
60092 */
60093
60094
60095 function isOnFirstLineOfStatement(token, leafNode) {
60096 let node = leafNode;
60097
60098 while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
60099 node = node.parent;
60100 }
60101
60102 node = node.parent;
60103 return !node || node.loc.start.line === token.loc.start.line;
60104 }
60105 /**
60106 * Check whether there are any blank (whitespace-only) lines between
60107 * two tokens on separate lines.
60108 * @param {Token} firstToken The first token.
60109 * @param {Token} secondToken The second token.
60110 * @returns {boolean} `true` if the tokens are on separate lines and
60111 * there exists a blank line between them, `false` otherwise.
60112 */
60113
60114
60115 function hasBlankLinesBetween(firstToken, secondToken) {
60116 const firstTokenLine = firstToken.loc.end.line;
60117 const secondTokenLine = secondToken.loc.start.line;
60118
60119 if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) {
60120 return false;
60121 }
60122
60123 for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
60124 if (!tokenInfo.firstTokensByLineNumber.has(line)) {
60125 return true;
60126 }
60127 }
60128
60129 return false;
60130 }
60131
60132 const ignoredNodeFirstTokens = new Set();
60133 const baseOffsetListeners = {
60134 "ArrayExpression, ArrayPattern"(node) {
60135 const openingBracket = sourceCode.getFirstToken(node);
60136 const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken);
60137 addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
60138 },
60139
60140 "ObjectExpression, ObjectPattern"(node) {
60141 const openingCurly = sourceCode.getFirstToken(node);
60142 const closingCurly = sourceCode.getTokenAfter(node.properties.length ? node.properties[node.properties.length - 1] : openingCurly, astUtils.isClosingBraceToken);
60143 addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
60144 },
60145
60146 ArrowFunctionExpression(node) {
60147 const firstToken = sourceCode.getFirstToken(node);
60148
60149 if (astUtils.isOpeningParenToken(firstToken)) {
60150 const openingParen = firstToken;
60151 const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
60152 parameterParens.add(openingParen);
60153 parameterParens.add(closingParen);
60154 addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
60155 }
60156
60157 addBlocklessNodeIndent(node.body);
60158 },
60159
60160 AssignmentExpression(node) {
60161 const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
60162 offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
60163 offsets.ignoreToken(operator);
60164 offsets.ignoreToken(sourceCode.getTokenAfter(operator));
60165 },
60166
60167 "BinaryExpression, LogicalExpression"(node) {
60168 const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
60169 /*
60170 * For backwards compatibility, don't check BinaryExpression indents, e.g.
60171 * var foo = bar &&
60172 * baz;
60173 */
60174
60175 const tokenAfterOperator = sourceCode.getTokenAfter(operator);
60176 offsets.ignoreToken(operator);
60177 offsets.ignoreToken(tokenAfterOperator);
60178 offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
60179 },
60180
60181 "BlockStatement, ClassBody"(node) {
60182 let blockIndentLevel;
60183
60184 if (node.parent && isOuterIIFE(node.parent)) {
60185 blockIndentLevel = options.outerIIFEBody;
60186 } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
60187 blockIndentLevel = options.FunctionExpression.body;
60188 } else if (node.parent && node.parent.type === "FunctionDeclaration") {
60189 blockIndentLevel = options.FunctionDeclaration.body;
60190 } else {
60191 blockIndentLevel = 1;
60192 }
60193 /*
60194 * For blocks that aren't lone statements, ensure that the opening curly brace
60195 * is aligned with the parent.
60196 */
60197
60198
60199 if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
60200 offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
60201 }
60202
60203 addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
60204 },
60205
60206 CallExpression: addFunctionCallIndent,
60207
60208 "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
60209 const classToken = sourceCode.getFirstToken(node);
60210 const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
60211 offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
60212 },
60213
60214 ConditionalExpression(node) {
60215 const firstToken = sourceCode.getFirstToken(node); // `flatTernaryExpressions` option is for the following style:
60216 // var a =
60217 // foo > 0 ? bar :
60218 // foo < 0 ? baz :
60219 // /*else*/ qiz ;
60220
60221 if (!options.flatTernaryExpressions || !astUtils.isTokenOnSameLine(node.test, node.consequent) || isOnFirstLineOfStatement(firstToken, node)) {
60222 const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
60223 const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
60224 const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
60225 const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
60226 const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
60227 offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
60228 offsets.setDesiredOffset(colonToken, firstToken, 1);
60229 offsets.setDesiredOffset(firstConsequentToken, firstToken, options.offsetTernaryExpressions ? 2 : 1);
60230 /*
60231 * The alternate and the consequent should usually have the same indentation.
60232 * If they share part of a line, align the alternate against the first token of the consequent.
60233 * This allows the alternate to be indented correctly in cases like this:
60234 * foo ? (
60235 * bar
60236 * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
60237 * baz // as a result, `baz` is offset by 1 rather than 2
60238 * )
60239 */
60240
60241 if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
60242 offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
60243 } else {
60244 /**
60245 * If the alternate and consequent do not share part of a line, offset the alternate from the first
60246 * token of the conditional expression. For example:
60247 * foo ? bar
60248 * : baz
60249 *
60250 * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
60251 * having no expected indentation.
60252 */
60253 offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" && options.offsetTernaryExpressions ? 2 : 1);
60254 }
60255 }
60256 },
60257
60258 "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body),
60259
60260 ExportNamedDeclaration(node) {
60261 if (node.declaration === null) {
60262 const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); // Indent the specifiers in `export {foo, bar, baz}`
60263
60264 addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, {
60265 skip: 1
60266 }), closingCurly, 1);
60267
60268 if (node.source) {
60269 // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
60270 offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
60271 }
60272 }
60273 },
60274
60275 ForStatement(node) {
60276 const forOpeningParen = sourceCode.getFirstToken(node, 1);
60277
60278 if (node.init) {
60279 offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
60280 }
60281
60282 if (node.test) {
60283 offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
60284 }
60285
60286 if (node.update) {
60287 offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
60288 }
60289
60290 addBlocklessNodeIndent(node.body);
60291 },
60292
60293 "FunctionDeclaration, FunctionExpression"(node) {
60294 const closingParen = sourceCode.getTokenBefore(node.body);
60295 const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
60296 parameterParens.add(openingParen);
60297 parameterParens.add(closingParen);
60298 addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
60299 },
60300
60301 IfStatement(node) {
60302 addBlocklessNodeIndent(node.consequent);
60303
60304 if (node.alternate && node.alternate.type !== "IfStatement") {
60305 addBlocklessNodeIndent(node.alternate);
60306 }
60307 },
60308
60309 ImportDeclaration(node) {
60310 if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
60311 const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
60312 const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
60313 addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
60314 }
60315
60316 const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
60317 const sourceToken = sourceCode.getLastToken(node, token => token.type === "String");
60318 const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";");
60319
60320 if (fromToken) {
60321 const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1];
60322 offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1);
60323 }
60324 },
60325
60326 ImportExpression(node) {
60327 const openingParen = sourceCode.getFirstToken(node, 1);
60328 const closingParen = sourceCode.getLastToken(node);
60329 parameterParens.add(openingParen);
60330 parameterParens.add(closingParen);
60331 offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
60332 addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments);
60333 },
60334
60335 "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
60336 const object = node.type === "MetaProperty" ? node.meta : node.object;
60337 const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
60338 const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
60339 const objectParenCount = sourceCode.getTokensBetween(object, node.property, {
60340 filter: astUtils.isClosingParenToken
60341 }).length;
60342 const firstObjectToken = objectParenCount ? sourceCode.getTokenBefore(object, {
60343 skip: objectParenCount - 1
60344 }) : sourceCode.getFirstToken(object);
60345 const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
60346 const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
60347
60348 if (node.computed) {
60349 // For computed MemberExpressions, match the closing bracket with the opening bracket.
60350 offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
60351 offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
60352 }
60353 /*
60354 * If the object ends on the same line that the property starts, match against the last token
60355 * of the object, to ensure that the MemberExpression is not indented.
60356 *
60357 * Otherwise, match against the first token of the object, e.g.
60358 * foo
60359 * .bar
60360 * .baz // <-- offset by 1 from `foo`
60361 */
60362
60363
60364 const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line ? lastObjectToken : firstObjectToken;
60365
60366 if (typeof options.MemberExpression === "number") {
60367 // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
60368 offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
60369 /*
60370 * For computed MemberExpressions, match the first token of the property against the opening bracket.
60371 * Otherwise, match the first token of the property against the object.
60372 */
60373
60374 offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
60375 } else {
60376 // If the MemberExpression option is off, ignore the dot and the first token of the property.
60377 offsets.ignoreToken(firstNonObjectToken);
60378 offsets.ignoreToken(secondNonObjectToken); // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
60379
60380 offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
60381 offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
60382 }
60383 },
60384
60385 NewExpression(node) {
60386 // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
60387 if (node.arguments.length > 0 || astUtils.isClosingParenToken(sourceCode.getLastToken(node)) && astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
60388 addFunctionCallIndent(node);
60389 }
60390 },
60391
60392 Property(node) {
60393 if (!node.shorthand && !node.method && node.kind === "init") {
60394 const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
60395 offsets.ignoreToken(sourceCode.getTokenAfter(colon));
60396 }
60397 },
60398
60399 SwitchStatement(node) {
60400 const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
60401 const closingCurly = sourceCode.getLastToken(node);
60402 offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
60403
60404 if (node.cases.length) {
60405 sourceCode.getTokensBetween(node.cases[node.cases.length - 1], closingCurly, {
60406 includeComments: true,
60407 filter: astUtils.isCommentToken
60408 }).forEach(token => offsets.ignoreToken(token));
60409 }
60410 },
60411
60412 SwitchCase(node) {
60413 if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
60414 const caseKeyword = sourceCode.getFirstToken(node);
60415 const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
60416 offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
60417 }
60418 },
60419
60420 TemplateLiteral(node) {
60421 node.expressions.forEach((expression, index) => {
60422 const previousQuasi = node.quasis[index];
60423 const nextQuasi = node.quasis[index + 1];
60424 const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line ? sourceCode.getFirstToken(previousQuasi) : null;
60425 offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
60426 offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
60427 });
60428 },
60429
60430 VariableDeclaration(node) {
60431 let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind) ? options.VariableDeclarator[node.kind] : DEFAULT_VARIABLE_INDENT;
60432 const firstToken = sourceCode.getFirstToken(node),
60433 lastToken = sourceCode.getLastToken(node);
60434
60435 if (options.VariableDeclarator[node.kind] === "first") {
60436 if (node.declarations.length > 1) {
60437 addElementListIndent(node.declarations, firstToken, lastToken, "first");
60438 return;
60439 }
60440
60441 variableIndent = DEFAULT_VARIABLE_INDENT;
60442 }
60443
60444 if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
60445 /*
60446 * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
60447 * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
60448 * the following indentations are correct:
60449 *
60450 * var foo = {
60451 * ok: true
60452 * };
60453 *
60454 * var foo = {
60455 * ok: true,
60456 * },
60457 * bar = 1;
60458 *
60459 * Account for when exiting the AST (after indentations have already been set for the nodes in
60460 * the declaration) by manually increasing the indentation level of the tokens in this declarator
60461 * on the same line as the start of the declaration, provided that there are declarators that
60462 * follow this one.
60463 */
60464 offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
60465 } else {
60466 offsets.setDesiredOffsets(node.range, firstToken, variableIndent);
60467 }
60468
60469 if (astUtils.isSemicolonToken(lastToken)) {
60470 offsets.ignoreToken(lastToken);
60471 }
60472 },
60473
60474 VariableDeclarator(node) {
60475 if (node.init) {
60476 const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
60477 const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
60478 offsets.ignoreToken(equalOperator);
60479 offsets.ignoreToken(tokenAfterOperator);
60480 offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
60481 offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
60482 }
60483 },
60484
60485 "JSXAttribute[value]"(node) {
60486 const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
60487 offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
60488 },
60489
60490 JSXElement(node) {
60491 if (node.closingElement) {
60492 addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
60493 }
60494 },
60495
60496 JSXOpeningElement(node) {
60497 const firstToken = sourceCode.getFirstToken(node);
60498 let closingToken;
60499
60500 if (node.selfClosing) {
60501 closingToken = sourceCode.getLastToken(node, {
60502 skip: 1
60503 });
60504 offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
60505 } else {
60506 closingToken = sourceCode.getLastToken(node);
60507 }
60508
60509 offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
60510 addElementListIndent(node.attributes, firstToken, closingToken, 1);
60511 },
60512
60513 JSXClosingElement(node) {
60514 const firstToken = sourceCode.getFirstToken(node);
60515 offsets.setDesiredOffsets(node.name.range, firstToken, 1);
60516 },
60517
60518 JSXFragment(node) {
60519 const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment);
60520 const firstClosingToken = sourceCode.getFirstToken(node.closingFragment);
60521 addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1);
60522 },
60523
60524 JSXOpeningFragment(node) {
60525 const firstToken = sourceCode.getFirstToken(node);
60526 const closingToken = sourceCode.getLastToken(node);
60527 offsets.setDesiredOffsets(node.range, firstToken, 1);
60528 offsets.matchOffsetOf(firstToken, closingToken);
60529 },
60530
60531 JSXClosingFragment(node) {
60532 const firstToken = sourceCode.getFirstToken(node);
60533 const slashToken = sourceCode.getLastToken(node, {
60534 skip: 1
60535 });
60536 const closingToken = sourceCode.getLastToken(node);
60537 const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken;
60538 offsets.setDesiredOffsets(node.range, firstToken, 1);
60539 offsets.matchOffsetOf(firstToken, tokenToMatch);
60540 },
60541
60542 JSXExpressionContainer(node) {
60543 const openingCurly = sourceCode.getFirstToken(node);
60544 const closingCurly = sourceCode.getLastToken(node);
60545 offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, 1);
60546 },
60547
60548 JSXSpreadAttribute(node) {
60549 const openingCurly = sourceCode.getFirstToken(node);
60550 const closingCurly = sourceCode.getLastToken(node);
60551 offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, 1);
60552 },
60553
60554 "*"(node) {
60555 const firstToken = sourceCode.getFirstToken(node); // Ensure that the children of every node are indented at least as much as the first token.
60556
60557 if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
60558 offsets.setDesiredOffsets(node.range, firstToken, 0);
60559 }
60560 }
60561
60562 };
60563 const listenerCallQueue = [];
60564 /*
60565 * To ignore the indentation of a node:
60566 * 1. Don't call the node's listener when entering it (if it has a listener)
60567 * 2. Don't set any offsets against the first token of the node.
60568 * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
60569 */
60570
60571 const offsetListeners = lodash.mapValues(baseOffsetListeners,
60572 /*
60573 * Offset listener calls are deferred until traversal is finished, and are called as
60574 * part of the final `Program:exit` listener. This is necessary because a node might
60575 * be matched by multiple selectors.
60576 *
60577 * Example: Suppose there is an offset listener for `Identifier`, and the user has
60578 * specified in configuration that `MemberExpression > Identifier` should be ignored.
60579 * Due to selector specificity rules, the `Identifier` listener will get called first. However,
60580 * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
60581 * should not have been called at all. Without doing extra selector matching, we don't know
60582 * whether the Identifier matches the `MemberExpression > Identifier` selector until the
60583 * `MemberExpression > Identifier` listener is called.
60584 *
60585 * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
60586 * ignored nodes are known.
60587 */
60588 listener => node => listenerCallQueue.push({
60589 listener,
60590 node
60591 })); // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
60592
60593 const ignoredNodes = new Set();
60594 /**
60595 * Ignores a node
60596 * @param {ASTNode} node The node to ignore
60597 * @returns {void}
60598 */
60599
60600 function addToIgnoredNodes(node) {
60601 ignoredNodes.add(node);
60602 ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
60603 }
60604
60605 const ignoredNodeListeners = options.ignoredNodes.reduce((listeners, ignoredSelector) => Object.assign(listeners, {
60606 [ignoredSelector]: addToIgnoredNodes
60607 }), {});
60608 /*
60609 * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
60610 * at the end.
60611 *
60612 * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
60613 * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
60614 * so those listeners wouldn't be called anyway.
60615 */
60616
60617 return Object.assign(offsetListeners, ignoredNodeListeners, {
60618 "*:exit"(node) {
60619 // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
60620 if (!KNOWN_NODES.has(node.type)) {
60621 addToIgnoredNodes(node);
60622 }
60623 },
60624
60625 "Program:exit"() {
60626 // If ignoreComments option is enabled, ignore all comment tokens.
60627 if (options.ignoreComments) {
60628 sourceCode.getAllComments().forEach(comment => offsets.ignoreToken(comment));
60629 } // Invoke the queued offset listeners for the nodes that aren't ignored.
60630
60631
60632 listenerCallQueue.filter(nodeInfo => !ignoredNodes.has(nodeInfo.node)).forEach(nodeInfo => nodeInfo.listener(nodeInfo.node)); // Update the offsets for ignored nodes to prevent their child tokens from being reported.
60633
60634 ignoredNodes.forEach(ignoreNode);
60635 addParensIndent(sourceCode.ast.tokens);
60636 /*
60637 * Create a Map from (tokenOrComment) => (precedingToken).
60638 * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
60639 */
60640
60641 const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => {
60642 const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, {
60643 includeComments: true
60644 });
60645 return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore);
60646 }, new WeakMap());
60647 sourceCode.lines.forEach((line, lineIndex) => {
60648 const lineNumber = lineIndex + 1;
60649
60650 if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) {
60651 // Don't check indentation on blank lines
60652 return;
60653 }
60654
60655 const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber);
60656
60657 if (firstTokenOfLine.loc.start.line !== lineNumber) {
60658 // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
60659 return;
60660 }
60661
60662 if (astUtils.isCommentToken(firstTokenOfLine)) {
60663 const tokenBefore = precedingTokens.get(firstTokenOfLine);
60664 const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
60665 const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
60666 const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
60667 /*
60668 * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
60669 *
60670 * let foo
60671 * // comment
60672 * ;(async () => {})()
60673 */
60674
60675 if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) {
60676 offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0);
60677 } // If a comment matches the expected indentation of the token immediately before or after, don't report it.
60678
60679
60680 if (mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) || mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))) {
60681 return;
60682 }
60683 } // If the token matches the expected indentation, don't report it.
60684
60685
60686 if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
60687 return;
60688 } // Otherwise, report the token/comment.
60689
60690
60691 report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
60692 });
60693 }
60694
60695 });
60696 }
60697
60698};
60699
60700/***/ }),
60701/* 481 */
60702/***/ (function(module, exports, __webpack_require__) {
60703
60704"use strict";
60705
60706
60707module.exports = createRBTree;
60708var RED = 0;
60709var BLACK = 1;
60710
60711function RBNode(color, key, value, left, right, count) {
60712 this._color = color;
60713 this.key = key;
60714 this.value = value;
60715 this.left = left;
60716 this.right = right;
60717 this._count = count;
60718}
60719
60720function cloneNode(node) {
60721 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count);
60722}
60723
60724function repaint(color, node) {
60725 return new RBNode(color, node.key, node.value, node.left, node.right, node._count);
60726}
60727
60728function recount(node) {
60729 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0);
60730}
60731
60732function RedBlackTree(compare, root) {
60733 this._compare = compare;
60734 this.root = root;
60735}
60736
60737var proto = RedBlackTree.prototype;
60738Object.defineProperty(proto, "keys", {
60739 get: function get() {
60740 var result = [];
60741 this.forEach(function (k, v) {
60742 result.push(k);
60743 });
60744 return result;
60745 }
60746});
60747Object.defineProperty(proto, "values", {
60748 get: function get() {
60749 var result = [];
60750 this.forEach(function (k, v) {
60751 result.push(v);
60752 });
60753 return result;
60754 }
60755}); //Returns the number of nodes in the tree
60756
60757Object.defineProperty(proto, "length", {
60758 get: function get() {
60759 if (this.root) {
60760 return this.root._count;
60761 }
60762
60763 return 0;
60764 }
60765}); //Insert a new item into the tree
60766
60767proto.insert = function (key, value) {
60768 var cmp = this._compare; //Find point to insert new node at
60769
60770 var n = this.root;
60771 var n_stack = [];
60772 var d_stack = [];
60773
60774 while (n) {
60775 var d = cmp(key, n.key);
60776 n_stack.push(n);
60777 d_stack.push(d);
60778
60779 if (d <= 0) {
60780 n = n.left;
60781 } else {
60782 n = n.right;
60783 }
60784 } //Rebuild path to leaf node
60785
60786
60787 n_stack.push(new RBNode(RED, key, value, null, null, 1));
60788
60789 for (var s = n_stack.length - 2; s >= 0; --s) {
60790 var n = n_stack[s];
60791
60792 if (d_stack[s] <= 0) {
60793 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s + 1], n.right, n._count + 1);
60794 } else {
60795 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s + 1], n._count + 1);
60796 }
60797 } //Rebalance tree using rotations
60798 //console.log("start insert", key, d_stack)
60799
60800
60801 for (var s = n_stack.length - 1; s > 1; --s) {
60802 var p = n_stack[s - 1];
60803 var n = n_stack[s];
60804
60805 if (p._color === BLACK || n._color === BLACK) {
60806 break;
60807 }
60808
60809 var pp = n_stack[s - 2];
60810
60811 if (pp.left === p) {
60812 if (p.left === n) {
60813 var y = pp.right;
60814
60815 if (y && y._color === RED) {
60816 //console.log("LLr")
60817 p._color = BLACK;
60818 pp.right = repaint(BLACK, y);
60819 pp._color = RED;
60820 s -= 1;
60821 } else {
60822 //console.log("LLb")
60823 pp._color = RED;
60824 pp.left = p.right;
60825 p._color = BLACK;
60826 p.right = pp;
60827 n_stack[s - 2] = p;
60828 n_stack[s - 1] = n;
60829 recount(pp);
60830 recount(p);
60831
60832 if (s >= 3) {
60833 var ppp = n_stack[s - 3];
60834
60835 if (ppp.left === pp) {
60836 ppp.left = p;
60837 } else {
60838 ppp.right = p;
60839 }
60840 }
60841
60842 break;
60843 }
60844 } else {
60845 var y = pp.right;
60846
60847 if (y && y._color === RED) {
60848 //console.log("LRr")
60849 p._color = BLACK;
60850 pp.right = repaint(BLACK, y);
60851 pp._color = RED;
60852 s -= 1;
60853 } else {
60854 //console.log("LRb")
60855 p.right = n.left;
60856 pp._color = RED;
60857 pp.left = n.right;
60858 n._color = BLACK;
60859 n.left = p;
60860 n.right = pp;
60861 n_stack[s - 2] = n;
60862 n_stack[s - 1] = p;
60863 recount(pp);
60864 recount(p);
60865 recount(n);
60866
60867 if (s >= 3) {
60868 var ppp = n_stack[s - 3];
60869
60870 if (ppp.left === pp) {
60871 ppp.left = n;
60872 } else {
60873 ppp.right = n;
60874 }
60875 }
60876
60877 break;
60878 }
60879 }
60880 } else {
60881 if (p.right === n) {
60882 var y = pp.left;
60883
60884 if (y && y._color === RED) {
60885 //console.log("RRr", y.key)
60886 p._color = BLACK;
60887 pp.left = repaint(BLACK, y);
60888 pp._color = RED;
60889 s -= 1;
60890 } else {
60891 //console.log("RRb")
60892 pp._color = RED;
60893 pp.right = p.left;
60894 p._color = BLACK;
60895 p.left = pp;
60896 n_stack[s - 2] = p;
60897 n_stack[s - 1] = n;
60898 recount(pp);
60899 recount(p);
60900
60901 if (s >= 3) {
60902 var ppp = n_stack[s - 3];
60903
60904 if (ppp.right === pp) {
60905 ppp.right = p;
60906 } else {
60907 ppp.left = p;
60908 }
60909 }
60910
60911 break;
60912 }
60913 } else {
60914 var y = pp.left;
60915
60916 if (y && y._color === RED) {
60917 //console.log("RLr")
60918 p._color = BLACK;
60919 pp.left = repaint(BLACK, y);
60920 pp._color = RED;
60921 s -= 1;
60922 } else {
60923 //console.log("RLb")
60924 p.left = n.right;
60925 pp._color = RED;
60926 pp.right = n.left;
60927 n._color = BLACK;
60928 n.right = p;
60929 n.left = pp;
60930 n_stack[s - 2] = n;
60931 n_stack[s - 1] = p;
60932 recount(pp);
60933 recount(p);
60934 recount(n);
60935
60936 if (s >= 3) {
60937 var ppp = n_stack[s - 3];
60938
60939 if (ppp.right === pp) {
60940 ppp.right = n;
60941 } else {
60942 ppp.left = n;
60943 }
60944 }
60945
60946 break;
60947 }
60948 }
60949 }
60950 } //Return new tree
60951
60952
60953 n_stack[0]._color = BLACK;
60954 return new RedBlackTree(cmp, n_stack[0]);
60955}; //Visit all nodes inorder
60956
60957
60958function doVisitFull(visit, node) {
60959 if (node.left) {
60960 var v = doVisitFull(visit, node.left);
60961
60962 if (v) {
60963 return v;
60964 }
60965 }
60966
60967 var v = visit(node.key, node.value);
60968
60969 if (v) {
60970 return v;
60971 }
60972
60973 if (node.right) {
60974 return doVisitFull(visit, node.right);
60975 }
60976} //Visit half nodes in order
60977
60978
60979function doVisitHalf(lo, compare, visit, node) {
60980 var l = compare(lo, node.key);
60981
60982 if (l <= 0) {
60983 if (node.left) {
60984 var v = doVisitHalf(lo, compare, visit, node.left);
60985
60986 if (v) {
60987 return v;
60988 }
60989 }
60990
60991 var v = visit(node.key, node.value);
60992
60993 if (v) {
60994 return v;
60995 }
60996 }
60997
60998 if (node.right) {
60999 return doVisitHalf(lo, compare, visit, node.right);
61000 }
61001} //Visit all nodes within a range
61002
61003
61004function doVisit(lo, hi, compare, visit, node) {
61005 var l = compare(lo, node.key);
61006 var h = compare(hi, node.key);
61007 var v;
61008
61009 if (l <= 0) {
61010 if (node.left) {
61011 v = doVisit(lo, hi, compare, visit, node.left);
61012
61013 if (v) {
61014 return v;
61015 }
61016 }
61017
61018 if (h > 0) {
61019 v = visit(node.key, node.value);
61020
61021 if (v) {
61022 return v;
61023 }
61024 }
61025 }
61026
61027 if (h > 0 && node.right) {
61028 return doVisit(lo, hi, compare, visit, node.right);
61029 }
61030}
61031
61032proto.forEach = function rbTreeForEach(visit, lo, hi) {
61033 if (!this.root) {
61034 return;
61035 }
61036
61037 switch (arguments.length) {
61038 case 1:
61039 return doVisitFull(visit, this.root);
61040 break;
61041
61042 case 2:
61043 return doVisitHalf(lo, this._compare, visit, this.root);
61044 break;
61045
61046 case 3:
61047 if (this._compare(lo, hi) >= 0) {
61048 return;
61049 }
61050
61051 return doVisit(lo, hi, this._compare, visit, this.root);
61052 break;
61053 }
61054}; //First item in list
61055
61056
61057Object.defineProperty(proto, "begin", {
61058 get: function get() {
61059 var stack = [];
61060 var n = this.root;
61061
61062 while (n) {
61063 stack.push(n);
61064 n = n.left;
61065 }
61066
61067 return new RedBlackTreeIterator(this, stack);
61068 }
61069}); //Last item in list
61070
61071Object.defineProperty(proto, "end", {
61072 get: function get() {
61073 var stack = [];
61074 var n = this.root;
61075
61076 while (n) {
61077 stack.push(n);
61078 n = n.right;
61079 }
61080
61081 return new RedBlackTreeIterator(this, stack);
61082 }
61083}); //Find the ith item in the tree
61084
61085proto.at = function (idx) {
61086 if (idx < 0) {
61087 return new RedBlackTreeIterator(this, []);
61088 }
61089
61090 var n = this.root;
61091 var stack = [];
61092
61093 while (true) {
61094 stack.push(n);
61095
61096 if (n.left) {
61097 if (idx < n.left._count) {
61098 n = n.left;
61099 continue;
61100 }
61101
61102 idx -= n.left._count;
61103 }
61104
61105 if (!idx) {
61106 return new RedBlackTreeIterator(this, stack);
61107 }
61108
61109 idx -= 1;
61110
61111 if (n.right) {
61112 if (idx >= n.right._count) {
61113 break;
61114 }
61115
61116 n = n.right;
61117 } else {
61118 break;
61119 }
61120 }
61121
61122 return new RedBlackTreeIterator(this, []);
61123};
61124
61125proto.ge = function (key) {
61126 var cmp = this._compare;
61127 var n = this.root;
61128 var stack = [];
61129 var last_ptr = 0;
61130
61131 while (n) {
61132 var d = cmp(key, n.key);
61133 stack.push(n);
61134
61135 if (d <= 0) {
61136 last_ptr = stack.length;
61137 }
61138
61139 if (d <= 0) {
61140 n = n.left;
61141 } else {
61142 n = n.right;
61143 }
61144 }
61145
61146 stack.length = last_ptr;
61147 return new RedBlackTreeIterator(this, stack);
61148};
61149
61150proto.gt = function (key) {
61151 var cmp = this._compare;
61152 var n = this.root;
61153 var stack = [];
61154 var last_ptr = 0;
61155
61156 while (n) {
61157 var d = cmp(key, n.key);
61158 stack.push(n);
61159
61160 if (d < 0) {
61161 last_ptr = stack.length;
61162 }
61163
61164 if (d < 0) {
61165 n = n.left;
61166 } else {
61167 n = n.right;
61168 }
61169 }
61170
61171 stack.length = last_ptr;
61172 return new RedBlackTreeIterator(this, stack);
61173};
61174
61175proto.lt = function (key) {
61176 var cmp = this._compare;
61177 var n = this.root;
61178 var stack = [];
61179 var last_ptr = 0;
61180
61181 while (n) {
61182 var d = cmp(key, n.key);
61183 stack.push(n);
61184
61185 if (d > 0) {
61186 last_ptr = stack.length;
61187 }
61188
61189 if (d <= 0) {
61190 n = n.left;
61191 } else {
61192 n = n.right;
61193 }
61194 }
61195
61196 stack.length = last_ptr;
61197 return new RedBlackTreeIterator(this, stack);
61198};
61199
61200proto.le = function (key) {
61201 var cmp = this._compare;
61202 var n = this.root;
61203 var stack = [];
61204 var last_ptr = 0;
61205
61206 while (n) {
61207 var d = cmp(key, n.key);
61208 stack.push(n);
61209
61210 if (d >= 0) {
61211 last_ptr = stack.length;
61212 }
61213
61214 if (d < 0) {
61215 n = n.left;
61216 } else {
61217 n = n.right;
61218 }
61219 }
61220
61221 stack.length = last_ptr;
61222 return new RedBlackTreeIterator(this, stack);
61223}; //Finds the item with key if it exists
61224
61225
61226proto.find = function (key) {
61227 var cmp = this._compare;
61228 var n = this.root;
61229 var stack = [];
61230
61231 while (n) {
61232 var d = cmp(key, n.key);
61233 stack.push(n);
61234
61235 if (d === 0) {
61236 return new RedBlackTreeIterator(this, stack);
61237 }
61238
61239 if (d <= 0) {
61240 n = n.left;
61241 } else {
61242 n = n.right;
61243 }
61244 }
61245
61246 return new RedBlackTreeIterator(this, []);
61247}; //Removes item with key from tree
61248
61249
61250proto.remove = function (key) {
61251 var iter = this.find(key);
61252
61253 if (iter) {
61254 return iter.remove();
61255 }
61256
61257 return this;
61258}; //Returns the item at `key`
61259
61260
61261proto.get = function (key) {
61262 var cmp = this._compare;
61263 var n = this.root;
61264
61265 while (n) {
61266 var d = cmp(key, n.key);
61267
61268 if (d === 0) {
61269 return n.value;
61270 }
61271
61272 if (d <= 0) {
61273 n = n.left;
61274 } else {
61275 n = n.right;
61276 }
61277 }
61278
61279 return;
61280}; //Iterator for red black tree
61281
61282
61283function RedBlackTreeIterator(tree, stack) {
61284 this.tree = tree;
61285 this._stack = stack;
61286}
61287
61288var iproto = RedBlackTreeIterator.prototype; //Test if iterator is valid
61289
61290Object.defineProperty(iproto, "valid", {
61291 get: function get() {
61292 return this._stack.length > 0;
61293 }
61294}); //Node of the iterator
61295
61296Object.defineProperty(iproto, "node", {
61297 get: function get() {
61298 if (this._stack.length > 0) {
61299 return this._stack[this._stack.length - 1];
61300 }
61301
61302 return null;
61303 },
61304 enumerable: true
61305}); //Makes a copy of an iterator
61306
61307iproto.clone = function () {
61308 return new RedBlackTreeIterator(this.tree, this._stack.slice());
61309}; //Swaps two nodes
61310
61311
61312function swapNode(n, v) {
61313 n.key = v.key;
61314 n.value = v.value;
61315 n.left = v.left;
61316 n.right = v.right;
61317 n._color = v._color;
61318 n._count = v._count;
61319} //Fix up a double black node in a tree
61320
61321
61322function fixDoubleBlack(stack) {
61323 var n, p, s, z;
61324
61325 for (var i = stack.length - 1; i >= 0; --i) {
61326 n = stack[i];
61327
61328 if (i === 0) {
61329 n._color = BLACK;
61330 return;
61331 } //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
61332
61333
61334 p = stack[i - 1];
61335
61336 if (p.left === n) {
61337 //console.log("left child")
61338 s = p.right;
61339
61340 if (s.right && s.right._color === RED) {
61341 //console.log("case 1: right sibling child red")
61342 s = p.right = cloneNode(s);
61343 z = s.right = cloneNode(s.right);
61344 p.right = s.left;
61345 s.left = p;
61346 s.right = z;
61347 s._color = p._color;
61348 n._color = BLACK;
61349 p._color = BLACK;
61350 z._color = BLACK;
61351 recount(p);
61352 recount(s);
61353
61354 if (i > 1) {
61355 var pp = stack[i - 2];
61356
61357 if (pp.left === p) {
61358 pp.left = s;
61359 } else {
61360 pp.right = s;
61361 }
61362 }
61363
61364 stack[i - 1] = s;
61365 return;
61366 } else if (s.left && s.left._color === RED) {
61367 //console.log("case 1: left sibling child red")
61368 s = p.right = cloneNode(s);
61369 z = s.left = cloneNode(s.left);
61370 p.right = z.left;
61371 s.left = z.right;
61372 z.left = p;
61373 z.right = s;
61374 z._color = p._color;
61375 p._color = BLACK;
61376 s._color = BLACK;
61377 n._color = BLACK;
61378 recount(p);
61379 recount(s);
61380 recount(z);
61381
61382 if (i > 1) {
61383 var pp = stack[i - 2];
61384
61385 if (pp.left === p) {
61386 pp.left = z;
61387 } else {
61388 pp.right = z;
61389 }
61390 }
61391
61392 stack[i - 1] = z;
61393 return;
61394 }
61395
61396 if (s._color === BLACK) {
61397 if (p._color === RED) {
61398 //console.log("case 2: black sibling, red parent", p.right.value)
61399 p._color = BLACK;
61400 p.right = repaint(RED, s);
61401 return;
61402 } else {
61403 //console.log("case 2: black sibling, black parent", p.right.value)
61404 p.right = repaint(RED, s);
61405 continue;
61406 }
61407 } else {
61408 //console.log("case 3: red sibling")
61409 s = cloneNode(s);
61410 p.right = s.left;
61411 s.left = p;
61412 s._color = p._color;
61413 p._color = RED;
61414 recount(p);
61415 recount(s);
61416
61417 if (i > 1) {
61418 var pp = stack[i - 2];
61419
61420 if (pp.left === p) {
61421 pp.left = s;
61422 } else {
61423 pp.right = s;
61424 }
61425 }
61426
61427 stack[i - 1] = s;
61428 stack[i] = p;
61429
61430 if (i + 1 < stack.length) {
61431 stack[i + 1] = n;
61432 } else {
61433 stack.push(n);
61434 }
61435
61436 i = i + 2;
61437 }
61438 } else {
61439 //console.log("right child")
61440 s = p.left;
61441
61442 if (s.left && s.left._color === RED) {
61443 //console.log("case 1: left sibling child red", p.value, p._color)
61444 s = p.left = cloneNode(s);
61445 z = s.left = cloneNode(s.left);
61446 p.left = s.right;
61447 s.right = p;
61448 s.left = z;
61449 s._color = p._color;
61450 n._color = BLACK;
61451 p._color = BLACK;
61452 z._color = BLACK;
61453 recount(p);
61454 recount(s);
61455
61456 if (i > 1) {
61457 var pp = stack[i - 2];
61458
61459 if (pp.right === p) {
61460 pp.right = s;
61461 } else {
61462 pp.left = s;
61463 }
61464 }
61465
61466 stack[i - 1] = s;
61467 return;
61468 } else if (s.right && s.right._color === RED) {
61469 //console.log("case 1: right sibling child red")
61470 s = p.left = cloneNode(s);
61471 z = s.right = cloneNode(s.right);
61472 p.left = z.right;
61473 s.right = z.left;
61474 z.right = p;
61475 z.left = s;
61476 z._color = p._color;
61477 p._color = BLACK;
61478 s._color = BLACK;
61479 n._color = BLACK;
61480 recount(p);
61481 recount(s);
61482 recount(z);
61483
61484 if (i > 1) {
61485 var pp = stack[i - 2];
61486
61487 if (pp.right === p) {
61488 pp.right = z;
61489 } else {
61490 pp.left = z;
61491 }
61492 }
61493
61494 stack[i - 1] = z;
61495 return;
61496 }
61497
61498 if (s._color === BLACK) {
61499 if (p._color === RED) {
61500 //console.log("case 2: black sibling, red parent")
61501 p._color = BLACK;
61502 p.left = repaint(RED, s);
61503 return;
61504 } else {
61505 //console.log("case 2: black sibling, black parent")
61506 p.left = repaint(RED, s);
61507 continue;
61508 }
61509 } else {
61510 //console.log("case 3: red sibling")
61511 s = cloneNode(s);
61512 p.left = s.right;
61513 s.right = p;
61514 s._color = p._color;
61515 p._color = RED;
61516 recount(p);
61517 recount(s);
61518
61519 if (i > 1) {
61520 var pp = stack[i - 2];
61521
61522 if (pp.right === p) {
61523 pp.right = s;
61524 } else {
61525 pp.left = s;
61526 }
61527 }
61528
61529 stack[i - 1] = s;
61530 stack[i] = p;
61531
61532 if (i + 1 < stack.length) {
61533 stack[i + 1] = n;
61534 } else {
61535 stack.push(n);
61536 }
61537
61538 i = i + 2;
61539 }
61540 }
61541 }
61542} //Removes item at iterator from tree
61543
61544
61545iproto.remove = function () {
61546 var stack = this._stack;
61547
61548 if (stack.length === 0) {
61549 return this.tree;
61550 } //First copy path to node
61551
61552
61553 var cstack = new Array(stack.length);
61554 var n = stack[stack.length - 1];
61555 cstack[cstack.length - 1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count);
61556
61557 for (var i = stack.length - 2; i >= 0; --i) {
61558 var n = stack[i];
61559
61560 if (n.left === stack[i + 1]) {
61561 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i + 1], n.right, n._count);
61562 } else {
61563 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count);
61564 }
61565 } //Get node
61566
61567
61568 n = cstack[cstack.length - 1]; //console.log("start remove: ", n.value)
61569 //If not leaf, then swap with previous node
61570
61571 if (n.left && n.right) {
61572 //console.log("moving to leaf")
61573 //First walk to previous leaf
61574 var split = cstack.length;
61575 n = n.left;
61576
61577 while (n.right) {
61578 cstack.push(n);
61579 n = n.right;
61580 } //Copy path to leaf
61581
61582
61583 var v = cstack[split - 1];
61584 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count));
61585 cstack[split - 1].key = n.key;
61586 cstack[split - 1].value = n.value; //Fix up stack
61587
61588 for (var i = cstack.length - 2; i >= split; --i) {
61589 n = cstack[i];
61590 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count);
61591 }
61592
61593 cstack[split - 1].left = cstack[split];
61594 } //console.log("stack=", cstack.map(function(v) { return v.value }))
61595 //Remove leaf node
61596
61597
61598 n = cstack[cstack.length - 1];
61599
61600 if (n._color === RED) {
61601 //Easy case: removing red leaf
61602 //console.log("RED leaf")
61603 var p = cstack[cstack.length - 2];
61604
61605 if (p.left === n) {
61606 p.left = null;
61607 } else if (p.right === n) {
61608 p.right = null;
61609 }
61610
61611 cstack.pop();
61612
61613 for (var i = 0; i < cstack.length; ++i) {
61614 cstack[i]._count--;
61615 }
61616
61617 return new RedBlackTree(this.tree._compare, cstack[0]);
61618 } else {
61619 if (n.left || n.right) {
61620 //Second easy case: Single child black parent
61621 //console.log("BLACK single child")
61622 if (n.left) {
61623 swapNode(n, n.left);
61624 } else if (n.right) {
61625 swapNode(n, n.right);
61626 } //Child must be red, so repaint it black to balance color
61627
61628
61629 n._color = BLACK;
61630
61631 for (var i = 0; i < cstack.length - 1; ++i) {
61632 cstack[i]._count--;
61633 }
61634
61635 return new RedBlackTree(this.tree._compare, cstack[0]);
61636 } else if (cstack.length === 1) {
61637 //Third easy case: root
61638 //console.log("ROOT")
61639 return new RedBlackTree(this.tree._compare, null);
61640 } else {
61641 //Hard case: Repaint n, and then do some nasty stuff
61642 //console.log("BLACK leaf no children")
61643 for (var i = 0; i < cstack.length; ++i) {
61644 cstack[i]._count--;
61645 }
61646
61647 var parent = cstack[cstack.length - 2];
61648 fixDoubleBlack(cstack); //Fix up links
61649
61650 if (parent.left === n) {
61651 parent.left = null;
61652 } else {
61653 parent.right = null;
61654 }
61655 }
61656 }
61657
61658 return new RedBlackTree(this.tree._compare, cstack[0]);
61659}; //Returns key
61660
61661
61662Object.defineProperty(iproto, "key", {
61663 get: function get() {
61664 if (this._stack.length > 0) {
61665 return this._stack[this._stack.length - 1].key;
61666 }
61667
61668 return;
61669 },
61670 enumerable: true
61671}); //Returns value
61672
61673Object.defineProperty(iproto, "value", {
61674 get: function get() {
61675 if (this._stack.length > 0) {
61676 return this._stack[this._stack.length - 1].value;
61677 }
61678
61679 return;
61680 },
61681 enumerable: true
61682}); //Returns the position of this iterator in the sorted list
61683
61684Object.defineProperty(iproto, "index", {
61685 get: function get() {
61686 var idx = 0;
61687 var stack = this._stack;
61688
61689 if (stack.length === 0) {
61690 var r = this.tree.root;
61691
61692 if (r) {
61693 return r._count;
61694 }
61695
61696 return 0;
61697 } else if (stack[stack.length - 1].left) {
61698 idx = stack[stack.length - 1].left._count;
61699 }
61700
61701 for (var s = stack.length - 2; s >= 0; --s) {
61702 if (stack[s + 1] === stack[s].right) {
61703 ++idx;
61704
61705 if (stack[s].left) {
61706 idx += stack[s].left._count;
61707 }
61708 }
61709 }
61710
61711 return idx;
61712 },
61713 enumerable: true
61714}); //Advances iterator to next element in list
61715
61716iproto.next = function () {
61717 var stack = this._stack;
61718
61719 if (stack.length === 0) {
61720 return;
61721 }
61722
61723 var n = stack[stack.length - 1];
61724
61725 if (n.right) {
61726 n = n.right;
61727
61728 while (n) {
61729 stack.push(n);
61730 n = n.left;
61731 }
61732 } else {
61733 stack.pop();
61734
61735 while (stack.length > 0 && stack[stack.length - 1].right === n) {
61736 n = stack[stack.length - 1];
61737 stack.pop();
61738 }
61739 }
61740}; //Checks if iterator is at end of tree
61741
61742
61743Object.defineProperty(iproto, "hasNext", {
61744 get: function get() {
61745 var stack = this._stack;
61746
61747 if (stack.length === 0) {
61748 return false;
61749 }
61750
61751 if (stack[stack.length - 1].right) {
61752 return true;
61753 }
61754
61755 for (var s = stack.length - 1; s > 0; --s) {
61756 if (stack[s - 1].left === stack[s]) {
61757 return true;
61758 }
61759 }
61760
61761 return false;
61762 }
61763}); //Update value
61764
61765iproto.update = function (value) {
61766 var stack = this._stack;
61767
61768 if (stack.length === 0) {
61769 throw new Error("Can't update empty node!");
61770 }
61771
61772 var cstack = new Array(stack.length);
61773 var n = stack[stack.length - 1];
61774 cstack[cstack.length - 1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count);
61775
61776 for (var i = stack.length - 2; i >= 0; --i) {
61777 n = stack[i];
61778
61779 if (n.left === stack[i + 1]) {
61780 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i + 1], n.right, n._count);
61781 } else {
61782 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count);
61783 }
61784 }
61785
61786 return new RedBlackTree(this.tree._compare, cstack[0]);
61787}; //Moves iterator backward one element
61788
61789
61790iproto.prev = function () {
61791 var stack = this._stack;
61792
61793 if (stack.length === 0) {
61794 return;
61795 }
61796
61797 var n = stack[stack.length - 1];
61798
61799 if (n.left) {
61800 n = n.left;
61801
61802 while (n) {
61803 stack.push(n);
61804 n = n.right;
61805 }
61806 } else {
61807 stack.pop();
61808
61809 while (stack.length > 0 && stack[stack.length - 1].left === n) {
61810 n = stack[stack.length - 1];
61811 stack.pop();
61812 }
61813 }
61814}; //Checks if iterator is at start of tree
61815
61816
61817Object.defineProperty(iproto, "hasPrev", {
61818 get: function get() {
61819 var stack = this._stack;
61820
61821 if (stack.length === 0) {
61822 return false;
61823 }
61824
61825 if (stack[stack.length - 1].left) {
61826 return true;
61827 }
61828
61829 for (var s = stack.length - 1; s > 0; --s) {
61830 if (stack[s - 1].right === stack[s]) {
61831 return true;
61832 }
61833 }
61834
61835 return false;
61836 }
61837}); //Default comparison function
61838
61839function defaultCompare(a, b) {
61840 if (a < b) {
61841 return -1;
61842 }
61843
61844 if (a > b) {
61845 return 1;
61846 }
61847
61848 return 0;
61849} //Build a tree
61850
61851
61852function createRBTree(compare) {
61853 return new RedBlackTree(compare || defaultCompare, null);
61854}
61855
61856/***/ }),
61857/* 482 */
61858/***/ (function(module, exports, __webpack_require__) {
61859
61860"use strict";
61861/**
61862 * @fileoverview This option sets a specific tab width for your code
61863 *
61864 * This rule has been ported and modified from nodeca.
61865 * @author Vitaly Puzrin
61866 * @author Gyandeep Singh
61867 */
61868 //------------------------------------------------------------------------------
61869// Requirements
61870//------------------------------------------------------------------------------
61871
61872const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
61873// Rule Definition
61874//------------------------------------------------------------------------------
61875
61876/* istanbul ignore next: this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. */
61877
61878
61879module.exports = {
61880 meta: {
61881 type: "layout",
61882 docs: {
61883 description: "enforce consistent indentation",
61884 category: "Stylistic Issues",
61885 recommended: false,
61886 url: "https://eslint.org/docs/rules/indent-legacy"
61887 },
61888 deprecated: true,
61889 replacedBy: ["indent"],
61890 fixable: "whitespace",
61891 schema: [{
61892 oneOf: [{
61893 enum: ["tab"]
61894 }, {
61895 type: "integer",
61896 minimum: 0
61897 }]
61898 }, {
61899 type: "object",
61900 properties: {
61901 SwitchCase: {
61902 type: "integer",
61903 minimum: 0
61904 },
61905 VariableDeclarator: {
61906 oneOf: [{
61907 type: "integer",
61908 minimum: 0
61909 }, {
61910 type: "object",
61911 properties: {
61912 var: {
61913 type: "integer",
61914 minimum: 0
61915 },
61916 let: {
61917 type: "integer",
61918 minimum: 0
61919 },
61920 const: {
61921 type: "integer",
61922 minimum: 0
61923 }
61924 }
61925 }]
61926 },
61927 outerIIFEBody: {
61928 type: "integer",
61929 minimum: 0
61930 },
61931 MemberExpression: {
61932 type: "integer",
61933 minimum: 0
61934 },
61935 FunctionDeclaration: {
61936 type: "object",
61937 properties: {
61938 parameters: {
61939 oneOf: [{
61940 type: "integer",
61941 minimum: 0
61942 }, {
61943 enum: ["first"]
61944 }]
61945 },
61946 body: {
61947 type: "integer",
61948 minimum: 0
61949 }
61950 }
61951 },
61952 FunctionExpression: {
61953 type: "object",
61954 properties: {
61955 parameters: {
61956 oneOf: [{
61957 type: "integer",
61958 minimum: 0
61959 }, {
61960 enum: ["first"]
61961 }]
61962 },
61963 body: {
61964 type: "integer",
61965 minimum: 0
61966 }
61967 }
61968 },
61969 CallExpression: {
61970 type: "object",
61971 properties: {
61972 parameters: {
61973 oneOf: [{
61974 type: "integer",
61975 minimum: 0
61976 }, {
61977 enum: ["first"]
61978 }]
61979 }
61980 }
61981 },
61982 ArrayExpression: {
61983 oneOf: [{
61984 type: "integer",
61985 minimum: 0
61986 }, {
61987 enum: ["first"]
61988 }]
61989 },
61990 ObjectExpression: {
61991 oneOf: [{
61992 type: "integer",
61993 minimum: 0
61994 }, {
61995 enum: ["first"]
61996 }]
61997 }
61998 },
61999 additionalProperties: false
62000 }],
62001 messages: {
62002 expected: "Expected indentation of {{expected}} but found {{actual}}."
62003 }
62004 },
62005
62006 create(context) {
62007 const DEFAULT_VARIABLE_INDENT = 1;
62008 const DEFAULT_PARAMETER_INDENT = null; // For backwards compatibility, don't check parameter indentation unless specified in the config
62009
62010 const DEFAULT_FUNCTION_BODY_INDENT = 1;
62011 let indentType = "space";
62012 let indentSize = 4;
62013 const options = {
62014 SwitchCase: 0,
62015 VariableDeclarator: {
62016 var: DEFAULT_VARIABLE_INDENT,
62017 let: DEFAULT_VARIABLE_INDENT,
62018 const: DEFAULT_VARIABLE_INDENT
62019 },
62020 outerIIFEBody: null,
62021 FunctionDeclaration: {
62022 parameters: DEFAULT_PARAMETER_INDENT,
62023 body: DEFAULT_FUNCTION_BODY_INDENT
62024 },
62025 FunctionExpression: {
62026 parameters: DEFAULT_PARAMETER_INDENT,
62027 body: DEFAULT_FUNCTION_BODY_INDENT
62028 },
62029 CallExpression: {
62030 arguments: DEFAULT_PARAMETER_INDENT
62031 },
62032 ArrayExpression: 1,
62033 ObjectExpression: 1
62034 };
62035 const sourceCode = context.getSourceCode();
62036
62037 if (context.options.length) {
62038 if (context.options[0] === "tab") {
62039 indentSize = 1;
62040 indentType = "tab";
62041 } else
62042 /* istanbul ignore else : this will be caught by options validation */
62043 if (typeof context.options[0] === "number") {
62044 indentSize = context.options[0];
62045 indentType = "space";
62046 }
62047
62048 if (context.options[1]) {
62049 const opts = context.options[1];
62050 options.SwitchCase = opts.SwitchCase || 0;
62051 const variableDeclaratorRules = opts.VariableDeclarator;
62052
62053 if (typeof variableDeclaratorRules === "number") {
62054 options.VariableDeclarator = {
62055 var: variableDeclaratorRules,
62056 let: variableDeclaratorRules,
62057 const: variableDeclaratorRules
62058 };
62059 } else if (typeof variableDeclaratorRules === "object") {
62060 Object.assign(options.VariableDeclarator, variableDeclaratorRules);
62061 }
62062
62063 if (typeof opts.outerIIFEBody === "number") {
62064 options.outerIIFEBody = opts.outerIIFEBody;
62065 }
62066
62067 if (typeof opts.MemberExpression === "number") {
62068 options.MemberExpression = opts.MemberExpression;
62069 }
62070
62071 if (typeof opts.FunctionDeclaration === "object") {
62072 Object.assign(options.FunctionDeclaration, opts.FunctionDeclaration);
62073 }
62074
62075 if (typeof opts.FunctionExpression === "object") {
62076 Object.assign(options.FunctionExpression, opts.FunctionExpression);
62077 }
62078
62079 if (typeof opts.CallExpression === "object") {
62080 Object.assign(options.CallExpression, opts.CallExpression);
62081 }
62082
62083 if (typeof opts.ArrayExpression === "number" || typeof opts.ArrayExpression === "string") {
62084 options.ArrayExpression = opts.ArrayExpression;
62085 }
62086
62087 if (typeof opts.ObjectExpression === "number" || typeof opts.ObjectExpression === "string") {
62088 options.ObjectExpression = opts.ObjectExpression;
62089 }
62090 }
62091 }
62092
62093 const caseIndentStore = {};
62094 /**
62095 * Creates an error message for a line, given the expected/actual indentation.
62096 * @param {int} expectedAmount The expected amount of indentation characters for this line
62097 * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
62098 * @param {int} actualTabs The actual number of indentation tabs that were found on this line
62099 * @returns {string} An error message for this line
62100 */
62101
62102 function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
62103 const expectedStatement = "".concat(expectedAmount, " ").concat(indentType).concat(expectedAmount === 1 ? "" : "s"); // e.g. "2 tabs"
62104
62105 const foundSpacesWord = "space".concat(actualSpaces === 1 ? "" : "s"); // e.g. "space"
62106
62107 const foundTabsWord = "tab".concat(actualTabs === 1 ? "" : "s"); // e.g. "tabs"
62108
62109 let foundStatement;
62110
62111 if (actualSpaces > 0 && actualTabs > 0) {
62112 foundStatement = "".concat(actualSpaces, " ").concat(foundSpacesWord, " and ").concat(actualTabs, " ").concat(foundTabsWord); // e.g. "1 space and 2 tabs"
62113 } else if (actualSpaces > 0) {
62114 /*
62115 * Abbreviate the message if the expected indentation is also spaces.
62116 * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
62117 */
62118 foundStatement = indentType === "space" ? actualSpaces : "".concat(actualSpaces, " ").concat(foundSpacesWord);
62119 } else if (actualTabs > 0) {
62120 foundStatement = indentType === "tab" ? actualTabs : "".concat(actualTabs, " ").concat(foundTabsWord);
62121 } else {
62122 foundStatement = "0";
62123 }
62124
62125 return {
62126 expected: expectedStatement,
62127 actual: foundStatement
62128 };
62129 }
62130 /**
62131 * Reports a given indent violation
62132 * @param {ASTNode} node Node violating the indent rule
62133 * @param {int} needed Expected indentation character count
62134 * @param {int} gottenSpaces Indentation space count in the actual node/code
62135 * @param {int} gottenTabs Indentation tab count in the actual node/code
62136 * @param {Object} [loc] Error line and column location
62137 * @param {boolean} isLastNodeCheck Is the error for last node check
62138 * @returns {void}
62139 */
62140
62141
62142 function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) {
62143 if (gottenSpaces && gottenTabs) {
62144 // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs.
62145 return;
62146 }
62147
62148 const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed);
62149 const textRange = isLastNodeCheck ? [node.range[1] - node.loc.end.column, node.range[1] - node.loc.end.column + gottenSpaces + gottenTabs] : [node.range[0] - node.loc.start.column, node.range[0] - node.loc.start.column + gottenSpaces + gottenTabs];
62150 context.report({
62151 node,
62152 loc,
62153 messageId: "expected",
62154 data: createErrorMessageData(needed, gottenSpaces, gottenTabs),
62155 fix: fixer => fixer.replaceTextRange(textRange, desiredIndent)
62156 });
62157 }
62158 /**
62159 * Get the actual indent of node
62160 * @param {ASTNode|Token} node Node to examine
62161 * @param {boolean} [byLastLine=false] get indent of node's last line
62162 * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also
62163 * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and
62164 * `badChar` is the amount of the other indentation character.
62165 */
62166
62167
62168 function getNodeIndent(node, byLastLine) {
62169 const token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node);
62170 const srcCharsBeforeNode = sourceCode.getText(token, token.loc.start.column).split("");
62171 const indentChars = srcCharsBeforeNode.slice(0, srcCharsBeforeNode.findIndex(char => char !== " " && char !== "\t"));
62172 const spaces = indentChars.filter(char => char === " ").length;
62173 const tabs = indentChars.filter(char => char === "\t").length;
62174 return {
62175 space: spaces,
62176 tab: tabs,
62177 goodChar: indentType === "space" ? spaces : tabs,
62178 badChar: indentType === "space" ? tabs : spaces
62179 };
62180 }
62181 /**
62182 * Checks node is the first in its own start line. By default it looks by start line.
62183 * @param {ASTNode} node The node to check
62184 * @param {boolean} [byEndLocation=false] Lookup based on start position or end
62185 * @returns {boolean} true if its the first in the its start line
62186 */
62187
62188
62189 function isNodeFirstInLine(node, byEndLocation) {
62190 const firstToken = byEndLocation === true ? sourceCode.getLastToken(node, 1) : sourceCode.getTokenBefore(node),
62191 startLine = byEndLocation === true ? node.loc.end.line : node.loc.start.line,
62192 endLine = firstToken ? firstToken.loc.end.line : -1;
62193 return startLine !== endLine;
62194 }
62195 /**
62196 * Check indent for node
62197 * @param {ASTNode} node Node to check
62198 * @param {int} neededIndent needed indent
62199 * @returns {void}
62200 */
62201
62202
62203 function checkNodeIndent(node, neededIndent) {
62204 const actualIndent = getNodeIndent(node, false);
62205
62206 if (node.type !== "ArrayExpression" && node.type !== "ObjectExpression" && (actualIndent.goodChar !== neededIndent || actualIndent.badChar !== 0) && isNodeFirstInLine(node)) {
62207 report(node, neededIndent, actualIndent.space, actualIndent.tab);
62208 }
62209
62210 if (node.type === "IfStatement" && node.alternate) {
62211 const elseToken = sourceCode.getTokenBefore(node.alternate);
62212 checkNodeIndent(elseToken, neededIndent);
62213
62214 if (!isNodeFirstInLine(node.alternate)) {
62215 checkNodeIndent(node.alternate, neededIndent);
62216 }
62217 }
62218
62219 if (node.type === "TryStatement" && node.handler) {
62220 const catchToken = sourceCode.getFirstToken(node.handler);
62221 checkNodeIndent(catchToken, neededIndent);
62222 }
62223
62224 if (node.type === "TryStatement" && node.finalizer) {
62225 const finallyToken = sourceCode.getTokenBefore(node.finalizer);
62226 checkNodeIndent(finallyToken, neededIndent);
62227 }
62228
62229 if (node.type === "DoWhileStatement") {
62230 const whileToken = sourceCode.getTokenAfter(node.body);
62231 checkNodeIndent(whileToken, neededIndent);
62232 }
62233 }
62234 /**
62235 * Check indent for nodes list
62236 * @param {ASTNode[]} nodes list of node objects
62237 * @param {int} indent needed indent
62238 * @returns {void}
62239 */
62240
62241
62242 function checkNodesIndent(nodes, indent) {
62243 nodes.forEach(node => checkNodeIndent(node, indent));
62244 }
62245 /**
62246 * Check last node line indent this detects, that block closed correctly
62247 * @param {ASTNode} node Node to examine
62248 * @param {int} lastLineIndent needed indent
62249 * @returns {void}
62250 */
62251
62252
62253 function checkLastNodeLineIndent(node, lastLineIndent) {
62254 const lastToken = sourceCode.getLastToken(node);
62255 const endIndent = getNodeIndent(lastToken, true);
62256
62257 if ((endIndent.goodChar !== lastLineIndent || endIndent.badChar !== 0) && isNodeFirstInLine(node, true)) {
62258 report(node, lastLineIndent, endIndent.space, endIndent.tab, {
62259 line: lastToken.loc.start.line,
62260 column: lastToken.loc.start.column
62261 }, true);
62262 }
62263 }
62264 /**
62265 * Check last node line indent this detects, that block closed correctly
62266 * This function for more complicated return statement case, where closing parenthesis may be followed by ';'
62267 * @param {ASTNode} node Node to examine
62268 * @param {int} firstLineIndent first line needed indent
62269 * @returns {void}
62270 */
62271
62272
62273 function checkLastReturnStatementLineIndent(node, firstLineIndent) {
62274 /*
62275 * in case if return statement ends with ');' we have traverse back to ')'
62276 * otherwise we'll measure indent for ';' and replace ')'
62277 */
62278 const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken);
62279 const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1);
62280
62281 if (textBeforeClosingParenthesis.trim()) {
62282 // There are tokens before the closing paren, don't report this case
62283 return;
62284 }
62285
62286 const endIndent = getNodeIndent(lastToken, true);
62287
62288 if (endIndent.goodChar !== firstLineIndent) {
62289 report(node, firstLineIndent, endIndent.space, endIndent.tab, {
62290 line: lastToken.loc.start.line,
62291 column: lastToken.loc.start.column
62292 }, true);
62293 }
62294 }
62295 /**
62296 * Check first node line indent is correct
62297 * @param {ASTNode} node Node to examine
62298 * @param {int} firstLineIndent needed indent
62299 * @returns {void}
62300 */
62301
62302
62303 function checkFirstNodeLineIndent(node, firstLineIndent) {
62304 const startIndent = getNodeIndent(node, false);
62305
62306 if ((startIndent.goodChar !== firstLineIndent || startIndent.badChar !== 0) && isNodeFirstInLine(node)) {
62307 report(node, firstLineIndent, startIndent.space, startIndent.tab, {
62308 line: node.loc.start.line,
62309 column: node.loc.start.column
62310 });
62311 }
62312 }
62313 /**
62314 * Returns a parent node of given node based on a specified type
62315 * if not present then return null
62316 * @param {ASTNode} node node to examine
62317 * @param {string} type type that is being looked for
62318 * @param {string} stopAtList end points for the evaluating code
62319 * @returns {ASTNode|void} if found then node otherwise null
62320 */
62321
62322
62323 function getParentNodeByType(node, type, stopAtList) {
62324 let parent = node.parent;
62325 const stopAtSet = new Set(stopAtList || ["Program"]);
62326
62327 while (parent.type !== type && !stopAtSet.has(parent.type) && parent.type !== "Program") {
62328 parent = parent.parent;
62329 }
62330
62331 return parent.type === type ? parent : null;
62332 }
62333 /**
62334 * Returns the VariableDeclarator based on the current node
62335 * if not present then return null
62336 * @param {ASTNode} node node to examine
62337 * @returns {ASTNode|void} if found then node otherwise null
62338 */
62339
62340
62341 function getVariableDeclaratorNode(node) {
62342 return getParentNodeByType(node, "VariableDeclarator");
62343 }
62344 /**
62345 * Check to see if the node is part of the multi-line variable declaration.
62346 * Also if its on the same line as the varNode
62347 * @param {ASTNode} node node to check
62348 * @param {ASTNode} varNode variable declaration node to check against
62349 * @returns {boolean} True if all the above condition satisfy
62350 */
62351
62352
62353 function isNodeInVarOnTop(node, varNode) {
62354 return varNode && varNode.parent.loc.start.line === node.loc.start.line && varNode.parent.declarations.length > 1;
62355 }
62356 /**
62357 * Check to see if the argument before the callee node is multi-line and
62358 * there should only be 1 argument before the callee node
62359 * @param {ASTNode} node node to check
62360 * @returns {boolean} True if arguments are multi-line
62361 */
62362
62363
62364 function isArgBeforeCalleeNodeMultiline(node) {
62365 const parent = node.parent;
62366
62367 if (parent.arguments.length >= 2 && parent.arguments[1] === node) {
62368 return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line;
62369 }
62370
62371 return false;
62372 }
62373 /**
62374 * Check to see if the node is a file level IIFE
62375 * @param {ASTNode} node The function node to check.
62376 * @returns {boolean} True if the node is the outer IIFE
62377 */
62378
62379
62380 function isOuterIIFE(node) {
62381 const parent = node.parent;
62382 let stmt = parent.parent;
62383 /*
62384 * Verify that the node is an IIEF
62385 */
62386
62387 if (parent.type !== "CallExpression" || parent.callee !== node) {
62388 return false;
62389 }
62390 /*
62391 * Navigate legal ancestors to determine whether this IIEF is outer
62392 */
62393
62394
62395 while (stmt.type === "UnaryExpression" && (stmt.operator === "!" || stmt.operator === "~" || stmt.operator === "+" || stmt.operator === "-") || stmt.type === "AssignmentExpression" || stmt.type === "LogicalExpression" || stmt.type === "SequenceExpression" || stmt.type === "VariableDeclarator") {
62396 stmt = stmt.parent;
62397 }
62398
62399 return (stmt.type === "ExpressionStatement" || stmt.type === "VariableDeclaration") && stmt.parent && stmt.parent.type === "Program";
62400 }
62401 /**
62402 * Check indent for function block content
62403 * @param {ASTNode} node A BlockStatement node that is inside of a function.
62404 * @returns {void}
62405 */
62406
62407
62408 function checkIndentInFunctionBlock(node) {
62409 /*
62410 * Search first caller in chain.
62411 * Ex.:
62412 *
62413 * Models <- Identifier
62414 * .User
62415 * .find()
62416 * .exec(function() {
62417 * // function body
62418 * });
62419 *
62420 * Looks for 'Models'
62421 */
62422 const calleeNode = node.parent; // FunctionExpression
62423
62424 let indent;
62425
62426 if (calleeNode.parent && (calleeNode.parent.type === "Property" || calleeNode.parent.type === "ArrayExpression")) {
62427 // If function is part of array or object, comma can be put at left
62428 indent = getNodeIndent(calleeNode, false).goodChar;
62429 } else {
62430 // If function is standalone, simple calculate indent
62431 indent = getNodeIndent(calleeNode).goodChar;
62432 }
62433
62434 if (calleeNode.parent.type === "CallExpression") {
62435 const calleeParent = calleeNode.parent;
62436
62437 if (calleeNode.type !== "FunctionExpression" && calleeNode.type !== "ArrowFunctionExpression") {
62438 if (calleeParent && calleeParent.loc.start.line < node.loc.start.line) {
62439 indent = getNodeIndent(calleeParent).goodChar;
62440 }
62441 } else {
62442 if (isArgBeforeCalleeNodeMultiline(calleeNode) && calleeParent.callee.loc.start.line === calleeParent.callee.loc.end.line && !isNodeFirstInLine(calleeNode)) {
62443 indent = getNodeIndent(calleeParent).goodChar;
62444 }
62445 }
62446 }
62447 /*
62448 * function body indent should be indent + indent size, unless this
62449 * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled.
62450 */
62451
62452
62453 let functionOffset = indentSize;
62454
62455 if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) {
62456 functionOffset = options.outerIIFEBody * indentSize;
62457 } else if (calleeNode.type === "FunctionExpression") {
62458 functionOffset = options.FunctionExpression.body * indentSize;
62459 } else if (calleeNode.type === "FunctionDeclaration") {
62460 functionOffset = options.FunctionDeclaration.body * indentSize;
62461 }
62462
62463 indent += functionOffset; // check if the node is inside a variable
62464
62465 const parentVarNode = getVariableDeclaratorNode(node);
62466
62467 if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) {
62468 indent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind];
62469 }
62470
62471 if (node.body.length > 0) {
62472 checkNodesIndent(node.body, indent);
62473 }
62474
62475 checkLastNodeLineIndent(node, indent - functionOffset);
62476 }
62477 /**
62478 * Checks if the given node starts and ends on the same line
62479 * @param {ASTNode} node The node to check
62480 * @returns {boolean} Whether or not the block starts and ends on the same line.
62481 */
62482
62483
62484 function isSingleLineNode(node) {
62485 const lastToken = sourceCode.getLastToken(node),
62486 startLine = node.loc.start.line,
62487 endLine = lastToken.loc.end.line;
62488 return startLine === endLine;
62489 }
62490 /**
62491 * Check indent for array block content or object block content
62492 * @param {ASTNode} node node to examine
62493 * @returns {void}
62494 */
62495
62496
62497 function checkIndentInArrayOrObjectBlock(node) {
62498 // Skip inline
62499 if (isSingleLineNode(node)) {
62500 return;
62501 }
62502
62503 let elements = node.type === "ArrayExpression" ? node.elements : node.properties; // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null
62504
62505 elements = elements.filter(elem => elem !== null);
62506 let nodeIndent;
62507 let elementsIndent;
62508 const parentVarNode = getVariableDeclaratorNode(node); // TODO - come up with a better strategy in future
62509
62510 if (isNodeFirstInLine(node)) {
62511 const parent = node.parent;
62512 nodeIndent = getNodeIndent(parent).goodChar;
62513
62514 if (!parentVarNode || parentVarNode.loc.start.line !== node.loc.start.line) {
62515 if (parent.type !== "VariableDeclarator" || parentVarNode === parentVarNode.parent.declarations[0]) {
62516 if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === parent.loc.start.line) {
62517 nodeIndent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind];
62518 } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") {
62519 const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements;
62520
62521 if (parentElements[0] && parentElements[0].loc.start.line === parent.loc.start.line && parentElements[0].loc.end.line !== parent.loc.start.line) {
62522 /*
62523 * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest.
62524 * e.g. [{
62525 * foo: 1
62526 * },
62527 * {
62528 * bar: 1
62529 * }]
62530 * the second object is not indented.
62531 */
62532 } else if (typeof options[parent.type] === "number") {
62533 nodeIndent += options[parent.type] * indentSize;
62534 } else {
62535 nodeIndent = parentElements[0].loc.start.column;
62536 }
62537 } else if (parent.type === "CallExpression" || parent.type === "NewExpression") {
62538 if (typeof options.CallExpression.arguments === "number") {
62539 nodeIndent += options.CallExpression.arguments * indentSize;
62540 } else if (options.CallExpression.arguments === "first") {
62541 if (parent.arguments.indexOf(node) !== -1) {
62542 nodeIndent = parent.arguments[0].loc.start.column;
62543 }
62544 } else {
62545 nodeIndent += indentSize;
62546 }
62547 } else if (parent.type === "LogicalExpression" || parent.type === "ArrowFunctionExpression") {
62548 nodeIndent += indentSize;
62549 }
62550 }
62551 }
62552
62553 checkFirstNodeLineIndent(node, nodeIndent);
62554 } else {
62555 nodeIndent = getNodeIndent(node).goodChar;
62556 }
62557
62558 if (options[node.type] === "first") {
62559 elementsIndent = elements.length ? elements[0].loc.start.column : 0; // If there are no elements, elementsIndent doesn't matter.
62560 } else {
62561 elementsIndent = nodeIndent + indentSize * options[node.type];
62562 }
62563 /*
62564 * Check if the node is a multiple variable declaration; if so, then
62565 * make sure indentation takes that into account.
62566 */
62567
62568
62569 if (isNodeInVarOnTop(node, parentVarNode)) {
62570 elementsIndent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind];
62571 }
62572
62573 checkNodesIndent(elements, elementsIndent);
62574
62575 if (elements.length > 0) {
62576 // Skip last block line check if last item in same line
62577 if (elements[elements.length - 1].loc.end.line === node.loc.end.line) {
62578 return;
62579 }
62580 }
62581
62582 checkLastNodeLineIndent(node, nodeIndent + (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0));
62583 }
62584 /**
62585 * Check if the node or node body is a BlockStatement or not
62586 * @param {ASTNode} node node to test
62587 * @returns {boolean} True if it or its body is a block statement
62588 */
62589
62590
62591 function isNodeBodyBlock(node) {
62592 return node.type === "BlockStatement" || node.type === "ClassBody" || node.body && node.body.type === "BlockStatement" || node.consequent && node.consequent.type === "BlockStatement";
62593 }
62594 /**
62595 * Check indentation for blocks
62596 * @param {ASTNode} node node to check
62597 * @returns {void}
62598 */
62599
62600
62601 function blockIndentationCheck(node) {
62602 // Skip inline blocks
62603 if (isSingleLineNode(node)) {
62604 return;
62605 }
62606
62607 if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "FunctionDeclaration" || node.parent.type === "ArrowFunctionExpression")) {
62608 checkIndentInFunctionBlock(node);
62609 return;
62610 }
62611
62612 let indent;
62613 let nodesToCheck = [];
62614 /*
62615 * For this statements we should check indent from statement beginning,
62616 * not from the beginning of the block.
62617 */
62618
62619 const statementsWithProperties = ["IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement"];
62620
62621 if (node.parent && statementsWithProperties.indexOf(node.parent.type) !== -1 && isNodeBodyBlock(node)) {
62622 indent = getNodeIndent(node.parent).goodChar;
62623 } else if (node.parent && node.parent.type === "CatchClause") {
62624 indent = getNodeIndent(node.parent.parent).goodChar;
62625 } else {
62626 indent = getNodeIndent(node).goodChar;
62627 }
62628
62629 if (node.type === "IfStatement" && node.consequent.type !== "BlockStatement") {
62630 nodesToCheck = [node.consequent];
62631 } else if (Array.isArray(node.body)) {
62632 nodesToCheck = node.body;
62633 } else {
62634 nodesToCheck = [node.body];
62635 }
62636
62637 if (nodesToCheck.length > 0) {
62638 checkNodesIndent(nodesToCheck, indent + indentSize);
62639 }
62640
62641 if (node.type === "BlockStatement") {
62642 checkLastNodeLineIndent(node, indent);
62643 }
62644 }
62645 /**
62646 * Filter out the elements which are on the same line of each other or the node.
62647 * basically have only 1 elements from each line except the variable declaration line.
62648 * @param {ASTNode} node Variable declaration node
62649 * @returns {ASTNode[]} Filtered elements
62650 */
62651
62652
62653 function filterOutSameLineVars(node) {
62654 return node.declarations.reduce((finalCollection, elem) => {
62655 const lastElem = finalCollection[finalCollection.length - 1];
62656
62657 if (elem.loc.start.line !== node.loc.start.line && !lastElem || lastElem && lastElem.loc.start.line !== elem.loc.start.line) {
62658 finalCollection.push(elem);
62659 }
62660
62661 return finalCollection;
62662 }, []);
62663 }
62664 /**
62665 * Check indentation for variable declarations
62666 * @param {ASTNode} node node to examine
62667 * @returns {void}
62668 */
62669
62670
62671 function checkIndentInVariableDeclarations(node) {
62672 const elements = filterOutSameLineVars(node);
62673 const nodeIndent = getNodeIndent(node).goodChar;
62674 const lastElement = elements[elements.length - 1];
62675 const elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind];
62676 checkNodesIndent(elements, elementsIndent); // Only check the last line if there is any token after the last item
62677
62678 if (sourceCode.getLastToken(node).loc.end.line <= lastElement.loc.end.line) {
62679 return;
62680 }
62681
62682 const tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement);
62683
62684 if (tokenBeforeLastElement.value === ",") {
62685 // Special case for comma-first syntax where the semicolon is indented
62686 checkLastNodeLineIndent(node, getNodeIndent(tokenBeforeLastElement).goodChar);
62687 } else {
62688 checkLastNodeLineIndent(node, elementsIndent - indentSize);
62689 }
62690 }
62691 /**
62692 * Check and decide whether to check for indentation for blockless nodes
62693 * Scenarios are for or while statements without braces around them
62694 * @param {ASTNode} node node to examine
62695 * @returns {void}
62696 */
62697
62698
62699 function blockLessNodes(node) {
62700 if (node.body.type !== "BlockStatement") {
62701 blockIndentationCheck(node);
62702 }
62703 }
62704 /**
62705 * Returns the expected indentation for the case statement
62706 * @param {ASTNode} node node to examine
62707 * @param {int} [providedSwitchIndent] indent for switch statement
62708 * @returns {int} indent size
62709 */
62710
62711
62712 function expectedCaseIndent(node, providedSwitchIndent) {
62713 const switchNode = node.type === "SwitchStatement" ? node : node.parent;
62714 const switchIndent = typeof providedSwitchIndent === "undefined" ? getNodeIndent(switchNode).goodChar : providedSwitchIndent;
62715 let caseIndent;
62716
62717 if (caseIndentStore[switchNode.loc.start.line]) {
62718 return caseIndentStore[switchNode.loc.start.line];
62719 }
62720
62721 if (switchNode.cases.length > 0 && options.SwitchCase === 0) {
62722 caseIndent = switchIndent;
62723 } else {
62724 caseIndent = switchIndent + indentSize * options.SwitchCase;
62725 }
62726
62727 caseIndentStore[switchNode.loc.start.line] = caseIndent;
62728 return caseIndent;
62729 }
62730 /**
62731 * Checks wether a return statement is wrapped in ()
62732 * @param {ASTNode} node node to examine
62733 * @returns {boolean} the result
62734 */
62735
62736
62737 function isWrappedInParenthesis(node) {
62738 const regex = /^return\s*?\(\s*?\);*?/u;
62739 const statementWithoutArgument = sourceCode.getText(node).replace(sourceCode.getText(node.argument), "");
62740 return regex.test(statementWithoutArgument);
62741 }
62742
62743 return {
62744 Program(node) {
62745 if (node.body.length > 0) {
62746 // Root nodes should have no indent
62747 checkNodesIndent(node.body, getNodeIndent(node).goodChar);
62748 }
62749 },
62750
62751 ClassBody: blockIndentationCheck,
62752 BlockStatement: blockIndentationCheck,
62753 WhileStatement: blockLessNodes,
62754 ForStatement: blockLessNodes,
62755 ForInStatement: blockLessNodes,
62756 ForOfStatement: blockLessNodes,
62757 DoWhileStatement: blockLessNodes,
62758
62759 IfStatement(node) {
62760 if (node.consequent.type !== "BlockStatement" && node.consequent.loc.start.line > node.loc.start.line) {
62761 blockIndentationCheck(node);
62762 }
62763 },
62764
62765 VariableDeclaration(node) {
62766 if (node.declarations[node.declarations.length - 1].loc.start.line > node.declarations[0].loc.start.line) {
62767 checkIndentInVariableDeclarations(node);
62768 }
62769 },
62770
62771 ObjectExpression(node) {
62772 checkIndentInArrayOrObjectBlock(node);
62773 },
62774
62775 ArrayExpression(node) {
62776 checkIndentInArrayOrObjectBlock(node);
62777 },
62778
62779 MemberExpression(node) {
62780 if (typeof options.MemberExpression === "undefined") {
62781 return;
62782 }
62783
62784 if (isSingleLineNode(node)) {
62785 return;
62786 }
62787 /*
62788 * The typical layout of variable declarations and assignments
62789 * alter the expectation of correct indentation. Skip them.
62790 * TODO: Add appropriate configuration options for variable
62791 * declarations and assignments.
62792 */
62793
62794
62795 if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) {
62796 return;
62797 }
62798
62799 if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) {
62800 return;
62801 }
62802
62803 const propertyIndent = getNodeIndent(node).goodChar + indentSize * options.MemberExpression;
62804 const checkNodes = [node.property];
62805 const dot = sourceCode.getTokenBefore(node.property);
62806
62807 if (dot.type === "Punctuator" && dot.value === ".") {
62808 checkNodes.push(dot);
62809 }
62810
62811 checkNodesIndent(checkNodes, propertyIndent);
62812 },
62813
62814 SwitchStatement(node) {
62815 // Switch is not a 'BlockStatement'
62816 const switchIndent = getNodeIndent(node).goodChar;
62817 const caseIndent = expectedCaseIndent(node, switchIndent);
62818 checkNodesIndent(node.cases, caseIndent);
62819 checkLastNodeLineIndent(node, switchIndent);
62820 },
62821
62822 SwitchCase(node) {
62823 // Skip inline cases
62824 if (isSingleLineNode(node)) {
62825 return;
62826 }
62827
62828 const caseIndent = expectedCaseIndent(node);
62829 checkNodesIndent(node.consequent, caseIndent + indentSize);
62830 },
62831
62832 FunctionDeclaration(node) {
62833 if (isSingleLineNode(node)) {
62834 return;
62835 }
62836
62837 if (options.FunctionDeclaration.parameters === "first" && node.params.length) {
62838 checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column);
62839 } else if (options.FunctionDeclaration.parameters !== null) {
62840 checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionDeclaration.parameters);
62841 }
62842 },
62843
62844 FunctionExpression(node) {
62845 if (isSingleLineNode(node)) {
62846 return;
62847 }
62848
62849 if (options.FunctionExpression.parameters === "first" && node.params.length) {
62850 checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column);
62851 } else if (options.FunctionExpression.parameters !== null) {
62852 checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionExpression.parameters);
62853 }
62854 },
62855
62856 ReturnStatement(node) {
62857 if (isSingleLineNode(node)) {
62858 return;
62859 }
62860
62861 const firstLineIndent = getNodeIndent(node).goodChar; // in case if return statement is wrapped in parenthesis
62862
62863 if (isWrappedInParenthesis(node)) {
62864 checkLastReturnStatementLineIndent(node, firstLineIndent);
62865 } else {
62866 checkNodeIndent(node, firstLineIndent);
62867 }
62868 },
62869
62870 CallExpression(node) {
62871 if (isSingleLineNode(node)) {
62872 return;
62873 }
62874
62875 if (options.CallExpression.arguments === "first" && node.arguments.length) {
62876 checkNodesIndent(node.arguments.slice(1), node.arguments[0].loc.start.column);
62877 } else if (options.CallExpression.arguments !== null) {
62878 checkNodesIndent(node.arguments, getNodeIndent(node).goodChar + indentSize * options.CallExpression.arguments);
62879 }
62880 }
62881
62882 };
62883 }
62884
62885};
62886
62887/***/ }),
62888/* 483 */
62889/***/ (function(module, exports, __webpack_require__) {
62890
62891"use strict";
62892/**
62893 * @fileoverview A rule to control the style of variable initializations.
62894 * @author Colin Ihrig
62895 */
62896 //------------------------------------------------------------------------------
62897// Helpers
62898//------------------------------------------------------------------------------
62899
62900/**
62901 * Checks whether or not a given node is a for loop.
62902 * @param {ASTNode} block A node to check.
62903 * @returns {boolean} `true` when the node is a for loop.
62904 */
62905
62906function isForLoop(block) {
62907 return block.type === "ForInStatement" || block.type === "ForOfStatement" || block.type === "ForStatement";
62908}
62909/**
62910 * Checks whether or not a given declarator node has its initializer.
62911 * @param {ASTNode} node A declarator node to check.
62912 * @returns {boolean} `true` when the node has its initializer.
62913 */
62914
62915
62916function isInitialized(node) {
62917 const declaration = node.parent;
62918 const block = declaration.parent;
62919
62920 if (isForLoop(block)) {
62921 if (block.type === "ForStatement") {
62922 return block.init === declaration;
62923 }
62924
62925 return block.left === declaration;
62926 }
62927
62928 return Boolean(node.init);
62929} //------------------------------------------------------------------------------
62930// Rule Definition
62931//------------------------------------------------------------------------------
62932
62933
62934module.exports = {
62935 meta: {
62936 type: "suggestion",
62937 docs: {
62938 description: "require or disallow initialization in variable declarations",
62939 category: "Variables",
62940 recommended: false,
62941 url: "https://eslint.org/docs/rules/init-declarations"
62942 },
62943 schema: {
62944 anyOf: [{
62945 type: "array",
62946 items: [{
62947 enum: ["always"]
62948 }],
62949 minItems: 0,
62950 maxItems: 1
62951 }, {
62952 type: "array",
62953 items: [{
62954 enum: ["never"]
62955 }, {
62956 type: "object",
62957 properties: {
62958 ignoreForLoopInit: {
62959 type: "boolean"
62960 }
62961 },
62962 additionalProperties: false
62963 }],
62964 minItems: 0,
62965 maxItems: 2
62966 }]
62967 },
62968 messages: {
62969 initialized: "Variable '{{idName}}' should be initialized on declaration.",
62970 notInitialized: "Variable '{{idName}}' should not be initialized on declaration."
62971 }
62972 },
62973
62974 create(context) {
62975 const MODE_ALWAYS = "always",
62976 MODE_NEVER = "never";
62977 const mode = context.options[0] || MODE_ALWAYS;
62978 const params = context.options[1] || {}; //--------------------------------------------------------------------------
62979 // Public API
62980 //--------------------------------------------------------------------------
62981
62982 return {
62983 "VariableDeclaration:exit"(node) {
62984 const kind = node.kind,
62985 declarations = node.declarations;
62986
62987 for (let i = 0; i < declarations.length; ++i) {
62988 const declaration = declarations[i],
62989 id = declaration.id,
62990 initialized = isInitialized(declaration),
62991 isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent);
62992 let messageId = "";
62993
62994 if (mode === MODE_ALWAYS && !initialized) {
62995 messageId = "initialized";
62996 } else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) {
62997 messageId = "notInitialized";
62998 }
62999
63000 if (id.type === "Identifier" && messageId) {
63001 context.report({
63002 node: declaration,
63003 messageId,
63004 data: {
63005 idName: id.name
63006 }
63007 });
63008 }
63009 }
63010 }
63011
63012 };
63013 }
63014
63015};
63016
63017/***/ }),
63018/* 484 */
63019/***/ (function(module, exports, __webpack_require__) {
63020
63021"use strict";
63022/**
63023 * @fileoverview A rule to ensure consistent quotes used in jsx syntax.
63024 * @author Mathias Schreck <https://github.com/lo1tuma>
63025 */
63026 //------------------------------------------------------------------------------
63027// Requirements
63028//------------------------------------------------------------------------------
63029
63030const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
63031// Constants
63032//------------------------------------------------------------------------------
63033
63034
63035const QUOTE_SETTINGS = {
63036 "prefer-double": {
63037 quote: "\"",
63038 description: "singlequote",
63039
63040 convert(str) {
63041 return str.replace(/'/gu, "\"");
63042 }
63043
63044 },
63045 "prefer-single": {
63046 quote: "'",
63047 description: "doublequote",
63048
63049 convert(str) {
63050 return str.replace(/"/gu, "'");
63051 }
63052
63053 }
63054}; //------------------------------------------------------------------------------
63055// Rule Definition
63056//------------------------------------------------------------------------------
63057
63058module.exports = {
63059 meta: {
63060 type: "layout",
63061 docs: {
63062 description: "enforce the consistent use of either double or single quotes in JSX attributes",
63063 category: "Stylistic Issues",
63064 recommended: false,
63065 url: "https://eslint.org/docs/rules/jsx-quotes"
63066 },
63067 fixable: "whitespace",
63068 schema: [{
63069 enum: ["prefer-single", "prefer-double"]
63070 }],
63071 messages: {
63072 unexpected: "Unexpected usage of {{description}}."
63073 }
63074 },
63075
63076 create(context) {
63077 const quoteOption = context.options[0] || "prefer-double",
63078 setting = QUOTE_SETTINGS[quoteOption];
63079 /**
63080 * Checks if the given string literal node uses the expected quotes
63081 * @param {ASTNode} node A string literal node.
63082 * @returns {boolean} Whether or not the string literal used the expected quotes.
63083 * @public
63084 */
63085
63086 function usesExpectedQuotes(node) {
63087 return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote);
63088 }
63089
63090 return {
63091 JSXAttribute(node) {
63092 const attributeValue = node.value;
63093
63094 if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) {
63095 context.report({
63096 node: attributeValue,
63097 messageId: "unexpected",
63098 data: {
63099 description: setting.description
63100 },
63101
63102 fix(fixer) {
63103 return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw));
63104 }
63105
63106 });
63107 }
63108 }
63109
63110 };
63111 }
63112
63113};
63114
63115/***/ }),
63116/* 485 */
63117/***/ (function(module, exports, __webpack_require__) {
63118
63119"use strict";
63120/**
63121 * @fileoverview Rule to specify spacing of object literal keys and values
63122 * @author Brandon Mills
63123 */
63124 //------------------------------------------------------------------------------
63125// Requirements
63126//------------------------------------------------------------------------------
63127
63128const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
63129// Helpers
63130//------------------------------------------------------------------------------
63131
63132/**
63133 * Checks whether a string contains a line terminator as defined in
63134 * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3
63135 * @param {string} str String to test.
63136 * @returns {boolean} True if str contains a line terminator.
63137 */
63138
63139
63140function containsLineTerminator(str) {
63141 return astUtils.LINEBREAK_MATCHER.test(str);
63142}
63143/**
63144 * Gets the last element of an array.
63145 * @param {Array} arr An array.
63146 * @returns {any} Last element of arr.
63147 */
63148
63149
63150function last(arr) {
63151 return arr[arr.length - 1];
63152}
63153/**
63154 * Checks whether a node is contained on a single line.
63155 * @param {ASTNode} node AST Node being evaluated.
63156 * @returns {boolean} True if the node is a single line.
63157 */
63158
63159
63160function isSingleLine(node) {
63161 return node.loc.end.line === node.loc.start.line;
63162}
63163/**
63164 * Checks whether the properties on a single line.
63165 * @param {ASTNode[]} properties List of Property AST nodes.
56c4a2cb 63166 * @returns {boolean} True if all properties is on a single line.
eb39fafa
DC
63167 */
63168
63169
63170function isSingleLineProperties(properties) {
63171 const [firstProp] = properties,
63172 lastProp = last(properties);
63173 return firstProp.loc.start.line === lastProp.loc.end.line;
63174}
63175/**
63176 * Initializes a single option property from the configuration with defaults for undefined values
63177 * @param {Object} toOptions Object to be initialized
63178 * @param {Object} fromOptions Object to be initialized from
63179 * @returns {Object} The object with correctly initialized options and values
63180 */
63181
63182
63183function initOptionProperty(toOptions, fromOptions) {
63184 toOptions.mode = fromOptions.mode || "strict"; // Set value of beforeColon
63185
63186 if (typeof fromOptions.beforeColon !== "undefined") {
63187 toOptions.beforeColon = +fromOptions.beforeColon;
63188 } else {
63189 toOptions.beforeColon = 0;
63190 } // Set value of afterColon
63191
63192
63193 if (typeof fromOptions.afterColon !== "undefined") {
63194 toOptions.afterColon = +fromOptions.afterColon;
63195 } else {
63196 toOptions.afterColon = 1;
63197 } // Set align if exists
63198
63199
63200 if (typeof fromOptions.align !== "undefined") {
63201 if (typeof fromOptions.align === "object") {
63202 toOptions.align = fromOptions.align;
63203 } else {
63204 // "string"
63205 toOptions.align = {
63206 on: fromOptions.align,
63207 mode: toOptions.mode,
63208 beforeColon: toOptions.beforeColon,
63209 afterColon: toOptions.afterColon
63210 };
63211 }
63212 }
63213
63214 return toOptions;
63215}
63216/**
63217 * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values
63218 * @param {Object} toOptions Object to be initialized
63219 * @param {Object} fromOptions Object to be initialized from
63220 * @returns {Object} The object with correctly initialized options and values
63221 */
63222
63223
63224function initOptions(toOptions, fromOptions) {
63225 if (typeof fromOptions.align === "object") {
63226 // Initialize the alignment configuration
63227 toOptions.align = initOptionProperty({}, fromOptions.align);
63228 toOptions.align.on = fromOptions.align.on || "colon";
63229 toOptions.align.mode = fromOptions.align.mode || "strict";
63230 toOptions.multiLine = initOptionProperty({}, fromOptions.multiLine || fromOptions);
63231 toOptions.singleLine = initOptionProperty({}, fromOptions.singleLine || fromOptions);
63232 } else {
63233 // string or undefined
63234 toOptions.multiLine = initOptionProperty({}, fromOptions.multiLine || fromOptions);
63235 toOptions.singleLine = initOptionProperty({}, fromOptions.singleLine || fromOptions); // If alignment options are defined in multiLine, pull them out into the general align configuration
63236
63237 if (toOptions.multiLine.align) {
63238 toOptions.align = {
63239 on: toOptions.multiLine.align.on,
63240 mode: toOptions.multiLine.align.mode || toOptions.multiLine.mode,
63241 beforeColon: toOptions.multiLine.align.beforeColon,
63242 afterColon: toOptions.multiLine.align.afterColon
63243 };
63244 }
63245 }
63246
63247 return toOptions;
63248} //------------------------------------------------------------------------------
63249// Rule Definition
63250//------------------------------------------------------------------------------
63251
63252
63253module.exports = {
63254 meta: {
63255 type: "layout",
63256 docs: {
63257 description: "enforce consistent spacing between keys and values in object literal properties",
63258 category: "Stylistic Issues",
63259 recommended: false,
63260 url: "https://eslint.org/docs/rules/key-spacing"
63261 },
63262 fixable: "whitespace",
63263 schema: [{
63264 anyOf: [{
63265 type: "object",
63266 properties: {
63267 align: {
63268 anyOf: [{
63269 enum: ["colon", "value"]
63270 }, {
63271 type: "object",
63272 properties: {
63273 mode: {
63274 enum: ["strict", "minimum"]
63275 },
63276 on: {
63277 enum: ["colon", "value"]
63278 },
63279 beforeColon: {
63280 type: "boolean"
63281 },
63282 afterColon: {
63283 type: "boolean"
63284 }
63285 },
63286 additionalProperties: false
63287 }]
63288 },
63289 mode: {
63290 enum: ["strict", "minimum"]
63291 },
63292 beforeColon: {
63293 type: "boolean"
63294 },
63295 afterColon: {
63296 type: "boolean"
63297 }
63298 },
63299 additionalProperties: false
63300 }, {
63301 type: "object",
63302 properties: {
63303 singleLine: {
63304 type: "object",
63305 properties: {
63306 mode: {
63307 enum: ["strict", "minimum"]
63308 },
63309 beforeColon: {
63310 type: "boolean"
63311 },
63312 afterColon: {
63313 type: "boolean"
63314 }
63315 },
63316 additionalProperties: false
63317 },
63318 multiLine: {
63319 type: "object",
63320 properties: {
63321 align: {
63322 anyOf: [{
63323 enum: ["colon", "value"]
63324 }, {
63325 type: "object",
63326 properties: {
63327 mode: {
63328 enum: ["strict", "minimum"]
63329 },
63330 on: {
63331 enum: ["colon", "value"]
63332 },
63333 beforeColon: {
63334 type: "boolean"
63335 },
63336 afterColon: {
63337 type: "boolean"
63338 }
63339 },
63340 additionalProperties: false
63341 }]
63342 },
63343 mode: {
63344 enum: ["strict", "minimum"]
63345 },
63346 beforeColon: {
63347 type: "boolean"
63348 },
63349 afterColon: {
63350 type: "boolean"
63351 }
63352 },
63353 additionalProperties: false
63354 }
63355 },
63356 additionalProperties: false
63357 }, {
63358 type: "object",
63359 properties: {
63360 singleLine: {
63361 type: "object",
63362 properties: {
63363 mode: {
63364 enum: ["strict", "minimum"]
63365 },
63366 beforeColon: {
63367 type: "boolean"
63368 },
63369 afterColon: {
63370 type: "boolean"
63371 }
63372 },
63373 additionalProperties: false
63374 },
63375 multiLine: {
63376 type: "object",
63377 properties: {
63378 mode: {
63379 enum: ["strict", "minimum"]
63380 },
63381 beforeColon: {
63382 type: "boolean"
63383 },
63384 afterColon: {
63385 type: "boolean"
63386 }
63387 },
63388 additionalProperties: false
63389 },
63390 align: {
63391 type: "object",
63392 properties: {
63393 mode: {
63394 enum: ["strict", "minimum"]
63395 },
63396 on: {
63397 enum: ["colon", "value"]
63398 },
63399 beforeColon: {
63400 type: "boolean"
63401 },
63402 afterColon: {
63403 type: "boolean"
63404 }
63405 },
63406 additionalProperties: false
63407 }
63408 },
63409 additionalProperties: false
63410 }]
63411 }],
63412 messages: {
63413 extraKey: "Extra space after {{computed}}key '{{key}}'.",
63414 extraValue: "Extra space before value for {{computed}}key '{{key}}'.",
63415 missingKey: "Missing space after {{computed}}key '{{key}}'.",
63416 missingValue: "Missing space before value for {{computed}}key '{{key}}'."
63417 }
63418 },
63419
63420 create(context) {
63421 /**
63422 * OPTIONS
63423 * "key-spacing": [2, {
63424 * beforeColon: false,
63425 * afterColon: true,
63426 * align: "colon" // Optional, or "value"
63427 * }
63428 */
63429 const options = context.options[0] || {},
63430 ruleOptions = initOptions({}, options),
63431 multiLineOptions = ruleOptions.multiLine,
63432 singleLineOptions = ruleOptions.singleLine,
63433 alignmentOptions = ruleOptions.align || null;
63434 const sourceCode = context.getSourceCode();
63435 /**
63436 * Checks whether a property is a member of the property group it follows.
63437 * @param {ASTNode} lastMember The last Property known to be in the group.
63438 * @param {ASTNode} candidate The next Property that might be in the group.
63439 * @returns {boolean} True if the candidate property is part of the group.
63440 */
63441
63442 function continuesPropertyGroup(lastMember, candidate) {
63443 const groupEndLine = lastMember.loc.start.line,
63444 candidateStartLine = candidate.loc.start.line;
63445
63446 if (candidateStartLine - groupEndLine <= 1) {
63447 return true;
63448 }
63449 /*
63450 * Check that the first comment is adjacent to the end of the group, the
63451 * last comment is adjacent to the candidate property, and that successive
63452 * comments are adjacent to each other.
63453 */
63454
63455
63456 const leadingComments = sourceCode.getCommentsBefore(candidate);
63457
63458 if (leadingComments.length && leadingComments[0].loc.start.line - groupEndLine <= 1 && candidateStartLine - last(leadingComments).loc.end.line <= 1) {
63459 for (let i = 1; i < leadingComments.length; i++) {
63460 if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) {
63461 return false;
63462 }
63463 }
63464
63465 return true;
63466 }
63467
63468 return false;
63469 }
63470 /**
63471 * Determines if the given property is key-value property.
63472 * @param {ASTNode} property Property node to check.
63473 * @returns {boolean} Whether the property is a key-value property.
63474 */
63475
63476
63477 function isKeyValueProperty(property) {
63478 return !(property.method || property.shorthand || property.kind !== "init" || property.type !== "Property");
63479 }
63480 /**
63481 * Starting from the given a node (a property.key node here) looks forward
63482 * until it finds the last token before a colon punctuator and returns it.
63483 * @param {ASTNode} node The node to start looking from.
63484 * @returns {ASTNode} The last token before a colon punctuator.
63485 */
63486
63487
63488 function getLastTokenBeforeColon(node) {
63489 const colonToken = sourceCode.getTokenAfter(node, astUtils.isColonToken);
63490 return sourceCode.getTokenBefore(colonToken);
63491 }
63492 /**
63493 * Starting from the given a node (a property.key node here) looks forward
63494 * until it finds the colon punctuator and returns it.
63495 * @param {ASTNode} node The node to start looking from.
63496 * @returns {ASTNode} The colon punctuator.
63497 */
63498
63499
63500 function getNextColon(node) {
63501 return sourceCode.getTokenAfter(node, astUtils.isColonToken);
63502 }
63503 /**
63504 * Gets an object literal property's key as the identifier name or string value.
63505 * @param {ASTNode} property Property node whose key to retrieve.
63506 * @returns {string} The property's key.
63507 */
63508
63509
63510 function getKey(property) {
63511 const key = property.key;
63512
63513 if (property.computed) {
63514 return sourceCode.getText().slice(key.range[0], key.range[1]);
63515 }
63516
63517 return astUtils.getStaticPropertyName(property);
63518 }
63519 /**
63520 * Reports an appropriately-formatted error if spacing is incorrect on one
63521 * side of the colon.
63522 * @param {ASTNode} property Key-value pair in an object literal.
63523 * @param {string} side Side being verified - either "key" or "value".
63524 * @param {string} whitespace Actual whitespace string.
63525 * @param {int} expected Expected whitespace length.
63526 * @param {string} mode Value of the mode as "strict" or "minimum"
63527 * @returns {void}
63528 */
63529
63530
63531 function report(property, side, whitespace, expected, mode) {
63532 const diff = whitespace.length - expected,
63533 nextColon = getNextColon(property.key),
63534 tokenBeforeColon = sourceCode.getTokenBefore(nextColon, {
63535 includeComments: true
63536 }),
63537 tokenAfterColon = sourceCode.getTokenAfter(nextColon, {
63538 includeComments: true
63539 }),
63540 isKeySide = side === "key",
63541 locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start,
63542 isExtra = diff > 0,
63543 diffAbs = Math.abs(diff),
63544 spaces = Array(diffAbs + 1).join(" ");
63545
63546 if ((diff && mode === "strict" || diff < 0 && mode === "minimum" || diff > 0 && !expected && mode === "minimum") && !(expected && containsLineTerminator(whitespace))) {
63547 let fix;
63548
63549 if (isExtra) {
63550 let range; // Remove whitespace
63551
63552 if (isKeySide) {
63553 range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs];
63554 } else {
63555 range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]];
63556 }
63557
63558 fix = function fix(fixer) {
63559 return fixer.removeRange(range);
63560 };
63561 } else {
63562 // Add whitespace
63563 if (isKeySide) {
63564 fix = function fix(fixer) {
63565 return fixer.insertTextAfter(tokenBeforeColon, spaces);
63566 };
63567 } else {
63568 fix = function fix(fixer) {
63569 return fixer.insertTextBefore(tokenAfterColon, spaces);
63570 };
63571 }
63572 }
63573
63574 let messageId = "";
63575
63576 if (isExtra) {
63577 messageId = side === "key" ? "extraKey" : "extraValue";
63578 } else {
63579 messageId = side === "key" ? "missingKey" : "missingValue";
63580 }
63581
63582 context.report({
63583 node: property[side],
63584 loc: locStart,
63585 messageId,
63586 data: {
63587 computed: property.computed ? "computed " : "",
63588 key: getKey(property)
63589 },
63590 fix
63591 });
63592 }
63593 }
63594 /**
63595 * Gets the number of characters in a key, including quotes around string
63596 * keys and braces around computed property keys.
63597 * @param {ASTNode} property Property of on object literal.
63598 * @returns {int} Width of the key.
63599 */
63600
63601
63602 function getKeyWidth(property) {
63603 const startToken = sourceCode.getFirstToken(property);
63604 const endToken = getLastTokenBeforeColon(property.key);
63605 return endToken.range[1] - startToken.range[0];
63606 }
63607 /**
63608 * Gets the whitespace around the colon in an object literal property.
63609 * @param {ASTNode} property Property node from an object literal.
63610 * @returns {Object} Whitespace before and after the property's colon.
63611 */
63612
63613
63614 function getPropertyWhitespace(property) {
63615 const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice(property.key.range[1], property.value.range[0]));
63616
63617 if (whitespace) {
63618 return {
63619 beforeColon: whitespace[1],
63620 afterColon: whitespace[2]
63621 };
63622 }
63623
63624 return null;
63625 }
63626 /**
63627 * Creates groups of properties.
63628 * @param {ASTNode} node ObjectExpression node being evaluated.
63629 * @returns {Array.<ASTNode[]>} Groups of property AST node lists.
63630 */
63631
63632
63633 function createGroups(node) {
63634 if (node.properties.length === 1) {
63635 return [node.properties];
63636 }
63637
63638 return node.properties.reduce((groups, property) => {
63639 const currentGroup = last(groups),
63640 prev = last(currentGroup);
63641
63642 if (!prev || continuesPropertyGroup(prev, property)) {
63643 currentGroup.push(property);
63644 } else {
63645 groups.push([property]);
63646 }
63647
63648 return groups;
63649 }, [[]]);
63650 }
63651 /**
63652 * Verifies correct vertical alignment of a group of properties.
63653 * @param {ASTNode[]} properties List of Property AST nodes.
63654 * @returns {void}
63655 */
63656
63657
63658 function verifyGroupAlignment(properties) {
63659 const length = properties.length,
63660 widths = properties.map(getKeyWidth),
63661 // Width of keys, including quotes
63662 align = alignmentOptions.on; // "value" or "colon"
63663
63664 let targetWidth = Math.max(...widths),
63665 beforeColon,
63666 afterColon,
63667 mode;
63668
63669 if (alignmentOptions && length > 1) {
63670 // When aligning values within a group, use the alignment configuration.
63671 beforeColon = alignmentOptions.beforeColon;
63672 afterColon = alignmentOptions.afterColon;
63673 mode = alignmentOptions.mode;
63674 } else {
63675 beforeColon = multiLineOptions.beforeColon;
63676 afterColon = multiLineOptions.afterColon;
63677 mode = alignmentOptions.mode;
63678 } // Conditionally include one space before or after colon
63679
63680
63681 targetWidth += align === "colon" ? beforeColon : afterColon;
63682
63683 for (let i = 0; i < length; i++) {
63684 const property = properties[i];
63685 const whitespace = getPropertyWhitespace(property);
63686
63687 if (whitespace) {
63688 // Object literal getters/setters lack a colon
63689 const width = widths[i];
63690
63691 if (align === "value") {
63692 report(property, "key", whitespace.beforeColon, beforeColon, mode);
63693 report(property, "value", whitespace.afterColon, targetWidth - width, mode);
63694 } else {
63695 // align = "colon"
63696 report(property, "key", whitespace.beforeColon, targetWidth - width, mode);
63697 report(property, "value", whitespace.afterColon, afterColon, mode);
63698 }
63699 }
63700 }
63701 }
63702 /**
63703 * Verifies spacing of property conforms to specified options.
63704 * @param {ASTNode} node Property node being evaluated.
63705 * @param {Object} lineOptions Configured singleLine or multiLine options
63706 * @returns {void}
63707 */
63708
63709
63710 function verifySpacing(node, lineOptions) {
63711 const actual = getPropertyWhitespace(node);
63712
63713 if (actual) {
63714 // Object literal getters/setters lack colons
63715 report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode);
63716 report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode);
63717 }
63718 }
63719 /**
63720 * Verifies spacing of each property in a list.
63721 * @param {ASTNode[]} properties List of Property AST nodes.
63722 * @param {Object} lineOptions Configured singleLine or multiLine options
63723 * @returns {void}
63724 */
63725
63726
63727 function verifyListSpacing(properties, lineOptions) {
63728 const length = properties.length;
63729
63730 for (let i = 0; i < length; i++) {
63731 verifySpacing(properties[i], lineOptions);
63732 }
63733 }
63734 /**
63735 * Verifies vertical alignment, taking into account groups of properties.
63736 * @param {ASTNode} node ObjectExpression node being evaluated.
63737 * @returns {void}
63738 */
63739
63740
63741 function verifyAlignment(node) {
63742 createGroups(node).forEach(group => {
63743 const properties = group.filter(isKeyValueProperty);
63744
63745 if (properties.length > 0 && isSingleLineProperties(properties)) {
63746 verifyListSpacing(properties, multiLineOptions);
63747 } else {
63748 verifyGroupAlignment(properties);
63749 }
63750 });
63751 } //--------------------------------------------------------------------------
63752 // Public API
63753 //--------------------------------------------------------------------------
63754
63755
63756 if (alignmentOptions) {
63757 // Verify vertical alignment
63758 return {
63759 ObjectExpression(node) {
63760 if (isSingleLine(node)) {
63761 verifyListSpacing(node.properties.filter(isKeyValueProperty), singleLineOptions);
63762 } else {
63763 verifyAlignment(node);
63764 }
63765 }
63766
63767 };
63768 } // Obey beforeColon and afterColon in each property as configured
63769
63770
63771 return {
63772 Property(node) {
63773 verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions);
63774 }
63775
63776 };
63777 }
63778
63779};
63780
63781/***/ }),
63782/* 486 */
63783/***/ (function(module, exports, __webpack_require__) {
63784
63785"use strict";
63786/**
63787 * @fileoverview Rule to enforce spacing before and after keywords.
63788 * @author Toru Nagashima
63789 */
63790 //------------------------------------------------------------------------------
63791// Requirements
63792//------------------------------------------------------------------------------
63793
63794const astUtils = __webpack_require__(426),
63795 keywords = __webpack_require__(460); //------------------------------------------------------------------------------
63796// Constants
63797//------------------------------------------------------------------------------
63798
63799
63800const PREV_TOKEN = /^[)\]}>]$/u;
63801const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u;
63802const PREV_TOKEN_M = /^[)\]}>*]$/u;
63803const NEXT_TOKEN_M = /^[{*]$/u;
63804const TEMPLATE_OPEN_PAREN = /\$\{$/u;
63805const TEMPLATE_CLOSE_PAREN = /^\}/u;
63806const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/u;
63807const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]); // check duplications.
63808
63809(function () {
63810 KEYS.sort();
63811
63812 for (let i = 1; i < KEYS.length; ++i) {
63813 if (KEYS[i] === KEYS[i - 1]) {
63814 throw new Error("Duplication was found in the keyword list: ".concat(KEYS[i]));
63815 }
63816 }
63817})(); //------------------------------------------------------------------------------
63818// Helpers
63819//------------------------------------------------------------------------------
63820
63821/**
63822 * Checks whether or not a given token is a "Template" token ends with "${".
63823 * @param {Token} token A token to check.
63824 * @returns {boolean} `true` if the token is a "Template" token ends with "${".
63825 */
63826
63827
63828function isOpenParenOfTemplate(token) {
63829 return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value);
63830}
63831/**
63832 * Checks whether or not a given token is a "Template" token starts with "}".
63833 * @param {Token} token A token to check.
63834 * @returns {boolean} `true` if the token is a "Template" token starts with "}".
63835 */
63836
63837
63838function isCloseParenOfTemplate(token) {
63839 return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value);
63840} //------------------------------------------------------------------------------
63841// Rule Definition
63842//------------------------------------------------------------------------------
63843
63844
63845module.exports = {
63846 meta: {
63847 type: "layout",
63848 docs: {
63849 description: "enforce consistent spacing before and after keywords",
63850 category: "Stylistic Issues",
63851 recommended: false,
63852 url: "https://eslint.org/docs/rules/keyword-spacing"
63853 },
63854 fixable: "whitespace",
63855 schema: [{
63856 type: "object",
63857 properties: {
63858 before: {
63859 type: "boolean",
63860 default: true
63861 },
63862 after: {
63863 type: "boolean",
63864 default: true
63865 },
63866 overrides: {
63867 type: "object",
63868 properties: KEYS.reduce((retv, key) => {
63869 retv[key] = {
63870 type: "object",
63871 properties: {
63872 before: {
63873 type: "boolean"
63874 },
63875 after: {
63876 type: "boolean"
63877 }
63878 },
63879 additionalProperties: false
63880 };
63881 return retv;
63882 }, {}),
63883 additionalProperties: false
63884 }
63885 },
63886 additionalProperties: false
63887 }],
63888 messages: {
63889 expectedBefore: "Expected space(s) before \"{{value}}\".",
63890 expectedAfter: "Expected space(s) after \"{{value}}\".",
63891 unexpectedBefore: "Unexpected space(s) before \"{{value}}\".",
63892 unexpectedAfter: "Unexpected space(s) after \"{{value}}\"."
63893 }
63894 },
63895
63896 create(context) {
63897 const sourceCode = context.getSourceCode();
63898 /**
63899 * Reports a given token if there are not space(s) before the token.
63900 * @param {Token} token A token to report.
63901 * @param {RegExp} pattern A pattern of the previous token to check.
63902 * @returns {void}
63903 */
63904
63905 function expectSpaceBefore(token, pattern) {
63906 const prevToken = sourceCode.getTokenBefore(token);
63907
63908 if (prevToken && (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && !isOpenParenOfTemplate(prevToken) && astUtils.isTokenOnSameLine(prevToken, token) && !sourceCode.isSpaceBetweenTokens(prevToken, token)) {
63909 context.report({
63910 loc: token.loc.start,
63911 messageId: "expectedBefore",
63912 data: token,
63913
63914 fix(fixer) {
63915 return fixer.insertTextBefore(token, " ");
63916 }
63917
63918 });
63919 }
63920 }
63921 /**
63922 * Reports a given token if there are space(s) before the token.
63923 * @param {Token} token A token to report.
63924 * @param {RegExp} pattern A pattern of the previous token to check.
63925 * @returns {void}
63926 */
63927
63928
63929 function unexpectSpaceBefore(token, pattern) {
63930 const prevToken = sourceCode.getTokenBefore(token);
63931
63932 if (prevToken && (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && !isOpenParenOfTemplate(prevToken) && astUtils.isTokenOnSameLine(prevToken, token) && sourceCode.isSpaceBetweenTokens(prevToken, token)) {
63933 context.report({
63934 loc: token.loc.start,
63935 messageId: "unexpectedBefore",
63936 data: token,
63937
63938 fix(fixer) {
63939 return fixer.removeRange([prevToken.range[1], token.range[0]]);
63940 }
63941
63942 });
63943 }
63944 }
63945 /**
63946 * Reports a given token if there are not space(s) after the token.
63947 * @param {Token} token A token to report.
63948 * @param {RegExp} pattern A pattern of the next token to check.
63949 * @returns {void}
63950 */
63951
63952
63953 function expectSpaceAfter(token, pattern) {
63954 const nextToken = sourceCode.getTokenAfter(token);
63955
63956 if (nextToken && (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && !isCloseParenOfTemplate(nextToken) && astUtils.isTokenOnSameLine(token, nextToken) && !sourceCode.isSpaceBetweenTokens(token, nextToken)) {
63957 context.report({
63958 loc: token.loc.start,
63959 messageId: "expectedAfter",
63960 data: token,
63961
63962 fix(fixer) {
63963 return fixer.insertTextAfter(token, " ");
63964 }
63965
63966 });
63967 }
63968 }
63969 /**
63970 * Reports a given token if there are space(s) after the token.
63971 * @param {Token} token A token to report.
63972 * @param {RegExp} pattern A pattern of the next token to check.
63973 * @returns {void}
63974 */
63975
63976
63977 function unexpectSpaceAfter(token, pattern) {
63978 const nextToken = sourceCode.getTokenAfter(token);
63979
63980 if (nextToken && (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && !isCloseParenOfTemplate(nextToken) && astUtils.isTokenOnSameLine(token, nextToken) && sourceCode.isSpaceBetweenTokens(token, nextToken)) {
63981 context.report({
63982 loc: token.loc.start,
63983 messageId: "unexpectedAfter",
63984 data: token,
63985
63986 fix(fixer) {
63987 return fixer.removeRange([token.range[1], nextToken.range[0]]);
63988 }
63989
63990 });
63991 }
63992 }
63993 /**
63994 * Parses the option object and determines check methods for each keyword.
63995 * @param {Object|undefined} options The option object to parse.
63996 * @returns {Object} - Normalized option object.
63997 * Keys are keywords (there are for every keyword).
63998 * Values are instances of `{"before": function, "after": function}`.
63999 */
64000
64001
64002 function parseOptions(options = {}) {
64003 const before = options.before !== false;
64004 const after = options.after !== false;
64005 const defaultValue = {
64006 before: before ? expectSpaceBefore : unexpectSpaceBefore,
64007 after: after ? expectSpaceAfter : unexpectSpaceAfter
64008 };
64009 const overrides = options && options.overrides || {};
64010 const retv = Object.create(null);
64011
64012 for (let i = 0; i < KEYS.length; ++i) {
64013 const key = KEYS[i];
64014 const override = overrides[key];
64015
64016 if (override) {
64017 const thisBefore = "before" in override ? override.before : before;
64018 const thisAfter = "after" in override ? override.after : after;
64019 retv[key] = {
64020 before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore,
64021 after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter
64022 };
64023 } else {
64024 retv[key] = defaultValue;
64025 }
64026 }
64027
64028 return retv;
64029 }
64030
64031 const checkMethodMap = parseOptions(context.options[0]);
64032 /**
64033 * Reports a given token if usage of spacing followed by the token is
64034 * invalid.
64035 * @param {Token} token A token to report.
64036 * @param {RegExp} [pattern] Optional. A pattern of the previous
64037 * token to check.
64038 * @returns {void}
64039 */
64040
64041 function checkSpacingBefore(token, pattern) {
64042 checkMethodMap[token.value].before(token, pattern || PREV_TOKEN);
64043 }
64044 /**
64045 * Reports a given token if usage of spacing preceded by the token is
64046 * invalid.
64047 * @param {Token} token A token to report.
64048 * @param {RegExp} [pattern] Optional. A pattern of the next
64049 * token to check.
64050 * @returns {void}
64051 */
64052
64053
64054 function checkSpacingAfter(token, pattern) {
64055 checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN);
64056 }
64057 /**
64058 * Reports a given token if usage of spacing around the token is invalid.
64059 * @param {Token} token A token to report.
64060 * @returns {void}
64061 */
64062
64063
64064 function checkSpacingAround(token) {
64065 checkSpacingBefore(token);
64066 checkSpacingAfter(token);
64067 }
64068 /**
64069 * Reports the first token of a given node if the first token is a keyword
64070 * and usage of spacing around the token is invalid.
64071 * @param {ASTNode|null} node A node to report.
64072 * @returns {void}
64073 */
64074
64075
64076 function checkSpacingAroundFirstToken(node) {
64077 const firstToken = node && sourceCode.getFirstToken(node);
64078
64079 if (firstToken && firstToken.type === "Keyword") {
64080 checkSpacingAround(firstToken);
64081 }
64082 }
64083 /**
64084 * Reports the first token of a given node if the first token is a keyword
64085 * and usage of spacing followed by the token is invalid.
64086 *
64087 * This is used for unary operators (e.g. `typeof`), `function`, and `super`.
64088 * Other rules are handling usage of spacing preceded by those keywords.
64089 * @param {ASTNode|null} node A node to report.
64090 * @returns {void}
64091 */
64092
64093
64094 function checkSpacingBeforeFirstToken(node) {
64095 const firstToken = node && sourceCode.getFirstToken(node);
64096
64097 if (firstToken && firstToken.type === "Keyword") {
64098 checkSpacingBefore(firstToken);
64099 }
64100 }
64101 /**
64102 * Reports the previous token of a given node if the token is a keyword and
64103 * usage of spacing around the token is invalid.
64104 * @param {ASTNode|null} node A node to report.
64105 * @returns {void}
64106 */
64107
64108
64109 function checkSpacingAroundTokenBefore(node) {
64110 if (node) {
64111 const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken);
64112 checkSpacingAround(token);
64113 }
64114 }
64115 /**
64116 * Reports `async` or `function` keywords of a given node if usage of
64117 * spacing around those keywords is invalid.
64118 * @param {ASTNode} node A node to report.
64119 * @returns {void}
64120 */
64121
64122
64123 function checkSpacingForFunction(node) {
64124 const firstToken = node && sourceCode.getFirstToken(node);
64125
64126 if (firstToken && (firstToken.type === "Keyword" && firstToken.value === "function" || firstToken.value === "async")) {
64127 checkSpacingBefore(firstToken);
64128 }
64129 }
64130 /**
64131 * Reports `class` and `extends` keywords of a given node if usage of
64132 * spacing around those keywords is invalid.
64133 * @param {ASTNode} node A node to report.
64134 * @returns {void}
64135 */
64136
64137
64138 function checkSpacingForClass(node) {
64139 checkSpacingAroundFirstToken(node);
64140 checkSpacingAroundTokenBefore(node.superClass);
64141 }
64142 /**
64143 * Reports `if` and `else` keywords of a given node if usage of spacing
64144 * around those keywords is invalid.
64145 * @param {ASTNode} node A node to report.
64146 * @returns {void}
64147 */
64148
64149
64150 function checkSpacingForIfStatement(node) {
64151 checkSpacingAroundFirstToken(node);
64152 checkSpacingAroundTokenBefore(node.alternate);
64153 }
64154 /**
64155 * Reports `try`, `catch`, and `finally` keywords of a given node if usage
64156 * of spacing around those keywords is invalid.
64157 * @param {ASTNode} node A node to report.
64158 * @returns {void}
64159 */
64160
64161
64162 function checkSpacingForTryStatement(node) {
64163 checkSpacingAroundFirstToken(node);
64164 checkSpacingAroundFirstToken(node.handler);
64165 checkSpacingAroundTokenBefore(node.finalizer);
64166 }
64167 /**
64168 * Reports `do` and `while` keywords of a given node if usage of spacing
64169 * around those keywords is invalid.
64170 * @param {ASTNode} node A node to report.
64171 * @returns {void}
64172 */
64173
64174
64175 function checkSpacingForDoWhileStatement(node) {
64176 checkSpacingAroundFirstToken(node);
64177 checkSpacingAroundTokenBefore(node.test);
64178 }
64179 /**
64180 * Reports `for` and `in` keywords of a given node if usage of spacing
64181 * around those keywords is invalid.
64182 * @param {ASTNode} node A node to report.
64183 * @returns {void}
64184 */
64185
64186
64187 function checkSpacingForForInStatement(node) {
64188 checkSpacingAroundFirstToken(node);
64189 checkSpacingAroundTokenBefore(node.right);
64190 }
64191 /**
64192 * Reports `for` and `of` keywords of a given node if usage of spacing
64193 * around those keywords is invalid.
64194 * @param {ASTNode} node A node to report.
64195 * @returns {void}
64196 */
64197
64198
64199 function checkSpacingForForOfStatement(node) {
64200 if (node.await) {
64201 checkSpacingBefore(sourceCode.getFirstToken(node, 0));
64202 checkSpacingAfter(sourceCode.getFirstToken(node, 1));
64203 } else {
64204 checkSpacingAroundFirstToken(node);
64205 }
64206
64207 checkSpacingAround(sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken));
64208 }
64209 /**
64210 * Reports `import`, `export`, `as`, and `from` keywords of a given node if
64211 * usage of spacing around those keywords is invalid.
64212 *
64213 * This rule handles the `*` token in module declarations.
64214 *
64215 * import*as A from "./a"; /*error Expected space(s) after "import".
64216 * error Expected space(s) before "as".
64217 * @param {ASTNode} node A node to report.
64218 * @returns {void}
64219 */
64220
64221
64222 function checkSpacingForModuleDeclaration(node) {
64223 const firstToken = sourceCode.getFirstToken(node);
64224 checkSpacingBefore(firstToken, PREV_TOKEN_M);
64225 checkSpacingAfter(firstToken, NEXT_TOKEN_M);
64226
64227 if (node.type === "ExportDefaultDeclaration") {
64228 checkSpacingAround(sourceCode.getTokenAfter(firstToken));
64229 }
64230
64231 if (node.source) {
64232 const fromToken = sourceCode.getTokenBefore(node.source);
64233 checkSpacingBefore(fromToken, PREV_TOKEN_M);
64234 checkSpacingAfter(fromToken, NEXT_TOKEN_M);
64235 }
64236 }
64237 /**
64238 * Reports `as` keyword of a given node if usage of spacing around this
64239 * keyword is invalid.
64240 * @param {ASTNode} node A node to report.
64241 * @returns {void}
64242 */
64243
64244
64245 function checkSpacingForImportNamespaceSpecifier(node) {
64246 const asToken = sourceCode.getFirstToken(node, 1);
64247 checkSpacingBefore(asToken, PREV_TOKEN_M);
64248 }
64249 /**
64250 * Reports `static`, `get`, and `set` keywords of a given node if usage of
64251 * spacing around those keywords is invalid.
64252 * @param {ASTNode} node A node to report.
64253 * @returns {void}
64254 */
64255
64256
64257 function checkSpacingForProperty(node) {
64258 if (node.static) {
64259 checkSpacingAroundFirstToken(node);
64260 }
64261
64262 if (node.kind === "get" || node.kind === "set" || (node.method || node.type === "MethodDefinition") && node.value.async) {
64263 const token = sourceCode.getTokenBefore(node.key, tok => {
64264 switch (tok.value) {
64265 case "get":
64266 case "set":
64267 case "async":
64268 return true;
64269
64270 default:
64271 return false;
64272 }
64273 });
64274
64275 if (!token) {
64276 throw new Error("Failed to find token get, set, or async beside method name");
64277 }
64278
64279 checkSpacingAround(token);
64280 }
64281 }
64282 /**
64283 * Reports `await` keyword of a given node if usage of spacing before
64284 * this keyword is invalid.
64285 * @param {ASTNode} node A node to report.
64286 * @returns {void}
64287 */
64288
64289
64290 function checkSpacingForAwaitExpression(node) {
64291 checkSpacingBefore(sourceCode.getFirstToken(node));
64292 }
64293
64294 return {
64295 // Statements
64296 DebuggerStatement: checkSpacingAroundFirstToken,
64297 WithStatement: checkSpacingAroundFirstToken,
64298 // Statements - Control flow
64299 BreakStatement: checkSpacingAroundFirstToken,
64300 ContinueStatement: checkSpacingAroundFirstToken,
64301 ReturnStatement: checkSpacingAroundFirstToken,
64302 ThrowStatement: checkSpacingAroundFirstToken,
64303 TryStatement: checkSpacingForTryStatement,
64304 // Statements - Choice
64305 IfStatement: checkSpacingForIfStatement,
64306 SwitchStatement: checkSpacingAroundFirstToken,
64307 SwitchCase: checkSpacingAroundFirstToken,
64308 // Statements - Loops
64309 DoWhileStatement: checkSpacingForDoWhileStatement,
64310 ForInStatement: checkSpacingForForInStatement,
64311 ForOfStatement: checkSpacingForForOfStatement,
64312 ForStatement: checkSpacingAroundFirstToken,
64313 WhileStatement: checkSpacingAroundFirstToken,
64314 // Statements - Declarations
64315 ClassDeclaration: checkSpacingForClass,
64316 ExportNamedDeclaration: checkSpacingForModuleDeclaration,
64317 ExportDefaultDeclaration: checkSpacingForModuleDeclaration,
64318 ExportAllDeclaration: checkSpacingForModuleDeclaration,
64319 FunctionDeclaration: checkSpacingForFunction,
64320 ImportDeclaration: checkSpacingForModuleDeclaration,
64321 VariableDeclaration: checkSpacingAroundFirstToken,
64322 // Expressions
64323 ArrowFunctionExpression: checkSpacingForFunction,
64324 AwaitExpression: checkSpacingForAwaitExpression,
64325 ClassExpression: checkSpacingForClass,
64326 FunctionExpression: checkSpacingForFunction,
64327 NewExpression: checkSpacingBeforeFirstToken,
64328 Super: checkSpacingBeforeFirstToken,
64329 ThisExpression: checkSpacingBeforeFirstToken,
64330 UnaryExpression: checkSpacingBeforeFirstToken,
64331 YieldExpression: checkSpacingBeforeFirstToken,
64332 // Others
64333 ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier,
64334 MethodDefinition: checkSpacingForProperty,
64335 Property: checkSpacingForProperty
64336 };
64337 }
64338
64339};
64340
64341/***/ }),
64342/* 487 */
64343/***/ (function(module, exports, __webpack_require__) {
64344
64345"use strict";
64346/**
64347 * @fileoverview Rule to enforce the position of line comments
64348 * @author Alberto Rodríguez
64349 */
64350
64351
64352const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
64353// Rule Definition
64354//------------------------------------------------------------------------------
64355
64356
64357module.exports = {
64358 meta: {
64359 type: "layout",
64360 docs: {
64361 description: "enforce position of line comments",
64362 category: "Stylistic Issues",
64363 recommended: false,
64364 url: "https://eslint.org/docs/rules/line-comment-position"
64365 },
64366 schema: [{
64367 oneOf: [{
64368 enum: ["above", "beside"]
64369 }, {
64370 type: "object",
64371 properties: {
64372 position: {
64373 enum: ["above", "beside"]
64374 },
64375 ignorePattern: {
64376 type: "string"
64377 },
64378 applyDefaultPatterns: {
64379 type: "boolean"
64380 },
64381 applyDefaultIgnorePatterns: {
64382 type: "boolean"
64383 }
64384 },
64385 additionalProperties: false
64386 }]
64387 }],
64388 messages: {
64389 above: "Expected comment to be above code.",
64390 beside: "Expected comment to be beside code."
64391 }
64392 },
64393
64394 create(context) {
64395 const options = context.options[0];
64396 let above,
64397 ignorePattern,
64398 applyDefaultIgnorePatterns = true;
64399
64400 if (!options || typeof options === "string") {
64401 above = !options || options === "above";
64402 } else {
64403 above = !options.position || options.position === "above";
64404 ignorePattern = options.ignorePattern;
64405
64406 if (Object.prototype.hasOwnProperty.call(options, "applyDefaultIgnorePatterns")) {
64407 applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns;
64408 } else {
64409 applyDefaultIgnorePatterns = options.applyDefaultPatterns !== false;
64410 }
64411 }
64412
64413 const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
64414 const fallThroughRegExp = /^\s*falls?\s?through/u;
64415 const customIgnoreRegExp = new RegExp(ignorePattern, "u");
64416 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
64417 // Public
64418 //--------------------------------------------------------------------------
64419
64420 return {
64421 Program() {
64422 const comments = sourceCode.getAllComments();
64423 comments.filter(token => token.type === "Line").forEach(node => {
64424 if (applyDefaultIgnorePatterns && (defaultIgnoreRegExp.test(node.value) || fallThroughRegExp.test(node.value))) {
64425 return;
64426 }
64427
64428 if (ignorePattern && customIgnoreRegExp.test(node.value)) {
64429 return;
64430 }
64431
64432 const previous = sourceCode.getTokenBefore(node, {
64433 includeComments: true
64434 });
64435 const isOnSameLine = previous && previous.loc.end.line === node.loc.start.line;
64436
64437 if (above) {
64438 if (isOnSameLine) {
64439 context.report({
64440 node,
64441 messageId: "above"
64442 });
64443 }
64444 } else {
64445 if (!isOnSameLine) {
64446 context.report({
64447 node,
64448 messageId: "beside"
64449 });
64450 }
64451 }
64452 });
64453 }
64454
64455 };
64456 }
64457
64458};
64459
64460/***/ }),
64461/* 488 */
64462/***/ (function(module, exports, __webpack_require__) {
64463
64464"use strict";
64465/**
64466 * @fileoverview Rule to enforce a single linebreak style.
64467 * @author Erik Mueller
64468 */
64469 //------------------------------------------------------------------------------
64470// Requirements
64471//------------------------------------------------------------------------------
64472
64473const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
64474// Rule Definition
64475//------------------------------------------------------------------------------
64476
64477
64478module.exports = {
64479 meta: {
64480 type: "layout",
64481 docs: {
64482 description: "enforce consistent linebreak style",
64483 category: "Stylistic Issues",
64484 recommended: false,
64485 url: "https://eslint.org/docs/rules/linebreak-style"
64486 },
64487 fixable: "whitespace",
64488 schema: [{
64489 enum: ["unix", "windows"]
64490 }],
64491 messages: {
64492 expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.",
64493 expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'."
64494 }
64495 },
64496
64497 create(context) {
64498 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
64499 // Helpers
64500 //--------------------------------------------------------------------------
64501
64502 /**
64503 * Builds a fix function that replaces text at the specified range in the source text.
64504 * @param {int[]} range The range to replace
64505 * @param {string} text The text to insert.
64506 * @returns {Function} Fixer function
64507 * @private
64508 */
64509
64510 function createFix(range, text) {
64511 return function (fixer) {
64512 return fixer.replaceTextRange(range, text);
64513 };
64514 } //--------------------------------------------------------------------------
64515 // Public
64516 //--------------------------------------------------------------------------
64517
64518
64519 return {
64520 Program: function checkForLinebreakStyle(node) {
64521 const linebreakStyle = context.options[0] || "unix",
64522 expectedLF = linebreakStyle === "unix",
64523 expectedLFChars = expectedLF ? "\n" : "\r\n",
64524 source = sourceCode.getText(),
64525 pattern = astUtils.createGlobalLinebreakMatcher();
64526 let match;
64527 let i = 0;
64528
64529 while ((match = pattern.exec(source)) !== null) {
64530 i++;
64531
64532 if (match[0] === expectedLFChars) {
64533 continue;
64534 }
64535
64536 const index = match.index;
64537 const range = [index, index + match[0].length];
64538 context.report({
64539 node,
64540 loc: {
6a5a0f88
TL
64541 start: {
64542 line: i,
64543 column: sourceCode.lines[i - 1].length
64544 },
64545 end: {
64546 line: i + 1,
64547 column: 0
64548 }
eb39fafa
DC
64549 },
64550 messageId: expectedLF ? "expectedLF" : "expectedCRLF",
64551 fix: createFix(range, expectedLFChars)
64552 });
64553 }
64554 }
64555 };
64556 }
64557
64558};
64559
64560/***/ }),
64561/* 489 */
64562/***/ (function(module, exports, __webpack_require__) {
64563
64564"use strict";
64565/**
64566 * @fileoverview Enforces empty lines around comments.
64567 * @author Jamund Ferguson
64568 */
64569 //------------------------------------------------------------------------------
64570// Requirements
64571//------------------------------------------------------------------------------
64572
64573const lodash = __webpack_require__(403),
64574 astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
64575// Helpers
64576//------------------------------------------------------------------------------
64577
64578/**
64579 * Return an array with with any line numbers that are empty.
64580 * @param {Array} lines An array of each line of the file.
64581 * @returns {Array} An array of line numbers.
64582 */
64583
64584
64585function getEmptyLineNums(lines) {
64586 const emptyLines = lines.map((line, i) => ({
64587 code: line.trim(),
64588 num: i + 1
64589 })).filter(line => !line.code).map(line => line.num);
64590 return emptyLines;
64591}
64592/**
64593 * Return an array with with any line numbers that contain comments.
64594 * @param {Array} comments An array of comment tokens.
64595 * @returns {Array} An array of line numbers.
64596 */
64597
64598
64599function getCommentLineNums(comments) {
64600 const lines = [];
64601 comments.forEach(token => {
64602 const start = token.loc.start.line;
64603 const end = token.loc.end.line;
64604 lines.push(start, end);
64605 });
64606 return lines;
64607} //------------------------------------------------------------------------------
64608// Rule Definition
64609//------------------------------------------------------------------------------
64610
64611
64612module.exports = {
64613 meta: {
64614 type: "layout",
64615 docs: {
64616 description: "require empty lines around comments",
64617 category: "Stylistic Issues",
64618 recommended: false,
64619 url: "https://eslint.org/docs/rules/lines-around-comment"
64620 },
64621 fixable: "whitespace",
64622 schema: [{
64623 type: "object",
64624 properties: {
64625 beforeBlockComment: {
64626 type: "boolean",
64627 default: true
64628 },
64629 afterBlockComment: {
64630 type: "boolean",
64631 default: false
64632 },
64633 beforeLineComment: {
64634 type: "boolean",
64635 default: false
64636 },
64637 afterLineComment: {
64638 type: "boolean",
64639 default: false
64640 },
64641 allowBlockStart: {
64642 type: "boolean",
64643 default: false
64644 },
64645 allowBlockEnd: {
64646 type: "boolean",
64647 default: false
64648 },
64649 allowClassStart: {
64650 type: "boolean"
64651 },
64652 allowClassEnd: {
64653 type: "boolean"
64654 },
64655 allowObjectStart: {
64656 type: "boolean"
64657 },
64658 allowObjectEnd: {
64659 type: "boolean"
64660 },
64661 allowArrayStart: {
64662 type: "boolean"
64663 },
64664 allowArrayEnd: {
64665 type: "boolean"
64666 },
64667 ignorePattern: {
64668 type: "string"
64669 },
64670 applyDefaultIgnorePatterns: {
64671 type: "boolean"
64672 }
64673 },
64674 additionalProperties: false
64675 }],
64676 messages: {
64677 after: "Expected line after comment.",
64678 before: "Expected line before comment."
64679 }
64680 },
64681
64682 create(context) {
64683 const options = Object.assign({}, context.options[0]);
64684 const ignorePattern = options.ignorePattern;
64685 const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
64686 const customIgnoreRegExp = new RegExp(ignorePattern, "u");
64687 const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false;
64688 options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true;
64689 const sourceCode = context.getSourceCode();
64690 const lines = sourceCode.lines,
64691 numLines = lines.length + 1,
64692 comments = sourceCode.getAllComments(),
64693 commentLines = getCommentLineNums(comments),
64694 emptyLines = getEmptyLineNums(lines),
64695 commentAndEmptyLines = commentLines.concat(emptyLines);
64696 /**
64697 * Returns whether or not comments are on lines starting with or ending with code
64698 * @param {token} token The comment token to check.
64699 * @returns {boolean} True if the comment is not alone.
64700 */
64701
64702 function codeAroundComment(token) {
64703 let currentToken = token;
64704
64705 do {
64706 currentToken = sourceCode.getTokenBefore(currentToken, {
64707 includeComments: true
64708 });
64709 } while (currentToken && astUtils.isCommentToken(currentToken));
64710
64711 if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) {
64712 return true;
64713 }
64714
64715 currentToken = token;
64716
64717 do {
64718 currentToken = sourceCode.getTokenAfter(currentToken, {
64719 includeComments: true
64720 });
64721 } while (currentToken && astUtils.isCommentToken(currentToken));
64722
64723 if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) {
64724 return true;
64725 }
64726
64727 return false;
64728 }
64729 /**
64730 * Returns whether or not comments are inside a node type or not.
64731 * @param {ASTNode} parent The Comment parent node.
64732 * @param {string} nodeType The parent type to check against.
64733 * @returns {boolean} True if the comment is inside nodeType.
64734 */
64735
64736
64737 function isParentNodeType(parent, nodeType) {
64738 return parent.type === nodeType || parent.body && parent.body.type === nodeType || parent.consequent && parent.consequent.type === nodeType;
64739 }
64740 /**
64741 * Returns the parent node that contains the given token.
64742 * @param {token} token The token to check.
64743 * @returns {ASTNode} The parent node that contains the given token.
64744 */
64745
64746
64747 function getParentNodeOfToken(token) {
64748 return sourceCode.getNodeByRangeIndex(token.range[0]);
64749 }
64750 /**
64751 * Returns whether or not comments are at the parent start or not.
64752 * @param {token} token The Comment token.
64753 * @param {string} nodeType The parent type to check against.
64754 * @returns {boolean} True if the comment is at parent start.
64755 */
64756
64757
64758 function isCommentAtParentStart(token, nodeType) {
64759 const parent = getParentNodeOfToken(token);
64760 return parent && isParentNodeType(parent, nodeType) && token.loc.start.line - parent.loc.start.line === 1;
64761 }
64762 /**
64763 * Returns whether or not comments are at the parent end or not.
64764 * @param {token} token The Comment token.
64765 * @param {string} nodeType The parent type to check against.
64766 * @returns {boolean} True if the comment is at parent end.
64767 */
64768
64769
64770 function isCommentAtParentEnd(token, nodeType) {
64771 const parent = getParentNodeOfToken(token);
64772 return parent && isParentNodeType(parent, nodeType) && parent.loc.end.line - token.loc.end.line === 1;
64773 }
64774 /**
64775 * Returns whether or not comments are at the block start or not.
64776 * @param {token} token The Comment token.
64777 * @returns {boolean} True if the comment is at block start.
64778 */
64779
64780
64781 function isCommentAtBlockStart(token) {
64782 return isCommentAtParentStart(token, "ClassBody") || isCommentAtParentStart(token, "BlockStatement") || isCommentAtParentStart(token, "SwitchCase");
64783 }
64784 /**
64785 * Returns whether or not comments are at the block end or not.
64786 * @param {token} token The Comment token.
64787 * @returns {boolean} True if the comment is at block end.
64788 */
64789
64790
64791 function isCommentAtBlockEnd(token) {
64792 return isCommentAtParentEnd(token, "ClassBody") || isCommentAtParentEnd(token, "BlockStatement") || isCommentAtParentEnd(token, "SwitchCase") || isCommentAtParentEnd(token, "SwitchStatement");
64793 }
64794 /**
64795 * Returns whether or not comments are at the class start or not.
64796 * @param {token} token The Comment token.
64797 * @returns {boolean} True if the comment is at class start.
64798 */
64799
64800
64801 function isCommentAtClassStart(token) {
64802 return isCommentAtParentStart(token, "ClassBody");
64803 }
64804 /**
64805 * Returns whether or not comments are at the class end or not.
64806 * @param {token} token The Comment token.
64807 * @returns {boolean} True if the comment is at class end.
64808 */
64809
64810
64811 function isCommentAtClassEnd(token) {
64812 return isCommentAtParentEnd(token, "ClassBody");
64813 }
64814 /**
64815 * Returns whether or not comments are at the object start or not.
64816 * @param {token} token The Comment token.
64817 * @returns {boolean} True if the comment is at object start.
64818 */
64819
64820
64821 function isCommentAtObjectStart(token) {
64822 return isCommentAtParentStart(token, "ObjectExpression") || isCommentAtParentStart(token, "ObjectPattern");
64823 }
64824 /**
64825 * Returns whether or not comments are at the object end or not.
64826 * @param {token} token The Comment token.
64827 * @returns {boolean} True if the comment is at object end.
64828 */
64829
64830
64831 function isCommentAtObjectEnd(token) {
64832 return isCommentAtParentEnd(token, "ObjectExpression") || isCommentAtParentEnd(token, "ObjectPattern");
64833 }
64834 /**
64835 * Returns whether or not comments are at the array start or not.
64836 * @param {token} token The Comment token.
64837 * @returns {boolean} True if the comment is at array start.
64838 */
64839
64840
64841 function isCommentAtArrayStart(token) {
64842 return isCommentAtParentStart(token, "ArrayExpression") || isCommentAtParentStart(token, "ArrayPattern");
64843 }
64844 /**
64845 * Returns whether or not comments are at the array end or not.
64846 * @param {token} token The Comment token.
64847 * @returns {boolean} True if the comment is at array end.
64848 */
64849
64850
64851 function isCommentAtArrayEnd(token) {
64852 return isCommentAtParentEnd(token, "ArrayExpression") || isCommentAtParentEnd(token, "ArrayPattern");
64853 }
64854 /**
64855 * Checks if a comment token has lines around it (ignores inline comments)
64856 * @param {token} token The Comment token.
64857 * @param {Object} opts Options to determine the newline.
64858 * @param {boolean} opts.after Should have a newline after this line.
64859 * @param {boolean} opts.before Should have a newline before this line.
64860 * @returns {void}
64861 */
64862
64863
64864 function checkForEmptyLine(token, opts) {
64865 if (applyDefaultIgnorePatterns && defaultIgnoreRegExp.test(token.value)) {
64866 return;
64867 }
64868
64869 if (ignorePattern && customIgnoreRegExp.test(token.value)) {
64870 return;
64871 }
64872
64873 let after = opts.after,
64874 before = opts.before;
64875 const prevLineNum = token.loc.start.line - 1,
64876 nextLineNum = token.loc.end.line + 1,
64877 commentIsNotAlone = codeAroundComment(token);
64878 const blockStartAllowed = options.allowBlockStart && isCommentAtBlockStart(token) && !(options.allowClassStart === false && isCommentAtClassStart(token)),
64879 blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(token) && !(options.allowClassEnd === false && isCommentAtClassEnd(token)),
64880 classStartAllowed = options.allowClassStart && isCommentAtClassStart(token),
64881 classEndAllowed = options.allowClassEnd && isCommentAtClassEnd(token),
64882 objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(token),
64883 objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(token),
64884 arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(token),
64885 arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(token);
64886 const exceptionStartAllowed = blockStartAllowed || classStartAllowed || objectStartAllowed || arrayStartAllowed;
64887 const exceptionEndAllowed = blockEndAllowed || classEndAllowed || objectEndAllowed || arrayEndAllowed; // ignore top of the file and bottom of the file
64888
64889 if (prevLineNum < 1) {
64890 before = false;
64891 }
64892
64893 if (nextLineNum >= numLines) {
64894 after = false;
64895 } // we ignore all inline comments
64896
64897
64898 if (commentIsNotAlone) {
64899 return;
64900 }
64901
64902 const previousTokenOrComment = sourceCode.getTokenBefore(token, {
64903 includeComments: true
64904 });
64905 const nextTokenOrComment = sourceCode.getTokenAfter(token, {
64906 includeComments: true
64907 }); // check for newline before
64908
64909 if (!exceptionStartAllowed && before && !lodash.includes(commentAndEmptyLines, prevLineNum) && !(astUtils.isCommentToken(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, token))) {
64910 const lineStart = token.range[0] - token.loc.start.column;
64911 const range = [lineStart, lineStart];
64912 context.report({
64913 node: token,
64914 messageId: "before",
64915
64916 fix(fixer) {
64917 return fixer.insertTextBeforeRange(range, "\n");
64918 }
64919
64920 });
64921 } // check for newline after
64922
64923
64924 if (!exceptionEndAllowed && after && !lodash.includes(commentAndEmptyLines, nextLineNum) && !(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) {
64925 context.report({
64926 node: token,
64927 messageId: "after",
64928
64929 fix(fixer) {
64930 return fixer.insertTextAfter(token, "\n");
64931 }
64932
64933 });
64934 }
64935 } //--------------------------------------------------------------------------
64936 // Public
64937 //--------------------------------------------------------------------------
64938
64939
64940 return {
64941 Program() {
64942 comments.forEach(token => {
64943 if (token.type === "Line") {
64944 if (options.beforeLineComment || options.afterLineComment) {
64945 checkForEmptyLine(token, {
64946 after: options.afterLineComment,
64947 before: options.beforeLineComment
64948 });
64949 }
64950 } else if (token.type === "Block") {
64951 if (options.beforeBlockComment || options.afterBlockComment) {
64952 checkForEmptyLine(token, {
64953 after: options.afterBlockComment,
64954 before: options.beforeBlockComment
64955 });
64956 }
64957 }
64958 });
64959 }
64960
64961 };
64962 }
64963
64964};
64965
64966/***/ }),
64967/* 490 */
64968/***/ (function(module, exports, __webpack_require__) {
64969
64970"use strict";
64971/**
64972 * @fileoverview Require or disallow newlines around directives.
64973 * @author Kai Cataldo
64974 * @deprecated
64975 */
64976
64977
64978const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
64979// Rule Definition
64980//------------------------------------------------------------------------------
64981
64982
64983module.exports = {
64984 meta: {
64985 type: "layout",
64986 docs: {
64987 description: "require or disallow newlines around directives",
64988 category: "Stylistic Issues",
64989 recommended: false,
64990 url: "https://eslint.org/docs/rules/lines-around-directive"
64991 },
64992 schema: [{
64993 oneOf: [{
64994 enum: ["always", "never"]
64995 }, {
64996 type: "object",
64997 properties: {
64998 before: {
64999 enum: ["always", "never"]
65000 },
65001 after: {
65002 enum: ["always", "never"]
65003 }
65004 },
65005 additionalProperties: false,
65006 minProperties: 2
65007 }]
65008 }],
65009 fixable: "whitespace",
65010 messages: {
65011 expected: "Expected newline {{location}} \"{{value}}\" directive.",
65012 unexpected: "Unexpected newline {{location}} \"{{value}}\" directive."
65013 },
65014 deprecated: true,
65015 replacedBy: ["padding-line-between-statements"]
65016 },
65017
65018 create(context) {
65019 const sourceCode = context.getSourceCode();
65020 const config = context.options[0] || "always";
65021 const expectLineBefore = typeof config === "string" ? config : config.before;
65022 const expectLineAfter = typeof config === "string" ? config : config.after; //--------------------------------------------------------------------------
65023 // Helpers
65024 //--------------------------------------------------------------------------
65025
65026 /**
65027 * Check if node is preceded by a blank newline.
65028 * @param {ASTNode} node Node to check.
65029 * @returns {boolean} Whether or not the passed in node is preceded by a blank newline.
65030 */
65031
65032 function hasNewlineBefore(node) {
65033 const tokenBefore = sourceCode.getTokenBefore(node, {
65034 includeComments: true
65035 });
65036 const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0;
65037 return node.loc.start.line - tokenLineBefore >= 2;
65038 }
65039 /**
65040 * Gets the last token of a node that is on the same line as the rest of the node.
65041 * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing
65042 * semicolon on a different line.
65043 * @param {ASTNode} node A directive node
65044 * @returns {Token} The last token of the node on the line
65045 */
65046
65047
65048 function getLastTokenOnLine(node) {
65049 const lastToken = sourceCode.getLastToken(node);
65050 const secondToLastToken = sourceCode.getTokenBefore(lastToken);
65051 return astUtils.isSemicolonToken(lastToken) && lastToken.loc.start.line > secondToLastToken.loc.end.line ? secondToLastToken : lastToken;
65052 }
65053 /**
65054 * Check if node is followed by a blank newline.
65055 * @param {ASTNode} node Node to check.
65056 * @returns {boolean} Whether or not the passed in node is followed by a blank newline.
65057 */
65058
65059
65060 function hasNewlineAfter(node) {
65061 const lastToken = getLastTokenOnLine(node);
65062 const tokenAfter = sourceCode.getTokenAfter(lastToken, {
65063 includeComments: true
65064 });
65065 return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2;
65066 }
65067 /**
65068 * Report errors for newlines around directives.
65069 * @param {ASTNode} node Node to check.
65070 * @param {string} location Whether the error was found before or after the directive.
65071 * @param {boolean} expected Whether or not a newline was expected or unexpected.
65072 * @returns {void}
65073 */
65074
65075
65076 function reportError(node, location, expected) {
65077 context.report({
65078 node,
65079 messageId: expected ? "expected" : "unexpected",
65080 data: {
65081 value: node.expression.value,
65082 location
65083 },
65084
65085 fix(fixer) {
65086 const lastToken = getLastTokenOnLine(node);
65087
65088 if (expected) {
65089 return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n");
65090 }
65091
65092 return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]);
65093 }
65094
65095 });
65096 }
65097 /**
65098 * Check lines around directives in node
65099 * @param {ASTNode} node node to check
65100 * @returns {void}
65101 */
65102
65103
65104 function checkDirectives(node) {
65105 const directives = astUtils.getDirectivePrologue(node);
65106
65107 if (!directives.length) {
65108 return;
65109 }
65110
65111 const firstDirective = directives[0];
65112 const leadingComments = sourceCode.getCommentsBefore(firstDirective);
65113 /*
65114 * Only check before the first directive if it is preceded by a comment or if it is at the top of
65115 * the file and expectLineBefore is set to "never". This is to not force a newline at the top of
65116 * the file if there are no comments as well as for compatibility with padded-blocks.
65117 */
65118
65119 if (leadingComments.length) {
65120 if (expectLineBefore === "always" && !hasNewlineBefore(firstDirective)) {
65121 reportError(firstDirective, "before", true);
65122 }
65123
65124 if (expectLineBefore === "never" && hasNewlineBefore(firstDirective)) {
65125 reportError(firstDirective, "before", false);
65126 }
65127 } else if (node.type === "Program" && expectLineBefore === "never" && !leadingComments.length && hasNewlineBefore(firstDirective)) {
65128 reportError(firstDirective, "before", false);
65129 }
65130
65131 const lastDirective = directives[directives.length - 1];
65132 const statements = node.type === "Program" ? node.body : node.body.body;
65133 /*
65134 * Do not check after the last directive if the body only
65135 * contains a directive prologue and isn't followed by a comment to ensure
65136 * this rule behaves well with padded-blocks.
65137 */
65138
65139 if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) {
65140 return;
65141 }
65142
65143 if (expectLineAfter === "always" && !hasNewlineAfter(lastDirective)) {
65144 reportError(lastDirective, "after", true);
65145 }
65146
65147 if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) {
65148 reportError(lastDirective, "after", false);
65149 }
65150 } //--------------------------------------------------------------------------
65151 // Public
65152 //--------------------------------------------------------------------------
65153
65154
65155 return {
65156 Program: checkDirectives,
65157 FunctionDeclaration: checkDirectives,
65158 FunctionExpression: checkDirectives,
65159 ArrowFunctionExpression: checkDirectives
65160 };
65161 }
65162
65163};
65164
65165/***/ }),
65166/* 491 */
65167/***/ (function(module, exports, __webpack_require__) {
65168
65169"use strict";
65170/**
65171 * @fileoverview Rule to check empty newline between class members
65172 * @author 薛定谔的猫<hh_2013@foxmail.com>
65173 */
65174
65175
65176const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
65177// Rule Definition
65178//------------------------------------------------------------------------------
65179
65180
65181module.exports = {
65182 meta: {
65183 type: "layout",
65184 docs: {
65185 description: "require or disallow an empty line between class members",
65186 category: "Stylistic Issues",
65187 recommended: false,
65188 url: "https://eslint.org/docs/rules/lines-between-class-members"
65189 },
65190 fixable: "whitespace",
65191 schema: [{
65192 enum: ["always", "never"]
65193 }, {
65194 type: "object",
65195 properties: {
65196 exceptAfterSingleLine: {
65197 type: "boolean",
65198 default: false
65199 }
65200 },
65201 additionalProperties: false
65202 }],
65203 messages: {
65204 never: "Unexpected blank line between class members.",
65205 always: "Expected blank line between class members."
65206 }
65207 },
65208
65209 create(context) {
65210 const options = [];
65211 options[0] = context.options[0] || "always";
65212 options[1] = context.options[1] || {
65213 exceptAfterSingleLine: false
65214 };
65215 const sourceCode = context.getSourceCode();
65216 /**
65217 * Return the last token among the consecutive tokens that have no exceed max line difference in between, before the first token in the next member.
65218 * @param {Token} prevLastToken The last token in the previous member node.
65219 * @param {Token} nextFirstToken The first token in the next member node.
65220 * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens.
65221 * @returns {Token} The last token among the consecutive tokens.
65222 */
65223
65224 function findLastConsecutiveTokenAfter(prevLastToken, nextFirstToken, maxLine) {
65225 const after = sourceCode.getTokenAfter(prevLastToken, {
65226 includeComments: true
65227 });
65228
65229 if (after !== nextFirstToken && after.loc.start.line - prevLastToken.loc.end.line <= maxLine) {
65230 return findLastConsecutiveTokenAfter(after, nextFirstToken, maxLine);
65231 }
65232
65233 return prevLastToken;
65234 }
65235 /**
65236 * Return the first token among the consecutive tokens that have no exceed max line difference in between, after the last token in the previous member.
65237 * @param {Token} nextFirstToken The first token in the next member node.
65238 * @param {Token} prevLastToken The last token in the previous member node.
65239 * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens.
65240 * @returns {Token} The first token among the consecutive tokens.
65241 */
65242
65243
65244 function findFirstConsecutiveTokenBefore(nextFirstToken, prevLastToken, maxLine) {
65245 const before = sourceCode.getTokenBefore(nextFirstToken, {
65246 includeComments: true
65247 });
65248
65249 if (before !== prevLastToken && nextFirstToken.loc.start.line - before.loc.end.line <= maxLine) {
65250 return findFirstConsecutiveTokenBefore(before, prevLastToken, maxLine);
65251 }
65252
65253 return nextFirstToken;
65254 }
65255 /**
65256 * Checks if there is a token or comment between two tokens.
65257 * @param {Token} before The token before.
65258 * @param {Token} after The token after.
65259 * @returns {boolean} True if there is a token or comment between two tokens.
65260 */
65261
65262
65263 function hasTokenOrCommentBetween(before, after) {
65264 return sourceCode.getTokensBetween(before, after, {
65265 includeComments: true
65266 }).length !== 0;
65267 }
65268
65269 return {
65270 ClassBody(node) {
65271 const body = node.body;
65272
65273 for (let i = 0; i < body.length - 1; i++) {
65274 const curFirst = sourceCode.getFirstToken(body[i]);
65275 const curLast = sourceCode.getLastToken(body[i]);
65276 const nextFirst = sourceCode.getFirstToken(body[i + 1]);
65277 const isMulti = !astUtils.isTokenOnSameLine(curFirst, curLast);
65278 const skip = !isMulti && options[1].exceptAfterSingleLine;
65279 const beforePadding = findLastConsecutiveTokenAfter(curLast, nextFirst, 1);
65280 const afterPadding = findFirstConsecutiveTokenBefore(nextFirst, curLast, 1);
65281 const isPadded = afterPadding.loc.start.line - beforePadding.loc.end.line > 1;
65282 const hasTokenInPadding = hasTokenOrCommentBetween(beforePadding, afterPadding);
65283 const curLineLastToken = findLastConsecutiveTokenAfter(curLast, nextFirst, 0);
65284
65285 if (options[0] === "always" && !skip && !isPadded || options[0] === "never" && isPadded) {
65286 context.report({
65287 node: body[i + 1],
65288 messageId: isPadded ? "never" : "always",
65289
65290 fix(fixer) {
65291 if (hasTokenInPadding) {
65292 return null;
65293 }
65294
65295 return isPadded ? fixer.replaceTextRange([beforePadding.range[1], afterPadding.range[0]], "\n") : fixer.insertTextAfter(curLineLastToken, "\n");
65296 }
65297
65298 });
65299 }
65300 }
65301 }
65302
65303 };
65304 }
65305
65306};
65307
65308/***/ }),
65309/* 492 */
65310/***/ (function(module, exports, __webpack_require__) {
65311
65312"use strict";
65313/**
65314 * @fileoverview Enforce a maximum number of classes per file
65315 * @author James Garbutt <https://github.com/43081j>
65316 */
65317 //------------------------------------------------------------------------------
65318// Requirements
65319//------------------------------------------------------------------------------
65320//------------------------------------------------------------------------------
65321// Rule Definition
65322//------------------------------------------------------------------------------
65323
65324module.exports = {
65325 meta: {
65326 type: "suggestion",
65327 docs: {
65328 description: "enforce a maximum number of classes per file",
65329 category: "Best Practices",
65330 recommended: false,
65331 url: "https://eslint.org/docs/rules/max-classes-per-file"
65332 },
65333 schema: [{
65334 type: "integer",
65335 minimum: 1
65336 }],
65337 messages: {
65338 maximumExceeded: "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}."
65339 }
65340 },
65341
65342 create(context) {
65343 const maxClasses = context.options[0] || 1;
65344 let classCount = 0;
65345 return {
65346 Program() {
65347 classCount = 0;
65348 },
65349
65350 "Program:exit"(node) {
65351 if (classCount > maxClasses) {
65352 context.report({
65353 node,
65354 messageId: "maximumExceeded",
65355 data: {
65356 classCount,
65357 max: maxClasses
65358 }
65359 });
65360 }
65361 },
65362
65363 "ClassDeclaration, ClassExpression"() {
65364 classCount++;
65365 }
65366
65367 };
65368 }
65369
65370};
65371
65372/***/ }),
65373/* 493 */
65374/***/ (function(module, exports, __webpack_require__) {
65375
65376"use strict";
65377/**
65378 * @fileoverview A rule to set the maximum depth block can be nested in a function.
65379 * @author Ian Christian Myers
65380 */
65381 //------------------------------------------------------------------------------
65382// Rule Definition
65383//------------------------------------------------------------------------------
65384
65385module.exports = {
65386 meta: {
65387 type: "suggestion",
65388 docs: {
65389 description: "enforce a maximum depth that blocks can be nested",
65390 category: "Stylistic Issues",
65391 recommended: false,
65392 url: "https://eslint.org/docs/rules/max-depth"
65393 },
65394 schema: [{
65395 oneOf: [{
65396 type: "integer",
65397 minimum: 0
65398 }, {
65399 type: "object",
65400 properties: {
65401 maximum: {
65402 type: "integer",
65403 minimum: 0
65404 },
65405 max: {
65406 type: "integer",
65407 minimum: 0
65408 }
65409 },
65410 additionalProperties: false
65411 }]
65412 }],
65413 messages: {
65414 tooDeeply: "Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}."
65415 }
65416 },
65417
65418 create(context) {
65419 //--------------------------------------------------------------------------
65420 // Helpers
65421 //--------------------------------------------------------------------------
65422 const functionStack = [],
65423 option = context.options[0];
65424 let maxDepth = 4;
65425
65426 if (typeof option === "object" && (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))) {
65427 maxDepth = option.maximum || option.max;
65428 }
65429
65430 if (typeof option === "number") {
65431 maxDepth = option;
65432 }
65433 /**
65434 * When parsing a new function, store it in our function stack
65435 * @returns {void}
65436 * @private
65437 */
65438
65439
65440 function startFunction() {
65441 functionStack.push(0);
65442 }
65443 /**
65444 * When parsing is done then pop out the reference
65445 * @returns {void}
65446 * @private
65447 */
65448
65449
65450 function endFunction() {
65451 functionStack.pop();
65452 }
65453 /**
65454 * Save the block and Evaluate the node
65455 * @param {ASTNode} node node to evaluate
65456 * @returns {void}
65457 * @private
65458 */
65459
65460
65461 function pushBlock(node) {
65462 const len = ++functionStack[functionStack.length - 1];
65463
65464 if (len > maxDepth) {
65465 context.report({
65466 node,
65467 messageId: "tooDeeply",
65468 data: {
65469 depth: len,
65470 maxDepth
65471 }
65472 });
65473 }
65474 }
65475 /**
65476 * Pop the saved block
65477 * @returns {void}
65478 * @private
65479 */
65480
65481
65482 function popBlock() {
65483 functionStack[functionStack.length - 1]--;
65484 } //--------------------------------------------------------------------------
65485 // Public API
65486 //--------------------------------------------------------------------------
65487
65488
65489 return {
65490 Program: startFunction,
65491 FunctionDeclaration: startFunction,
65492 FunctionExpression: startFunction,
65493 ArrowFunctionExpression: startFunction,
65494
65495 IfStatement(node) {
65496 if (node.parent.type !== "IfStatement") {
65497 pushBlock(node);
65498 }
65499 },
65500
65501 SwitchStatement: pushBlock,
65502 TryStatement: pushBlock,
65503 DoWhileStatement: pushBlock,
65504 WhileStatement: pushBlock,
65505 WithStatement: pushBlock,
65506 ForStatement: pushBlock,
65507 ForInStatement: pushBlock,
65508 ForOfStatement: pushBlock,
65509 "IfStatement:exit": popBlock,
65510 "SwitchStatement:exit": popBlock,
65511 "TryStatement:exit": popBlock,
65512 "DoWhileStatement:exit": popBlock,
65513 "WhileStatement:exit": popBlock,
65514 "WithStatement:exit": popBlock,
65515 "ForStatement:exit": popBlock,
65516 "ForInStatement:exit": popBlock,
65517 "ForOfStatement:exit": popBlock,
65518 "FunctionDeclaration:exit": endFunction,
65519 "FunctionExpression:exit": endFunction,
65520 "ArrowFunctionExpression:exit": endFunction,
65521 "Program:exit": endFunction
65522 };
65523 }
65524
65525};
65526
65527/***/ }),
65528/* 494 */
65529/***/ (function(module, exports, __webpack_require__) {
65530
65531"use strict";
65532/**
65533 * @fileoverview Rule to check for max length on a line.
65534 * @author Matt DuVall <http://www.mattduvall.com>
65535 */
65536 //------------------------------------------------------------------------------
65537// Constants
65538//------------------------------------------------------------------------------
65539
65540const OPTIONS_SCHEMA = {
65541 type: "object",
65542 properties: {
65543 code: {
65544 type: "integer",
65545 minimum: 0
65546 },
65547 comments: {
65548 type: "integer",
65549 minimum: 0
65550 },
65551 tabWidth: {
65552 type: "integer",
65553 minimum: 0
65554 },
65555 ignorePattern: {
65556 type: "string"
65557 },
65558 ignoreComments: {
65559 type: "boolean"
65560 },
65561 ignoreStrings: {
65562 type: "boolean"
65563 },
65564 ignoreUrls: {
65565 type: "boolean"
65566 },
65567 ignoreTemplateLiterals: {
65568 type: "boolean"
65569 },
65570 ignoreRegExpLiterals: {
65571 type: "boolean"
65572 },
65573 ignoreTrailingComments: {
65574 type: "boolean"
65575 }
65576 },
65577 additionalProperties: false
65578};
65579const OPTIONS_OR_INTEGER_SCHEMA = {
65580 anyOf: [OPTIONS_SCHEMA, {
65581 type: "integer",
65582 minimum: 0
65583 }]
65584}; //------------------------------------------------------------------------------
65585// Rule Definition
65586//------------------------------------------------------------------------------
65587
65588module.exports = {
65589 meta: {
65590 type: "layout",
65591 docs: {
65592 description: "enforce a maximum line length",
65593 category: "Stylistic Issues",
65594 recommended: false,
65595 url: "https://eslint.org/docs/rules/max-len"
65596 },
65597 schema: [OPTIONS_OR_INTEGER_SCHEMA, OPTIONS_OR_INTEGER_SCHEMA, OPTIONS_SCHEMA],
65598 messages: {
65599 max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.",
65600 maxComment: "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}."
65601 }
65602 },
65603
65604 create(context) {
65605 /*
65606 * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
65607 * - They're matching an entire string that we know is a URI
65608 * - We're matching part of a string where we think there *might* be a URL
65609 * - We're only concerned about URLs, as picking out any URI would cause
65610 * too many false positives
65611 * - We don't care about matching the entire URL, any small segment is fine
65612 */
65613 const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u;
65614 const sourceCode = context.getSourceCode();
65615 /**
65616 * Computes the length of a line that may contain tabs. The width of each
65617 * tab will be the number of spaces to the next tab stop.
65618 * @param {string} line The line.
65619 * @param {int} tabWidth The width of each tab stop in spaces.
65620 * @returns {int} The computed line length.
65621 * @private
65622 */
65623
65624 function computeLineLength(line, tabWidth) {
65625 let extraCharacterCount = 0;
65626 line.replace(/\t/gu, (match, offset) => {
65627 const totalOffset = offset + extraCharacterCount,
65628 previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
65629 spaceCount = tabWidth - previousTabStopOffset;
65630 extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
65631 });
65632 return Array.from(line).length + extraCharacterCount;
65633 } // The options object must be the last option specified…
65634
65635
65636 const options = Object.assign({}, context.options[context.options.length - 1]); // …but max code length…
65637
65638 if (typeof context.options[0] === "number") {
65639 options.code = context.options[0];
65640 } // …and tabWidth can be optionally specified directly as integers.
65641
65642
65643 if (typeof context.options[1] === "number") {
65644 options.tabWidth = context.options[1];
65645 }
65646
65647 const maxLength = typeof options.code === "number" ? options.code : 80,
65648 tabWidth = typeof options.tabWidth === "number" ? options.tabWidth : 4,
65649 ignoreComments = !!options.ignoreComments,
65650 ignoreStrings = !!options.ignoreStrings,
65651 ignoreTemplateLiterals = !!options.ignoreTemplateLiterals,
65652 ignoreRegExpLiterals = !!options.ignoreRegExpLiterals,
65653 ignoreTrailingComments = !!options.ignoreTrailingComments || !!options.ignoreComments,
65654 ignoreUrls = !!options.ignoreUrls,
65655 maxCommentLength = options.comments;
65656 let ignorePattern = options.ignorePattern || null;
65657
65658 if (ignorePattern) {
65659 ignorePattern = new RegExp(ignorePattern, "u");
65660 } //--------------------------------------------------------------------------
65661 // Helpers
65662 //--------------------------------------------------------------------------
65663
65664 /**
65665 * Tells if a given comment is trailing: it starts on the current line and
65666 * extends to or past the end of the current line.
65667 * @param {string} line The source line we want to check for a trailing comment on
65668 * @param {number} lineNumber The one-indexed line number for line
65669 * @param {ASTNode} comment The comment to inspect
65670 * @returns {boolean} If the comment is trailing on the given line
65671 */
65672
65673
65674 function isTrailingComment(line, lineNumber, comment) {
65675 return comment && comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line && (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length);
65676 }
65677 /**
65678 * Tells if a comment encompasses the entire line.
65679 * @param {string} line The source line with a trailing comment
65680 * @param {number} lineNumber The one-indexed line number this is on
65681 * @param {ASTNode} comment The comment to remove
65682 * @returns {boolean} If the comment covers the entire line
65683 */
65684
65685
65686 function isFullLineComment(line, lineNumber, comment) {
65687 const start = comment.loc.start,
65688 end = comment.loc.end,
65689 isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim();
65690 return comment && (start.line < lineNumber || start.line === lineNumber && isFirstTokenOnLine) && (end.line > lineNumber || end.line === lineNumber && end.column === line.length);
65691 }
65692 /**
65693 * Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
65694 * @param {ASTNode} node A node to check.
65695 * @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
65696 */
65697
65698
65699 function isJSXEmptyExpressionInSingleLineContainer(node) {
65700 if (!node || !node.parent || node.type !== "JSXEmptyExpression" || node.parent.type !== "JSXExpressionContainer") {
65701 return false;
65702 }
65703
65704 const parent = node.parent;
65705 return parent.loc.start.line === parent.loc.end.line;
65706 }
65707 /**
65708 * Gets the line after the comment and any remaining trailing whitespace is
65709 * stripped.
65710 * @param {string} line The source line with a trailing comment
65711 * @param {ASTNode} comment The comment to remove
65712 * @returns {string} Line without comment and trailing whitespace
65713 */
65714
65715
65716 function stripTrailingComment(line, comment) {
65717 // loc.column is zero-indexed
65718 return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
65719 }
65720 /**
65721 * Ensure that an array exists at [key] on `object`, and add `value` to it.
65722 * @param {Object} object the object to mutate
65723 * @param {string} key the object's key
65724 * @param {*} value the value to add
65725 * @returns {void}
65726 * @private
65727 */
65728
65729
65730 function ensureArrayAndPush(object, key, value) {
65731 if (!Array.isArray(object[key])) {
65732 object[key] = [];
65733 }
65734
65735 object[key].push(value);
65736 }
65737 /**
65738 * Retrieves an array containing all strings (" or ') in the source code.
65739 * @returns {ASTNode[]} An array of string nodes.
65740 */
65741
65742
65743 function getAllStrings() {
65744 return sourceCode.ast.tokens.filter(token => token.type === "String" || token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute");
65745 }
65746 /**
65747 * Retrieves an array containing all template literals in the source code.
65748 * @returns {ASTNode[]} An array of template literal nodes.
65749 */
65750
65751
65752 function getAllTemplateLiterals() {
65753 return sourceCode.ast.tokens.filter(token => token.type === "Template");
65754 }
65755 /**
65756 * Retrieves an array containing all RegExp literals in the source code.
65757 * @returns {ASTNode[]} An array of RegExp literal nodes.
65758 */
65759
65760
65761 function getAllRegExpLiterals() {
65762 return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression");
65763 }
65764 /**
65765 * A reducer to group an AST node by line number, both start and end.
65766 * @param {Object} acc the accumulator
65767 * @param {ASTNode} node the AST node in question
65768 * @returns {Object} the modified accumulator
65769 * @private
65770 */
65771
65772
65773 function groupByLineNumber(acc, node) {
65774 for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
65775 ensureArrayAndPush(acc, i, node);
65776 }
65777
65778 return acc;
65779 }
65780 /**
65781 * Returns an array of all comments in the source code.
65782 * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer,
65783 * the element is changed with JSXExpressionContainer node.
65784 * @returns {ASTNode[]} An array of comment nodes
65785 */
65786
65787
65788 function getAllComments() {
65789 const comments = [];
65790 sourceCode.getAllComments().forEach(commentNode => {
65791 const containingNode = sourceCode.getNodeByRangeIndex(commentNode.range[0]);
65792
65793 if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {
65794 // push a unique node only
65795 if (comments[comments.length - 1] !== containingNode.parent) {
65796 comments.push(containingNode.parent);
65797 }
65798 } else {
65799 comments.push(commentNode);
65800 }
65801 });
65802 return comments;
65803 }
65804 /**
65805 * Check the program for max length
65806 * @param {ASTNode} node Node to examine
65807 * @returns {void}
65808 * @private
65809 */
65810
65811
65812 function checkProgramForMaxLength(node) {
65813 // split (honors line-ending)
65814 const lines = sourceCode.lines,
65815 // list of comments to ignore
65816 comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? getAllComments() : []; // we iterate over comments in parallel with the lines
65817
65818 let commentsIndex = 0;
65819 const strings = getAllStrings();
65820 const stringsByLine = strings.reduce(groupByLineNumber, {});
65821 const templateLiterals = getAllTemplateLiterals();
65822 const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});
65823 const regExpLiterals = getAllRegExpLiterals();
65824 const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});
65825 lines.forEach((line, i) => {
65826 // i is zero-indexed, line numbers are one-indexed
65827 const lineNumber = i + 1;
65828 /*
65829 * if we're checking comment length; we need to know whether this
65830 * line is a comment
65831 */
65832
65833 let lineIsComment = false;
65834 let textToMeasure;
65835 /*
65836 * We can short-circuit the comment checks if we're already out of
65837 * comments to check.
65838 */
65839
65840 if (commentsIndex < comments.length) {
65841 let comment = null; // iterate over comments until we find one past the current line
65842
65843 do {
65844 comment = comments[++commentsIndex];
65845 } while (comment && comment.loc.start.line <= lineNumber); // and step back by one
65846
65847
65848 comment = comments[--commentsIndex];
65849
65850 if (isFullLineComment(line, lineNumber, comment)) {
65851 lineIsComment = true;
65852 textToMeasure = line;
65853 } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
65854 textToMeasure = stripTrailingComment(line, comment); // ignore multiple trailing comments in the same line
65855
65856 let lastIndex = commentsIndex;
65857
65858 while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) {
65859 textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]);
65860 }
65861 } else {
65862 textToMeasure = line;
65863 }
65864 } else {
65865 textToMeasure = line;
65866 }
65867
65868 if (ignorePattern && ignorePattern.test(textToMeasure) || ignoreUrls && URL_REGEXP.test(textToMeasure) || ignoreStrings && stringsByLine[lineNumber] || ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]) {
65869 // ignore this line
65870 return;
65871 }
65872
65873 const lineLength = computeLineLength(textToMeasure, tabWidth);
65874 const commentLengthApplies = lineIsComment && maxCommentLength;
65875
65876 if (lineIsComment && ignoreComments) {
65877 return;
65878 }
65879
65880 if (commentLengthApplies) {
65881 if (lineLength > maxCommentLength) {
65882 context.report({
65883 node,
65884 loc: {
65885 line: lineNumber,
65886 column: 0
65887 },
65888 messageId: "maxComment",
65889 data: {
65890 lineLength,
65891 maxCommentLength
65892 }
65893 });
65894 }
65895 } else if (lineLength > maxLength) {
65896 context.report({
65897 node,
65898 loc: {
65899 line: lineNumber,
65900 column: 0
65901 },
65902 messageId: "max",
65903 data: {
65904 lineLength,
65905 maxLength
65906 }
65907 });
65908 }
65909 });
65910 } //--------------------------------------------------------------------------
65911 // Public API
65912 //--------------------------------------------------------------------------
65913
65914
65915 return {
65916 Program: checkProgramForMaxLength
65917 };
65918 }
65919
65920};
65921
65922/***/ }),
65923/* 495 */
65924/***/ (function(module, exports, __webpack_require__) {
65925
65926"use strict";
65927/**
65928 * @fileoverview enforce a maximum file length
65929 * @author Alberto Rodríguez
65930 */
65931 //------------------------------------------------------------------------------
65932// Requirements
65933//------------------------------------------------------------------------------
65934
65935const lodash = __webpack_require__(403);
65936
65937const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
65938// Rule Definition
65939//------------------------------------------------------------------------------
65940
65941
65942module.exports = {
65943 meta: {
65944 type: "suggestion",
65945 docs: {
65946 description: "enforce a maximum number of lines per file",
65947 category: "Stylistic Issues",
65948 recommended: false,
65949 url: "https://eslint.org/docs/rules/max-lines"
65950 },
65951 schema: [{
65952 oneOf: [{
65953 type: "integer",
65954 minimum: 0
65955 }, {
65956 type: "object",
65957 properties: {
65958 max: {
65959 type: "integer",
65960 minimum: 0
65961 },
65962 skipComments: {
65963 type: "boolean"
65964 },
65965 skipBlankLines: {
65966 type: "boolean"
65967 }
65968 },
65969 additionalProperties: false
65970 }]
65971 }],
65972 messages: {
65973 exceed: "File has too many lines ({{actual}}). Maximum allowed is {{max}}."
65974 }
65975 },
65976
65977 create(context) {
65978 const option = context.options[0];
65979 let max = 300;
65980
65981 if (typeof option === "object" && Object.prototype.hasOwnProperty.call(option, "max")) {
65982 max = option.max;
65983 } else if (typeof option === "number") {
65984 max = option;
65985 }
65986
65987 const skipComments = option && option.skipComments;
65988 const skipBlankLines = option && option.skipBlankLines;
65989 const sourceCode = context.getSourceCode();
65990 /**
65991 * Returns whether or not a token is a comment node type
65992 * @param {Token} token The token to check
65993 * @returns {boolean} True if the token is a comment node
65994 */
65995
65996 function isCommentNodeType(token) {
65997 return token && (token.type === "Block" || token.type === "Line");
65998 }
65999 /**
66000 * Returns the line numbers of a comment that don't have any code on the same line
66001 * @param {Node} comment The comment node to check
66002 * @returns {number[]} The line numbers
66003 */
66004
66005
66006 function getLinesWithoutCode(comment) {
66007 let start = comment.loc.start.line;
66008 let end = comment.loc.end.line;
66009 let token;
66010 token = comment;
66011
66012 do {
66013 token = sourceCode.getTokenBefore(token, {
66014 includeComments: true
66015 });
66016 } while (isCommentNodeType(token));
66017
66018 if (token && astUtils.isTokenOnSameLine(token, comment)) {
66019 start += 1;
66020 }
66021
66022 token = comment;
66023
66024 do {
66025 token = sourceCode.getTokenAfter(token, {
66026 includeComments: true
66027 });
66028 } while (isCommentNodeType(token));
66029
66030 if (token && astUtils.isTokenOnSameLine(comment, token)) {
66031 end -= 1;
66032 }
66033
66034 if (start <= end) {
66035 return lodash.range(start, end + 1);
66036 }
66037
66038 return [];
66039 }
66040
66041 return {
66042 "Program:exit"() {
66043 let lines = sourceCode.lines.map((text, i) => ({
66044 lineNumber: i + 1,
66045 text
66046 }));
66047
66048 if (skipBlankLines) {
66049 lines = lines.filter(l => l.text.trim() !== "");
66050 }
66051
66052 if (skipComments) {
66053 const comments = sourceCode.getAllComments();
66054 const commentLines = lodash.flatten(comments.map(comment => getLinesWithoutCode(comment)));
66055 lines = lines.filter(l => !lodash.includes(commentLines, l.lineNumber));
66056 }
66057
66058 if (lines.length > max) {
66059 context.report({
66060 loc: {
66061 line: 1,
66062 column: 0
66063 },
66064 messageId: "exceed",
66065 data: {
66066 max,
66067 actual: lines.length
66068 }
66069 });
66070 }
66071 }
66072
66073 };
66074 }
66075
66076};
66077
66078/***/ }),
66079/* 496 */
66080/***/ (function(module, exports, __webpack_require__) {
66081
66082"use strict";
66083/**
66084 * @fileoverview A rule to set the maximum number of line of code in a function.
66085 * @author Pete Ward <peteward44@gmail.com>
66086 */
66087 //------------------------------------------------------------------------------
66088// Requirements
66089//------------------------------------------------------------------------------
66090
66091const astUtils = __webpack_require__(426);
66092
66093const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
66094// Constants
66095//------------------------------------------------------------------------------
66096
66097
66098const OPTIONS_SCHEMA = {
66099 type: "object",
66100 properties: {
66101 max: {
66102 type: "integer",
66103 minimum: 0
66104 },
66105 skipComments: {
66106 type: "boolean"
66107 },
66108 skipBlankLines: {
66109 type: "boolean"
66110 },
66111 IIFEs: {
66112 type: "boolean"
66113 }
66114 },
66115 additionalProperties: false
66116};
66117const OPTIONS_OR_INTEGER_SCHEMA = {
66118 oneOf: [OPTIONS_SCHEMA, {
66119 type: "integer",
66120 minimum: 1
66121 }]
66122};
66123/**
66124 * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values.
66125 * @param {Array} comments An array of comment nodes.
66126 * @returns {Map.<string,Node>} A map with numeric keys (source code line numbers) and comment token values.
66127 */
66128
66129function getCommentLineNumbers(comments) {
66130 const map = new Map();
66131 comments.forEach(comment => {
66132 for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
66133 map.set(i, comment);
66134 }
66135 });
66136 return map;
66137} //------------------------------------------------------------------------------
66138// Rule Definition
66139//------------------------------------------------------------------------------
66140
66141
66142module.exports = {
66143 meta: {
66144 type: "suggestion",
66145 docs: {
66146 description: "enforce a maximum number of line of code in a function",
66147 category: "Stylistic Issues",
66148 recommended: false,
66149 url: "https://eslint.org/docs/rules/max-lines-per-function"
66150 },
66151 schema: [OPTIONS_OR_INTEGER_SCHEMA],
66152 messages: {
66153 exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}."
66154 }
66155 },
66156
66157 create(context) {
66158 const sourceCode = context.getSourceCode();
66159 const lines = sourceCode.lines;
66160 const option = context.options[0];
66161 let maxLines = 50;
66162 let skipComments = false;
66163 let skipBlankLines = false;
66164 let IIFEs = false;
66165
66166 if (typeof option === "object") {
66167 maxLines = typeof option.max === "number" ? option.max : 50;
66168 skipComments = !!option.skipComments;
66169 skipBlankLines = !!option.skipBlankLines;
66170 IIFEs = !!option.IIFEs;
66171 } else if (typeof option === "number") {
66172 maxLines = option;
66173 }
66174
66175 const commentLineNumbers = getCommentLineNumbers(sourceCode.getAllComments()); //--------------------------------------------------------------------------
66176 // Helpers
66177 //--------------------------------------------------------------------------
66178
66179 /**
66180 * Tells if a comment encompasses the entire line.
66181 * @param {string} line The source line with a trailing comment
66182 * @param {number} lineNumber The one-indexed line number this is on
66183 * @param {ASTNode} comment The comment to remove
66184 * @returns {boolean} If the comment covers the entire line
66185 */
66186
66187 function isFullLineComment(line, lineNumber, comment) {
66188 const start = comment.loc.start,
66189 end = comment.loc.end,
66190 isFirstTokenOnLine = start.line === lineNumber && !line.slice(0, start.column).trim(),
66191 isLastTokenOnLine = end.line === lineNumber && !line.slice(end.column).trim();
66192 return comment && (start.line < lineNumber || isFirstTokenOnLine) && (end.line > lineNumber || isLastTokenOnLine);
66193 }
66194 /**
66195 * Identifies is a node is a FunctionExpression which is part of an IIFE
66196 * @param {ASTNode} node Node to test
66197 * @returns {boolean} True if it's an IIFE
66198 */
66199
66200
66201 function isIIFE(node) {
6a5a0f88 66202 return (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node;
eb39fafa
DC
66203 }
66204 /**
66205 * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property
66206 * @param {ASTNode} node Node to test
66207 * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property
66208 */
66209
66210
66211 function isEmbedded(node) {
66212 if (!node.parent) {
66213 return false;
66214 }
66215
66216 if (node !== node.parent.value) {
66217 return false;
66218 }
66219
66220 if (node.parent.type === "MethodDefinition") {
66221 return true;
66222 }
66223
66224 if (node.parent.type === "Property") {
66225 return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set";
66226 }
66227
66228 return false;
66229 }
66230 /**
66231 * Count the lines in the function
66232 * @param {ASTNode} funcNode Function AST node
66233 * @returns {void}
66234 * @private
66235 */
66236
66237
66238 function processFunction(funcNode) {
66239 const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;
66240
66241 if (!IIFEs && isIIFE(node)) {
66242 return;
66243 }
66244
66245 let lineCount = 0;
66246
66247 for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
66248 const line = lines[i];
66249
66250 if (skipComments) {
66251 if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) {
66252 continue;
66253 }
66254 }
66255
66256 if (skipBlankLines) {
66257 if (line.match(/^\s*$/u)) {
66258 continue;
66259 }
66260 }
66261
66262 lineCount++;
66263 }
66264
66265 if (lineCount > maxLines) {
66266 const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(funcNode));
66267 context.report({
66268 node,
66269 messageId: "exceed",
66270 data: {
66271 name,
66272 lineCount,
66273 maxLines
66274 }
66275 });
66276 }
66277 } //--------------------------------------------------------------------------
66278 // Public API
66279 //--------------------------------------------------------------------------
66280
66281
66282 return {
66283 FunctionDeclaration: processFunction,
66284 FunctionExpression: processFunction,
66285 ArrowFunctionExpression: processFunction
66286 };
66287 }
66288
66289};
66290
66291/***/ }),
66292/* 497 */
66293/***/ (function(module, exports, __webpack_require__) {
66294
66295"use strict";
66296/**
66297 * @fileoverview Rule to enforce a maximum number of nested callbacks.
66298 * @author Ian Christian Myers
66299 */
66300 //------------------------------------------------------------------------------
66301// Rule Definition
66302//------------------------------------------------------------------------------
66303
66304module.exports = {
66305 meta: {
66306 type: "suggestion",
66307 docs: {
66308 description: "enforce a maximum depth that callbacks can be nested",
66309 category: "Stylistic Issues",
66310 recommended: false,
66311 url: "https://eslint.org/docs/rules/max-nested-callbacks"
66312 },
66313 schema: [{
66314 oneOf: [{
66315 type: "integer",
66316 minimum: 0
66317 }, {
66318 type: "object",
66319 properties: {
66320 maximum: {
66321 type: "integer",
66322 minimum: 0
66323 },
66324 max: {
66325 type: "integer",
66326 minimum: 0
66327 }
66328 },
66329 additionalProperties: false
66330 }]
66331 }],
66332 messages: {
66333 exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}."
66334 }
66335 },
66336
66337 create(context) {
66338 //--------------------------------------------------------------------------
66339 // Constants
66340 //--------------------------------------------------------------------------
66341 const option = context.options[0];
66342 let THRESHOLD = 10;
66343
66344 if (typeof option === "object" && (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))) {
66345 THRESHOLD = option.maximum || option.max;
66346 } else if (typeof option === "number") {
66347 THRESHOLD = option;
66348 } //--------------------------------------------------------------------------
66349 // Helpers
66350 //--------------------------------------------------------------------------
66351
66352
66353 const callbackStack = [];
66354 /**
66355 * Checks a given function node for too many callbacks.
66356 * @param {ASTNode} node The node to check.
66357 * @returns {void}
66358 * @private
66359 */
66360
66361 function checkFunction(node) {
66362 const parent = node.parent;
66363
66364 if (parent.type === "CallExpression") {
66365 callbackStack.push(node);
66366 }
66367
66368 if (callbackStack.length > THRESHOLD) {
66369 const opts = {
66370 num: callbackStack.length,
66371 max: THRESHOLD
66372 };
66373 context.report({
66374 node,
66375 messageId: "exceed",
66376 data: opts
66377 });
66378 }
66379 }
66380 /**
66381 * Pops the call stack.
66382 * @returns {void}
66383 * @private
66384 */
66385
66386
66387 function popStack() {
66388 callbackStack.pop();
66389 } //--------------------------------------------------------------------------
66390 // Public API
66391 //--------------------------------------------------------------------------
66392
66393
66394 return {
66395 ArrowFunctionExpression: checkFunction,
66396 "ArrowFunctionExpression:exit": popStack,
66397 FunctionExpression: checkFunction,
66398 "FunctionExpression:exit": popStack
66399 };
66400 }
66401
66402};
66403
66404/***/ }),
66405/* 498 */
66406/***/ (function(module, exports, __webpack_require__) {
66407
66408"use strict";
66409/**
66410 * @fileoverview Rule to flag when a function has too many parameters
66411 * @author Ilya Volodin
66412 */
66413 //------------------------------------------------------------------------------
66414// Requirements
66415//------------------------------------------------------------------------------
66416
66417const lodash = __webpack_require__(403);
66418
66419const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
66420// Rule Definition
66421//------------------------------------------------------------------------------
66422
66423
66424module.exports = {
66425 meta: {
66426 type: "suggestion",
66427 docs: {
66428 description: "enforce a maximum number of parameters in function definitions",
66429 category: "Stylistic Issues",
66430 recommended: false,
66431 url: "https://eslint.org/docs/rules/max-params"
66432 },
66433 schema: [{
66434 oneOf: [{
66435 type: "integer",
66436 minimum: 0
66437 }, {
66438 type: "object",
66439 properties: {
66440 maximum: {
66441 type: "integer",
66442 minimum: 0
66443 },
66444 max: {
66445 type: "integer",
66446 minimum: 0
66447 }
66448 },
66449 additionalProperties: false
66450 }]
66451 }],
66452 messages: {
66453 exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}."
66454 }
66455 },
66456
66457 create(context) {
66458 const sourceCode = context.getSourceCode();
66459 const option = context.options[0];
66460 let numParams = 3;
66461
66462 if (typeof option === "object" && (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))) {
66463 numParams = option.maximum || option.max;
66464 }
66465
66466 if (typeof option === "number") {
66467 numParams = option;
66468 }
66469 /**
66470 * Checks a function to see if it has too many parameters.
66471 * @param {ASTNode} node The node to check.
66472 * @returns {void}
66473 * @private
66474 */
66475
66476
66477 function checkFunction(node) {
66478 if (node.params.length > numParams) {
66479 context.report({
66480 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
66481 node,
66482 messageId: "exceed",
66483 data: {
66484 name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)),
66485 count: node.params.length,
66486 max: numParams
66487 }
66488 });
66489 }
66490 }
66491
66492 return {
66493 FunctionDeclaration: checkFunction,
66494 ArrowFunctionExpression: checkFunction,
66495 FunctionExpression: checkFunction
66496 };
66497 }
66498
66499};
66500
66501/***/ }),
66502/* 499 */
66503/***/ (function(module, exports, __webpack_require__) {
66504
66505"use strict";
66506/**
66507 * @fileoverview A rule to set the maximum number of statements in a function.
66508 * @author Ian Christian Myers
66509 */
66510 //------------------------------------------------------------------------------
66511// Requirements
66512//------------------------------------------------------------------------------
66513
66514const lodash = __webpack_require__(403);
66515
66516const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
66517// Rule Definition
66518//------------------------------------------------------------------------------
66519
66520
66521module.exports = {
66522 meta: {
66523 type: "suggestion",
66524 docs: {
66525 description: "enforce a maximum number of statements allowed in function blocks",
66526 category: "Stylistic Issues",
66527 recommended: false,
66528 url: "https://eslint.org/docs/rules/max-statements"
66529 },
66530 schema: [{
66531 oneOf: [{
66532 type: "integer",
66533 minimum: 0
66534 }, {
66535 type: "object",
66536 properties: {
66537 maximum: {
66538 type: "integer",
66539 minimum: 0
66540 },
66541 max: {
66542 type: "integer",
66543 minimum: 0
66544 }
66545 },
66546 additionalProperties: false
66547 }]
66548 }, {
66549 type: "object",
66550 properties: {
66551 ignoreTopLevelFunctions: {
66552 type: "boolean"
66553 }
66554 },
66555 additionalProperties: false
66556 }],
66557 messages: {
66558 exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}."
66559 }
66560 },
66561
66562 create(context) {
66563 //--------------------------------------------------------------------------
66564 // Helpers
66565 //--------------------------------------------------------------------------
66566 const functionStack = [],
66567 option = context.options[0],
66568 ignoreTopLevelFunctions = context.options[1] && context.options[1].ignoreTopLevelFunctions || false,
66569 topLevelFunctions = [];
66570 let maxStatements = 10;
66571
66572 if (typeof option === "object" && (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))) {
66573 maxStatements = option.maximum || option.max;
66574 } else if (typeof option === "number") {
66575 maxStatements = option;
66576 }
66577 /**
66578 * Reports a node if it has too many statements
66579 * @param {ASTNode} node node to evaluate
66580 * @param {int} count Number of statements in node
66581 * @param {int} max Maximum number of statements allowed
66582 * @returns {void}
66583 * @private
66584 */
66585
66586
66587 function reportIfTooManyStatements(node, count, max) {
66588 if (count > max) {
66589 const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node));
66590 context.report({
66591 node,
66592 messageId: "exceed",
66593 data: {
66594 name,
66595 count,
66596 max
66597 }
66598 });
66599 }
66600 }
66601 /**
66602 * When parsing a new function, store it in our function stack
66603 * @returns {void}
66604 * @private
66605 */
66606
66607
66608 function startFunction() {
66609 functionStack.push(0);
66610 }
66611 /**
66612 * Evaluate the node at the end of function
66613 * @param {ASTNode} node node to evaluate
66614 * @returns {void}
66615 * @private
66616 */
66617
66618
66619 function endFunction(node) {
66620 const count = functionStack.pop();
66621
66622 if (ignoreTopLevelFunctions && functionStack.length === 0) {
66623 topLevelFunctions.push({
66624 node,
66625 count
66626 });
66627 } else {
66628 reportIfTooManyStatements(node, count, maxStatements);
66629 }
66630 }
66631 /**
66632 * Increment the count of the functions
66633 * @param {ASTNode} node node to evaluate
66634 * @returns {void}
66635 * @private
66636 */
66637
66638
66639 function countStatements(node) {
66640 functionStack[functionStack.length - 1] += node.body.length;
66641 } //--------------------------------------------------------------------------
66642 // Public API
66643 //--------------------------------------------------------------------------
66644
66645
66646 return {
66647 FunctionDeclaration: startFunction,
66648 FunctionExpression: startFunction,
66649 ArrowFunctionExpression: startFunction,
66650 BlockStatement: countStatements,
66651 "FunctionDeclaration:exit": endFunction,
66652 "FunctionExpression:exit": endFunction,
66653 "ArrowFunctionExpression:exit": endFunction,
66654
66655 "Program:exit"() {
66656 if (topLevelFunctions.length === 1) {
66657 return;
66658 }
66659
66660 topLevelFunctions.forEach(element => {
66661 const count = element.count;
66662 const node = element.node;
66663 reportIfTooManyStatements(node, count, maxStatements);
66664 });
66665 }
66666
66667 };
66668 }
66669
66670};
66671
66672/***/ }),
66673/* 500 */
66674/***/ (function(module, exports, __webpack_require__) {
66675
66676"use strict";
66677/**
66678 * @fileoverview Specify the maximum number of statements allowed per line.
66679 * @author Kenneth Williams
66680 */
66681 //------------------------------------------------------------------------------
66682// Requirements
66683//------------------------------------------------------------------------------
66684
66685const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
66686// Rule Definition
66687//------------------------------------------------------------------------------
66688
66689
66690module.exports = {
66691 meta: {
66692 type: "layout",
66693 docs: {
66694 description: "enforce a maximum number of statements allowed per line",
66695 category: "Stylistic Issues",
66696 recommended: false,
66697 url: "https://eslint.org/docs/rules/max-statements-per-line"
66698 },
66699 schema: [{
66700 type: "object",
66701 properties: {
66702 max: {
66703 type: "integer",
66704 minimum: 1,
66705 default: 1
66706 }
66707 },
66708 additionalProperties: false
66709 }],
66710 messages: {
66711 exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}."
66712 }
66713 },
66714
66715 create(context) {
66716 const sourceCode = context.getSourceCode(),
66717 options = context.options[0] || {},
66718 maxStatementsPerLine = typeof options.max !== "undefined" ? options.max : 1;
66719 let lastStatementLine = 0,
66720 numberOfStatementsOnThisLine = 0,
66721 firstExtraStatement; //--------------------------------------------------------------------------
66722 // Helpers
66723 //--------------------------------------------------------------------------
66724
66725 const SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/u;
66726 /**
66727 * Reports with the first extra statement, and clears it.
66728 * @returns {void}
66729 */
66730
66731 function reportFirstExtraStatementAndClear() {
66732 if (firstExtraStatement) {
66733 context.report({
66734 node: firstExtraStatement,
66735 messageId: "exceed",
66736 data: {
66737 numberOfStatementsOnThisLine,
66738 maxStatementsPerLine,
66739 statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements"
66740 }
66741 });
66742 }
66743
66744 firstExtraStatement = null;
66745 }
66746 /**
66747 * Gets the actual last token of a given node.
66748 * @param {ASTNode} node A node to get. This is a node except EmptyStatement.
66749 * @returns {Token} The actual last token.
66750 */
66751
66752
66753 function getActualLastToken(node) {
66754 return sourceCode.getLastToken(node, astUtils.isNotSemicolonToken);
66755 }
66756 /**
66757 * Addresses a given node.
66758 * It updates the state of this rule, then reports the node if the node violated this rule.
66759 * @param {ASTNode} node A node to check.
66760 * @returns {void}
66761 */
66762
66763
66764 function enterStatement(node) {
66765 const line = node.loc.start.line;
66766 /*
66767 * Skip to allow non-block statements if this is direct child of control statements.
66768 * `if (a) foo();` is counted as 1.
66769 * But `if (a) foo(); else foo();` should be counted as 2.
66770 */
66771
66772 if (SINGLE_CHILD_ALLOWED.test(node.parent.type) && node.parent.alternate !== node) {
66773 return;
66774 } // Update state.
66775
66776
66777 if (line === lastStatementLine) {
66778 numberOfStatementsOnThisLine += 1;
66779 } else {
66780 reportFirstExtraStatementAndClear();
66781 numberOfStatementsOnThisLine = 1;
66782 lastStatementLine = line;
66783 } // Reports if the node violated this rule.
66784
66785
66786 if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) {
66787 firstExtraStatement = firstExtraStatement || node;
66788 }
66789 }
66790 /**
66791 * Updates the state of this rule with the end line of leaving node to check with the next statement.
66792 * @param {ASTNode} node A node to check.
66793 * @returns {void}
66794 */
66795
66796
66797 function leaveStatement(node) {
66798 const line = getActualLastToken(node).loc.end.line; // Update state.
66799
66800 if (line !== lastStatementLine) {
66801 reportFirstExtraStatementAndClear();
66802 numberOfStatementsOnThisLine = 1;
66803 lastStatementLine = line;
66804 }
66805 } //--------------------------------------------------------------------------
66806 // Public API
66807 //--------------------------------------------------------------------------
66808
66809
66810 return {
66811 BreakStatement: enterStatement,
66812 ClassDeclaration: enterStatement,
66813 ContinueStatement: enterStatement,
66814 DebuggerStatement: enterStatement,
66815 DoWhileStatement: enterStatement,
66816 ExpressionStatement: enterStatement,
66817 ForInStatement: enterStatement,
66818 ForOfStatement: enterStatement,
66819 ForStatement: enterStatement,
66820 FunctionDeclaration: enterStatement,
66821 IfStatement: enterStatement,
66822 ImportDeclaration: enterStatement,
66823 LabeledStatement: enterStatement,
66824 ReturnStatement: enterStatement,
66825 SwitchStatement: enterStatement,
66826 ThrowStatement: enterStatement,
66827 TryStatement: enterStatement,
66828 VariableDeclaration: enterStatement,
66829 WhileStatement: enterStatement,
66830 WithStatement: enterStatement,
66831 ExportNamedDeclaration: enterStatement,
66832 ExportDefaultDeclaration: enterStatement,
66833 ExportAllDeclaration: enterStatement,
66834 "BreakStatement:exit": leaveStatement,
66835 "ClassDeclaration:exit": leaveStatement,
66836 "ContinueStatement:exit": leaveStatement,
66837 "DebuggerStatement:exit": leaveStatement,
66838 "DoWhileStatement:exit": leaveStatement,
66839 "ExpressionStatement:exit": leaveStatement,
66840 "ForInStatement:exit": leaveStatement,
66841 "ForOfStatement:exit": leaveStatement,
66842 "ForStatement:exit": leaveStatement,
66843 "FunctionDeclaration:exit": leaveStatement,
66844 "IfStatement:exit": leaveStatement,
66845 "ImportDeclaration:exit": leaveStatement,
66846 "LabeledStatement:exit": leaveStatement,
66847 "ReturnStatement:exit": leaveStatement,
66848 "SwitchStatement:exit": leaveStatement,
66849 "ThrowStatement:exit": leaveStatement,
66850 "TryStatement:exit": leaveStatement,
66851 "VariableDeclaration:exit": leaveStatement,
66852 "WhileStatement:exit": leaveStatement,
66853 "WithStatement:exit": leaveStatement,
66854 "ExportNamedDeclaration:exit": leaveStatement,
66855 "ExportDefaultDeclaration:exit": leaveStatement,
66856 "ExportAllDeclaration:exit": leaveStatement,
66857 "Program:exit": reportFirstExtraStatementAndClear
66858 };
66859 }
66860
66861};
66862
66863/***/ }),
66864/* 501 */
66865/***/ (function(module, exports, __webpack_require__) {
66866
66867"use strict";
66868/**
66869 * @fileoverview enforce a particular style for multiline comments
66870 * @author Teddy Katz
66871 */
66872
66873
66874const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
66875// Rule Definition
66876//------------------------------------------------------------------------------
66877
66878
66879module.exports = {
66880 meta: {
66881 type: "suggestion",
66882 docs: {
66883 description: "enforce a particular style for multiline comments",
66884 category: "Stylistic Issues",
66885 recommended: false,
66886 url: "https://eslint.org/docs/rules/multiline-comment-style"
66887 },
66888 fixable: "whitespace",
66889 schema: [{
66890 enum: ["starred-block", "separate-lines", "bare-block"]
66891 }],
66892 messages: {
66893 expectedBlock: "Expected a block comment instead of consecutive line comments.",
66894 expectedBareBlock: "Expected a block comment without padding stars.",
66895 startNewline: "Expected a linebreak after '/*'.",
66896 endNewline: "Expected a linebreak before '*/'.",
66897 missingStar: "Expected a '*' at the start of this line.",
66898 alignment: "Expected this line to be aligned with the start of the comment.",
66899 expectedLines: "Expected multiple line comments instead of a block comment."
66900 }
66901 },
66902
66903 create(context) {
66904 const sourceCode = context.getSourceCode();
66905 const option = context.options[0] || "starred-block"; //----------------------------------------------------------------------
66906 // Helpers
66907 //----------------------------------------------------------------------
66908
66909 /**
66910 * Checks if a comment line is starred.
66911 * @param {string} line A string representing a comment line.
66912 * @returns {boolean} Whether or not the comment line is starred.
66913 */
66914
66915 function isStarredCommentLine(line) {
66916 return /^\s*\*/u.test(line);
66917 }
66918 /**
66919 * Checks if a comment group is in starred-block form.
66920 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
66921 * @returns {boolean} Whether or not the comment group is in starred block form.
66922 */
66923
66924
66925 function isStarredBlockComment([firstComment]) {
66926 if (firstComment.type !== "Block") {
66927 return false;
66928 }
66929
66930 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); // The first and last lines can only contain whitespace.
66931
66932 return lines.length > 0 && lines.every((line, i) => (i === 0 || i === lines.length - 1 ? /^\s*$/u : /^\s*\*/u).test(line));
66933 }
66934 /**
66935 * Checks if a comment group is in JSDoc form.
66936 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
66937 * @returns {boolean} Whether or not the comment group is in JSDoc form.
66938 */
66939
66940
66941 function isJSDocComment([firstComment]) {
66942 if (firstComment.type !== "Block") {
66943 return false;
66944 }
66945
66946 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
66947 return /^\*\s*$/u.test(lines[0]) && lines.slice(1, -1).every(line => /^\s* /u.test(line)) && /^\s*$/u.test(lines[lines.length - 1]);
66948 }
66949 /**
66950 * Processes a comment group that is currently in separate-line form, calculating the offset for each line.
66951 * @param {Token[]} commentGroup A group of comments containing multiple line comments.
66952 * @returns {string[]} An array of the processed lines.
66953 */
66954
66955
66956 function processSeparateLineComments(commentGroup) {
66957 const allLinesHaveLeadingSpace = commentGroup.map(({
66958 value
66959 }) => value).filter(line => line.trim().length).every(line => line.startsWith(" "));
66960 return commentGroup.map(({
66961 value
66962 }) => allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value);
66963 }
66964 /**
66965 * Processes a comment group that is currently in starred-block form, calculating the offset for each line.
66966 * @param {Token} comment A single block comment token in starred-block form.
66967 * @returns {string[]} An array of the processed lines.
66968 */
66969
66970
66971 function processStarredBlockComment(comment) {
66972 const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).filter((line, i, linesArr) => !(i === 0 || i === linesArr.length - 1)).map(line => line.replace(/^\s*$/u, ""));
66973 const allLinesHaveLeadingSpace = lines.map(line => line.replace(/\s*\*/u, "")).filter(line => line.trim().length).every(line => line.startsWith(" "));
66974 return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, ""));
66975 }
66976 /**
66977 * Processes a comment group that is currently in bare-block form, calculating the offset for each line.
66978 * @param {Token} comment A single block comment token in bare-block form.
66979 * @returns {string[]} An array of the processed lines.
66980 */
66981
66982
66983 function processBareBlockComment(comment) {
66984 const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).map(line => line.replace(/^\s*$/u, ""));
66985 const leadingWhitespace = "".concat(sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]), " ");
66986 let offset = "";
66987 /*
66988 * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines.
66989 * The first line should not be checked because it is inline with the opening block comment delimiter.
66990 */
66991
66992 for (const [i, line] of lines.entries()) {
66993 if (!line.trim().length || i === 0) {
66994 continue;
66995 }
66996
66997 const [, lineOffset] = line.match(/^(\s*\*?\s*)/u);
66998
66999 if (lineOffset.length < leadingWhitespace.length) {
67000 const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length);
67001
67002 if (newOffset.length > offset.length) {
67003 offset = newOffset;
67004 }
67005 }
67006 }
67007
67008 return lines.map(line => {
67009 const match = line.match(/^(\s*\*?\s*)(.*)/u);
67010 const [, lineOffset, lineContents] = match;
67011
67012 if (lineOffset.length > leadingWhitespace.length) {
67013 return "".concat(lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))).concat(lineContents);
67014 }
67015
67016 if (lineOffset.length < leadingWhitespace.length) {
67017 return "".concat(lineOffset.slice(leadingWhitespace.length)).concat(lineContents);
67018 }
67019
67020 return lineContents;
67021 });
67022 }
67023 /**
67024 * Gets a list of comment lines in a group, formatting leading whitespace as necessary.
67025 * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment.
67026 * @returns {string[]} A list of comment lines.
67027 */
67028
67029
67030 function getCommentLines(commentGroup) {
67031 const [firstComment] = commentGroup;
67032
67033 if (firstComment.type === "Line") {
67034 return processSeparateLineComments(commentGroup);
67035 }
67036
67037 if (isStarredBlockComment(commentGroup)) {
67038 return processStarredBlockComment(firstComment);
67039 }
67040
67041 return processBareBlockComment(firstComment);
67042 }
67043 /**
67044 * Gets the initial offset (whitespace) from the beginning of a line to a given comment token.
67045 * @param {Token} comment The token to check.
67046 * @returns {string} The offset from the beginning of a line to the token.
67047 */
67048
67049
67050 function getInitialOffset(comment) {
67051 return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]);
67052 }
67053 /**
67054 * Converts a comment into starred-block form
67055 * @param {Token} firstComment The first comment of the group being converted
67056 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
67057 * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
67058 */
67059
67060
67061 function convertToStarredBlock(firstComment, commentLinesList) {
67062 const initialOffset = getInitialOffset(firstComment);
67063 return "/*\n".concat(commentLinesList.map(line => "".concat(initialOffset, " * ").concat(line)).join("\n"), "\n").concat(initialOffset, " */");
67064 }
67065 /**
67066 * Converts a comment into separate-line form
67067 * @param {Token} firstComment The first comment of the group being converted
67068 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
67069 * @returns {string} A representation of the comment value in separate-line form
67070 */
67071
67072
67073 function convertToSeparateLines(firstComment, commentLinesList) {
67074 return commentLinesList.map(line => "// ".concat(line)).join("\n".concat(getInitialOffset(firstComment)));
67075 }
67076 /**
67077 * Converts a comment into bare-block form
67078 * @param {Token} firstComment The first comment of the group being converted
67079 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
67080 * @returns {string} A representation of the comment value in bare-block form
67081 */
67082
67083
67084 function convertToBlock(firstComment, commentLinesList) {
67085 return "/* ".concat(commentLinesList.join("\n".concat(getInitialOffset(firstComment), " ")), " */");
67086 }
67087 /**
67088 * Each method checks a group of comments to see if it's valid according to the given option.
67089 * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
67090 * block comment or multiple line comments.
67091 * @returns {void}
67092 */
67093
67094
67095 const commentGroupCheckers = {
67096 "starred-block"(commentGroup) {
67097 const [firstComment] = commentGroup;
67098 const commentLines = getCommentLines(commentGroup);
67099
67100 if (commentLines.some(value => value.includes("*/"))) {
67101 return;
67102 }
67103
67104 if (commentGroup.length > 1) {
67105 context.report({
67106 loc: {
67107 start: firstComment.loc.start,
67108 end: commentGroup[commentGroup.length - 1].loc.end
67109 },
67110 messageId: "expectedBlock",
67111
67112 fix(fixer) {
67113 const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]];
67114 return commentLines.some(value => value.startsWith("/")) ? null : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines));
67115 }
67116
67117 });
67118 } else {
67119 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
67120 const expectedLeadingWhitespace = getInitialOffset(firstComment);
67121 const expectedLinePrefix = "".concat(expectedLeadingWhitespace, " *");
67122
67123 if (!/^\*?\s*$/u.test(lines[0])) {
67124 const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0];
67125 context.report({
67126 loc: {
67127 start: firstComment.loc.start,
67128 end: {
67129 line: firstComment.loc.start.line,
67130 column: firstComment.loc.start.column + 2
67131 }
67132 },
67133 messageId: "startNewline",
67134 fix: fixer => fixer.insertTextAfterRange([start, start + 2], "\n".concat(expectedLinePrefix))
67135 });
67136 }
67137
67138 if (!/^\s*$/u.test(lines[lines.length - 1])) {
67139 context.report({
67140 loc: {
67141 start: {
67142 line: firstComment.loc.end.line,
67143 column: firstComment.loc.end.column - 2
67144 },
67145 end: firstComment.loc.end
67146 },
67147 messageId: "endNewline",
67148 fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], "\n".concat(expectedLinePrefix, "/"))
67149 });
67150 }
67151
67152 for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) {
67153 const lineText = sourceCode.lines[lineNumber - 1];
67154 const errorType = isStarredCommentLine(lineText) ? "alignment" : "missingStar";
67155
67156 if (!lineText.startsWith(expectedLinePrefix)) {
67157 context.report({
67158 loc: {
67159 start: {
67160 line: lineNumber,
67161 column: 0
67162 },
67163 end: {
67164 line: lineNumber,
67165 column: lineText.length
67166 }
67167 },
67168 messageId: errorType,
67169
67170 fix(fixer) {
67171 const lineStartIndex = sourceCode.getIndexFromLoc({
67172 line: lineNumber,
67173 column: 0
67174 });
67175
67176 if (errorType === "alignment") {
67177 const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || [];
67178 const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
67179 return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix);
67180 }
67181
67182 const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || [];
67183 const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
67184 let offset;
67185
67186 for (const [idx, line] of lines.entries()) {
67187 if (!/\S+/u.test(line)) {
67188 continue;
67189 }
67190
67191 const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx];
67192 const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || [];
67193 offset = "".concat(commentTextPrefix.slice(prefix.length)).concat(initialOffset);
67194
67195 if (/^\s*\//u.test(lineText) && offset.length === 0) {
67196 offset += " ";
67197 }
67198
67199 break;
67200 }
67201
67202 return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], "".concat(expectedLinePrefix).concat(offset));
67203 }
67204
67205 });
67206 }
67207 }
67208 }
67209 },
67210
67211 "separate-lines"(commentGroup) {
67212 const [firstComment] = commentGroup;
67213
67214 if (firstComment.type !== "Block" || isJSDocComment(commentGroup)) {
67215 return;
67216 }
67217
67218 const commentLines = getCommentLines(commentGroup);
67219 const tokenAfter = sourceCode.getTokenAfter(firstComment, {
67220 includeComments: true
67221 });
67222
67223 if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) {
67224 return;
67225 }
67226
67227 context.report({
67228 loc: {
67229 start: firstComment.loc.start,
67230 end: {
67231 line: firstComment.loc.start.line,
67232 column: firstComment.loc.start.column + 2
67233 }
67234 },
67235 messageId: "expectedLines",
67236
67237 fix(fixer) {
67238 return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines));
67239 }
67240
67241 });
67242 },
67243
67244 "bare-block"(commentGroup) {
67245 if (isJSDocComment(commentGroup)) {
67246 return;
67247 }
67248
67249 const [firstComment] = commentGroup;
67250 const commentLines = getCommentLines(commentGroup); // Disallows consecutive line comments in favor of using a block comment.
67251
67252 if (firstComment.type === "Line" && commentLines.length > 1 && !commentLines.some(value => value.includes("*/"))) {
67253 context.report({
67254 loc: {
67255 start: firstComment.loc.start,
67256 end: commentGroup[commentGroup.length - 1].loc.end
67257 },
67258 messageId: "expectedBlock",
67259
67260 fix(fixer) {
67261 return fixer.replaceTextRange([firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]], convertToBlock(firstComment, commentLines));
67262 }
67263
67264 });
67265 } // Prohibits block comments from having a * at the beginning of each line.
67266
67267
67268 if (isStarredBlockComment(commentGroup)) {
67269 context.report({
67270 loc: {
67271 start: firstComment.loc.start,
67272 end: {
67273 line: firstComment.loc.start.line,
67274 column: firstComment.loc.start.column + 2
67275 }
67276 },
67277 messageId: "expectedBareBlock",
67278
67279 fix(fixer) {
67280 return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines));
67281 }
67282
67283 });
67284 }
67285 }
67286
67287 }; //----------------------------------------------------------------------
67288 // Public
67289 //----------------------------------------------------------------------
67290
67291 return {
67292 Program() {
67293 return sourceCode.getAllComments().filter(comment => comment.type !== "Shebang").filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value)).filter(comment => {
67294 const tokenBefore = sourceCode.getTokenBefore(comment, {
67295 includeComments: true
67296 });
67297 return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
67298 }).reduce((commentGroups, comment, index, commentList) => {
67299 const tokenBefore = sourceCode.getTokenBefore(comment, {
67300 includeComments: true
67301 });
67302
67303 if (comment.type === "Line" && index && commentList[index - 1].type === "Line" && tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 && tokenBefore === commentList[index - 1]) {
67304 commentGroups[commentGroups.length - 1].push(comment);
67305 } else {
67306 commentGroups.push([comment]);
67307 }
67308
67309 return commentGroups;
67310 }, []).filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line)).forEach(commentGroupCheckers[option]);
67311 }
67312
67313 };
67314 }
67315
67316};
67317
67318/***/ }),
67319/* 502 */
67320/***/ (function(module, exports, __webpack_require__) {
67321
67322"use strict";
67323/**
67324 * @fileoverview Enforce newlines between operands of ternary expressions
67325 * @author Kai Cataldo
67326 */
67327
67328
67329const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
67330// Rule Definition
67331//------------------------------------------------------------------------------
67332
67333
67334module.exports = {
67335 meta: {
67336 type: "layout",
67337 docs: {
67338 description: "enforce newlines between operands of ternary expressions",
67339 category: "Stylistic Issues",
67340 recommended: false,
67341 url: "https://eslint.org/docs/rules/multiline-ternary"
67342 },
67343 schema: [{
67344 enum: ["always", "always-multiline", "never"]
67345 }],
67346 messages: {
67347 expectedTestCons: "Expected newline between test and consequent of ternary expression.",
67348 expectedConsAlt: "Expected newline between consequent and alternate of ternary expression.",
67349 unexpectedTestCons: "Unexpected newline between test and consequent of ternary expression.",
67350 unexpectedConsAlt: "Unexpected newline between consequent and alternate of ternary expression."
67351 }
67352 },
67353
67354 create(context) {
67355 const option = context.options[0];
67356 const multiline = option !== "never";
67357 const allowSingleLine = option === "always-multiline"; //--------------------------------------------------------------------------
67358 // Helpers
67359 //--------------------------------------------------------------------------
67360
67361 /**
67362 * Tests whether node is preceded by supplied tokens
67363 * @param {ASTNode} node node to check
67364 * @param {ASTNode} parentNode parent of node to report
67365 * @param {boolean} expected whether newline was expected or not
67366 * @returns {void}
67367 * @private
67368 */
67369
67370 function reportError(node, parentNode, expected) {
67371 context.report({
67372 node,
67373 messageId: "".concat(expected ? "expected" : "unexpected").concat(node === parentNode.test ? "TestCons" : "ConsAlt")
67374 });
67375 } //--------------------------------------------------------------------------
67376 // Public
67377 //--------------------------------------------------------------------------
67378
67379
67380 return {
67381 ConditionalExpression(node) {
67382 const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(node.test, node.consequent);
67383 const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(node.consequent, node.alternate);
67384
67385 if (!multiline) {
67386 if (!areTestAndConsequentOnSameLine) {
67387 reportError(node.test, node, false);
67388 }
67389
67390 if (!areConsequentAndAlternateOnSameLine) {
67391 reportError(node.consequent, node, false);
67392 }
67393 } else {
67394 if (allowSingleLine && node.loc.start.line === node.loc.end.line) {
67395 return;
67396 }
67397
67398 if (areTestAndConsequentOnSameLine) {
67399 reportError(node.test, node, true);
67400 }
67401
67402 if (areConsequentAndAlternateOnSameLine) {
67403 reportError(node.consequent, node, true);
67404 }
67405 }
67406 }
67407
67408 };
67409 }
67410
67411};
67412
67413/***/ }),
67414/* 503 */
67415/***/ (function(module, exports, __webpack_require__) {
67416
67417"use strict";
67418/**
67419 * @fileoverview Rule to flag use of constructors without capital letters
67420 * @author Nicholas C. Zakas
67421 */
67422 //------------------------------------------------------------------------------
67423// Requirements
67424//------------------------------------------------------------------------------
67425
67426const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
67427// Helpers
67428//------------------------------------------------------------------------------
67429
67430
67431const CAPS_ALLOWED = ["Array", "Boolean", "Date", "Error", "Function", "Number", "Object", "RegExp", "String", "Symbol", "BigInt"];
67432/**
67433 * Ensure that if the key is provided, it must be an array.
67434 * @param {Object} obj Object to check with `key`.
67435 * @param {string} key Object key to check on `obj`.
67436 * @param {*} fallback If obj[key] is not present, this will be returned.
67437 * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback`
67438 */
67439
67440function checkArray(obj, key, fallback) {
67441 /* istanbul ignore if */
67442 if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
67443 throw new TypeError("".concat(key, ", if provided, must be an Array"));
67444 }
67445
67446 return obj[key] || fallback;
67447}
67448/**
67449 * A reducer function to invert an array to an Object mapping the string form of the key, to `true`.
67450 * @param {Object} map Accumulator object for the reduce.
67451 * @param {string} key Object key to set to `true`.
67452 * @returns {Object} Returns the updated Object for further reduction.
67453 */
67454
67455
67456function invert(map, key) {
67457 map[key] = true;
67458 return map;
67459}
67460/**
67461 * Creates an object with the cap is new exceptions as its keys and true as their values.
67462 * @param {Object} config Rule configuration
67463 * @returns {Object} Object with cap is new exceptions.
67464 */
67465
67466
67467function calculateCapIsNewExceptions(config) {
67468 let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
67469
67470 if (capIsNewExceptions !== CAPS_ALLOWED) {
67471 capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
67472 }
67473
67474 return capIsNewExceptions.reduce(invert, {});
67475} //------------------------------------------------------------------------------
67476// Rule Definition
67477//------------------------------------------------------------------------------
67478
67479
67480module.exports = {
67481 meta: {
67482 type: "suggestion",
67483 docs: {
67484 description: "require constructor names to begin with a capital letter",
67485 category: "Stylistic Issues",
67486 recommended: false,
67487 url: "https://eslint.org/docs/rules/new-cap"
67488 },
67489 schema: [{
67490 type: "object",
67491 properties: {
67492 newIsCap: {
67493 type: "boolean",
67494 default: true
67495 },
67496 capIsNew: {
67497 type: "boolean",
67498 default: true
67499 },
67500 newIsCapExceptions: {
67501 type: "array",
67502 items: {
67503 type: "string"
67504 }
67505 },
67506 newIsCapExceptionPattern: {
67507 type: "string"
67508 },
67509 capIsNewExceptions: {
67510 type: "array",
67511 items: {
67512 type: "string"
67513 }
67514 },
67515 capIsNewExceptionPattern: {
67516 type: "string"
67517 },
67518 properties: {
67519 type: "boolean",
67520 default: true
67521 }
67522 },
67523 additionalProperties: false
67524 }],
67525 messages: {
67526 upper: "A function with a name starting with an uppercase letter should only be used as a constructor.",
67527 lower: "A constructor name should not start with a lowercase letter."
67528 }
67529 },
67530
67531 create(context) {
67532 const config = Object.assign({}, context.options[0]);
67533 config.newIsCap = config.newIsCap !== false;
67534 config.capIsNew = config.capIsNew !== false;
67535 const skipProperties = config.properties === false;
67536 const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
67537 const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern, "u") : null;
67538 const capIsNewExceptions = calculateCapIsNewExceptions(config);
67539 const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern, "u") : null;
67540 const listeners = {};
67541 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
67542 // Helpers
67543 //--------------------------------------------------------------------------
67544
67545 /**
67546 * Get exact callee name from expression
67547 * @param {ASTNode} node CallExpression or NewExpression node
67548 * @returns {string} name
67549 */
67550
67551 function extractNameFromExpression(node) {
67552 let name = "";
67553
67554 if (node.callee.type === "MemberExpression") {
67555 name = astUtils.getStaticPropertyName(node.callee) || "";
67556 } else {
67557 name = node.callee.name;
67558 }
67559
67560 return name;
67561 }
67562 /**
67563 * Returns the capitalization state of the string -
67564 * Whether the first character is uppercase, lowercase, or non-alphabetic
67565 * @param {string} str String
67566 * @returns {string} capitalization state: "non-alpha", "lower", or "upper"
67567 */
67568
67569
67570 function getCap(str) {
67571 const firstChar = str.charAt(0);
67572 const firstCharLower = firstChar.toLowerCase();
67573 const firstCharUpper = firstChar.toUpperCase();
67574
67575 if (firstCharLower === firstCharUpper) {
67576 // char has no uppercase variant, so it's non-alphabetic
67577 return "non-alpha";
67578 }
67579
67580 if (firstChar === firstCharLower) {
67581 return "lower";
67582 }
67583
67584 return "upper";
67585 }
67586 /**
67587 * Check if capitalization is allowed for a CallExpression
67588 * @param {Object} allowedMap Object mapping calleeName to a Boolean
67589 * @param {ASTNode} node CallExpression node
67590 * @param {string} calleeName Capitalized callee name from a CallExpression
67591 * @param {Object} pattern RegExp object from options pattern
67592 * @returns {boolean} Returns true if the callee may be capitalized
67593 */
67594
67595
67596 function isCapAllowed(allowedMap, node, calleeName, pattern) {
67597 const sourceText = sourceCode.getText(node.callee);
67598
67599 if (allowedMap[calleeName] || allowedMap[sourceText]) {
67600 return true;
67601 }
67602
67603 if (pattern && pattern.test(sourceText)) {
67604 return true;
67605 }
67606
67607 if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
67608 // allow if callee is Date.UTC
67609 return node.callee.object.type === "Identifier" && node.callee.object.name === "Date";
67610 }
67611
67612 return skipProperties && node.callee.type === "MemberExpression";
67613 }
67614 /**
67615 * Reports the given messageId for the given node. The location will be the start of the property or the callee.
67616 * @param {ASTNode} node CallExpression or NewExpression node.
67617 * @param {string} messageId The messageId to report.
67618 * @returns {void}
67619 */
67620
67621
67622 function report(node, messageId) {
67623 let callee = node.callee;
67624
67625 if (callee.type === "MemberExpression") {
67626 callee = callee.property;
67627 }
67628
67629 context.report({
67630 node,
56c4a2cb 67631 loc: callee.loc,
eb39fafa
DC
67632 messageId
67633 });
67634 } //--------------------------------------------------------------------------
67635 // Public
67636 //--------------------------------------------------------------------------
67637
67638
67639 if (config.newIsCap) {
67640 listeners.NewExpression = function (node) {
67641 const constructorName = extractNameFromExpression(node);
67642
67643 if (constructorName) {
67644 const capitalization = getCap(constructorName);
67645 const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern);
67646
67647 if (!isAllowed) {
67648 report(node, "lower");
67649 }
67650 }
67651 };
67652 }
67653
67654 if (config.capIsNew) {
67655 listeners.CallExpression = function (node) {
67656 const calleeName = extractNameFromExpression(node);
67657
67658 if (calleeName) {
67659 const capitalization = getCap(calleeName);
67660 const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern);
67661
67662 if (!isAllowed) {
67663 report(node, "upper");
67664 }
67665 }
67666 };
67667 }
67668
67669 return listeners;
67670 }
67671
67672};
67673
67674/***/ }),
67675/* 504 */
67676/***/ (function(module, exports, __webpack_require__) {
67677
67678"use strict";
67679/**
67680 * @fileoverview Rule to flag when using constructor without parentheses
67681 * @author Ilya Volodin
67682 */
67683 //------------------------------------------------------------------------------
67684// Requirements
67685//------------------------------------------------------------------------------
67686
67687const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
67688// Helpers
67689//------------------------------------------------------------------------------
67690//------------------------------------------------------------------------------
67691// Rule Definition
67692//------------------------------------------------------------------------------
67693
67694
67695module.exports = {
67696 meta: {
67697 type: "layout",
67698 docs: {
67699 description: "enforce or disallow parentheses when invoking a constructor with no arguments",
67700 category: "Stylistic Issues",
67701 recommended: false,
67702 url: "https://eslint.org/docs/rules/new-parens"
67703 },
67704 fixable: "code",
67705 schema: {
67706 anyOf: [{
67707 type: "array",
67708 items: [{
67709 enum: ["always", "never"]
67710 }],
67711 minItems: 0,
67712 maxItems: 1
67713 }]
67714 },
67715 messages: {
67716 missing: "Missing '()' invoking a constructor.",
67717 unnecessary: "Unnecessary '()' invoking a constructor with no arguments."
67718 }
67719 },
67720
67721 create(context) {
67722 const options = context.options;
67723 const always = options[0] !== "never"; // Default is always
67724
67725 const sourceCode = context.getSourceCode();
67726 return {
67727 NewExpression(node) {
67728 if (node.arguments.length !== 0) {
67729 return; // if there are arguments, there have to be parens
67730 }
67731
67732 const lastToken = sourceCode.getLastToken(node);
67733 const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken); // `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens
67734
67735 const hasParens = hasLastParen && astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) && node.callee.range[1] < node.range[1];
67736
67737 if (always) {
67738 if (!hasParens) {
67739 context.report({
67740 node,
67741 messageId: "missing",
67742 fix: fixer => fixer.insertTextAfter(node, "()")
67743 });
67744 }
67745 } else {
67746 if (hasParens) {
67747 context.report({
67748 node,
67749 messageId: "unnecessary",
67750 fix: fixer => [fixer.remove(sourceCode.getTokenBefore(lastToken)), fixer.remove(lastToken), fixer.insertTextBefore(node, "("), fixer.insertTextAfter(node, ")")]
67751 });
67752 }
67753 }
67754 }
67755
67756 };
67757 }
67758
67759};
67760
67761/***/ }),
67762/* 505 */
67763/***/ (function(module, exports, __webpack_require__) {
67764
67765"use strict";
67766/**
67767 * @fileoverview Rule to check empty newline after "var" statement
67768 * @author Gopal Venkatesan
67769 * @deprecated
67770 */
67771 //------------------------------------------------------------------------------
67772// Requirements
67773//------------------------------------------------------------------------------
67774
67775const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
67776// Rule Definition
67777//------------------------------------------------------------------------------
67778
67779
67780module.exports = {
67781 meta: {
67782 type: "layout",
67783 docs: {
67784 description: "require or disallow an empty line after variable declarations",
67785 category: "Stylistic Issues",
67786 recommended: false,
67787 url: "https://eslint.org/docs/rules/newline-after-var"
67788 },
67789 schema: [{
67790 enum: ["never", "always"]
67791 }],
67792 fixable: "whitespace",
67793 messages: {
67794 expected: "Expected blank line after variable declarations.",
67795 unexpected: "Unexpected blank line after variable declarations."
67796 },
67797 deprecated: true,
67798 replacedBy: ["padding-line-between-statements"]
67799 },
67800
67801 create(context) {
67802 const sourceCode = context.getSourceCode(); // Default `mode` to "always".
67803
67804 const mode = context.options[0] === "never" ? "never" : "always"; // Cache starting and ending line numbers of comments for faster lookup
67805
67806 const commentEndLine = sourceCode.getAllComments().reduce((result, token) => {
67807 result[token.loc.start.line] = token.loc.end.line;
67808 return result;
67809 }, {}); //--------------------------------------------------------------------------
67810 // Helpers
67811 //--------------------------------------------------------------------------
67812
67813 /**
67814 * Gets a token from the given node to compare line to the next statement.
67815 *
67816 * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy.
67817 *
67818 * - The last token is semicolon.
67819 * - The semicolon is on a different line from the previous token of the semicolon.
67820 *
67821 * This behavior would address semicolon-less style code. e.g.:
67822 *
67823 * var foo = 1
67824 *
67825 * ;(a || b).doSomething()
67826 * @param {ASTNode} node The node to get.
67827 * @returns {Token} The token to compare line to the next statement.
67828 */
67829
67830 function getLastToken(node) {
67831 const lastToken = sourceCode.getLastToken(node);
67832
67833 if (lastToken.type === "Punctuator" && lastToken.value === ";") {
67834 const prevToken = sourceCode.getTokenBefore(lastToken);
67835
67836 if (prevToken.loc.end.line !== lastToken.loc.start.line) {
67837 return prevToken;
67838 }
67839 }
67840
67841 return lastToken;
67842 }
67843 /**
67844 * Determine if provided keyword is a variable declaration
67845 * @private
67846 * @param {string} keyword keyword to test
67847 * @returns {boolean} True if `keyword` is a type of var
67848 */
67849
67850
67851 function isVar(keyword) {
67852 return keyword === "var" || keyword === "let" || keyword === "const";
67853 }
67854 /**
67855 * Determine if provided keyword is a variant of for specifiers
67856 * @private
67857 * @param {string} keyword keyword to test
67858 * @returns {boolean} True if `keyword` is a variant of for specifier
67859 */
67860
67861
67862 function isForTypeSpecifier(keyword) {
67863 return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
67864 }
67865 /**
67866 * Determine if provided keyword is an export specifiers
67867 * @private
67868 * @param {string} nodeType nodeType to test
67869 * @returns {boolean} True if `nodeType` is an export specifier
67870 */
67871
67872
67873 function isExportSpecifier(nodeType) {
67874 return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" || nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration";
67875 }
67876 /**
67877 * Determine if provided node is the last of their parent block.
67878 * @private
67879 * @param {ASTNode} node node to test
67880 * @returns {boolean} True if `node` is last of their parent block.
67881 */
67882
67883
67884 function isLastNode(node) {
67885 const token = sourceCode.getTokenAfter(node);
67886 return !token || token.type === "Punctuator" && token.value === "}";
67887 }
67888 /**
67889 * Gets the last line of a group of consecutive comments
67890 * @param {number} commentStartLine The starting line of the group
67891 * @returns {number} The number of the last comment line of the group
67892 */
67893
67894
67895 function getLastCommentLineOfBlock(commentStartLine) {
67896 const currentCommentEnd = commentEndLine[commentStartLine];
67897 return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd;
67898 }
67899 /**
67900 * Determine if a token starts more than one line after a comment ends
67901 * @param {token} token The token being checked
67902 * @param {integer} commentStartLine The line number on which the comment starts
67903 * @returns {boolean} True if `token` does not start immediately after a comment
67904 */
67905
67906
67907 function hasBlankLineAfterComment(token, commentStartLine) {
67908 return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1;
67909 }
67910 /**
67911 * Checks that a blank line exists after a variable declaration when mode is
67912 * set to "always", or checks that there is no blank line when mode is set
67913 * to "never"
67914 * @private
67915 * @param {ASTNode} node `VariableDeclaration` node to test
67916 * @returns {void}
67917 */
67918
67919
67920 function checkForBlankLine(node) {
67921 /*
67922 * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will
67923 * sometimes be second-last if there is a semicolon on a different line.
67924 */
67925 const lastToken = getLastToken(node),
67926
67927 /*
67928 * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken
67929 * is the last token of the node.
67930 */
67931 nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node),
67932 nextLineNum = lastToken.loc.end.line + 1; // Ignore if there is no following statement
67933
67934 if (!nextToken) {
67935 return;
67936 } // Ignore if parent of node is a for variant
67937
67938
67939 if (isForTypeSpecifier(node.parent.type)) {
67940 return;
67941 } // Ignore if parent of node is an export specifier
67942
67943
67944 if (isExportSpecifier(node.parent.type)) {
67945 return;
67946 }
67947 /*
67948 * Some coding styles use multiple `var` statements, so do nothing if
67949 * the next token is a `var` statement.
67950 */
67951
67952
67953 if (nextToken.type === "Keyword" && isVar(nextToken.value)) {
67954 return;
67955 } // Ignore if it is last statement in a block
67956
67957
67958 if (isLastNode(node)) {
67959 return;
67960 } // Next statement is not a `var`...
67961
67962
67963 const noNextLineToken = nextToken.loc.start.line > nextLineNum;
67964 const hasNextLineComment = typeof commentEndLine[nextLineNum] !== "undefined";
67965
67966 if (mode === "never" && noNextLineToken && !hasNextLineComment) {
67967 context.report({
67968 node,
67969 messageId: "unexpected",
67970 data: {
67971 identifier: node.name
67972 },
67973
67974 fix(fixer) {
67975 const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
67976 return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], "".concat(linesBetween.slice(0, -1).join(""), "\n").concat(linesBetween[linesBetween.length - 1]));
67977 }
67978
67979 });
67980 } // Token on the next line, or comment without blank line
67981
67982
67983 if (mode === "always" && (!noNextLineToken || hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum))) {
67984 context.report({
67985 node,
67986 messageId: "expected",
67987 data: {
67988 identifier: node.name
67989 },
67990
67991 fix(fixer) {
67992 if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {
67993 return fixer.insertTextBefore(nextToken, "\n\n");
67994 }
67995
67996 return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n");
67997 }
67998
67999 });
68000 }
68001 } //--------------------------------------------------------------------------
68002 // Public
68003 //--------------------------------------------------------------------------
68004
68005
68006 return {
68007 VariableDeclaration: checkForBlankLine
68008 };
68009 }
68010
68011};
68012
68013/***/ }),
68014/* 506 */
68015/***/ (function(module, exports, __webpack_require__) {
68016
68017"use strict";
68018/**
68019 * @fileoverview Rule to require newlines before `return` statement
68020 * @author Kai Cataldo
68021 * @deprecated
68022 */
68023 //------------------------------------------------------------------------------
68024// Rule Definition
68025//------------------------------------------------------------------------------
68026
68027module.exports = {
68028 meta: {
68029 type: "layout",
68030 docs: {
68031 description: "require an empty line before `return` statements",
68032 category: "Stylistic Issues",
68033 recommended: false,
68034 url: "https://eslint.org/docs/rules/newline-before-return"
68035 },
68036 fixable: "whitespace",
68037 schema: [],
68038 messages: {
68039 expected: "Expected newline before return statement."
68040 },
68041 deprecated: true,
68042 replacedBy: ["padding-line-between-statements"]
68043 },
68044
68045 create(context) {
68046 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
68047 // Helpers
68048 //--------------------------------------------------------------------------
68049
68050 /**
68051 * Tests whether node is preceded by supplied tokens
68052 * @param {ASTNode} node node to check
68053 * @param {Array} testTokens array of tokens to test against
68054 * @returns {boolean} Whether or not the node is preceded by one of the supplied tokens
68055 * @private
68056 */
68057
68058 function isPrecededByTokens(node, testTokens) {
68059 const tokenBefore = sourceCode.getTokenBefore(node);
68060 return testTokens.some(token => tokenBefore.value === token);
68061 }
68062 /**
68063 * Checks whether node is the first node after statement or in block
68064 * @param {ASTNode} node node to check
68065 * @returns {boolean} Whether or not the node is the first node after statement or in block
68066 * @private
68067 */
68068
68069
68070 function isFirstNode(node) {
68071 const parentType = node.parent.type;
68072
68073 if (node.parent.body) {
68074 return Array.isArray(node.parent.body) ? node.parent.body[0] === node : node.parent.body === node;
68075 }
68076
68077 if (parentType === "IfStatement") {
68078 return isPrecededByTokens(node, ["else", ")"]);
68079 }
68080
68081 if (parentType === "DoWhileStatement") {
68082 return isPrecededByTokens(node, ["do"]);
68083 }
68084
68085 if (parentType === "SwitchCase") {
68086 return isPrecededByTokens(node, [":"]);
68087 }
68088
68089 return isPrecededByTokens(node, [")"]);
68090 }
68091 /**
68092 * Returns the number of lines of comments that precede the node
68093 * @param {ASTNode} node node to check for overlapping comments
68094 * @param {number} lineNumTokenBefore line number of previous token, to check for overlapping comments
68095 * @returns {number} Number of lines of comments that precede the node
68096 * @private
68097 */
68098
68099
68100 function calcCommentLines(node, lineNumTokenBefore) {
68101 const comments = sourceCode.getCommentsBefore(node);
68102 let numLinesComments = 0;
68103
68104 if (!comments.length) {
68105 return numLinesComments;
68106 }
68107
68108 comments.forEach(comment => {
68109 numLinesComments++;
68110
68111 if (comment.type === "Block") {
68112 numLinesComments += comment.loc.end.line - comment.loc.start.line;
68113 } // avoid counting lines with inline comments twice
68114
68115
68116 if (comment.loc.start.line === lineNumTokenBefore) {
68117 numLinesComments--;
68118 }
68119
68120 if (comment.loc.end.line === node.loc.start.line) {
68121 numLinesComments--;
68122 }
68123 });
68124 return numLinesComments;
68125 }
68126 /**
68127 * Returns the line number of the token before the node that is passed in as an argument
68128 * @param {ASTNode} node The node to use as the start of the calculation
68129 * @returns {number} Line number of the token before `node`
68130 * @private
68131 */
68132
68133
68134 function getLineNumberOfTokenBefore(node) {
68135 const tokenBefore = sourceCode.getTokenBefore(node);
68136 let lineNumTokenBefore;
68137 /**
68138 * Global return (at the beginning of a script) is a special case.
68139 * If there is no token before `return`, then we expect no line
68140 * break before the return. Comments are allowed to occupy lines
68141 * before the global return, just no blank lines.
68142 * Setting lineNumTokenBefore to zero in that case results in the
68143 * desired behavior.
68144 */
68145
68146 if (tokenBefore) {
68147 lineNumTokenBefore = tokenBefore.loc.end.line;
68148 } else {
68149 lineNumTokenBefore = 0; // global return at beginning of script
68150 }
68151
68152 return lineNumTokenBefore;
68153 }
68154 /**
68155 * Checks whether node is preceded by a newline
68156 * @param {ASTNode} node node to check
68157 * @returns {boolean} Whether or not the node is preceded by a newline
68158 * @private
68159 */
68160
68161
68162 function hasNewlineBefore(node) {
68163 const lineNumNode = node.loc.start.line;
68164 const lineNumTokenBefore = getLineNumberOfTokenBefore(node);
68165 const commentLines = calcCommentLines(node, lineNumTokenBefore);
68166 return lineNumNode - lineNumTokenBefore - commentLines > 1;
68167 }
68168 /**
68169 * Checks whether it is safe to apply a fix to a given return statement.
68170 *
68171 * The fix is not considered safe if the given return statement has leading comments,
68172 * as we cannot safely determine if the newline should be added before or after the comments.
68173 * For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211
68174 * @param {ASTNode} node The return statement node to check.
68175 * @returns {boolean} `true` if it can fix the node.
68176 * @private
68177 */
68178
68179
68180 function canFix(node) {
68181 const leadingComments = sourceCode.getCommentsBefore(node);
68182 const lastLeadingComment = leadingComments[leadingComments.length - 1];
68183 const tokenBefore = sourceCode.getTokenBefore(node);
68184
68185 if (leadingComments.length === 0) {
68186 return true;
68187 }
68188 /*
68189 * if the last leading comment ends in the same line as the previous token and
68190 * does not share a line with the `return` node, we can consider it safe to fix.
68191 * Example:
68192 * function a() {
68193 * var b; //comment
68194 * return;
68195 * }
68196 */
68197
68198
68199 if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && lastLeadingComment.loc.end.line !== node.loc.start.line) {
68200 return true;
68201 }
68202
68203 return false;
68204 } //--------------------------------------------------------------------------
68205 // Public
68206 //--------------------------------------------------------------------------
68207
68208
68209 return {
68210 ReturnStatement(node) {
68211 if (!isFirstNode(node) && !hasNewlineBefore(node)) {
68212 context.report({
68213 node,
68214 messageId: "expected",
68215
68216 fix(fixer) {
68217 if (canFix(node)) {
68218 const tokenBefore = sourceCode.getTokenBefore(node);
68219 const newlines = node.loc.start.line === tokenBefore.loc.end.line ? "\n\n" : "\n";
68220 return fixer.insertTextBefore(node, newlines);
68221 }
68222
68223 return null;
68224 }
68225
68226 });
68227 }
68228 }
68229
68230 };
68231 }
68232
68233};
68234
68235/***/ }),
68236/* 507 */
68237/***/ (function(module, exports, __webpack_require__) {
68238
68239"use strict";
68240/**
68241 * @fileoverview Rule to ensure newline per method call when chaining calls
68242 * @author Rajendra Patil
68243 * @author Burak Yigit Kaya
68244 */
68245
68246
68247const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
68248// Rule Definition
68249//------------------------------------------------------------------------------
68250
68251
68252module.exports = {
68253 meta: {
68254 type: "layout",
68255 docs: {
68256 description: "require a newline after each call in a method chain",
68257 category: "Stylistic Issues",
68258 recommended: false,
68259 url: "https://eslint.org/docs/rules/newline-per-chained-call"
68260 },
68261 fixable: "whitespace",
68262 schema: [{
68263 type: "object",
68264 properties: {
68265 ignoreChainWithDepth: {
68266 type: "integer",
68267 minimum: 1,
68268 maximum: 10,
68269 default: 2
68270 }
68271 },
68272 additionalProperties: false
68273 }],
68274 messages: {
68275 expected: "Expected line break before `{{callee}}`."
68276 }
68277 },
68278
68279 create(context) {
68280 const options = context.options[0] || {},
68281 ignoreChainWithDepth = options.ignoreChainWithDepth || 2;
68282 const sourceCode = context.getSourceCode();
68283 /**
68284 * Get the prefix of a given MemberExpression node.
68285 * If the MemberExpression node is a computed value it returns a
68286 * left bracket. If not it returns a period.
68287 * @param {ASTNode} node A MemberExpression node to get
68288 * @returns {string} The prefix of the node.
68289 */
68290
68291 function getPrefix(node) {
68292 return node.computed ? "[" : ".";
68293 }
68294 /**
68295 * Gets the property text of a given MemberExpression node.
68296 * If the text is multiline, this returns only the first line.
68297 * @param {ASTNode} node A MemberExpression node to get.
68298 * @returns {string} The property text of the node.
68299 */
68300
68301
68302 function getPropertyText(node) {
68303 const prefix = getPrefix(node);
68304 const lines = sourceCode.getText(node.property).split(astUtils.LINEBREAK_MATCHER);
68305 const suffix = node.computed && lines.length === 1 ? "]" : "";
68306 return prefix + lines[0] + suffix;
68307 }
68308
68309 return {
68310 "CallExpression:exit"(node) {
68311 if (!node.callee || node.callee.type !== "MemberExpression") {
68312 return;
68313 }
68314
68315 const callee = node.callee;
68316 let parent = callee.object;
68317 let depth = 1;
68318
68319 while (parent && parent.callee) {
68320 depth += 1;
68321 parent = parent.callee.object;
68322 }
68323
68324 if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) {
56c4a2cb 68325 const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken);
eb39fafa
DC
68326 context.report({
68327 node: callee.property,
56c4a2cb
DC
68328 loc: {
68329 start: firstTokenAfterObject.loc.start,
68330 end: callee.loc.end
68331 },
eb39fafa
DC
68332 messageId: "expected",
68333 data: {
68334 callee: getPropertyText(callee)
68335 },
68336
68337 fix(fixer) {
eb39fafa
DC
68338 return fixer.insertTextBefore(firstTokenAfterObject, "\n");
68339 }
68340
68341 });
68342 }
68343 }
68344
68345 };
68346 }
68347
68348};
68349
68350/***/ }),
68351/* 508 */
68352/***/ (function(module, exports, __webpack_require__) {
68353
68354"use strict";
68355/**
68356 * @fileoverview Rule to flag use of alert, confirm, prompt
68357 * @author Nicholas C. Zakas
68358 */
68359 //------------------------------------------------------------------------------
68360// Requirements
68361//------------------------------------------------------------------------------
68362
68363const {
68364 getStaticPropertyName: getPropertyName,
68365 getVariableByName
68366} = __webpack_require__(426); //------------------------------------------------------------------------------
68367// Helpers
68368//------------------------------------------------------------------------------
68369
68370/**
68371 * Checks if the given name is a prohibited identifier.
68372 * @param {string} name The name to check
68373 * @returns {boolean} Whether or not the name is prohibited.
68374 */
68375
68376
68377function isProhibitedIdentifier(name) {
68378 return /^(alert|confirm|prompt)$/u.test(name);
68379}
68380/**
68381 * Finds the eslint-scope reference in the given scope.
68382 * @param {Object} scope The scope to search.
68383 * @param {ASTNode} node The identifier node.
68384 * @returns {Reference|null} Returns the found reference or null if none were found.
68385 */
68386
68387
68388function findReference(scope, node) {
68389 const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && reference.identifier.range[1] === node.range[1]);
68390
68391 if (references.length === 1) {
68392 return references[0];
68393 }
68394
68395 return null;
68396}
68397/**
68398 * Checks if the given identifier node is shadowed in the given scope.
68399 * @param {Object} scope The current scope.
68400 * @param {string} node The identifier node to check
68401 * @returns {boolean} Whether or not the name is shadowed.
68402 */
68403
68404
68405function isShadowed(scope, node) {
68406 const reference = findReference(scope, node);
68407 return reference && reference.resolved && reference.resolved.defs.length > 0;
68408}
68409/**
68410 * Checks if the given identifier node is a ThisExpression in the global scope or the global window property.
68411 * @param {Object} scope The current scope.
68412 * @param {string} node The identifier node to check
68413 * @returns {boolean} Whether or not the node is a reference to the global object.
68414 */
68415
68416
68417function isGlobalThisReferenceOrGlobalWindow(scope, node) {
68418 if (scope.type === "global" && node.type === "ThisExpression") {
68419 return true;
68420 }
68421
68422 if (node.name === "window" || node.name === "globalThis" && getVariableByName(scope, "globalThis")) {
68423 return !isShadowed(scope, node);
68424 }
68425
68426 return false;
68427} //------------------------------------------------------------------------------
68428// Rule Definition
68429//------------------------------------------------------------------------------
68430
68431
68432module.exports = {
68433 meta: {
68434 type: "suggestion",
68435 docs: {
68436 description: "disallow the use of `alert`, `confirm`, and `prompt`",
68437 category: "Best Practices",
68438 recommended: false,
68439 url: "https://eslint.org/docs/rules/no-alert"
68440 },
68441 schema: [],
68442 messages: {
68443 unexpected: "Unexpected {{name}}."
68444 }
68445 },
68446
68447 create(context) {
68448 return {
68449 CallExpression(node) {
68450 const callee = node.callee,
68451 currentScope = context.getScope(); // without window.
68452
68453 if (callee.type === "Identifier") {
68454 const name = callee.name;
68455
68456 if (!isShadowed(currentScope, callee) && isProhibitedIdentifier(callee.name)) {
68457 context.report({
68458 node,
68459 messageId: "unexpected",
68460 data: {
68461 name
68462 }
68463 });
68464 }
68465 } else if (callee.type === "MemberExpression" && isGlobalThisReferenceOrGlobalWindow(currentScope, callee.object)) {
68466 const name = getPropertyName(callee);
68467
68468 if (isProhibitedIdentifier(name)) {
68469 context.report({
68470 node,
68471 messageId: "unexpected",
68472 data: {
68473 name
68474 }
68475 });
68476 }
68477 }
68478 }
68479
68480 };
68481 }
68482
68483};
68484
68485/***/ }),
68486/* 509 */
68487/***/ (function(module, exports, __webpack_require__) {
68488
68489"use strict";
68490/**
68491 * @fileoverview Disallow construction of dense arrays using the Array constructor
68492 * @author Matt DuVall <http://www.mattduvall.com/>
68493 */
68494 //------------------------------------------------------------------------------
68495// Rule Definition
68496//------------------------------------------------------------------------------
68497
68498module.exports = {
68499 meta: {
68500 type: "suggestion",
68501 docs: {
68502 description: "disallow `Array` constructors",
68503 category: "Stylistic Issues",
68504 recommended: false,
68505 url: "https://eslint.org/docs/rules/no-array-constructor"
68506 },
68507 schema: [],
68508 messages: {
68509 preferLiteral: "The array literal notation [] is preferable."
68510 }
68511 },
68512
68513 create(context) {
68514 /**
68515 * Disallow construction of dense arrays using the Array constructor
68516 * @param {ASTNode} node node to evaluate
68517 * @returns {void}
68518 * @private
68519 */
68520 function check(node) {
68521 if (node.arguments.length !== 1 && node.callee.type === "Identifier" && node.callee.name === "Array") {
68522 context.report({
68523 node,
68524 messageId: "preferLiteral"
68525 });
68526 }
68527 }
68528
68529 return {
68530 CallExpression: check,
68531 NewExpression: check
68532 };
68533 }
68534
68535};
68536
68537/***/ }),
68538/* 510 */
68539/***/ (function(module, exports, __webpack_require__) {
68540
68541"use strict";
68542/**
68543 * @fileoverview disallow using an async function as a Promise executor
68544 * @author Teddy Katz
68545 */
68546 //------------------------------------------------------------------------------
68547// Rule Definition
68548//------------------------------------------------------------------------------
68549
68550module.exports = {
68551 meta: {
68552 type: "problem",
68553 docs: {
68554 description: "disallow using an async function as a Promise executor",
68555 category: "Possible Errors",
68556 recommended: true,
68557 url: "https://eslint.org/docs/rules/no-async-promise-executor"
68558 },
68559 fixable: null,
68560 schema: [],
68561 messages: {
68562 async: "Promise executor functions should not be async."
68563 }
68564 },
68565
68566 create(context) {
68567 return {
68568 "NewExpression[callee.name='Promise'][arguments.0.async=true]"(node) {
68569 context.report({
68570 node: context.getSourceCode().getFirstToken(node.arguments[0], token => token.value === "async"),
68571 messageId: "async"
68572 });
68573 }
68574
68575 };
68576 }
68577
68578};
68579
68580/***/ }),
68581/* 511 */
68582/***/ (function(module, exports, __webpack_require__) {
68583
68584"use strict";
68585/**
68586 * @fileoverview Rule to disallow uses of await inside of loops.
68587 * @author Nat Mote (nmote)
68588 */
68589
68590/**
68591 * Check whether it should stop traversing ancestors at the given node.
68592 * @param {ASTNode} node A node to check.
68593 * @returns {boolean} `true` if it should stop traversing.
68594 */
68595
68596function isBoundary(node) {
68597 const t = node.type;
68598 return t === "FunctionDeclaration" || t === "FunctionExpression" || t === "ArrowFunctionExpression" ||
68599 /*
68600 * Don't report the await expressions on for-await-of loop since it's
68601 * asynchronous iteration intentionally.
68602 */
68603 t === "ForOfStatement" && node.await === true;
68604}
68605/**
68606 * Check whether the given node is in loop.
68607 * @param {ASTNode} node A node to check.
68608 * @param {ASTNode} parent A parent node to check.
68609 * @returns {boolean} `true` if the node is in loop.
68610 */
68611
68612
68613function isLooped(node, parent) {
68614 switch (parent.type) {
68615 case "ForStatement":
68616 return node === parent.test || node === parent.update || node === parent.body;
68617
68618 case "ForOfStatement":
68619 case "ForInStatement":
68620 return node === parent.body;
68621
68622 case "WhileStatement":
68623 case "DoWhileStatement":
68624 return node === parent.test || node === parent.body;
68625
68626 default:
68627 return false;
68628 }
68629}
68630
68631module.exports = {
68632 meta: {
68633 type: "problem",
68634 docs: {
68635 description: "disallow `await` inside of loops",
68636 category: "Possible Errors",
68637 recommended: false,
68638 url: "https://eslint.org/docs/rules/no-await-in-loop"
68639 },
68640 schema: [],
68641 messages: {
68642 unexpectedAwait: "Unexpected `await` inside a loop."
68643 }
68644 },
68645
68646 create(context) {
68647 /**
68648 * Validate an await expression.
68649 * @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate.
68650 * @returns {void}
68651 */
68652 function validate(awaitNode) {
68653 if (awaitNode.type === "ForOfStatement" && !awaitNode.await) {
68654 return;
68655 }
68656
68657 let node = awaitNode;
68658 let parent = node.parent;
68659
68660 while (parent && !isBoundary(parent)) {
68661 if (isLooped(node, parent)) {
68662 context.report({
68663 node: awaitNode,
68664 messageId: "unexpectedAwait"
68665 });
68666 return;
68667 }
68668
68669 node = parent;
68670 parent = parent.parent;
68671 }
68672 }
68673
68674 return {
68675 AwaitExpression: validate,
68676 ForOfStatement: validate
68677 };
68678 }
68679
68680};
68681
68682/***/ }),
68683/* 512 */
68684/***/ (function(module, exports, __webpack_require__) {
68685
68686"use strict";
68687/**
68688 * @fileoverview Rule to flag bitwise identifiers
68689 * @author Nicholas C. Zakas
68690 */
68691
68692/*
68693 *
68694 * Set of bitwise operators.
68695 *
68696 */
68697
68698const BITWISE_OPERATORS = ["^", "|", "&", "<<", ">>", ">>>", "^=", "|=", "&=", "<<=", ">>=", ">>>=", "~"]; //------------------------------------------------------------------------------
68699// Rule Definition
68700//------------------------------------------------------------------------------
68701
68702module.exports = {
68703 meta: {
68704 type: "suggestion",
68705 docs: {
68706 description: "disallow bitwise operators",
68707 category: "Stylistic Issues",
68708 recommended: false,
68709 url: "https://eslint.org/docs/rules/no-bitwise"
68710 },
68711 schema: [{
68712 type: "object",
68713 properties: {
68714 allow: {
68715 type: "array",
68716 items: {
68717 enum: BITWISE_OPERATORS
68718 },
68719 uniqueItems: true
68720 },
68721 int32Hint: {
68722 type: "boolean",
68723 default: false
68724 }
68725 },
68726 additionalProperties: false
68727 }],
68728 messages: {
68729 unexpected: "Unexpected use of '{{operator}}'."
68730 }
68731 },
68732
68733 create(context) {
68734 const options = context.options[0] || {};
68735 const allowed = options.allow || [];
68736 const int32Hint = options.int32Hint === true;
68737 /**
68738 * Reports an unexpected use of a bitwise operator.
68739 * @param {ASTNode} node Node which contains the bitwise operator.
68740 * @returns {void}
68741 */
68742
68743 function report(node) {
68744 context.report({
68745 node,
68746 messageId: "unexpected",
68747 data: {
68748 operator: node.operator
68749 }
68750 });
68751 }
68752 /**
68753 * Checks if the given node has a bitwise operator.
68754 * @param {ASTNode} node The node to check.
68755 * @returns {boolean} Whether or not the node has a bitwise operator.
68756 */
68757
68758
68759 function hasBitwiseOperator(node) {
68760 return BITWISE_OPERATORS.indexOf(node.operator) !== -1;
68761 }
68762 /**
68763 * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`.
68764 * @param {ASTNode} node The node to check.
68765 * @returns {boolean} Whether or not the node has a bitwise operator.
68766 */
68767
68768
68769 function allowedOperator(node) {
68770 return allowed.indexOf(node.operator) !== -1;
68771 }
68772 /**
68773 * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0"
68774 * @param {ASTNode} node The node to check.
68775 * @returns {boolean} whether the node is used in integer typecasting.
68776 */
68777
68778
68779 function isInt32Hint(node) {
68780 return int32Hint && node.operator === "|" && node.right && node.right.type === "Literal" && node.right.value === 0;
68781 }
68782 /**
68783 * Report if the given node contains a bitwise operator.
68784 * @param {ASTNode} node The node to check.
68785 * @returns {void}
68786 */
68787
68788
68789 function checkNodeForBitwiseOperator(node) {
68790 if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) {
68791 report(node);
68792 }
68793 }
68794
68795 return {
68796 AssignmentExpression: checkNodeForBitwiseOperator,
68797 BinaryExpression: checkNodeForBitwiseOperator,
68798 UnaryExpression: checkNodeForBitwiseOperator
68799 };
68800 }
68801
68802};
68803
68804/***/ }),
68805/* 513 */
68806/***/ (function(module, exports, __webpack_require__) {
68807
68808"use strict";
68809/**
68810 * @fileoverview disallow use of the Buffer() constructor
68811 * @author Teddy Katz
68812 */
68813 //------------------------------------------------------------------------------
68814// Rule Definition
68815//------------------------------------------------------------------------------
68816
68817module.exports = {
68818 meta: {
56c4a2cb 68819 deprecated: true,
6a5a0f88 68820 replacedBy: [],
eb39fafa
DC
68821 type: "problem",
68822 docs: {
68823 description: "disallow use of the `Buffer()` constructor",
68824 category: "Node.js and CommonJS",
68825 recommended: false,
68826 url: "https://eslint.org/docs/rules/no-buffer-constructor"
68827 },
68828 schema: [],
68829 messages: {
68830 deprecated: "{{expr}} is deprecated. Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead."
68831 }
68832 },
68833
68834 create(context) {
68835 //----------------------------------------------------------------------
68836 // Public
68837 //----------------------------------------------------------------------
68838 return {
68839 "CallExpression[callee.name='Buffer'], NewExpression[callee.name='Buffer']"(node) {
68840 context.report({
68841 node,
68842 messageId: "deprecated",
68843 data: {
68844 expr: node.type === "CallExpression" ? "Buffer()" : "new Buffer()"
68845 }
68846 });
68847 }
68848
68849 };
68850 }
68851
68852};
68853
68854/***/ }),
68855/* 514 */
68856/***/ (function(module, exports, __webpack_require__) {
68857
68858"use strict";
68859/**
68860 * @fileoverview Rule to flag use of arguments.callee and arguments.caller.
68861 * @author Nicholas C. Zakas
68862 */
68863 //------------------------------------------------------------------------------
68864// Rule Definition
68865//------------------------------------------------------------------------------
68866
68867module.exports = {
68868 meta: {
68869 type: "suggestion",
68870 docs: {
68871 description: "disallow the use of `arguments.caller` or `arguments.callee`",
68872 category: "Best Practices",
68873 recommended: false,
68874 url: "https://eslint.org/docs/rules/no-caller"
68875 },
68876 schema: [],
68877 messages: {
68878 unexpected: "Avoid arguments.{{prop}}."
68879 }
68880 },
68881
68882 create(context) {
68883 return {
68884 MemberExpression(node) {
68885 const objectName = node.object.name,
68886 propertyName = node.property.name;
68887
68888 if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) {
68889 context.report({
68890 node,
68891 messageId: "unexpected",
68892 data: {
68893 prop: propertyName
68894 }
68895 });
68896 }
68897 }
68898
68899 };
68900 }
68901
68902};
68903
68904/***/ }),
68905/* 515 */
68906/***/ (function(module, exports, __webpack_require__) {
68907
68908"use strict";
68909/**
68910 * @fileoverview Rule to flag use of an lexical declarations inside a case clause
68911 * @author Erik Arvidsson
68912 */
68913 //------------------------------------------------------------------------------
68914// Rule Definition
68915//------------------------------------------------------------------------------
68916
68917module.exports = {
68918 meta: {
68919 type: "suggestion",
68920 docs: {
68921 description: "disallow lexical declarations in case clauses",
68922 category: "Best Practices",
68923 recommended: true,
68924 url: "https://eslint.org/docs/rules/no-case-declarations"
68925 },
68926 schema: [],
68927 messages: {
68928 unexpected: "Unexpected lexical declaration in case block."
68929 }
68930 },
68931
68932 create(context) {
68933 /**
68934 * Checks whether or not a node is a lexical declaration.
68935 * @param {ASTNode} node A direct child statement of a switch case.
68936 * @returns {boolean} Whether or not the node is a lexical declaration.
68937 */
68938 function isLexicalDeclaration(node) {
68939 switch (node.type) {
68940 case "FunctionDeclaration":
68941 case "ClassDeclaration":
68942 return true;
68943
68944 case "VariableDeclaration":
68945 return node.kind !== "var";
68946
68947 default:
68948 return false;
68949 }
68950 }
68951
68952 return {
68953 SwitchCase(node) {
68954 for (let i = 0; i < node.consequent.length; i++) {
68955 const statement = node.consequent[i];
68956
68957 if (isLexicalDeclaration(statement)) {
68958 context.report({
68959 node: statement,
68960 messageId: "unexpected"
68961 });
68962 }
68963 }
68964 }
68965
68966 };
68967 }
68968
68969};
68970
68971/***/ }),
68972/* 516 */
68973/***/ (function(module, exports, __webpack_require__) {
68974
68975"use strict";
68976/**
68977 * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier
68978 * @author Ian Christian Myers
68979 * @deprecated in ESLint v5.1.0
68980 */
68981 //------------------------------------------------------------------------------
68982// Requirements
68983//------------------------------------------------------------------------------
68984
68985const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
68986// Rule Definition
68987//------------------------------------------------------------------------------
68988
68989
68990module.exports = {
68991 meta: {
68992 type: "suggestion",
68993 docs: {
68994 description: "disallow `catch` clause parameters from shadowing variables in the outer scope",
68995 category: "Variables",
68996 recommended: false,
68997 url: "https://eslint.org/docs/rules/no-catch-shadow"
68998 },
68999 replacedBy: ["no-shadow"],
69000 deprecated: true,
69001 schema: [],
69002 messages: {
69003 mutable: "Value of '{{name}}' may be overwritten in IE 8 and earlier."
69004 }
69005 },
69006
69007 create(context) {
69008 //--------------------------------------------------------------------------
69009 // Helpers
69010 //--------------------------------------------------------------------------
69011
69012 /**
69013 * Check if the parameters are been shadowed
69014 * @param {Object} scope current scope
69015 * @param {string} name parameter name
69016 * @returns {boolean} True is its been shadowed
69017 */
69018 function paramIsShadowing(scope, name) {
69019 return astUtils.getVariableByName(scope, name) !== null;
69020 } //--------------------------------------------------------------------------
69021 // Public API
69022 //--------------------------------------------------------------------------
69023
69024
69025 return {
69026 "CatchClause[param!=null]"(node) {
69027 let scope = context.getScope();
69028 /*
69029 * When ecmaVersion >= 6, CatchClause creates its own scope
69030 * so start from one upper scope to exclude the current node
69031 */
69032
69033 if (scope.block === node) {
69034 scope = scope.upper;
69035 }
69036
69037 if (paramIsShadowing(scope, node.param.name)) {
69038 context.report({
69039 node,
69040 messageId: "mutable",
69041 data: {
69042 name: node.param.name
69043 }
69044 });
69045 }
69046 }
69047
69048 };
69049 }
69050
69051};
69052
69053/***/ }),
69054/* 517 */
69055/***/ (function(module, exports, __webpack_require__) {
69056
69057"use strict";
69058/**
69059 * @fileoverview A rule to disallow modifying variables of class declarations
69060 * @author Toru Nagashima
69061 */
69062
69063
69064const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
69065// Rule Definition
69066//------------------------------------------------------------------------------
69067
69068
69069module.exports = {
69070 meta: {
69071 type: "problem",
69072 docs: {
69073 description: "disallow reassigning class members",
69074 category: "ECMAScript 6",
69075 recommended: true,
69076 url: "https://eslint.org/docs/rules/no-class-assign"
69077 },
69078 schema: [],
69079 messages: {
69080 class: "'{{name}}' is a class."
69081 }
69082 },
69083
69084 create(context) {
69085 /**
69086 * Finds and reports references that are non initializer and writable.
69087 * @param {Variable} variable A variable to check.
69088 * @returns {void}
69089 */
69090 function checkVariable(variable) {
69091 astUtils.getModifyingReferences(variable.references).forEach(reference => {
69092 context.report({
69093 node: reference.identifier,
69094 messageId: "class",
69095 data: {
69096 name: reference.identifier.name
69097 }
69098 });
69099 });
69100 }
69101 /**
69102 * Finds and reports references that are non initializer and writable.
69103 * @param {ASTNode} node A ClassDeclaration/ClassExpression node to check.
69104 * @returns {void}
69105 */
69106
69107
69108 function checkForClass(node) {
69109 context.getDeclaredVariables(node).forEach(checkVariable);
69110 }
69111
69112 return {
69113 ClassDeclaration: checkForClass,
69114 ClassExpression: checkForClass
69115 };
69116 }
69117
69118};
69119
69120/***/ }),
69121/* 518 */
69122/***/ (function(module, exports, __webpack_require__) {
69123
69124"use strict";
69125/**
69126 * @fileoverview The rule should warn against code that tries to compare against -0.
69127 * @author Aladdin-ADD <hh_2013@foxmail.com>
69128 */
69129 //------------------------------------------------------------------------------
69130// Rule Definition
69131//------------------------------------------------------------------------------
69132
69133module.exports = {
69134 meta: {
69135 type: "problem",
69136 docs: {
69137 description: "disallow comparing against -0",
69138 category: "Possible Errors",
69139 recommended: true,
69140 url: "https://eslint.org/docs/rules/no-compare-neg-zero"
69141 },
69142 fixable: null,
69143 schema: [],
69144 messages: {
69145 unexpected: "Do not use the '{{operator}}' operator to compare against -0."
69146 }
69147 },
69148
69149 create(context) {
69150 //--------------------------------------------------------------------------
69151 // Helpers
69152 //--------------------------------------------------------------------------
69153
69154 /**
69155 * Checks a given node is -0
69156 * @param {ASTNode} node A node to check.
69157 * @returns {boolean} `true` if the node is -0.
69158 */
69159 function isNegZero(node) {
69160 return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0;
69161 }
69162
69163 const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]);
69164 return {
69165 BinaryExpression(node) {
69166 if (OPERATORS_TO_CHECK.has(node.operator)) {
69167 if (isNegZero(node.left) || isNegZero(node.right)) {
69168 context.report({
69169 node,
69170 messageId: "unexpected",
69171 data: {
69172 operator: node.operator
69173 }
69174 });
69175 }
69176 }
69177 }
69178
69179 };
69180 }
69181
69182};
69183
69184/***/ }),
69185/* 519 */
69186/***/ (function(module, exports, __webpack_require__) {
69187
69188"use strict";
69189/**
69190 * @fileoverview Rule to flag assignment in a conditional statement's test expression
69191 * @author Stephen Murray <spmurrayzzz>
69192 */
69193 //------------------------------------------------------------------------------
69194// Requirements
69195//------------------------------------------------------------------------------
69196
69197const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
69198// Helpers
69199//------------------------------------------------------------------------------
69200
69201
69202const TEST_CONDITION_PARENT_TYPES = new Set(["IfStatement", "WhileStatement", "DoWhileStatement", "ForStatement", "ConditionalExpression"]);
69203const NODE_DESCRIPTIONS = {
69204 DoWhileStatement: "a 'do...while' statement",
69205 ForStatement: "a 'for' statement",
69206 IfStatement: "an 'if' statement",
69207 WhileStatement: "a 'while' statement"
69208}; //------------------------------------------------------------------------------
69209// Rule Definition
69210//------------------------------------------------------------------------------
69211
69212module.exports = {
69213 meta: {
69214 type: "problem",
69215 docs: {
69216 description: "disallow assignment operators in conditional expressions",
69217 category: "Possible Errors",
69218 recommended: true,
69219 url: "https://eslint.org/docs/rules/no-cond-assign"
69220 },
69221 schema: [{
69222 enum: ["except-parens", "always"]
69223 }],
69224 messages: {
69225 unexpected: "Unexpected assignment within {{type}}.",
69226 // must match JSHint's error message
69227 missing: "Expected a conditional expression and instead saw an assignment."
69228 }
69229 },
69230
69231 create(context) {
69232 const prohibitAssign = context.options[0] || "except-parens";
69233 const sourceCode = context.getSourceCode();
69234 /**
69235 * Check whether an AST node is the test expression for a conditional statement.
69236 * @param {!Object} node The node to test.
69237 * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`.
69238 */
69239
69240 function isConditionalTestExpression(node) {
69241 return node.parent && TEST_CONDITION_PARENT_TYPES.has(node.parent.type) && node === node.parent.test;
69242 }
69243 /**
69244 * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement.
69245 * @param {!Object} node The node to use at the start of the search.
69246 * @returns {?Object} The closest ancestor node that represents a conditional statement.
69247 */
69248
69249
69250 function findConditionalAncestor(node) {
69251 let currentAncestor = node;
69252
69253 do {
69254 if (isConditionalTestExpression(currentAncestor)) {
69255 return currentAncestor.parent;
69256 }
69257 } while ((currentAncestor = currentAncestor.parent) && !astUtils.isFunction(currentAncestor));
69258
69259 return null;
69260 }
69261 /**
69262 * Check whether the code represented by an AST node is enclosed in two sets of parentheses.
69263 * @param {!Object} node The node to test.
69264 * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`.
69265 */
69266
69267
69268 function isParenthesisedTwice(node) {
69269 const previousToken = sourceCode.getTokenBefore(node, 1),
69270 nextToken = sourceCode.getTokenAfter(node, 1);
69271 return astUtils.isParenthesised(sourceCode, node) && previousToken && astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1];
69272 }
69273 /**
69274 * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses.
69275 * @param {!Object} node The node for the conditional statement.
69276 * @returns {void}
69277 */
69278
69279
69280 function testForAssign(node) {
69281 if (node.test && node.test.type === "AssignmentExpression" && (node.type === "ForStatement" ? !astUtils.isParenthesised(sourceCode, node.test) : !isParenthesisedTwice(node.test))) {
69282 context.report({
69283 node: node.test,
69284 messageId: "missing"
69285 });
69286 }
69287 }
69288 /**
69289 * Check whether an assignment expression is descended from a conditional statement's test expression.
69290 * @param {!Object} node The node for the assignment expression.
69291 * @returns {void}
69292 */
69293
69294
69295 function testForConditionalAncestor(node) {
69296 const ancestor = findConditionalAncestor(node);
69297
69298 if (ancestor) {
69299 context.report({
69300 node,
69301 messageId: "unexpected",
69302 data: {
69303 type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type
69304 }
69305 });
69306 }
69307 }
69308
69309 if (prohibitAssign === "always") {
69310 return {
69311 AssignmentExpression: testForConditionalAncestor
69312 };
69313 }
69314
69315 return {
69316 DoWhileStatement: testForAssign,
69317 ForStatement: testForAssign,
69318 IfStatement: testForAssign,
69319 WhileStatement: testForAssign,
69320 ConditionalExpression: testForAssign
69321 };
69322 }
69323
69324};
69325
69326/***/ }),
69327/* 520 */
69328/***/ (function(module, exports, __webpack_require__) {
69329
69330"use strict";
69331/**
69332 * @fileoverview A rule to warn against using arrow functions when they could be
69333 * confused with comparisons
69334 * @author Jxck <https://github.com/Jxck>
69335 */
69336
69337
69338const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
69339// Helpers
69340//------------------------------------------------------------------------------
69341
69342/**
69343 * Checks whether or not a node is a conditional expression.
69344 * @param {ASTNode} node node to test
69345 * @returns {boolean} `true` if the node is a conditional expression.
69346 */
69347
69348
69349function isConditional(node) {
69350 return node && node.type === "ConditionalExpression";
69351} //------------------------------------------------------------------------------
69352// Rule Definition
69353//------------------------------------------------------------------------------
69354
69355
69356module.exports = {
69357 meta: {
69358 type: "suggestion",
69359 docs: {
69360 description: "disallow arrow functions where they could be confused with comparisons",
69361 category: "ECMAScript 6",
69362 recommended: false,
69363 url: "https://eslint.org/docs/rules/no-confusing-arrow"
69364 },
69365 fixable: "code",
69366 schema: [{
69367 type: "object",
69368 properties: {
69369 allowParens: {
69370 type: "boolean",
69371 default: true
69372 }
69373 },
69374 additionalProperties: false
69375 }],
69376 messages: {
69377 confusing: "Arrow function used ambiguously with a conditional expression."
69378 }
69379 },
69380
69381 create(context) {
69382 const config = context.options[0] || {};
69383 const allowParens = config.allowParens || config.allowParens === void 0;
69384 const sourceCode = context.getSourceCode();
69385 /**
69386 * Reports if an arrow function contains an ambiguous conditional.
69387 * @param {ASTNode} node A node to check and report.
69388 * @returns {void}
69389 */
69390
69391 function checkArrowFunc(node) {
69392 const body = node.body;
69393
69394 if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
69395 context.report({
69396 node,
69397 messageId: "confusing",
69398
69399 fix(fixer) {
69400 // if `allowParens` is not set to true don't bother wrapping in parens
69401 return allowParens && fixer.replaceText(node.body, "(".concat(sourceCode.getText(node.body), ")"));
69402 }
69403
69404 });
69405 }
69406 }
69407
69408 return {
69409 ArrowFunctionExpression: checkArrowFunc
69410 };
69411 }
69412
69413};
69414
69415/***/ }),
69416/* 521 */
69417/***/ (function(module, exports, __webpack_require__) {
69418
69419"use strict";
69420/**
69421 * @fileoverview Rule to flag use of console object
69422 * @author Nicholas C. Zakas
69423 */
69424 //------------------------------------------------------------------------------
69425// Requirements
69426//------------------------------------------------------------------------------
69427
69428const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
69429// Rule Definition
69430//------------------------------------------------------------------------------
69431
69432
69433module.exports = {
69434 meta: {
69435 type: "suggestion",
69436 docs: {
69437 description: "disallow the use of `console`",
69438 category: "Possible Errors",
69439 recommended: false,
69440 url: "https://eslint.org/docs/rules/no-console"
69441 },
69442 schema: [{
69443 type: "object",
69444 properties: {
69445 allow: {
69446 type: "array",
69447 items: {
69448 type: "string"
69449 },
69450 minItems: 1,
69451 uniqueItems: true
69452 }
69453 },
69454 additionalProperties: false
69455 }],
69456 messages: {
69457 unexpected: "Unexpected console statement."
69458 }
69459 },
69460
69461 create(context) {
69462 const options = context.options[0] || {};
69463 const allowed = options.allow || [];
69464 /**
69465 * Checks whether the given reference is 'console' or not.
69466 * @param {eslint-scope.Reference} reference The reference to check.
69467 * @returns {boolean} `true` if the reference is 'console'.
69468 */
69469
69470 function isConsole(reference) {
69471 const id = reference.identifier;
69472 return id && id.name === "console";
69473 }
69474 /**
69475 * Checks whether the property name of the given MemberExpression node
69476 * is allowed by options or not.
69477 * @param {ASTNode} node The MemberExpression node to check.
69478 * @returns {boolean} `true` if the property name of the node is allowed.
69479 */
69480
69481
69482 function isAllowed(node) {
69483 const propertyName = astUtils.getStaticPropertyName(node);
69484 return propertyName && allowed.indexOf(propertyName) !== -1;
69485 }
69486 /**
69487 * Checks whether the given reference is a member access which is not
69488 * allowed by options or not.
69489 * @param {eslint-scope.Reference} reference The reference to check.
69490 * @returns {boolean} `true` if the reference is a member access which
69491 * is not allowed by options.
69492 */
69493
69494
69495 function isMemberAccessExceptAllowed(reference) {
69496 const node = reference.identifier;
69497 const parent = node.parent;
69498 return parent.type === "MemberExpression" && parent.object === node && !isAllowed(parent);
69499 }
69500 /**
69501 * Reports the given reference as a violation.
69502 * @param {eslint-scope.Reference} reference The reference to report.
69503 * @returns {void}
69504 */
69505
69506
69507 function report(reference) {
69508 const node = reference.identifier.parent;
69509 context.report({
69510 node,
69511 loc: node.loc,
69512 messageId: "unexpected"
69513 });
69514 }
69515
69516 return {
69517 "Program:exit"() {
69518 const scope = context.getScope();
69519 const consoleVar = astUtils.getVariableByName(scope, "console");
69520 const shadowed = consoleVar && consoleVar.defs.length > 0;
69521 /*
69522 * 'scope.through' includes all references to undefined
69523 * variables. If the variable 'console' is not defined, it uses
69524 * 'scope.through'.
69525 */
69526
69527 const references = consoleVar ? consoleVar.references : scope.through.filter(isConsole);
69528
69529 if (!shadowed) {
69530 references.filter(isMemberAccessExceptAllowed).forEach(report);
69531 }
69532 }
69533
69534 };
69535 }
69536
69537};
69538
69539/***/ }),
69540/* 522 */
69541/***/ (function(module, exports, __webpack_require__) {
69542
69543"use strict";
69544/**
69545 * @fileoverview A rule to disallow modifying variables that are declared using `const`
69546 * @author Toru Nagashima
69547 */
69548
69549
69550const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
69551// Rule Definition
69552//------------------------------------------------------------------------------
69553
69554
69555module.exports = {
69556 meta: {
69557 type: "problem",
69558 docs: {
69559 description: "disallow reassigning `const` variables",
69560 category: "ECMAScript 6",
69561 recommended: true,
69562 url: "https://eslint.org/docs/rules/no-const-assign"
69563 },
69564 schema: [],
69565 messages: {
69566 const: "'{{name}}' is constant."
69567 }
69568 },
69569
69570 create(context) {
69571 /**
69572 * Finds and reports references that are non initializer and writable.
69573 * @param {Variable} variable A variable to check.
69574 * @returns {void}
69575 */
69576 function checkVariable(variable) {
69577 astUtils.getModifyingReferences(variable.references).forEach(reference => {
69578 context.report({
69579 node: reference.identifier,
69580 messageId: "const",
69581 data: {
69582 name: reference.identifier.name
69583 }
69584 });
69585 });
69586 }
69587
69588 return {
69589 VariableDeclaration(node) {
69590 if (node.kind === "const") {
69591 context.getDeclaredVariables(node).forEach(checkVariable);
69592 }
69593 }
69594
69595 };
69596 }
69597
69598};
69599
69600/***/ }),
69601/* 523 */
69602/***/ (function(module, exports, __webpack_require__) {
69603
69604"use strict";
69605/**
69606 * @fileoverview Rule to flag use constant conditions
69607 * @author Christian Schulz <http://rndm.de>
69608 */
69609 //------------------------------------------------------------------------------
69610// Helpers
69611//------------------------------------------------------------------------------
69612
69613const EQUALITY_OPERATORS = ["===", "!==", "==", "!="];
69614const RELATIONAL_OPERATORS = [">", "<", ">=", "<=", "in", "instanceof"]; //------------------------------------------------------------------------------
69615// Rule Definition
69616//------------------------------------------------------------------------------
69617
69618module.exports = {
69619 meta: {
69620 type: "problem",
69621 docs: {
69622 description: "disallow constant expressions in conditions",
69623 category: "Possible Errors",
69624 recommended: true,
69625 url: "https://eslint.org/docs/rules/no-constant-condition"
69626 },
69627 schema: [{
69628 type: "object",
69629 properties: {
69630 checkLoops: {
69631 type: "boolean",
69632 default: true
69633 }
69634 },
69635 additionalProperties: false
69636 }],
69637 messages: {
69638 unexpected: "Unexpected constant condition."
69639 }
69640 },
69641
69642 create(context) {
69643 const options = context.options[0] || {},
69644 checkLoops = options.checkLoops !== false,
69645 loopSetStack = [];
69646 let loopsInCurrentScope = new Set(); //--------------------------------------------------------------------------
69647 // Helpers
69648 //--------------------------------------------------------------------------
69649
69650 /**
69651 * Checks if a branch node of LogicalExpression short circuits the whole condition
69652 * @param {ASTNode} node The branch of main condition which needs to be checked
69653 * @param {string} operator The operator of the main LogicalExpression.
69654 * @returns {boolean} true when condition short circuits whole condition
69655 */
69656
69657 function isLogicalIdentity(node, operator) {
69658 switch (node.type) {
69659 case "Literal":
69660 return operator === "||" && node.value === true || operator === "&&" && node.value === false;
69661
69662 case "UnaryExpression":
69663 return operator === "&&" && node.operator === "void";
69664
69665 case "LogicalExpression":
69666 return isLogicalIdentity(node.left, node.operator) || isLogicalIdentity(node.right, node.operator);
69667 // no default
69668 }
69669
69670 return false;
69671 }
69672 /**
69673 * Checks if a node has a constant truthiness value.
69674 * @param {ASTNode} node The AST node to check.
69675 * @param {boolean} inBooleanPosition `false` if checking branch of a condition.
69676 * `true` in all other cases
69677 * @returns {Bool} true when node's truthiness is constant
69678 * @private
69679 */
69680
69681
69682 function isConstant(node, inBooleanPosition) {
69683 // node.elements can return null values in the case of sparse arrays ex. [,]
69684 if (!node) {
69685 return true;
69686 }
69687
69688 switch (node.type) {
69689 case "Literal":
69690 case "ArrowFunctionExpression":
69691 case "FunctionExpression":
69692 case "ObjectExpression":
69693 return true;
69694
69695 case "TemplateLiteral":
69696 return inBooleanPosition && node.quasis.some(quasi => quasi.value.cooked.length) || node.expressions.every(exp => isConstant(exp, inBooleanPosition));
69697
69698 case "ArrayExpression":
69699 {
69700 if (node.parent.type === "BinaryExpression" && node.parent.operator === "+") {
69701 return node.elements.every(element => isConstant(element, false));
69702 }
69703
69704 return true;
69705 }
69706
69707 case "UnaryExpression":
69708 if (node.operator === "void") {
69709 return true;
69710 }
69711
69712 return node.operator === "typeof" && inBooleanPosition || isConstant(node.argument, true);
69713
69714 case "BinaryExpression":
69715 return isConstant(node.left, false) && isConstant(node.right, false) && node.operator !== "in";
69716
69717 case "LogicalExpression":
69718 {
69719 const isLeftConstant = isConstant(node.left, inBooleanPosition);
69720 const isRightConstant = isConstant(node.right, inBooleanPosition);
69721 const isLeftShortCircuit = isLeftConstant && isLogicalIdentity(node.left, node.operator);
69722 const isRightShortCircuit = isRightConstant && isLogicalIdentity(node.right, node.operator);
69723 return isLeftConstant && isRightConstant || // in the case of an "OR", we need to know if the right constant value is truthy
69724 node.operator === "||" && isRightConstant && node.right.value && (!node.parent || node.parent.type !== "BinaryExpression" || !(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator))) || isLeftShortCircuit || isRightShortCircuit;
69725 }
69726
69727 case "AssignmentExpression":
69728 return node.operator === "=" && isConstant(node.right, inBooleanPosition);
69729
69730 case "SequenceExpression":
69731 return isConstant(node.expressions[node.expressions.length - 1], inBooleanPosition);
69732 // no default
69733 }
69734
69735 return false;
69736 }
69737 /**
69738 * Tracks when the given node contains a constant condition.
69739 * @param {ASTNode} node The AST node to check.
69740 * @returns {void}
69741 * @private
69742 */
69743
69744
69745 function trackConstantConditionLoop(node) {
69746 if (node.test && isConstant(node.test, true)) {
69747 loopsInCurrentScope.add(node);
69748 }
69749 }
69750 /**
69751 * Reports when the set contains the given constant condition node
69752 * @param {ASTNode} node The AST node to check.
69753 * @returns {void}
69754 * @private
69755 */
69756
69757
69758 function checkConstantConditionLoopInSet(node) {
69759 if (loopsInCurrentScope.has(node)) {
69760 loopsInCurrentScope.delete(node);
69761 context.report({
69762 node: node.test,
69763 messageId: "unexpected"
69764 });
69765 }
69766 }
69767 /**
69768 * Reports when the given node contains a constant condition.
69769 * @param {ASTNode} node The AST node to check.
69770 * @returns {void}
69771 * @private
69772 */
69773
69774
69775 function reportIfConstant(node) {
69776 if (node.test && isConstant(node.test, true)) {
69777 context.report({
69778 node: node.test,
69779 messageId: "unexpected"
69780 });
69781 }
69782 }
69783 /**
69784 * Stores current set of constant loops in loopSetStack temporarily
69785 * and uses a new set to track constant loops
69786 * @returns {void}
69787 * @private
69788 */
69789
69790
69791 function enterFunction() {
69792 loopSetStack.push(loopsInCurrentScope);
69793 loopsInCurrentScope = new Set();
69794 }
69795 /**
69796 * Reports when the set still contains stored constant conditions
69797 * @returns {void}
69798 * @private
69799 */
69800
69801
69802 function exitFunction() {
69803 loopsInCurrentScope = loopSetStack.pop();
69804 }
69805 /**
69806 * Checks node when checkLoops option is enabled
69807 * @param {ASTNode} node The AST node to check.
69808 * @returns {void}
69809 * @private
69810 */
69811
69812
69813 function checkLoop(node) {
69814 if (checkLoops) {
69815 trackConstantConditionLoop(node);
69816 }
69817 } //--------------------------------------------------------------------------
69818 // Public
69819 //--------------------------------------------------------------------------
69820
69821
69822 return {
69823 ConditionalExpression: reportIfConstant,
69824 IfStatement: reportIfConstant,
69825 WhileStatement: checkLoop,
69826 "WhileStatement:exit": checkConstantConditionLoopInSet,
69827 DoWhileStatement: checkLoop,
69828 "DoWhileStatement:exit": checkConstantConditionLoopInSet,
69829 ForStatement: checkLoop,
69830 "ForStatement > .test": node => checkLoop(node.parent),
69831 "ForStatement:exit": checkConstantConditionLoopInSet,
69832 FunctionDeclaration: enterFunction,
69833 "FunctionDeclaration:exit": exitFunction,
69834 FunctionExpression: enterFunction,
69835 "FunctionExpression:exit": exitFunction,
69836 YieldExpression: () => loopsInCurrentScope.clear()
69837 };
69838 }
69839
69840};
69841
69842/***/ }),
69843/* 524 */
69844/***/ (function(module, exports, __webpack_require__) {
69845
69846"use strict";
69847/**
69848 * @fileoverview Rule to disallow returning value from constructor.
69849 * @author Pig Fang <https://github.com/g-plane>
69850 */
69851 //------------------------------------------------------------------------------
69852// Rule Definition
69853//------------------------------------------------------------------------------
69854
69855module.exports = {
69856 meta: {
69857 type: "problem",
69858 docs: {
69859 description: "disallow returning value from constructor",
69860 category: "Best Practices",
69861 recommended: false,
69862 url: "https://eslint.org/docs/rules/no-constructor-return"
69863 },
69864 schema: {},
69865 fixable: null,
69866 messages: {
69867 unexpected: "Unexpected return statement in constructor."
69868 }
69869 },
69870
69871 create(context) {
69872 const stack = [];
69873 return {
69874 onCodePathStart(_, node) {
69875 stack.push(node);
69876 },
69877
69878 onCodePathEnd() {
69879 stack.pop();
69880 },
69881
69882 ReturnStatement(node) {
69883 const last = stack[stack.length - 1];
69884
69885 if (!last.parent) {
69886 return;
69887 }
69888
69889 if (last.parent.type === "MethodDefinition" && last.parent.kind === "constructor" && (node.parent.parent === last || node.argument)) {
69890 context.report({
69891 node,
69892 messageId: "unexpected"
69893 });
69894 }
69895 }
69896
69897 };
69898 }
69899
69900};
69901
69902/***/ }),
69903/* 525 */
69904/***/ (function(module, exports, __webpack_require__) {
69905
69906"use strict";
69907/**
69908 * @fileoverview Rule to flag use of continue statement
69909 * @author Borislav Zhivkov
69910 */
69911 //------------------------------------------------------------------------------
69912// Rule Definition
69913//------------------------------------------------------------------------------
69914
69915module.exports = {
69916 meta: {
69917 type: "suggestion",
69918 docs: {
69919 description: "disallow `continue` statements",
69920 category: "Stylistic Issues",
69921 recommended: false,
69922 url: "https://eslint.org/docs/rules/no-continue"
69923 },
69924 schema: [],
69925 messages: {
69926 unexpected: "Unexpected use of continue statement."
69927 }
69928 },
69929
69930 create(context) {
69931 return {
69932 ContinueStatement(node) {
69933 context.report({
69934 node,
69935 messageId: "unexpected"
69936 });
69937 }
69938
69939 };
69940 }
69941
69942};
69943
69944/***/ }),
69945/* 526 */
69946/***/ (function(module, exports, __webpack_require__) {
69947
69948"use strict";
69949/**
69950 * @fileoverview Rule to forbid control characters from regular expressions.
69951 * @author Nicholas C. Zakas
69952 */
69953
69954
69955const RegExpValidator = __webpack_require__(527).RegExpValidator;
69956
69957const collector = new class {
69958 constructor() {
69959 this.ecmaVersion = 2018;
69960 this._source = "";
69961 this._controlChars = [];
69962 this._validator = new RegExpValidator(this);
69963 }
69964
69965 onPatternEnter() {
69966 this._controlChars = [];
69967 }
69968
69969 onCharacter(start, end, cp) {
69970 if (cp >= 0x00 && cp <= 0x1F && (this._source.codePointAt(start) === cp || this._source.slice(start, end).startsWith("\\x") || this._source.slice(start, end).startsWith("\\u"))) {
69971 this._controlChars.push("\\x".concat("0".concat(cp.toString(16)).slice(-2)));
69972 }
69973 }
69974
69975 collectControlChars(regexpStr) {
69976 try {
69977 this._source = regexpStr;
69978
69979 this._validator.validatePattern(regexpStr); // Call onCharacter hook
69980
69981 } catch (err) {// Ignore syntax errors in RegExp.
69982 }
69983
69984 return this._controlChars;
69985 }
69986
69987}(); //------------------------------------------------------------------------------
69988// Rule Definition
69989//------------------------------------------------------------------------------
69990
69991module.exports = {
69992 meta: {
69993 type: "problem",
69994 docs: {
69995 description: "disallow control characters in regular expressions",
69996 category: "Possible Errors",
69997 recommended: true,
69998 url: "https://eslint.org/docs/rules/no-control-regex"
69999 },
70000 schema: [],
70001 messages: {
70002 unexpected: "Unexpected control character(s) in regular expression: {{controlChars}}."
70003 }
70004 },
70005
70006 create(context) {
70007 /**
70008 * Get the regex expression
70009 * @param {ASTNode} node node to evaluate
70010 * @returns {RegExp|null} Regex if found else null
70011 * @private
70012 */
70013 function getRegExpPattern(node) {
70014 if (node.regex) {
70015 return node.regex.pattern;
70016 }
70017
70018 if (typeof node.value === "string" && (node.parent.type === "NewExpression" || node.parent.type === "CallExpression") && node.parent.callee.type === "Identifier" && node.parent.callee.name === "RegExp" && node.parent.arguments[0] === node) {
70019 return node.value;
70020 }
70021
70022 return null;
70023 }
70024
70025 return {
70026 Literal(node) {
70027 const pattern = getRegExpPattern(node);
70028
70029 if (pattern) {
70030 const controlCharacters = collector.collectControlChars(pattern);
70031
70032 if (controlCharacters.length > 0) {
70033 context.report({
70034 node,
70035 messageId: "unexpected",
70036 data: {
70037 controlChars: controlCharacters.join(", ")
70038 }
70039 });
70040 }
70041 }
70042 }
70043
70044 };
70045 }
70046
70047};
70048
70049/***/ }),
70050/* 527 */
70051/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) {
70052
70053"use strict";
70054__webpack_require__.r(__webpack_exports__);
70055/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AST", function() { return ast; });
70056/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegExpParser", function() { return RegExpParser; });
70057/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegExpValidator", function() { return RegExpValidator; });
70058/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseRegExpLiteral", function() { return parseRegExpLiteral; });
70059/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateRegExpLiteral", function() { return validateRegExpLiteral; });
70060/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visitRegExpAST", function() { return visitRegExpAST; });
70061/*! @author Toru Nagashima <https://github.com/mysticatea> */
70062var ast = /*#__PURE__*/Object.freeze({});
56c4a2cb
DC
70063let largeIdStartRanges = undefined;
70064let largeIdContinueRanges = undefined;
eb39fafa
DC
70065
70066function isIdStart(cp) {
70067 if (cp < 0x41) return false;
70068 if (cp < 0x5b) return true;
70069 if (cp < 0x61) return false;
70070 if (cp < 0x7b) return true;
70071 return isLargeIdStart(cp);
70072}
70073
70074function isIdContinue(cp) {
70075 if (cp < 0x30) return false;
70076 if (cp < 0x3a) return true;
70077 if (cp < 0x41) return false;
70078 if (cp < 0x5b) return true;
70079 if (cp === 0x5f) return true;
70080 if (cp < 0x61) return false;
70081 if (cp < 0x7b) return true;
70082 return isLargeIdStart(cp) || isLargeIdContinue(cp);
70083}
70084
70085function isLargeIdStart(cp) {
56c4a2cb 70086 return isInRange(cp, largeIdStartRanges || (largeIdStartRanges = initLargeIdStartRanges()));
eb39fafa
DC
70087}
70088
70089function isLargeIdContinue(cp) {
56c4a2cb
DC
70090 return isInRange(cp, largeIdContinueRanges || (largeIdContinueRanges = initLargeIdContinueRanges()));
70091}
eb39fafa 70092
56c4a2cb
DC
70093function initLargeIdStartRanges() {
70094 return restoreRanges("170 0 11 0 5 0 6 22 2 30 2 457 5 11 15 4 8 0 2 0 130 4 2 1 3 3 2 0 7 0 2 2 2 0 2 19 2 82 2 138 9 165 2 37 3 0 7 40 72 26 5 3 46 42 36 1 2 98 2 0 16 1 8 1 11 2 3 0 17 0 2 29 30 88 12 0 25 32 10 1 5 0 6 21 5 0 10 0 4 0 24 24 8 10 54 20 2 17 61 53 4 0 19 0 8 9 16 15 5 7 3 1 3 21 2 6 2 0 4 3 4 0 17 0 14 1 2 2 15 1 11 0 9 5 5 1 3 21 2 6 2 1 2 1 2 1 32 3 2 0 20 2 17 8 2 2 2 21 2 6 2 1 2 4 4 0 19 0 16 1 24 0 12 7 3 1 3 21 2 6 2 1 2 4 4 0 31 1 2 2 16 0 18 0 2 5 4 2 2 3 4 1 2 0 2 1 4 1 4 2 4 11 23 0 53 7 2 2 2 22 2 15 4 0 27 2 6 1 31 0 5 7 2 2 2 22 2 9 2 4 4 0 33 0 2 1 16 1 18 8 2 2 2 40 3 0 17 0 6 2 9 2 25 5 6 17 4 23 2 8 2 0 3 6 59 47 2 1 13 6 59 1 2 0 2 4 2 23 2 0 2 9 2 1 10 0 3 4 2 0 22 3 33 0 64 7 2 35 28 4 116 42 21 0 17 5 5 3 4 0 4 1 8 2 5 12 13 0 18 37 2 0 6 0 3 42 2 332 2 3 3 6 2 0 2 3 3 40 2 3 3 32 2 3 3 6 2 0 2 3 3 14 2 56 2 3 3 66 38 15 17 85 3 5 4 619 3 16 2 25 6 74 4 10 8 12 2 3 15 17 15 17 15 12 2 2 16 51 36 0 5 0 68 88 8 40 2 0 6 69 11 30 50 29 3 4 12 43 5 25 55 22 10 52 83 0 94 46 18 6 56 29 14 1 11 43 27 35 42 2 11 35 3 8 8 42 3 2 42 3 2 5 2 1 4 0 6 191 65 277 3 5 3 37 3 5 3 7 2 0 2 0 2 0 2 30 3 52 2 6 2 0 4 2 2 6 4 3 3 5 5 12 6 2 2 6 117 0 14 0 17 12 102 0 5 0 3 9 2 0 3 5 7 0 2 0 2 0 2 15 3 3 6 4 5 0 18 40 2680 46 2 46 2 132 7 3 4 1 13 37 2 0 6 0 3 55 8 0 17 22 10 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 551 2 26 8 8 4 3 4 5 85 5 4 2 89 2 3 6 42 2 93 18 31 49 15 513 6591 65 20988 4 1164 68 45 3 268 4 15 11 1 21 46 17 30 3 79 40 8 3 102 3 52 3 8 43 12 2 2 2 3 2 22 30 51 15 49 63 5 4 0 2 1 12 27 11 22 26 28 8 46 29 0 17 4 2 9 11 4 2 40 24 2 2 7 21 22 4 0 4 49 2 0 4 1 3 4 3 0 2 0 25 2 3 10 8 2 13 5 3 5 3 5 10 6 2 6 2 42 2 13 7 114 30 11171 13 22 5 48 8453 365 3 105 39 6 13 4 6 0 2 9 2 12 2 4 2 0 2 1 2 1 2 107 34 362 19 63 3 53 41 11 117 4 2 134 37 25 7 25 12 88 4 5 3 5 3 5 3 2 36 11 2 25 2 18 2 1 2 14 3 13 35 122 70 52 268 28 4 48 48 31 14 29 6 37 11 29 3 35 5 7 2 4 43 157 19 35 5 35 5 39 9 51 157 310 10 21 11 7 153 5 3 0 2 43 2 1 4 0 3 22 11 22 10 30 66 18 2 1 11 21 11 25 71 55 7 1 65 0 16 3 2 2 2 28 43 28 4 28 36 7 2 27 28 53 11 21 11 18 14 17 111 72 56 50 14 50 14 35 349 41 7 1 79 28 11 0 9 21 107 20 28 22 13 52 76 44 33 24 27 35 30 0 3 0 9 34 4 0 13 47 15 3 22 0 2 0 36 17 2 24 85 6 2 0 2 3 2 14 2 9 8 46 39 7 3 1 3 21 2 6 2 1 2 4 4 0 19 0 13 4 159 52 19 3 21 2 31 47 21 1 2 0 185 46 42 3 37 47 21 0 60 42 14 0 72 26 230 43 117 63 32 7 3 0 3 7 2 1 2 23 16 0 2 0 95 7 3 38 17 0 2 0 29 0 11 39 8 0 22 0 12 45 20 0 35 56 264 8 2 36 18 0 50 29 113 6 2 1 2 37 22 0 26 5 2 1 2 31 15 0 328 18 190 0 80 921 103 110 18 195 2749 1070 4050 582 8634 568 8 30 114 29 19 47 17 3 32 20 6 18 689 63 129 74 6 0 67 12 65 1 2 0 29 6135 9 1237 43 8 8952 286 50 2 18 3 9 395 2309 106 6 12 4 8 8 9 5991 84 2 70 2 1 3 0 3 1 3 3 2 11 2 0 2 6 2 64 2 3 3 7 2 6 2 27 2 3 2 4 2 0 4 6 2 339 3 24 2 24 2 30 2 24 2 30 2 24 2 30 2 24 2 30 2 24 2 7 2357 44 11 6 17 0 370 43 1301 196 60 67 8 0 1205 3 2 26 2 1 2 0 3 0 2 9 2 3 2 0 2 0 7 0 5 0 2 0 2 0 2 2 2 1 2 0 3 0 2 0 2 0 2 0 2 0 2 1 2 0 3 3 2 6 2 3 2 3 2 0 2 9 2 16 6 2 2 4 2 16 4421 42717 35 4148 12 221 3 5761 15 7472 3104 541 1507 4938");
eb39fafa
DC
70095}
70096
56c4a2cb
DC
70097function initLargeIdContinueRanges() {
70098 return restoreRanges("183 0 585 111 24 0 252 4 266 44 2 0 2 1 2 1 2 0 73 10 49 30 7 0 102 6 3 5 3 1 2 3 3 9 24 0 31 26 92 10 16 9 34 8 10 0 25 3 2 8 2 2 2 4 44 2 120 14 2 32 55 2 2 17 2 6 11 1 3 9 18 2 57 0 2 6 3 1 3 2 10 0 11 1 3 9 15 0 3 2 57 0 2 4 5 1 3 2 4 0 21 11 4 0 12 2 57 0 2 7 2 2 2 2 21 1 3 9 11 5 2 2 57 0 2 6 3 1 3 2 8 2 11 1 3 9 19 0 60 4 4 2 2 3 10 0 15 9 17 4 58 6 2 2 2 3 8 1 12 1 3 9 18 2 57 0 2 6 2 2 2 3 8 1 12 1 3 9 17 3 56 1 2 6 2 2 2 3 10 0 11 1 3 9 18 2 71 0 5 5 2 0 2 7 7 9 3 1 62 0 3 6 13 7 2 9 88 0 3 8 12 5 3 9 63 1 7 9 12 0 2 0 2 0 5 1 50 19 2 1 6 10 2 35 10 0 101 19 2 9 13 3 5 2 2 2 3 6 4 3 14 11 2 14 704 2 10 8 929 2 30 2 30 1 31 1 65 31 10 0 3 9 34 2 3 9 144 0 119 11 5 11 11 9 129 10 61 4 58 9 2 28 3 10 7 9 23 13 2 1 64 4 48 16 12 9 18 8 13 2 31 12 3 9 45 13 49 19 9 9 7 9 119 2 2 20 5 0 7 0 3 2 199 57 2 4 576 1 20 0 124 12 5 0 4 11 3071 2 142 0 97 31 555 5 106 1 30086 9 70 0 5 9 33 1 81 1 273 0 4 0 5 0 24 4 5 0 84 1 51 17 11 9 7 17 14 10 29 7 26 12 45 3 48 13 16 9 12 0 11 9 48 13 13 0 9 1 3 9 34 2 51 0 2 2 3 1 6 1 2 0 42 4 6 1 237 7 2 1 3 9 20261 0 738 15 17 15 4 1 25 2 193 9 38 0 702 0 227 0 150 4 294 9 1368 2 2 1 6 3 41 2 5 0 166 1 574 3 9 9 370 1 154 10 176 2 54 14 32 9 16 3 46 10 54 9 7 2 37 13 2 9 6 1 45 0 13 2 49 13 9 3 2 11 83 11 7 0 161 11 6 9 7 3 56 1 2 6 3 1 3 2 10 0 11 1 3 6 4 4 193 17 10 9 5 0 82 19 13 9 214 6 3 8 28 1 83 16 16 9 82 12 9 9 84 14 5 9 243 14 166 9 71 5 2 1 3 3 2 0 2 1 13 9 120 6 3 6 4 0 29 9 41 6 2 3 9 0 10 10 47 15 406 7 2 7 17 9 57 21 2 13 123 5 4 0 2 1 2 6 2 0 9 9 49 4 2 1 2 4 9 9 330 3 19306 9 135 4 60 6 26 9 1014 0 2 54 8 3 82 0 12 1 19628 1 5319 4 4 5 9 7 3 6 31 3 149 2 1418 49 513 54 5 49 9 0 15 0 23 4 2 14 1361 6 2 16 3 6 2 1 2 4 262 6 10 9 419 13 1495 6 110 6 6 9 4759 9 787719 239");
70099}
eb39fafa 70100
56c4a2cb
DC
70101function isInRange(cp, ranges) {
70102 let l = 0,
70103 r = ranges.length / 2 | 0,
70104 i = 0,
70105 min = 0,
70106 max = 0;
eb39fafa 70107
56c4a2cb
DC
70108 while (l < r) {
70109 i = (l + r) / 2 | 0;
70110 min = ranges[2 * i];
70111 max = ranges[2 * i + 1];
70112
70113 if (cp < min) {
70114 r = i;
70115 } else if (cp > max) {
70116 l = i + 1;
70117 } else {
70118 return true;
eb39fafa
DC
70119 }
70120 }
70121
56c4a2cb
DC
70122 return false;
70123}
eb39fafa 70124
56c4a2cb
DC
70125function restoreRanges(data) {
70126 let last = 0;
70127 return data.split(" ").map(s => last += parseInt(s, 10) | 0);
70128}
eb39fafa 70129
56c4a2cb
DC
70130class DataSet {
70131 constructor(raw2018, raw2019, raw2020) {
70132 this._raw2018 = raw2018;
70133 this._raw2019 = raw2019;
70134 this._raw2020 = raw2020;
70135 }
eb39fafa 70136
56c4a2cb
DC
70137 get es2018() {
70138 return this._set2018 || (this._set2018 = new Set(this._raw2018.split(" ")));
70139 }
eb39fafa 70140
56c4a2cb
DC
70141 get es2019() {
70142 return this._set2019 || (this._set2019 = new Set(this._raw2019.split(" ")));
70143 }
eb39fafa 70144
56c4a2cb
DC
70145 get es2020() {
70146 return this._set2020 || (this._set2020 = new Set(this._raw2020.split(" ")));
eb39fafa
DC
70147 }
70148
eb39fafa
DC
70149}
70150
56c4a2cb
DC
70151const gcNameSet = new Set(["General_Category", "gc"]);
70152const scNameSet = new Set(["Script", "Script_Extensions", "sc", "scx"]);
70153const gcValueSets = new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "");
70154const scValueSets = new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho");
70155const binPropertySets = new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "");
eb39fafa 70156
56c4a2cb
DC
70157function isValidUnicodeProperty(version, name, value) {
70158 if (gcNameSet.has(name)) {
70159 return version >= 2018 && gcValueSets.es2018.has(value);
eb39fafa
DC
70160 }
70161
56c4a2cb
DC
70162 if (scNameSet.has(name)) {
70163 return version >= 2018 && scValueSets.es2018.has(value) || version >= 2019 && scValueSets.es2019.has(value) || version >= 2020 && scValueSets.es2020.has(value);
eb39fafa
DC
70164 }
70165
70166 return false;
70167}
70168
56c4a2cb
DC
70169function isValidLoneUnicodeProperty(version, value) {
70170 return version >= 2018 && binPropertySets.es2018.has(value) || version >= 2019 && binPropertySets.es2019.has(value);
70171}
70172
eb39fafa
DC
70173const Backspace = 0x08;
70174const CharacterTabulation = 0x09;
70175const LineFeed = 0x0a;
70176const LineTabulation = 0x0b;
70177const FormFeed = 0x0c;
70178const CarriageReturn = 0x0d;
70179const ExclamationMark = 0x21;
70180const DollarSign = 0x24;
70181const LeftParenthesis = 0x28;
70182const RightParenthesis = 0x29;
70183const Asterisk = 0x2a;
70184const PlusSign = 0x2b;
70185const Comma = 0x2c;
70186const HyphenMinus = 0x2d;
70187const FullStop = 0x2e;
70188const Solidus = 0x2f;
70189const DigitZero = 0x30;
70190const DigitOne = 0x31;
70191const DigitSeven = 0x37;
70192const DigitNine = 0x39;
70193const Colon = 0x3a;
70194const LessThanSign = 0x3c;
70195const EqualsSign = 0x3d;
70196const GreaterThanSign = 0x3e;
70197const QuestionMark = 0x3f;
70198const LatinCapitalLetterA = 0x41;
70199const LatinCapitalLetterB = 0x42;
70200const LatinCapitalLetterD = 0x44;
70201const LatinCapitalLetterF = 0x46;
70202const LatinCapitalLetterP = 0x50;
70203const LatinCapitalLetterS = 0x53;
70204const LatinCapitalLetterW = 0x57;
70205const LatinCapitalLetterZ = 0x5a;
70206const LowLine = 0x5f;
70207const LatinSmallLetterA = 0x61;
70208const LatinSmallLetterB = 0x62;
70209const LatinSmallLetterC = 0x63;
70210const LatinSmallLetterD = 0x64;
70211const LatinSmallLetterF = 0x66;
70212const LatinSmallLetterG = 0x67;
70213const LatinSmallLetterI = 0x69;
70214const LatinSmallLetterK = 0x6b;
70215const LatinSmallLetterM = 0x6d;
70216const LatinSmallLetterN = 0x6e;
70217const LatinSmallLetterP = 0x70;
70218const LatinSmallLetterR = 0x72;
70219const LatinSmallLetterS = 0x73;
70220const LatinSmallLetterT = 0x74;
70221const LatinSmallLetterU = 0x75;
70222const LatinSmallLetterV = 0x76;
70223const LatinSmallLetterW = 0x77;
70224const LatinSmallLetterX = 0x78;
70225const LatinSmallLetterY = 0x79;
70226const LatinSmallLetterZ = 0x7a;
70227const LeftSquareBracket = 0x5b;
70228const ReverseSolidus = 0x5c;
70229const RightSquareBracket = 0x5d;
70230const CircumflexAccent = 0x5e;
70231const LeftCurlyBracket = 0x7b;
70232const VerticalLine = 0x7c;
70233const RightCurlyBracket = 0x7d;
70234const ZeroWidthNonJoiner = 0x200c;
70235const ZeroWidthJoiner = 0x200d;
70236const LineSeparator = 0x2028;
70237const ParagraphSeparator = 0x2029;
70238const MinCodePoint = 0x00;
70239const MaxCodePoint = 0x10ffff;
70240
70241function isLatinLetter(code) {
70242 return code >= LatinCapitalLetterA && code <= LatinCapitalLetterZ || code >= LatinSmallLetterA && code <= LatinSmallLetterZ;
70243}
70244
70245function isDecimalDigit(code) {
70246 return code >= DigitZero && code <= DigitNine;
70247}
70248
70249function isOctalDigit(code) {
70250 return code >= DigitZero && code <= DigitSeven;
70251}
70252
70253function isHexDigit(code) {
70254 return code >= DigitZero && code <= DigitNine || code >= LatinCapitalLetterA && code <= LatinCapitalLetterF || code >= LatinSmallLetterA && code <= LatinSmallLetterF;
70255}
70256
70257function isLineTerminator(code) {
70258 return code === LineFeed || code === CarriageReturn || code === LineSeparator || code === ParagraphSeparator;
70259}
70260
70261function isValidUnicode(code) {
70262 return code >= MinCodePoint && code <= MaxCodePoint;
70263}
70264
70265function digitToInt(code) {
70266 if (code >= LatinSmallLetterA && code <= LatinSmallLetterF) {
70267 return code - LatinSmallLetterA + 10;
70268 }
70269
70270 if (code >= LatinCapitalLetterA && code <= LatinCapitalLetterF) {
70271 return code - LatinCapitalLetterA + 10;
70272 }
70273
70274 return code - DigitZero;
70275}
70276
56c4a2cb
DC
70277function isLeadSurrogate(code) {
70278 return code >= 0xd800 && code <= 0xdbff;
70279}
70280
70281function isTrailSurrogate(code) {
70282 return code >= 0xdc00 && code <= 0xdfff;
70283}
70284
70285function combineSurrogatePair(lead, trail) {
70286 return (lead - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000;
70287}
70288
eb39fafa
DC
70289const legacyImpl = {
70290 at(s, end, i) {
70291 return i < end ? s.charCodeAt(i) : -1;
70292 },
70293
70294 width(c) {
70295 return 1;
70296 }
70297
70298};
70299const unicodeImpl = {
70300 at(s, end, i) {
70301 return i < end ? s.codePointAt(i) : -1;
70302 },
70303
70304 width(c) {
70305 return c > 0xffff ? 2 : 1;
70306 }
70307
70308};
70309
70310class Reader {
70311 constructor() {
70312 this._impl = legacyImpl;
70313 this._s = "";
70314 this._i = 0;
70315 this._end = 0;
70316 this._cp1 = -1;
70317 this._w1 = 1;
70318 this._cp2 = -1;
70319 this._w2 = 1;
70320 this._cp3 = -1;
70321 this._w3 = 1;
70322 this._cp4 = -1;
70323 }
70324
70325 get source() {
70326 return this._s;
70327 }
70328
70329 get index() {
70330 return this._i;
70331 }
70332
70333 get currentCodePoint() {
70334 return this._cp1;
70335 }
70336
70337 get nextCodePoint() {
70338 return this._cp2;
70339 }
70340
70341 get nextCodePoint2() {
70342 return this._cp3;
70343 }
70344
70345 get nextCodePoint3() {
70346 return this._cp4;
70347 }
70348
70349 reset(source, start, end, uFlag) {
70350 this._impl = uFlag ? unicodeImpl : legacyImpl;
70351 this._s = source;
70352 this._end = end;
70353 this.rewind(start);
70354 }
70355
70356 rewind(index) {
70357 const impl = this._impl;
70358 this._i = index;
70359 this._cp1 = impl.at(this._s, this._end, index);
70360 this._w1 = impl.width(this._cp1);
70361 this._cp2 = impl.at(this._s, this._end, index + this._w1);
70362 this._w2 = impl.width(this._cp2);
70363 this._cp3 = impl.at(this._s, this._end, index + this._w1 + this._w2);
70364 this._w3 = impl.width(this._cp3);
70365 this._cp4 = impl.at(this._s, this._end, index + this._w1 + this._w2 + this._w3);
70366 }
70367
70368 advance() {
70369 if (this._cp1 !== -1) {
70370 const impl = this._impl;
70371 this._i += this._w1;
70372 this._cp1 = this._cp2;
70373 this._w1 = this._w2;
70374 this._cp2 = this._cp3;
70375 this._w2 = impl.width(this._cp2);
70376 this._cp3 = this._cp4;
70377 this._w3 = impl.width(this._cp3);
70378 this._cp4 = impl.at(this._s, this._end, this._i + this._w1 + this._w2 + this._w3);
70379 }
70380 }
70381
70382 eat(cp) {
70383 if (this._cp1 === cp) {
70384 this.advance();
70385 return true;
70386 }
70387
70388 return false;
70389 }
70390
70391 eat2(cp1, cp2) {
70392 if (this._cp1 === cp1 && this._cp2 === cp2) {
70393 this.advance();
70394 this.advance();
70395 return true;
70396 }
70397
70398 return false;
70399 }
70400
70401 eat3(cp1, cp2, cp3) {
70402 if (this._cp1 === cp1 && this._cp2 === cp2 && this._cp3 === cp3) {
70403 this.advance();
70404 this.advance();
70405 this.advance();
70406 return true;
70407 }
70408
70409 return false;
70410 }
70411
70412}
70413
70414class RegExpSyntaxError extends SyntaxError {
70415 constructor(source, uFlag, index, message) {
70416 if (source) {
70417 if (!source.startsWith("/")) {
70418 source = "/".concat(source, "/").concat(uFlag ? "u" : "");
70419 }
70420
70421 source = ": ".concat(source);
70422 }
70423
70424 super("Invalid regular expression".concat(source, ": ").concat(message));
70425 this.index = index;
70426 }
70427
70428}
70429
70430function isSyntaxCharacter(cp) {
70431 return cp === CircumflexAccent || cp === DollarSign || cp === ReverseSolidus || cp === FullStop || cp === Asterisk || cp === PlusSign || cp === QuestionMark || cp === LeftParenthesis || cp === RightParenthesis || cp === LeftSquareBracket || cp === RightSquareBracket || cp === LeftCurlyBracket || cp === RightCurlyBracket || cp === VerticalLine;
70432}
70433
70434function isRegExpIdentifierStart(cp) {
70435 return isIdStart(cp) || cp === DollarSign || cp === LowLine;
70436}
70437
70438function isRegExpIdentifierPart(cp) {
70439 return isIdContinue(cp) || cp === DollarSign || cp === LowLine || cp === ZeroWidthNonJoiner || cp === ZeroWidthJoiner;
70440}
70441
70442function isUnicodePropertyNameCharacter(cp) {
70443 return isLatinLetter(cp) || cp === LowLine;
70444}
70445
70446function isUnicodePropertyValueCharacter(cp) {
70447 return isUnicodePropertyNameCharacter(cp) || isDecimalDigit(cp);
70448}
70449
70450class RegExpValidator {
70451 constructor(options) {
70452 this._reader = new Reader();
70453 this._uFlag = false;
70454 this._nFlag = false;
70455 this._lastIntValue = 0;
70456 this._lastMinValue = 0;
70457 this._lastMaxValue = 0;
70458 this._lastStrValue = "";
70459 this._lastKeyValue = "";
70460 this._lastValValue = "";
70461 this._lastAssertionIsQuantifiable = false;
70462 this._numCapturingParens = 0;
70463 this._groupNames = new Set();
70464 this._backreferenceNames = new Set();
70465 this._options = options || {};
70466 }
70467
70468 validateLiteral(source, start = 0, end = source.length) {
70469 this._uFlag = this._nFlag = false;
70470 this.reset(source, start, end);
70471 this.onLiteralEnter(start);
70472
70473 if (this.eat(Solidus) && this.eatRegExpBody() && this.eat(Solidus)) {
70474 const flagStart = this.index;
70475 const uFlag = source.includes("u", flagStart);
70476 this.validateFlags(source, flagStart, end);
70477 this.validatePattern(source, start + 1, flagStart - 1, uFlag);
70478 } else if (start >= end) {
70479 this.raise("Empty");
70480 } else {
70481 const c = String.fromCodePoint(this.currentCodePoint);
70482 this.raise("Unexpected character '".concat(c, "'"));
70483 }
70484
70485 this.onLiteralLeave(start, end);
70486 }
70487
70488 validateFlags(source, start = 0, end = source.length) {
70489 const existingFlags = new Set();
70490 let global = false;
70491 let ignoreCase = false;
70492 let multiline = false;
70493 let sticky = false;
70494 let unicode = false;
70495 let dotAll = false;
70496
70497 for (let i = start; i < end; ++i) {
70498 const flag = source.charCodeAt(i);
70499
70500 if (existingFlags.has(flag)) {
70501 this.raise("Duplicated flag '".concat(source[i], "'"));
70502 }
70503
70504 existingFlags.add(flag);
70505
70506 if (flag === LatinSmallLetterG) {
70507 global = true;
70508 } else if (flag === LatinSmallLetterI) {
70509 ignoreCase = true;
70510 } else if (flag === LatinSmallLetterM) {
70511 multiline = true;
70512 } else if (flag === LatinSmallLetterU && this.ecmaVersion >= 2015) {
70513 unicode = true;
70514 } else if (flag === LatinSmallLetterY && this.ecmaVersion >= 2015) {
70515 sticky = true;
70516 } else if (flag === LatinSmallLetterS && this.ecmaVersion >= 2018) {
70517 dotAll = true;
70518 } else {
70519 this.raise("Invalid flag '".concat(source[i], "'"));
70520 }
70521 }
70522
70523 this.onFlags(start, end, global, ignoreCase, multiline, unicode, sticky, dotAll);
70524 }
70525
70526 validatePattern(source, start = 0, end = source.length, uFlag = false) {
70527 this._uFlag = uFlag && this.ecmaVersion >= 2015;
70528 this._nFlag = uFlag && this.ecmaVersion >= 2018;
70529 this.reset(source, start, end);
56c4a2cb 70530 this.consumePattern();
eb39fafa
DC
70531
70532 if (!this._nFlag && this.ecmaVersion >= 2018 && this._groupNames.size > 0) {
70533 this._nFlag = true;
70534 this.rewind(start);
56c4a2cb 70535 this.consumePattern();
eb39fafa
DC
70536 }
70537 }
70538
70539 get strict() {
70540 return Boolean(this._options.strict || this._uFlag);
70541 }
70542
70543 get ecmaVersion() {
70544 return this._options.ecmaVersion || 2020;
70545 }
70546
70547 onLiteralEnter(start) {
70548 if (this._options.onLiteralEnter) {
70549 this._options.onLiteralEnter(start);
70550 }
70551 }
70552
70553 onLiteralLeave(start, end) {
70554 if (this._options.onLiteralLeave) {
70555 this._options.onLiteralLeave(start, end);
70556 }
70557 }
70558
70559 onFlags(start, end, global, ignoreCase, multiline, unicode, sticky, dotAll) {
70560 if (this._options.onFlags) {
70561 this._options.onFlags(start, end, global, ignoreCase, multiline, unicode, sticky, dotAll);
70562 }
70563 }
70564
70565 onPatternEnter(start) {
70566 if (this._options.onPatternEnter) {
70567 this._options.onPatternEnter(start);
70568 }
70569 }
70570
70571 onPatternLeave(start, end) {
70572 if (this._options.onPatternLeave) {
70573 this._options.onPatternLeave(start, end);
70574 }
70575 }
70576
70577 onDisjunctionEnter(start) {
70578 if (this._options.onDisjunctionEnter) {
70579 this._options.onDisjunctionEnter(start);
70580 }
70581 }
70582
70583 onDisjunctionLeave(start, end) {
70584 if (this._options.onDisjunctionLeave) {
70585 this._options.onDisjunctionLeave(start, end);
70586 }
70587 }
70588
70589 onAlternativeEnter(start, index) {
70590 if (this._options.onAlternativeEnter) {
70591 this._options.onAlternativeEnter(start, index);
70592 }
70593 }
70594
70595 onAlternativeLeave(start, end, index) {
70596 if (this._options.onAlternativeLeave) {
70597 this._options.onAlternativeLeave(start, end, index);
70598 }
70599 }
70600
70601 onGroupEnter(start) {
70602 if (this._options.onGroupEnter) {
70603 this._options.onGroupEnter(start);
70604 }
70605 }
70606
70607 onGroupLeave(start, end) {
70608 if (this._options.onGroupLeave) {
70609 this._options.onGroupLeave(start, end);
70610 }
70611 }
70612
70613 onCapturingGroupEnter(start, name) {
70614 if (this._options.onCapturingGroupEnter) {
70615 this._options.onCapturingGroupEnter(start, name);
70616 }
70617 }
70618
70619 onCapturingGroupLeave(start, end, name) {
70620 if (this._options.onCapturingGroupLeave) {
70621 this._options.onCapturingGroupLeave(start, end, name);
70622 }
70623 }
70624
70625 onQuantifier(start, end, min, max, greedy) {
70626 if (this._options.onQuantifier) {
70627 this._options.onQuantifier(start, end, min, max, greedy);
70628 }
70629 }
70630
70631 onLookaroundAssertionEnter(start, kind, negate) {
70632 if (this._options.onLookaroundAssertionEnter) {
70633 this._options.onLookaroundAssertionEnter(start, kind, negate);
70634 }
70635 }
70636
70637 onLookaroundAssertionLeave(start, end, kind, negate) {
70638 if (this._options.onLookaroundAssertionLeave) {
70639 this._options.onLookaroundAssertionLeave(start, end, kind, negate);
70640 }
70641 }
70642
70643 onEdgeAssertion(start, end, kind) {
70644 if (this._options.onEdgeAssertion) {
70645 this._options.onEdgeAssertion(start, end, kind);
70646 }
70647 }
70648
70649 onWordBoundaryAssertion(start, end, kind, negate) {
70650 if (this._options.onWordBoundaryAssertion) {
70651 this._options.onWordBoundaryAssertion(start, end, kind, negate);
70652 }
70653 }
70654
70655 onAnyCharacterSet(start, end, kind) {
70656 if (this._options.onAnyCharacterSet) {
70657 this._options.onAnyCharacterSet(start, end, kind);
70658 }
70659 }
70660
70661 onEscapeCharacterSet(start, end, kind, negate) {
70662 if (this._options.onEscapeCharacterSet) {
70663 this._options.onEscapeCharacterSet(start, end, kind, negate);
70664 }
70665 }
70666
70667 onUnicodePropertyCharacterSet(start, end, kind, key, value, negate) {
70668 if (this._options.onUnicodePropertyCharacterSet) {
70669 this._options.onUnicodePropertyCharacterSet(start, end, kind, key, value, negate);
70670 }
70671 }
70672
70673 onCharacter(start, end, value) {
70674 if (this._options.onCharacter) {
70675 this._options.onCharacter(start, end, value);
70676 }
70677 }
70678
70679 onBackreference(start, end, ref) {
70680 if (this._options.onBackreference) {
70681 this._options.onBackreference(start, end, ref);
70682 }
70683 }
70684
70685 onCharacterClassEnter(start, negate) {
70686 if (this._options.onCharacterClassEnter) {
70687 this._options.onCharacterClassEnter(start, negate);
70688 }
70689 }
70690
70691 onCharacterClassLeave(start, end, negate) {
70692 if (this._options.onCharacterClassLeave) {
70693 this._options.onCharacterClassLeave(start, end, negate);
70694 }
70695 }
70696
70697 onCharacterClassRange(start, end, min, max) {
70698 if (this._options.onCharacterClassRange) {
70699 this._options.onCharacterClassRange(start, end, min, max);
70700 }
70701 }
70702
70703 get source() {
70704 return this._reader.source;
70705 }
70706
70707 get index() {
70708 return this._reader.index;
70709 }
70710
70711 get currentCodePoint() {
70712 return this._reader.currentCodePoint;
70713 }
70714
70715 get nextCodePoint() {
70716 return this._reader.nextCodePoint;
70717 }
70718
70719 get nextCodePoint2() {
70720 return this._reader.nextCodePoint2;
70721 }
70722
70723 get nextCodePoint3() {
70724 return this._reader.nextCodePoint3;
70725 }
70726
70727 reset(source, start, end) {
70728 this._reader.reset(source, start, end, this._uFlag);
70729 }
70730
70731 rewind(index) {
70732 this._reader.rewind(index);
70733 }
70734
70735 advance() {
70736 this._reader.advance();
70737 }
70738
70739 eat(cp) {
70740 return this._reader.eat(cp);
70741 }
70742
70743 eat2(cp1, cp2) {
70744 return this._reader.eat2(cp1, cp2);
70745 }
70746
70747 eat3(cp1, cp2, cp3) {
70748 return this._reader.eat3(cp1, cp2, cp3);
70749 }
70750
70751 raise(message) {
70752 throw new RegExpSyntaxError(this.source, this._uFlag, this.index, message);
70753 }
70754
70755 eatRegExpBody() {
70756 const start = this.index;
70757 let inClass = false;
70758 let escaped = false;
70759
70760 for (;;) {
70761 const cp = this.currentCodePoint;
70762
70763 if (cp === -1 || isLineTerminator(cp)) {
70764 const kind = inClass ? "character class" : "regular expression";
70765 this.raise("Unterminated ".concat(kind));
70766 }
70767
70768 if (escaped) {
70769 escaped = false;
70770 } else if (cp === ReverseSolidus) {
70771 escaped = true;
70772 } else if (cp === LeftSquareBracket) {
70773 inClass = true;
70774 } else if (cp === RightSquareBracket) {
70775 inClass = false;
70776 } else if (cp === Solidus && !inClass || cp === Asterisk && this.index === start) {
70777 break;
70778 }
70779
70780 this.advance();
70781 }
70782
70783 return this.index !== start;
70784 }
70785
56c4a2cb 70786 consumePattern() {
eb39fafa
DC
70787 const start = this.index;
70788 this._numCapturingParens = this.countCapturingParens();
70789
70790 this._groupNames.clear();
70791
70792 this._backreferenceNames.clear();
70793
70794 this.onPatternEnter(start);
56c4a2cb 70795 this.consumeDisjunction();
eb39fafa
DC
70796 const cp = this.currentCodePoint;
70797
70798 if (this.currentCodePoint !== -1) {
70799 if (cp === RightParenthesis) {
70800 this.raise("Unmatched ')'");
70801 }
70802
70803 if (cp === ReverseSolidus) {
70804 this.raise("\\ at end of pattern");
70805 }
70806
70807 if (cp === RightSquareBracket || cp === RightCurlyBracket) {
70808 this.raise("Lone quantifier brackets");
70809 }
70810
70811 const c = String.fromCodePoint(cp);
70812 this.raise("Unexpected character '".concat(c, "'"));
70813 }
70814
70815 for (const name of this._backreferenceNames) {
70816 if (!this._groupNames.has(name)) {
70817 this.raise("Invalid named capture referenced");
70818 }
70819 }
70820
70821 this.onPatternLeave(start, this.index);
70822 }
70823
70824 countCapturingParens() {
70825 const start = this.index;
70826 let inClass = false;
70827 let escaped = false;
70828 let count = 0;
70829 let cp = 0;
70830
70831 while ((cp = this.currentCodePoint) !== -1) {
70832 if (escaped) {
70833 escaped = false;
70834 } else if (cp === ReverseSolidus) {
70835 escaped = true;
70836 } else if (cp === LeftSquareBracket) {
70837 inClass = true;
70838 } else if (cp === RightSquareBracket) {
70839 inClass = false;
70840 } else if (cp === LeftParenthesis && !inClass && (this.nextCodePoint !== QuestionMark || this.nextCodePoint2 === LessThanSign && this.nextCodePoint3 !== EqualsSign && this.nextCodePoint3 !== ExclamationMark)) {
70841 count += 1;
70842 }
70843
70844 this.advance();
70845 }
70846
70847 this.rewind(start);
70848 return count;
70849 }
70850
56c4a2cb 70851 consumeDisjunction() {
eb39fafa
DC
70852 const start = this.index;
70853 let i = 0;
70854 this.onDisjunctionEnter(start);
eb39fafa 70855
56c4a2cb
DC
70856 do {
70857 this.consumeAlternative(i++);
70858 } while (this.eat(VerticalLine));
eb39fafa 70859
56c4a2cb 70860 if (this.consumeQuantifier(true)) {
eb39fafa
DC
70861 this.raise("Nothing to repeat");
70862 }
70863
70864 if (this.eat(LeftCurlyBracket)) {
70865 this.raise("Lone quantifier brackets");
70866 }
70867
70868 this.onDisjunctionLeave(start, this.index);
70869 }
70870
56c4a2cb 70871 consumeAlternative(i) {
eb39fafa
DC
70872 const start = this.index;
70873 this.onAlternativeEnter(start, i);
70874
56c4a2cb 70875 while (this.currentCodePoint !== -1 && this.consumeTerm()) {}
eb39fafa
DC
70876
70877 this.onAlternativeLeave(start, this.index, i);
70878 }
70879
56c4a2cb
DC
70880 consumeTerm() {
70881 if (this._uFlag || this.strict) {
70882 return this.consumeAssertion() || this.consumeAtom() && this.consumeOptionalQuantifier();
eb39fafa
DC
70883 }
70884
56c4a2cb
DC
70885 return this.consumeAssertion() && (!this._lastAssertionIsQuantifiable || this.consumeOptionalQuantifier()) || this.consumeExtendedAtom() && this.consumeOptionalQuantifier();
70886 }
eb39fafa 70887
56c4a2cb
DC
70888 consumeOptionalQuantifier() {
70889 this.consumeQuantifier();
70890 return true;
eb39fafa
DC
70891 }
70892
56c4a2cb 70893 consumeAssertion() {
eb39fafa
DC
70894 const start = this.index;
70895 this._lastAssertionIsQuantifiable = false;
70896
70897 if (this.eat(CircumflexAccent)) {
70898 this.onEdgeAssertion(start, this.index, "start");
70899 return true;
70900 }
70901
70902 if (this.eat(DollarSign)) {
70903 this.onEdgeAssertion(start, this.index, "end");
70904 return true;
70905 }
70906
70907 if (this.eat2(ReverseSolidus, LatinCapitalLetterB)) {
70908 this.onWordBoundaryAssertion(start, this.index, "word", true);
70909 return true;
70910 }
70911
70912 if (this.eat2(ReverseSolidus, LatinSmallLetterB)) {
70913 this.onWordBoundaryAssertion(start, this.index, "word", false);
70914 return true;
70915 }
70916
70917 if (this.eat2(LeftParenthesis, QuestionMark)) {
70918 const lookbehind = this.ecmaVersion >= 2018 && this.eat(LessThanSign);
70919 let negate = false;
70920
70921 if (this.eat(EqualsSign) || (negate = this.eat(ExclamationMark))) {
70922 const kind = lookbehind ? "lookbehind" : "lookahead";
70923 this.onLookaroundAssertionEnter(start, kind, negate);
56c4a2cb 70924 this.consumeDisjunction();
eb39fafa
DC
70925
70926 if (!this.eat(RightParenthesis)) {
70927 this.raise("Unterminated group");
70928 }
70929
70930 this._lastAssertionIsQuantifiable = !lookbehind && !this.strict;
70931 this.onLookaroundAssertionLeave(start, this.index, kind, negate);
70932 return true;
70933 }
70934
70935 this.rewind(start);
70936 }
70937
70938 return false;
70939 }
70940
56c4a2cb 70941 consumeQuantifier(noConsume = false) {
eb39fafa
DC
70942 const start = this.index;
70943 let min = 0;
70944 let max = 0;
70945 let greedy = false;
70946
70947 if (this.eat(Asterisk)) {
70948 min = 0;
70949 max = Number.POSITIVE_INFINITY;
70950 } else if (this.eat(PlusSign)) {
70951 min = 1;
70952 max = Number.POSITIVE_INFINITY;
70953 } else if (this.eat(QuestionMark)) {
70954 min = 0;
70955 max = 1;
56c4a2cb 70956 } else if (this.eatBracedQuantifier(noConsume)) {
eb39fafa
DC
70957 min = this._lastMinValue;
70958 max = this._lastMaxValue;
70959 } else {
70960 return false;
70961 }
70962
70963 greedy = !this.eat(QuestionMark);
70964
56c4a2cb 70965 if (!noConsume) {
eb39fafa
DC
70966 this.onQuantifier(start, this.index, min, max, greedy);
70967 }
70968
70969 return true;
70970 }
70971
70972 eatBracedQuantifier(noError) {
70973 const start = this.index;
70974
70975 if (this.eat(LeftCurlyBracket)) {
70976 this._lastMinValue = 0;
70977 this._lastMaxValue = Number.POSITIVE_INFINITY;
70978
70979 if (this.eatDecimalDigits()) {
70980 this._lastMinValue = this._lastMaxValue = this._lastIntValue;
70981
70982 if (this.eat(Comma)) {
70983 this._lastMaxValue = this.eatDecimalDigits() ? this._lastIntValue : Number.POSITIVE_INFINITY;
70984 }
70985
70986 if (this.eat(RightCurlyBracket)) {
70987 if (!noError && this._lastMaxValue < this._lastMinValue) {
70988 this.raise("numbers out of order in {} quantifier");
70989 }
70990
70991 return true;
70992 }
70993 }
70994
56c4a2cb 70995 if (!noError && (this._uFlag || this.strict)) {
eb39fafa
DC
70996 this.raise("Incomplete quantifier");
70997 }
70998
70999 this.rewind(start);
71000 }
71001
71002 return false;
71003 }
71004
56c4a2cb
DC
71005 consumeAtom() {
71006 return this.consumePatternCharacter() || this.consumeDot() || this.consumeReverseSolidusAtomEscape() || this.consumeCharacterClass() || this.consumeUncapturingGroup() || this.consumeCapturingGroup();
eb39fafa
DC
71007 }
71008
56c4a2cb 71009 consumeDot() {
eb39fafa
DC
71010 if (this.eat(FullStop)) {
71011 this.onAnyCharacterSet(this.index - 1, this.index, "any");
71012 return true;
71013 }
71014
71015 return false;
71016 }
71017
56c4a2cb 71018 consumeReverseSolidusAtomEscape() {
eb39fafa
DC
71019 const start = this.index;
71020
71021 if (this.eat(ReverseSolidus)) {
56c4a2cb 71022 if (this.consumeAtomEscape()) {
eb39fafa
DC
71023 return true;
71024 }
71025
71026 this.rewind(start);
71027 }
71028
71029 return false;
71030 }
71031
56c4a2cb 71032 consumeUncapturingGroup() {
eb39fafa
DC
71033 const start = this.index;
71034
71035 if (this.eat3(LeftParenthesis, QuestionMark, Colon)) {
71036 this.onGroupEnter(start);
56c4a2cb 71037 this.consumeDisjunction();
eb39fafa
DC
71038
71039 if (!this.eat(RightParenthesis)) {
71040 this.raise("Unterminated group");
71041 }
71042
71043 this.onGroupLeave(start, this.index);
71044 return true;
71045 }
71046
71047 return false;
71048 }
71049
56c4a2cb 71050 consumeCapturingGroup() {
eb39fafa
DC
71051 const start = this.index;
71052
71053 if (this.eat(LeftParenthesis)) {
56c4a2cb 71054 let name = null;
eb39fafa
DC
71055
71056 if (this.ecmaVersion >= 2018) {
56c4a2cb
DC
71057 if (this.consumeGroupSpecifier()) {
71058 name = this._lastStrValue;
71059 }
eb39fafa
DC
71060 } else if (this.currentCodePoint === QuestionMark) {
71061 this.raise("Invalid group");
71062 }
71063
eb39fafa 71064 this.onCapturingGroupEnter(start, name);
56c4a2cb 71065 this.consumeDisjunction();
eb39fafa
DC
71066
71067 if (!this.eat(RightParenthesis)) {
71068 this.raise("Unterminated group");
71069 }
71070
71071 this.onCapturingGroupLeave(start, this.index, name);
71072 return true;
71073 }
71074
71075 return false;
71076 }
71077
56c4a2cb
DC
71078 consumeExtendedAtom() {
71079 return this.consumeDot() || this.consumeReverseSolidusAtomEscape() || this.consumeReverseSolidusFollowedByC() || this.consumeCharacterClass() || this.consumeUncapturingGroup() || this.consumeCapturingGroup() || this.consumeInvalidBracedQuantifier() || this.consumeExtendedPatternCharacter();
eb39fafa
DC
71080 }
71081
56c4a2cb
DC
71082 consumeReverseSolidusFollowedByC() {
71083 const start = this.index;
71084
eb39fafa
DC
71085 if (this.currentCodePoint === ReverseSolidus && this.nextCodePoint === LatinSmallLetterC) {
71086 this._lastIntValue = this.currentCodePoint;
71087 this.advance();
56c4a2cb 71088 this.onCharacter(start, this.index, ReverseSolidus);
eb39fafa
DC
71089 return true;
71090 }
71091
71092 return false;
71093 }
71094
56c4a2cb 71095 consumeInvalidBracedQuantifier() {
eb39fafa
DC
71096 if (this.eatBracedQuantifier(true)) {
71097 this.raise("Nothing to repeat");
71098 }
71099
71100 return false;
71101 }
71102
56c4a2cb 71103 consumePatternCharacter() {
eb39fafa
DC
71104 const start = this.index;
71105 const cp = this.currentCodePoint;
71106
71107 if (cp !== -1 && !isSyntaxCharacter(cp)) {
71108 this.advance();
71109 this.onCharacter(start, this.index, cp);
71110 return true;
71111 }
71112
71113 return false;
71114 }
71115
56c4a2cb 71116 consumeExtendedPatternCharacter() {
eb39fafa
DC
71117 const start = this.index;
71118 const cp = this.currentCodePoint;
71119
71120 if (cp !== -1 && cp !== CircumflexAccent && cp !== DollarSign && cp !== ReverseSolidus && cp !== FullStop && cp !== Asterisk && cp !== PlusSign && cp !== QuestionMark && cp !== LeftParenthesis && cp !== RightParenthesis && cp !== LeftSquareBracket && cp !== VerticalLine) {
71121 this.advance();
71122 this.onCharacter(start, this.index, cp);
71123 return true;
71124 }
71125
71126 return false;
71127 }
71128
56c4a2cb 71129 consumeGroupSpecifier() {
eb39fafa
DC
71130 if (this.eat(QuestionMark)) {
71131 if (this.eatGroupName()) {
71132 if (!this._groupNames.has(this._lastStrValue)) {
71133 this._groupNames.add(this._lastStrValue);
71134
56c4a2cb 71135 return true;
eb39fafa
DC
71136 }
71137
71138 this.raise("Duplicate capture group name");
71139 }
71140
71141 this.raise("Invalid group");
71142 }
eb39fafa 71143
56c4a2cb
DC
71144 return false;
71145 }
eb39fafa 71146
56c4a2cb
DC
71147 consumeAtomEscape() {
71148 if (this.consumeBackreference() || this.consumeCharacterClassEscape() || this.consumeCharacterEscape() || this._nFlag && this.consumeKGroupName()) {
71149 return true;
71150 }
eb39fafa 71151
56c4a2cb
DC
71152 if (this.strict || this._uFlag) {
71153 this.raise("Invalid escape");
eb39fafa
DC
71154 }
71155
71156 return false;
71157 }
71158
56c4a2cb
DC
71159 consumeBackreference() {
71160 const start = this.index;
eb39fafa 71161
56c4a2cb
DC
71162 if (this.eatDecimalEscape()) {
71163 const n = this._lastIntValue;
eb39fafa 71164
56c4a2cb
DC
71165 if (n <= this._numCapturingParens) {
71166 this.onBackreference(start - 1, this.index, n);
71167 return true;
eb39fafa
DC
71168 }
71169
56c4a2cb
DC
71170 if (this.strict || this._uFlag) {
71171 this.raise("Invalid escape");
71172 }
71173
71174 this.rewind(start);
eb39fafa
DC
71175 }
71176
71177 return false;
71178 }
71179
56c4a2cb 71180 consumeCharacterClassEscape() {
eb39fafa 71181 const start = this.index;
eb39fafa 71182
56c4a2cb
DC
71183 if (this.eat(LatinSmallLetterD)) {
71184 this._lastIntValue = -1;
71185 this.onEscapeCharacterSet(start - 1, this.index, "digit", false);
71186 return true;
eb39fafa
DC
71187 }
71188
56c4a2cb
DC
71189 if (this.eat(LatinCapitalLetterD)) {
71190 this._lastIntValue = -1;
71191 this.onEscapeCharacterSet(start - 1, this.index, "digit", true);
eb39fafa
DC
71192 return true;
71193 }
71194
56c4a2cb
DC
71195 if (this.eat(LatinSmallLetterS)) {
71196 this._lastIntValue = -1;
71197 this.onEscapeCharacterSet(start - 1, this.index, "space", false);
71198 return true;
eb39fafa
DC
71199 }
71200
56c4a2cb
DC
71201 if (this.eat(LatinCapitalLetterS)) {
71202 this._lastIntValue = -1;
71203 this.onEscapeCharacterSet(start - 1, this.index, "space", true);
71204 return true;
eb39fafa
DC
71205 }
71206
56c4a2cb
DC
71207 if (this.eat(LatinSmallLetterW)) {
71208 this._lastIntValue = -1;
71209 this.onEscapeCharacterSet(start - 1, this.index, "word", false);
eb39fafa
DC
71210 return true;
71211 }
71212
56c4a2cb
DC
71213 if (this.eat(LatinCapitalLetterW)) {
71214 this._lastIntValue = -1;
71215 this.onEscapeCharacterSet(start - 1, this.index, "word", true);
71216 return true;
eb39fafa
DC
71217 }
71218
56c4a2cb 71219 let negate = false;
eb39fafa 71220
56c4a2cb
DC
71221 if (this._uFlag && this.ecmaVersion >= 2018 && (this.eat(LatinSmallLetterP) || (negate = this.eat(LatinCapitalLetterP)))) {
71222 this._lastIntValue = -1;
eb39fafa 71223
56c4a2cb
DC
71224 if (this.eat(LeftCurlyBracket) && this.eatUnicodePropertyValueExpression() && this.eat(RightCurlyBracket)) {
71225 this.onUnicodePropertyCharacterSet(start - 1, this.index, "property", this._lastKeyValue, this._lastValValue || null, negate);
71226 return true;
71227 }
71228
71229 this.raise("Invalid property name");
eb39fafa
DC
71230 }
71231
71232 return false;
71233 }
71234
56c4a2cb 71235 consumeCharacterEscape() {
eb39fafa
DC
71236 const start = this.index;
71237
56c4a2cb
DC
71238 if (this.eatControlEscape() || this.eatCControlLetter() || this.eatZero() || this.eatHexEscapeSequence() || this.eatRegExpUnicodeEscapeSequence() || !this.strict && !this._uFlag && this.eatLegacyOctalEscapeSequence() || this.eatIdentityEscape()) {
71239 this.onCharacter(start - 1, this.index, this._lastIntValue);
71240 return true;
eb39fafa
DC
71241 }
71242
71243 return false;
71244 }
71245
56c4a2cb 71246 consumeKGroupName() {
eb39fafa
DC
71247 const start = this.index;
71248
71249 if (this.eat(LatinSmallLetterK)) {
71250 if (this.eatGroupName()) {
71251 const groupName = this._lastStrValue;
71252
71253 this._backreferenceNames.add(groupName);
71254
71255 this.onBackreference(start - 1, this.index, groupName);
71256 return true;
71257 }
71258
71259 this.raise("Invalid named reference");
71260 }
71261
71262 return false;
71263 }
71264
56c4a2cb 71265 consumeCharacterClass() {
eb39fafa
DC
71266 const start = this.index;
71267
56c4a2cb
DC
71268 if (this.eat(LeftSquareBracket)) {
71269 const negate = this.eat(CircumflexAccent);
71270 this.onCharacterClassEnter(start, negate);
71271 this.consumeClassRanges();
71272
71273 if (!this.eat(RightSquareBracket)) {
71274 this.raise("Unterminated character class");
71275 }
71276
71277 this.onCharacterClassLeave(start, this.index, negate);
71278 return true;
71279 }
71280
71281 return false;
71282 }
71283
71284 consumeClassRanges() {
71285 const strict = this.strict || this._uFlag;
71286
71287 for (;;) {
71288 const rangeStart = this.index;
71289
71290 if (!this.consumeClassAtom()) {
71291 break;
71292 }
71293
71294 const min = this._lastIntValue;
71295
71296 if (!this.eat(HyphenMinus)) {
71297 continue;
71298 }
71299
71300 this.onCharacter(this.index - 1, this.index, HyphenMinus);
71301
71302 if (!this.consumeClassAtom()) {
71303 break;
71304 }
71305
71306 const max = this._lastIntValue;
71307
71308 if (min === -1 || max === -1) {
71309 if (strict) {
71310 this.raise("Invalid character class");
71311 }
71312
71313 continue;
71314 }
71315
71316 if (min > max) {
71317 this.raise("Range out of order in character class");
71318 }
71319
71320 this.onCharacterClassRange(rangeStart, this.index, min, max);
71321 }
71322 }
71323
71324 consumeClassAtom() {
71325 const start = this.index;
71326 const cp = this.currentCodePoint;
71327
71328 if (cp !== -1 && cp !== ReverseSolidus && cp !== RightSquareBracket) {
71329 this.advance();
71330 this._lastIntValue = cp;
71331 this.onCharacter(start, this.index, this._lastIntValue);
71332 return true;
71333 }
71334
71335 if (this.eat(ReverseSolidus)) {
71336 if (this.consumeClassEscape()) {
71337 return true;
71338 }
71339
71340 if (!this.strict && this.currentCodePoint === LatinSmallLetterC) {
71341 this._lastIntValue = ReverseSolidus;
71342 this.onCharacter(start, this.index, this._lastIntValue);
71343 return true;
71344 }
71345
71346 if (this.strict || this._uFlag) {
71347 this.raise("Invalid escape");
71348 }
71349
71350 this.rewind(start);
71351 }
71352
71353 return false;
71354 }
71355
71356 consumeClassEscape() {
71357 const start = this.index;
71358
71359 if (this.eat(LatinSmallLetterB)) {
71360 this._lastIntValue = Backspace;
71361 this.onCharacter(start - 1, this.index, this._lastIntValue);
71362 return true;
71363 }
71364
71365 if (this._uFlag && this.eat(HyphenMinus)) {
71366 this._lastIntValue = HyphenMinus;
eb39fafa
DC
71367 this.onCharacter(start - 1, this.index, this._lastIntValue);
71368 return true;
71369 }
71370
56c4a2cb
DC
71371 let cp = 0;
71372
71373 if (!this.strict && !this._uFlag && this.currentCodePoint === LatinSmallLetterC && (isDecimalDigit(cp = this.nextCodePoint) || cp === LowLine)) {
71374 this.advance();
71375 this.advance();
71376 this._lastIntValue = cp % 0x20;
71377 this.onCharacter(start - 1, this.index, this._lastIntValue);
71378 return true;
71379 }
71380
71381 return this.consumeCharacterClassEscape() || this.consumeCharacterEscape();
71382 }
71383
71384 eatGroupName() {
71385 if (this.eat(LessThanSign)) {
71386 if (this.eatRegExpIdentifierName() && this.eat(GreaterThanSign)) {
71387 return true;
71388 }
71389
71390 this.raise("Invalid capture group name");
71391 }
71392
71393 return false;
71394 }
71395
71396 eatRegExpIdentifierName() {
71397 if (this.eatRegExpIdentifierStart()) {
71398 this._lastStrValue = String.fromCodePoint(this._lastIntValue);
71399
71400 while (this.eatRegExpIdentifierPart()) {
71401 this._lastStrValue += String.fromCodePoint(this._lastIntValue);
71402 }
71403
71404 return true;
71405 }
71406
71407 return false;
71408 }
71409
71410 eatRegExpIdentifierStart() {
71411 const start = this.index;
71412 const forceUFlag = !this._uFlag && this.ecmaVersion >= 2020;
71413 let cp = this.currentCodePoint;
71414 this.advance();
71415
71416 if (cp === ReverseSolidus && this.eatRegExpUnicodeEscapeSequence(forceUFlag)) {
71417 cp = this._lastIntValue;
71418 } else if (forceUFlag && isLeadSurrogate(cp) && isTrailSurrogate(this.currentCodePoint)) {
71419 cp = combineSurrogatePair(cp, this.currentCodePoint);
71420 this.advance();
71421 }
71422
71423 if (isRegExpIdentifierStart(cp)) {
71424 this._lastIntValue = cp;
71425 return true;
71426 }
71427
71428 if (this.index !== start) {
71429 this.rewind(start);
71430 }
71431
71432 return false;
71433 }
71434
71435 eatRegExpIdentifierPart() {
71436 const start = this.index;
71437 const forceUFlag = !this._uFlag && this.ecmaVersion >= 2020;
71438 let cp = this.currentCodePoint;
71439 this.advance();
71440
71441 if (cp === ReverseSolidus && this.eatRegExpUnicodeEscapeSequence(forceUFlag)) {
71442 cp = this._lastIntValue;
71443 } else if (forceUFlag && isLeadSurrogate(cp) && isTrailSurrogate(this.currentCodePoint)) {
71444 cp = combineSurrogatePair(cp, this.currentCodePoint);
71445 this.advance();
71446 }
71447
71448 if (isRegExpIdentifierPart(cp)) {
71449 this._lastIntValue = cp;
71450 return true;
71451 }
71452
71453 if (this.index !== start) {
71454 this.rewind(start);
71455 }
71456
eb39fafa
DC
71457 return false;
71458 }
71459
71460 eatCControlLetter() {
71461 const start = this.index;
71462
71463 if (this.eat(LatinSmallLetterC)) {
71464 if (this.eatControlLetter()) {
71465 return true;
71466 }
71467
71468 this.rewind(start);
71469 }
71470
71471 return false;
71472 }
71473
71474 eatZero() {
71475 if (this.currentCodePoint === DigitZero && !isDecimalDigit(this.nextCodePoint)) {
71476 this._lastIntValue = 0;
71477 this.advance();
71478 return true;
71479 }
71480
71481 return false;
71482 }
71483
71484 eatControlEscape() {
56c4a2cb
DC
71485 if (this.eat(LatinSmallLetterF)) {
71486 this._lastIntValue = FormFeed;
eb39fafa
DC
71487 return true;
71488 }
71489
71490 if (this.eat(LatinSmallLetterN)) {
71491 this._lastIntValue = LineFeed;
71492 return true;
71493 }
71494
56c4a2cb
DC
71495 if (this.eat(LatinSmallLetterR)) {
71496 this._lastIntValue = CarriageReturn;
eb39fafa
DC
71497 return true;
71498 }
71499
56c4a2cb
DC
71500 if (this.eat(LatinSmallLetterT)) {
71501 this._lastIntValue = CharacterTabulation;
eb39fafa
DC
71502 return true;
71503 }
71504
56c4a2cb
DC
71505 if (this.eat(LatinSmallLetterV)) {
71506 this._lastIntValue = LineTabulation;
eb39fafa
DC
71507 return true;
71508 }
71509
71510 return false;
71511 }
71512
71513 eatControlLetter() {
71514 const cp = this.currentCodePoint;
71515
71516 if (isLatinLetter(cp)) {
71517 this.advance();
71518 this._lastIntValue = cp % 0x20;
71519 return true;
71520 }
71521
71522 return false;
71523 }
71524
56c4a2cb 71525 eatRegExpUnicodeEscapeSequence(forceUFlag = false) {
eb39fafa 71526 const start = this.index;
56c4a2cb 71527 const uFlag = forceUFlag || this._uFlag;
eb39fafa
DC
71528
71529 if (this.eat(LatinSmallLetterU)) {
56c4a2cb
DC
71530 if (uFlag && this.eatRegExpUnicodeSurrogatePairEscape() || this.eatFixedHexDigits(4) || uFlag && this.eatRegExpUnicodeCodePointEscape()) {
71531 return true;
71532 }
eb39fafa 71533
56c4a2cb
DC
71534 if (this.strict || uFlag) {
71535 this.raise("Invalid unicode escape");
71536 }
eb39fafa 71537
56c4a2cb
DC
71538 this.rewind(start);
71539 }
eb39fafa 71540
56c4a2cb
DC
71541 return false;
71542 }
eb39fafa 71543
56c4a2cb
DC
71544 eatRegExpUnicodeSurrogatePairEscape() {
71545 const start = this.index;
eb39fafa 71546
56c4a2cb
DC
71547 if (this.eatFixedHexDigits(4)) {
71548 const lead = this._lastIntValue;
eb39fafa 71549
56c4a2cb
DC
71550 if (isLeadSurrogate(lead) && this.eat(ReverseSolidus) && this.eat(LatinSmallLetterU) && this.eatFixedHexDigits(4)) {
71551 const trail = this._lastIntValue;
eb39fafa 71552
56c4a2cb
DC
71553 if (isTrailSurrogate(trail)) {
71554 this._lastIntValue = combineSurrogatePair(lead, trail);
71555 return true;
71556 }
eb39fafa
DC
71557 }
71558
71559 this.rewind(start);
71560 }
71561
71562 return false;
71563 }
71564
56c4a2cb
DC
71565 eatRegExpUnicodeCodePointEscape() {
71566 const start = this.index;
eb39fafa 71567
56c4a2cb
DC
71568 if (this.eat(LeftCurlyBracket) && this.eatHexDigits() && this.eat(RightCurlyBracket) && isValidUnicode(this._lastIntValue)) {
71569 return true;
eb39fafa
DC
71570 }
71571
56c4a2cb
DC
71572 this.rewind(start);
71573 return false;
71574 }
71575
71576 eatIdentityEscape() {
71577 const cp = this.currentCodePoint;
71578
71579 if (this.isValidIdentityEscape(cp)) {
71580 this._lastIntValue = cp;
eb39fafa
DC
71581 this.advance();
71582 return true;
71583 }
71584
71585 return false;
71586 }
71587
71588 isValidIdentityEscape(cp) {
71589 if (cp === -1) {
71590 return false;
71591 }
71592
56c4a2cb
DC
71593 if (this._uFlag) {
71594 return isSyntaxCharacter(cp) || cp === Solidus;
71595 }
71596
eb39fafa
DC
71597 if (this.strict) {
71598 return !isIdContinue(cp);
71599 }
71600
56c4a2cb
DC
71601 if (this._nFlag) {
71602 return !(cp === LatinSmallLetterC || cp === LatinSmallLetterK);
71603 }
71604
71605 return cp !== LatinSmallLetterC;
eb39fafa
DC
71606 }
71607
71608 eatDecimalEscape() {
71609 this._lastIntValue = 0;
71610 let cp = this.currentCodePoint;
71611
71612 if (cp >= DigitOne && cp <= DigitNine) {
71613 do {
71614 this._lastIntValue = 10 * this._lastIntValue + (cp - DigitZero);
71615 this.advance();
71616 } while ((cp = this.currentCodePoint) >= DigitZero && cp <= DigitNine);
71617
71618 return true;
71619 }
71620
71621 return false;
71622 }
71623
eb39fafa
DC
71624 eatUnicodePropertyValueExpression() {
71625 const start = this.index;
71626
71627 if (this.eatUnicodePropertyName() && this.eat(EqualsSign)) {
71628 this._lastKeyValue = this._lastStrValue;
71629
71630 if (this.eatUnicodePropertyValue()) {
71631 this._lastValValue = this._lastStrValue;
71632
71633 if (isValidUnicodeProperty(this.ecmaVersion, this._lastKeyValue, this._lastValValue)) {
71634 return true;
71635 }
71636
71637 this.raise("Invalid property name");
71638 }
71639 }
71640
71641 this.rewind(start);
71642
71643 if (this.eatLoneUnicodePropertyNameOrValue()) {
71644 const nameOrValue = this._lastStrValue;
71645
71646 if (isValidUnicodeProperty(this.ecmaVersion, "General_Category", nameOrValue)) {
71647 this._lastKeyValue = "General_Category";
71648 this._lastValValue = nameOrValue;
71649 return true;
71650 }
71651
71652 if (isValidLoneUnicodeProperty(this.ecmaVersion, nameOrValue)) {
71653 this._lastKeyValue = nameOrValue;
71654 this._lastValValue = "";
71655 return true;
71656 }
71657
71658 this.raise("Invalid property name");
71659 }
71660
71661 return false;
71662 }
71663
71664 eatUnicodePropertyName() {
71665 this._lastStrValue = "";
71666
71667 while (isUnicodePropertyNameCharacter(this.currentCodePoint)) {
71668 this._lastStrValue += String.fromCodePoint(this.currentCodePoint);
71669 this.advance();
71670 }
71671
71672 return this._lastStrValue !== "";
71673 }
71674
71675 eatUnicodePropertyValue() {
71676 this._lastStrValue = "";
71677
71678 while (isUnicodePropertyValueCharacter(this.currentCodePoint)) {
71679 this._lastStrValue += String.fromCodePoint(this.currentCodePoint);
71680 this.advance();
71681 }
71682
71683 return this._lastStrValue !== "";
71684 }
71685
71686 eatLoneUnicodePropertyNameOrValue() {
71687 return this.eatUnicodePropertyValue();
71688 }
71689
eb39fafa
DC
71690 eatHexEscapeSequence() {
71691 const start = this.index;
71692
71693 if (this.eat(LatinSmallLetterX)) {
71694 if (this.eatFixedHexDigits(2)) {
71695 return true;
71696 }
71697
56c4a2cb 71698 if (this._uFlag || this.strict) {
eb39fafa
DC
71699 this.raise("Invalid escape");
71700 }
71701
71702 this.rewind(start);
71703 }
71704
71705 return false;
71706 }
71707
71708 eatDecimalDigits() {
71709 const start = this.index;
71710 this._lastIntValue = 0;
71711
71712 while (isDecimalDigit(this.currentCodePoint)) {
71713 this._lastIntValue = 10 * this._lastIntValue + digitToInt(this.currentCodePoint);
71714 this.advance();
71715 }
71716
71717 return this.index !== start;
71718 }
71719
71720 eatHexDigits() {
71721 const start = this.index;
71722 this._lastIntValue = 0;
71723
71724 while (isHexDigit(this.currentCodePoint)) {
71725 this._lastIntValue = 16 * this._lastIntValue + digitToInt(this.currentCodePoint);
71726 this.advance();
71727 }
71728
71729 return this.index !== start;
71730 }
71731
71732 eatLegacyOctalEscapeSequence() {
71733 if (this.eatOctalDigit()) {
71734 const n1 = this._lastIntValue;
71735
71736 if (this.eatOctalDigit()) {
71737 const n2 = this._lastIntValue;
71738
71739 if (n1 <= 3 && this.eatOctalDigit()) {
71740 this._lastIntValue = n1 * 64 + n2 * 8 + this._lastIntValue;
71741 } else {
71742 this._lastIntValue = n1 * 8 + n2;
71743 }
71744 } else {
71745 this._lastIntValue = n1;
71746 }
71747
71748 return true;
71749 }
71750
71751 return false;
71752 }
71753
71754 eatOctalDigit() {
71755 const cp = this.currentCodePoint;
71756
71757 if (isOctalDigit(cp)) {
71758 this.advance();
71759 this._lastIntValue = cp - DigitZero;
71760 return true;
71761 }
71762
71763 this._lastIntValue = 0;
71764 return false;
71765 }
71766
71767 eatFixedHexDigits(length) {
71768 const start = this.index;
71769 this._lastIntValue = 0;
71770
71771 for (let i = 0; i < length; ++i) {
71772 const cp = this.currentCodePoint;
71773
71774 if (!isHexDigit(cp)) {
71775 this.rewind(start);
71776 return false;
71777 }
71778
71779 this._lastIntValue = 16 * this._lastIntValue + digitToInt(cp);
71780 this.advance();
71781 }
71782
71783 return true;
71784 }
71785
71786}
71787
71788const DummyPattern = {};
71789const DummyFlags = {};
71790const DummyCapturingGroup = {};
71791
71792class RegExpParserState {
71793 constructor(options) {
71794 this._node = DummyPattern;
71795 this._flags = DummyFlags;
71796 this._backreferences = [];
71797 this._capturingGroups = [];
71798 this.source = "";
71799 this.strict = Boolean(options && options.strict);
71800 this.ecmaVersion = options && options.ecmaVersion || 2020;
71801 }
71802
71803 get pattern() {
71804 if (this._node.type !== "Pattern") {
71805 throw new Error("UnknownError");
71806 }
71807
71808 return this._node;
71809 }
71810
71811 get flags() {
71812 if (this._flags.type !== "Flags") {
71813 throw new Error("UnknownError");
71814 }
71815
71816 return this._flags;
71817 }
71818
71819 onFlags(start, end, global, ignoreCase, multiline, unicode, sticky, dotAll) {
71820 this._flags = {
71821 type: "Flags",
71822 parent: null,
71823 start,
71824 end,
71825 raw: this.source.slice(start, end),
71826 global,
71827 ignoreCase,
71828 multiline,
71829 unicode,
71830 sticky,
71831 dotAll
71832 };
71833 }
71834
71835 onPatternEnter(start) {
71836 this._node = {
71837 type: "Pattern",
71838 parent: null,
71839 start,
71840 end: start,
71841 raw: "",
71842 alternatives: []
71843 };
71844 this._backreferences.length = 0;
71845 this._capturingGroups.length = 0;
71846 }
71847
71848 onPatternLeave(start, end) {
71849 this._node.end = end;
71850 this._node.raw = this.source.slice(start, end);
71851
71852 for (const reference of this._backreferences) {
71853 const ref = reference.ref;
71854 const group = typeof ref === "number" ? this._capturingGroups[ref - 1] : this._capturingGroups.find(g => g.name === ref);
71855 reference.resolved = group;
71856 group.references.push(reference);
71857 }
71858 }
71859
71860 onAlternativeEnter(start) {
71861 const parent = this._node;
71862
71863 if (parent.type !== "Assertion" && parent.type !== "CapturingGroup" && parent.type !== "Group" && parent.type !== "Pattern") {
71864 throw new Error("UnknownError");
71865 }
71866
71867 this._node = {
71868 type: "Alternative",
71869 parent,
71870 start,
71871 end: start,
71872 raw: "",
71873 elements: []
71874 };
71875 parent.alternatives.push(this._node);
71876 }
71877
71878 onAlternativeLeave(start, end) {
71879 const node = this._node;
71880
71881 if (node.type !== "Alternative") {
71882 throw new Error("UnknownError");
71883 }
71884
71885 node.end = end;
71886 node.raw = this.source.slice(start, end);
71887 this._node = node.parent;
71888 }
71889
71890 onGroupEnter(start) {
71891 const parent = this._node;
71892
71893 if (parent.type !== "Alternative") {
71894 throw new Error("UnknownError");
71895 }
71896
71897 this._node = {
71898 type: "Group",
71899 parent,
71900 start,
71901 end: start,
71902 raw: "",
71903 alternatives: []
71904 };
71905 parent.elements.push(this._node);
71906 }
71907
71908 onGroupLeave(start, end) {
71909 const node = this._node;
71910
71911 if (node.type !== "Group" || node.parent.type !== "Alternative") {
71912 throw new Error("UnknownError");
71913 }
71914
71915 node.end = end;
71916 node.raw = this.source.slice(start, end);
71917 this._node = node.parent;
71918 }
71919
71920 onCapturingGroupEnter(start, name) {
71921 const parent = this._node;
71922
71923 if (parent.type !== "Alternative") {
71924 throw new Error("UnknownError");
71925 }
71926
71927 this._node = {
71928 type: "CapturingGroup",
71929 parent,
71930 start,
71931 end: start,
71932 raw: "",
71933 name,
71934 alternatives: [],
71935 references: []
71936 };
71937 parent.elements.push(this._node);
71938
71939 this._capturingGroups.push(this._node);
71940 }
71941
71942 onCapturingGroupLeave(start, end) {
71943 const node = this._node;
71944
71945 if (node.type !== "CapturingGroup" || node.parent.type !== "Alternative") {
71946 throw new Error("UnknownError");
71947 }
71948
71949 node.end = end;
71950 node.raw = this.source.slice(start, end);
71951 this._node = node.parent;
71952 }
71953
71954 onQuantifier(start, end, min, max, greedy) {
71955 const parent = this._node;
71956
71957 if (parent.type !== "Alternative") {
71958 throw new Error("UnknownError");
71959 }
71960
71961 const element = parent.elements.pop();
71962
71963 if (element == null || element.type === "Quantifier" || element.type === "Assertion" && element.kind !== "lookahead") {
71964 throw new Error("UnknownError");
71965 }
71966
71967 const node = {
71968 type: "Quantifier",
71969 parent,
71970 start: element.start,
71971 end,
71972 raw: this.source.slice(element.start, end),
71973 min,
71974 max,
71975 greedy,
71976 element
71977 };
71978 parent.elements.push(node);
71979 element.parent = node;
71980 }
71981
71982 onLookaroundAssertionEnter(start, kind, negate) {
71983 const parent = this._node;
71984
71985 if (parent.type !== "Alternative") {
71986 throw new Error("UnknownError");
71987 }
71988
71989 const node = this._node = {
71990 type: "Assertion",
71991 parent,
71992 start,
71993 end: start,
71994 raw: "",
71995 kind,
71996 negate,
71997 alternatives: []
71998 };
71999 parent.elements.push(node);
72000 }
72001
72002 onLookaroundAssertionLeave(start, end) {
72003 const node = this._node;
72004
72005 if (node.type !== "Assertion" || node.parent.type !== "Alternative") {
72006 throw new Error("UnknownError");
72007 }
72008
72009 node.end = end;
72010 node.raw = this.source.slice(start, end);
72011 this._node = node.parent;
72012 }
72013
72014 onEdgeAssertion(start, end, kind) {
72015 const parent = this._node;
72016
72017 if (parent.type !== "Alternative") {
72018 throw new Error("UnknownError");
72019 }
72020
72021 parent.elements.push({
72022 type: "Assertion",
72023 parent,
72024 start,
72025 end,
72026 raw: this.source.slice(start, end),
72027 kind
72028 });
72029 }
72030
72031 onWordBoundaryAssertion(start, end, kind, negate) {
72032 const parent = this._node;
72033
72034 if (parent.type !== "Alternative") {
72035 throw new Error("UnknownError");
72036 }
72037
72038 parent.elements.push({
72039 type: "Assertion",
72040 parent,
72041 start,
72042 end,
72043 raw: this.source.slice(start, end),
72044 kind,
72045 negate
72046 });
72047 }
72048
72049 onAnyCharacterSet(start, end, kind) {
72050 const parent = this._node;
72051
72052 if (parent.type !== "Alternative") {
72053 throw new Error("UnknownError");
72054 }
72055
72056 parent.elements.push({
72057 type: "CharacterSet",
72058 parent,
72059 start,
72060 end,
72061 raw: this.source.slice(start, end),
72062 kind
72063 });
72064 }
72065
72066 onEscapeCharacterSet(start, end, kind, negate) {
72067 const parent = this._node;
72068
72069 if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
72070 throw new Error("UnknownError");
72071 }
72072
72073 parent.elements.push({
72074 type: "CharacterSet",
72075 parent,
72076 start,
72077 end,
72078 raw: this.source.slice(start, end),
72079 kind,
72080 negate
72081 });
72082 }
72083
72084 onUnicodePropertyCharacterSet(start, end, kind, key, value, negate) {
72085 const parent = this._node;
72086
72087 if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
72088 throw new Error("UnknownError");
72089 }
72090
72091 parent.elements.push({
72092 type: "CharacterSet",
72093 parent,
72094 start,
72095 end,
72096 raw: this.source.slice(start, end),
72097 kind,
72098 key,
72099 value,
72100 negate
72101 });
72102 }
72103
72104 onCharacter(start, end, value) {
72105 const parent = this._node;
72106
72107 if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
72108 throw new Error("UnknownError");
72109 }
72110
72111 parent.elements.push({
72112 type: "Character",
72113 parent,
72114 start,
72115 end,
72116 raw: this.source.slice(start, end),
72117 value
72118 });
72119 }
72120
72121 onBackreference(start, end, ref) {
72122 const parent = this._node;
72123
72124 if (parent.type !== "Alternative") {
72125 throw new Error("UnknownError");
72126 }
72127
72128 const node = {
72129 type: "Backreference",
72130 parent,
72131 start,
72132 end,
72133 raw: this.source.slice(start, end),
72134 ref,
72135 resolved: DummyCapturingGroup
72136 };
72137 parent.elements.push(node);
72138
72139 this._backreferences.push(node);
72140 }
72141
72142 onCharacterClassEnter(start, negate) {
72143 const parent = this._node;
72144
72145 if (parent.type !== "Alternative") {
72146 throw new Error("UnknownError");
72147 }
72148
72149 this._node = {
72150 type: "CharacterClass",
72151 parent,
72152 start,
72153 end: start,
72154 raw: "",
72155 negate,
72156 elements: []
72157 };
72158 parent.elements.push(this._node);
72159 }
72160
72161 onCharacterClassLeave(start, end) {
72162 const node = this._node;
72163
72164 if (node.type !== "CharacterClass" || node.parent.type !== "Alternative") {
72165 throw new Error("UnknownError");
72166 }
72167
72168 node.end = end;
72169 node.raw = this.source.slice(start, end);
72170 this._node = node.parent;
72171 }
72172
72173 onCharacterClassRange(start, end) {
72174 const parent = this._node;
72175
72176 if (parent.type !== "CharacterClass") {
72177 throw new Error("UnknownError");
72178 }
72179
72180 const elements = parent.elements;
72181 const max = elements.pop();
72182 const hyphen = elements.pop();
72183 const min = elements.pop();
72184
72185 if (!min || !max || !hyphen || min.type !== "Character" || max.type !== "Character" || hyphen.type !== "Character" || hyphen.value !== HyphenMinus) {
72186 throw new Error("UnknownError");
72187 }
72188
72189 const node = {
72190 type: "CharacterClassRange",
72191 parent,
72192 start,
72193 end,
72194 raw: this.source.slice(start, end),
72195 min,
72196 max
72197 };
72198 min.parent = node;
72199 max.parent = node;
72200 elements.push(node);
72201 }
72202
72203}
72204
72205class RegExpParser {
72206 constructor(options) {
72207 this._state = new RegExpParserState(options);
72208 this._validator = new RegExpValidator(this._state);
72209 }
72210
72211 parseLiteral(source, start = 0, end = source.length) {
72212 this._state.source = source;
72213
72214 this._validator.validateLiteral(source, start, end);
72215
72216 const pattern = this._state.pattern;
72217 const flags = this._state.flags;
72218 const literal = {
72219 type: "RegExpLiteral",
72220 parent: null,
72221 start,
72222 end,
72223 raw: source,
72224 pattern,
72225 flags
72226 };
72227 pattern.parent = literal;
72228 flags.parent = literal;
72229 return literal;
72230 }
72231
72232 parseFlags(source, start = 0, end = source.length) {
72233 this._state.source = source;
72234
72235 this._validator.validateFlags(source, start, end);
72236
72237 return this._state.flags;
72238 }
72239
72240 parsePattern(source, start = 0, end = source.length, uFlag = false) {
72241 this._state.source = source;
72242
72243 this._validator.validatePattern(source, start, end, uFlag);
72244
72245 return this._state.pattern;
72246 }
72247
72248}
72249
72250class RegExpVisitor {
72251 constructor(handlers) {
72252 this._handlers = handlers;
72253 }
72254
72255 visit(node) {
72256 switch (node.type) {
72257 case "Alternative":
72258 this.visitAlternative(node);
72259 break;
72260
72261 case "Assertion":
72262 this.visitAssertion(node);
72263 break;
72264
72265 case "Backreference":
72266 this.visitBackreference(node);
72267 break;
72268
72269 case "CapturingGroup":
72270 this.visitCapturingGroup(node);
72271 break;
72272
72273 case "Character":
72274 this.visitCharacter(node);
72275 break;
72276
72277 case "CharacterClass":
72278 this.visitCharacterClass(node);
72279 break;
72280
72281 case "CharacterClassRange":
72282 this.visitCharacterClassRange(node);
72283 break;
72284
72285 case "CharacterSet":
72286 this.visitCharacterSet(node);
72287 break;
72288
72289 case "Flags":
72290 this.visitFlags(node);
72291 break;
72292
72293 case "Group":
72294 this.visitGroup(node);
72295 break;
72296
72297 case "Pattern":
72298 this.visitPattern(node);
72299 break;
72300
72301 case "Quantifier":
72302 this.visitQuantifier(node);
72303 break;
72304
72305 case "RegExpLiteral":
72306 this.visitRegExpLiteral(node);
72307 break;
72308
72309 default:
72310 throw new Error("Unknown type: ".concat(node.type));
72311 }
72312 }
72313
72314 visitAlternative(node) {
72315 if (this._handlers.onAlternativeEnter) {
72316 this._handlers.onAlternativeEnter(node);
72317 }
72318
72319 node.elements.forEach(this.visit, this);
72320
72321 if (this._handlers.onAlternativeLeave) {
72322 this._handlers.onAlternativeLeave(node);
72323 }
72324 }
72325
72326 visitAssertion(node) {
72327 if (this._handlers.onAssertionEnter) {
72328 this._handlers.onAssertionEnter(node);
72329 }
72330
72331 if (node.kind === "lookahead" || node.kind === "lookbehind") {
72332 node.alternatives.forEach(this.visit, this);
72333 }
72334
72335 if (this._handlers.onAssertionLeave) {
72336 this._handlers.onAssertionLeave(node);
72337 }
72338 }
72339
72340 visitBackreference(node) {
72341 if (this._handlers.onBackreferenceEnter) {
72342 this._handlers.onBackreferenceEnter(node);
72343 }
72344
72345 if (this._handlers.onBackreferenceLeave) {
72346 this._handlers.onBackreferenceLeave(node);
72347 }
72348 }
72349
72350 visitCapturingGroup(node) {
72351 if (this._handlers.onCapturingGroupEnter) {
72352 this._handlers.onCapturingGroupEnter(node);
72353 }
72354
72355 node.alternatives.forEach(this.visit, this);
72356
72357 if (this._handlers.onCapturingGroupLeave) {
72358 this._handlers.onCapturingGroupLeave(node);
72359 }
72360 }
72361
72362 visitCharacter(node) {
72363 if (this._handlers.onCharacterEnter) {
72364 this._handlers.onCharacterEnter(node);
72365 }
72366
72367 if (this._handlers.onCharacterLeave) {
72368 this._handlers.onCharacterLeave(node);
72369 }
72370 }
72371
72372 visitCharacterClass(node) {
72373 if (this._handlers.onCharacterClassEnter) {
72374 this._handlers.onCharacterClassEnter(node);
72375 }
72376
72377 node.elements.forEach(this.visit, this);
72378
72379 if (this._handlers.onCharacterClassLeave) {
72380 this._handlers.onCharacterClassLeave(node);
72381 }
72382 }
72383
72384 visitCharacterClassRange(node) {
72385 if (this._handlers.onCharacterClassRangeEnter) {
72386 this._handlers.onCharacterClassRangeEnter(node);
72387 }
72388
72389 this.visitCharacter(node.min);
72390 this.visitCharacter(node.max);
72391
72392 if (this._handlers.onCharacterClassRangeLeave) {
72393 this._handlers.onCharacterClassRangeLeave(node);
72394 }
72395 }
72396
72397 visitCharacterSet(node) {
72398 if (this._handlers.onCharacterSetEnter) {
72399 this._handlers.onCharacterSetEnter(node);
72400 }
72401
72402 if (this._handlers.onCharacterSetLeave) {
72403 this._handlers.onCharacterSetLeave(node);
72404 }
72405 }
72406
72407 visitFlags(node) {
72408 if (this._handlers.onFlagsEnter) {
72409 this._handlers.onFlagsEnter(node);
72410 }
72411
72412 if (this._handlers.onFlagsLeave) {
72413 this._handlers.onFlagsLeave(node);
72414 }
72415 }
72416
72417 visitGroup(node) {
72418 if (this._handlers.onGroupEnter) {
72419 this._handlers.onGroupEnter(node);
72420 }
72421
72422 node.alternatives.forEach(this.visit, this);
72423
72424 if (this._handlers.onGroupLeave) {
72425 this._handlers.onGroupLeave(node);
72426 }
72427 }
72428
72429 visitPattern(node) {
72430 if (this._handlers.onPatternEnter) {
72431 this._handlers.onPatternEnter(node);
72432 }
72433
72434 node.alternatives.forEach(this.visit, this);
72435
72436 if (this._handlers.onPatternLeave) {
72437 this._handlers.onPatternLeave(node);
72438 }
72439 }
72440
72441 visitQuantifier(node) {
72442 if (this._handlers.onQuantifierEnter) {
72443 this._handlers.onQuantifierEnter(node);
72444 }
72445
72446 this.visit(node.element);
72447
72448 if (this._handlers.onQuantifierLeave) {
72449 this._handlers.onQuantifierLeave(node);
72450 }
72451 }
72452
72453 visitRegExpLiteral(node) {
72454 if (this._handlers.onRegExpLiteralEnter) {
72455 this._handlers.onRegExpLiteralEnter(node);
72456 }
72457
72458 this.visitPattern(node.pattern);
72459 this.visitFlags(node.flags);
72460
72461 if (this._handlers.onRegExpLiteralLeave) {
72462 this._handlers.onRegExpLiteralLeave(node);
72463 }
72464 }
72465
72466}
72467
72468function parseRegExpLiteral(source, options) {
72469 return new RegExpParser(options).parseLiteral(String(source));
72470}
72471
72472function validateRegExpLiteral(source, options) {
72473 return new RegExpValidator(options).validateLiteral(source);
72474}
72475
72476function visitRegExpAST(node, handlers) {
72477 new RegExpVisitor(handlers).visit(node);
72478}
72479
72480
72481
72482/***/ }),
72483/* 528 */
72484/***/ (function(module, exports, __webpack_require__) {
72485
72486"use strict";
72487/**
72488 * @fileoverview Rule to flag use of a debugger statement
72489 * @author Nicholas C. Zakas
72490 */
72491 //------------------------------------------------------------------------------
72492// Rule Definition
72493//------------------------------------------------------------------------------
72494
72495module.exports = {
72496 meta: {
72497 type: "problem",
72498 docs: {
72499 description: "disallow the use of `debugger`",
72500 category: "Possible Errors",
72501 recommended: true,
72502 url: "https://eslint.org/docs/rules/no-debugger"
72503 },
72504 fixable: null,
72505 schema: [],
72506 messages: {
72507 unexpected: "Unexpected 'debugger' statement."
72508 }
72509 },
72510
72511 create(context) {
72512 return {
72513 DebuggerStatement(node) {
72514 context.report({
72515 node,
72516 messageId: "unexpected"
72517 });
72518 }
72519
72520 };
72521 }
72522
72523};
72524
72525/***/ }),
72526/* 529 */
72527/***/ (function(module, exports, __webpack_require__) {
72528
72529"use strict";
72530/**
72531 * @fileoverview Rule to flag when deleting variables
72532 * @author Ilya Volodin
72533 */
72534 //------------------------------------------------------------------------------
72535// Rule Definition
72536//------------------------------------------------------------------------------
72537
72538module.exports = {
72539 meta: {
72540 type: "suggestion",
72541 docs: {
72542 description: "disallow deleting variables",
72543 category: "Variables",
72544 recommended: true,
72545 url: "https://eslint.org/docs/rules/no-delete-var"
72546 },
72547 schema: [],
72548 messages: {
72549 unexpected: "Variables should not be deleted."
72550 }
72551 },
72552
72553 create(context) {
72554 return {
72555 UnaryExpression(node) {
72556 if (node.operator === "delete" && node.argument.type === "Identifier") {
72557 context.report({
72558 node,
72559 messageId: "unexpected"
72560 });
72561 }
72562 }
72563
72564 };
72565 }
72566
72567};
72568
72569/***/ }),
72570/* 530 */
72571/***/ (function(module, exports, __webpack_require__) {
72572
72573"use strict";
72574/**
72575 * @fileoverview Rule to check for ambiguous div operator in regexes
72576 * @author Matt DuVall <http://www.mattduvall.com>
72577 */
72578 //------------------------------------------------------------------------------
72579// Rule Definition
72580//------------------------------------------------------------------------------
72581
72582module.exports = {
72583 meta: {
72584 type: "suggestion",
72585 docs: {
72586 description: "disallow division operators explicitly at the beginning of regular expressions",
72587 category: "Best Practices",
72588 recommended: false,
72589 url: "https://eslint.org/docs/rules/no-div-regex"
72590 },
72591 fixable: "code",
72592 schema: [],
72593 messages: {
72594 unexpected: "A regular expression literal can be confused with '/='."
72595 }
72596 },
72597
72598 create(context) {
72599 const sourceCode = context.getSourceCode();
72600 return {
72601 Literal(node) {
72602 const token = sourceCode.getFirstToken(node);
72603
72604 if (token.type === "RegularExpression" && token.value[1] === "=") {
72605 context.report({
72606 node,
72607 messageId: "unexpected",
72608
72609 fix(fixer) {
72610 return fixer.replaceTextRange([token.range[0] + 1, token.range[0] + 2], "[=]");
72611 }
72612
72613 });
72614 }
72615 }
72616
72617 };
72618 }
72619
72620};
72621
72622/***/ }),
72623/* 531 */
72624/***/ (function(module, exports, __webpack_require__) {
72625
72626"use strict";
72627/**
72628 * @fileoverview Rule to flag duplicate arguments
72629 * @author Jamund Ferguson
72630 */
72631 //------------------------------------------------------------------------------
72632// Rule Definition
72633//------------------------------------------------------------------------------
72634
72635module.exports = {
72636 meta: {
72637 type: "problem",
72638 docs: {
72639 description: "disallow duplicate arguments in `function` definitions",
72640 category: "Possible Errors",
72641 recommended: true,
72642 url: "https://eslint.org/docs/rules/no-dupe-args"
72643 },
72644 schema: [],
72645 messages: {
72646 unexpected: "Duplicate param '{{name}}'."
72647 }
72648 },
72649
72650 create(context) {
72651 //--------------------------------------------------------------------------
72652 // Helpers
72653 //--------------------------------------------------------------------------
72654
72655 /**
72656 * Checks whether or not a given definition is a parameter's.
72657 * @param {eslint-scope.DefEntry} def A definition to check.
72658 * @returns {boolean} `true` if the definition is a parameter's.
72659 */
72660 function isParameter(def) {
72661 return def.type === "Parameter";
72662 }
72663 /**
72664 * Determines if a given node has duplicate parameters.
72665 * @param {ASTNode} node The node to check.
72666 * @returns {void}
72667 * @private
72668 */
72669
72670
72671 function checkParams(node) {
72672 const variables = context.getDeclaredVariables(node);
72673
72674 for (let i = 0; i < variables.length; ++i) {
72675 const variable = variables[i]; // Checks and reports duplications.
72676
72677 const defs = variable.defs.filter(isParameter);
72678
72679 if (defs.length >= 2) {
72680 context.report({
72681 node,
72682 messageId: "unexpected",
72683 data: {
72684 name: variable.name
72685 }
72686 });
72687 }
72688 }
72689 } //--------------------------------------------------------------------------
72690 // Public API
72691 //--------------------------------------------------------------------------
72692
72693
72694 return {
72695 FunctionDeclaration: checkParams,
72696 FunctionExpression: checkParams
72697 };
72698 }
72699
72700};
72701
72702/***/ }),
72703/* 532 */
72704/***/ (function(module, exports, __webpack_require__) {
72705
72706"use strict";
72707/**
72708 * @fileoverview A rule to disallow duplicate name in class members.
72709 * @author Toru Nagashima
72710 */
72711
72712
72713const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
72714// Rule Definition
72715//------------------------------------------------------------------------------
72716
72717
72718module.exports = {
72719 meta: {
72720 type: "problem",
72721 docs: {
72722 description: "disallow duplicate class members",
72723 category: "ECMAScript 6",
72724 recommended: true,
72725 url: "https://eslint.org/docs/rules/no-dupe-class-members"
72726 },
72727 schema: [],
72728 messages: {
72729 unexpected: "Duplicate name '{{name}}'."
72730 }
72731 },
72732
72733 create(context) {
72734 let stack = [];
72735 /**
72736 * Gets state of a given member name.
72737 * @param {string} name A name of a member.
72738 * @param {boolean} isStatic A flag which specifies that is a static member.
72739 * @returns {Object} A state of a given member name.
72740 * - retv.init {boolean} A flag which shows the name is declared as normal member.
72741 * - retv.get {boolean} A flag which shows the name is declared as getter.
72742 * - retv.set {boolean} A flag which shows the name is declared as setter.
72743 */
72744
72745 function getState(name, isStatic) {
72746 const stateMap = stack[stack.length - 1];
72747 const key = "$".concat(name); // to avoid "__proto__".
72748
72749 if (!stateMap[key]) {
72750 stateMap[key] = {
72751 nonStatic: {
72752 init: false,
72753 get: false,
72754 set: false
72755 },
72756 static: {
72757 init: false,
72758 get: false,
72759 set: false
72760 }
72761 };
72762 }
72763
72764 return stateMap[key][isStatic ? "static" : "nonStatic"];
72765 }
72766
72767 return {
72768 // Initializes the stack of state of member declarations.
72769 Program() {
72770 stack = [];
72771 },
72772
72773 // Initializes state of member declarations for the class.
72774 ClassBody() {
72775 stack.push(Object.create(null));
72776 },
72777
72778 // Disposes the state for the class.
72779 "ClassBody:exit"() {
72780 stack.pop();
72781 },
72782
72783 // Reports the node if its name has been declared already.
72784 MethodDefinition(node) {
72785 const name = astUtils.getStaticPropertyName(node);
72786
72787 if (name === null || node.kind === "constructor") {
72788 return;
72789 }
72790
72791 const state = getState(name, node.static);
72792 let isDuplicate = false;
72793
72794 if (node.kind === "get") {
72795 isDuplicate = state.init || state.get;
72796 state.get = true;
72797 } else if (node.kind === "set") {
72798 isDuplicate = state.init || state.set;
72799 state.set = true;
72800 } else {
72801 isDuplicate = state.init || state.get || state.set;
72802 state.init = true;
72803 }
72804
72805 if (isDuplicate) {
72806 context.report({
72807 node,
72808 messageId: "unexpected",
72809 data: {
72810 name
72811 }
72812 });
72813 }
72814 }
72815
72816 };
72817 }
72818
72819};
72820
72821/***/ }),
72822/* 533 */
72823/***/ (function(module, exports, __webpack_require__) {
72824
72825"use strict";
72826/**
72827 * @fileoverview Rule to disallow duplicate conditions in if-else-if chains
72828 * @author Milos Djermanovic
72829 */
72830 //------------------------------------------------------------------------------
72831// Requirements
72832//------------------------------------------------------------------------------
72833
72834const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
72835// Helpers
72836//------------------------------------------------------------------------------
72837
72838/**
72839 * Determines whether the first given array is a subset of the second given array.
72840 * @param {Function} comparator A function to compare two elements, should return `true` if they are equal.
72841 * @param {Array} arrA The array to compare from.
72842 * @param {Array} arrB The array to compare against.
72843 * @returns {boolean} `true` if the array `arrA` is a subset of the array `arrB`.
72844 */
72845
72846
72847function isSubsetByComparator(comparator, arrA, arrB) {
72848 return arrA.every(a => arrB.some(b => comparator(a, b)));
72849}
72850/**
72851 * Splits the given node by the given logical operator.
72852 * @param {string} operator Logical operator `||` or `&&`.
72853 * @param {ASTNode} node The node to split.
72854 * @returns {ASTNode[]} Array of conditions that makes the node when joined by the operator.
72855 */
72856
72857
72858function splitByLogicalOperator(operator, node) {
72859 if (node.type === "LogicalExpression" && node.operator === operator) {
72860 return [...splitByLogicalOperator(operator, node.left), ...splitByLogicalOperator(operator, node.right)];
72861 }
72862
72863 return [node];
72864}
72865
72866const splitByOr = splitByLogicalOperator.bind(null, "||");
72867const splitByAnd = splitByLogicalOperator.bind(null, "&&"); //------------------------------------------------------------------------------
72868// Rule Definition
72869//------------------------------------------------------------------------------
72870
72871module.exports = {
72872 meta: {
72873 type: "problem",
72874 docs: {
72875 description: "disallow duplicate conditions in if-else-if chains",
72876 category: "Possible Errors",
72877 recommended: true,
72878 url: "https://eslint.org/docs/rules/no-dupe-else-if"
72879 },
72880 schema: [],
72881 messages: {
72882 unexpected: "This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain."
72883 }
72884 },
72885
72886 create(context) {
72887 const sourceCode = context.getSourceCode();
72888 /**
72889 * Determines whether the two given nodes are considered to be equal. In particular, given that the nodes
72890 * represent expressions in a boolean context, `||` and `&&` can be considered as commutative operators.
72891 * @param {ASTNode} a First node.
72892 * @param {ASTNode} b Second node.
72893 * @returns {boolean} `true` if the nodes are considered to be equal.
72894 */
72895
72896 function equal(a, b) {
72897 if (a.type !== b.type) {
72898 return false;
72899 }
72900
72901 if (a.type === "LogicalExpression" && (a.operator === "||" || a.operator === "&&") && a.operator === b.operator) {
72902 return equal(a.left, b.left) && equal(a.right, b.right) || equal(a.left, b.right) && equal(a.right, b.left);
72903 }
72904
72905 return astUtils.equalTokens(a, b, sourceCode);
72906 }
72907
72908 const isSubset = isSubsetByComparator.bind(null, equal);
72909 return {
72910 IfStatement(node) {
72911 const test = node.test,
72912 conditionsToCheck = test.type === "LogicalExpression" && test.operator === "&&" ? [test, ...splitByAnd(test)] : [test];
72913 let current = node,
72914 listToCheck = conditionsToCheck.map(c => splitByOr(c).map(splitByAnd));
72915
72916 while (current.parent && current.parent.type === "IfStatement" && current.parent.alternate === current) {
72917 current = current.parent;
72918 const currentOrOperands = splitByOr(current.test).map(splitByAnd);
72919 listToCheck = listToCheck.map(orOperands => orOperands.filter(orOperand => !currentOrOperands.some(currentOrOperand => isSubset(currentOrOperand, orOperand))));
72920
72921 if (listToCheck.some(orOperands => orOperands.length === 0)) {
72922 context.report({
72923 node: test,
72924 messageId: "unexpected"
72925 });
72926 break;
72927 }
72928 }
72929 }
72930
72931 };
72932 }
72933
72934};
72935
72936/***/ }),
72937/* 534 */
72938/***/ (function(module, exports, __webpack_require__) {
72939
72940"use strict";
72941/**
72942 * @fileoverview Rule to flag use of duplicate keys in an object.
72943 * @author Ian Christian Myers
72944 */
72945 //------------------------------------------------------------------------------
72946// Requirements
72947//------------------------------------------------------------------------------
72948
72949const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
72950// Helpers
72951//------------------------------------------------------------------------------
72952
72953
72954const GET_KIND = /^(?:init|get)$/u;
72955const SET_KIND = /^(?:init|set)$/u;
72956/**
72957 * The class which stores properties' information of an object.
72958 */
72959
72960class ObjectInfo {
72961 // eslint-disable-next-line jsdoc/require-description
72962
72963 /**
72964 * @param {ObjectInfo|null} upper The information of the outer object.
72965 * @param {ASTNode} node The ObjectExpression node of this information.
72966 */
72967 constructor(upper, node) {
72968 this.upper = upper;
72969 this.node = node;
72970 this.properties = new Map();
72971 }
72972 /**
72973 * Gets the information of the given Property node.
72974 * @param {ASTNode} node The Property node to get.
72975 * @returns {{get: boolean, set: boolean}} The information of the property.
72976 */
72977
72978
72979 getPropertyInfo(node) {
72980 const name = astUtils.getStaticPropertyName(node);
72981
72982 if (!this.properties.has(name)) {
72983 this.properties.set(name, {
72984 get: false,
72985 set: false
72986 });
72987 }
72988
72989 return this.properties.get(name);
72990 }
72991 /**
72992 * Checks whether the given property has been defined already or not.
72993 * @param {ASTNode} node The Property node to check.
72994 * @returns {boolean} `true` if the property has been defined.
72995 */
72996
72997
72998 isPropertyDefined(node) {
72999 const entry = this.getPropertyInfo(node);
73000 return GET_KIND.test(node.kind) && entry.get || SET_KIND.test(node.kind) && entry.set;
73001 }
73002 /**
73003 * Defines the given property.
73004 * @param {ASTNode} node The Property node to define.
73005 * @returns {void}
73006 */
73007
73008
73009 defineProperty(node) {
73010 const entry = this.getPropertyInfo(node);
73011
73012 if (GET_KIND.test(node.kind)) {
73013 entry.get = true;
73014 }
73015
73016 if (SET_KIND.test(node.kind)) {
73017 entry.set = true;
73018 }
73019 }
73020
73021} //------------------------------------------------------------------------------
73022// Rule Definition
73023//------------------------------------------------------------------------------
73024
73025
73026module.exports = {
73027 meta: {
73028 type: "problem",
73029 docs: {
73030 description: "disallow duplicate keys in object literals",
73031 category: "Possible Errors",
73032 recommended: true,
73033 url: "https://eslint.org/docs/rules/no-dupe-keys"
73034 },
73035 schema: [],
73036 messages: {
73037 unexpected: "Duplicate key '{{name}}'."
73038 }
73039 },
73040
73041 create(context) {
73042 let info = null;
73043 return {
73044 ObjectExpression(node) {
73045 info = new ObjectInfo(info, node);
73046 },
73047
73048 "ObjectExpression:exit"() {
73049 info = info.upper;
73050 },
73051
73052 Property(node) {
73053 const name = astUtils.getStaticPropertyName(node); // Skip destructuring.
73054
73055 if (node.parent.type !== "ObjectExpression") {
73056 return;
73057 } // Skip if the name is not static.
73058
73059
73060 if (name === null) {
73061 return;
73062 } // Reports if the name is defined already.
73063
73064
73065 if (info.isPropertyDefined(node)) {
73066 context.report({
73067 node: info.node,
73068 loc: node.key.loc,
73069 messageId: "unexpected",
73070 data: {
73071 name
73072 }
73073 });
73074 } // Update info.
73075
73076
73077 info.defineProperty(node);
73078 }
73079
73080 };
73081 }
73082
73083};
73084
73085/***/ }),
73086/* 535 */
73087/***/ (function(module, exports, __webpack_require__) {
73088
73089"use strict";
73090/**
73091 * @fileoverview Rule to disallow a duplicate case label.
73092 * @author Dieter Oberkofler
73093 * @author Burak Yigit Kaya
73094 */
73095 //------------------------------------------------------------------------------
73096// Rule Definition
73097//------------------------------------------------------------------------------
73098
73099module.exports = {
73100 meta: {
73101 type: "problem",
73102 docs: {
73103 description: "disallow duplicate case labels",
73104 category: "Possible Errors",
73105 recommended: true,
73106 url: "https://eslint.org/docs/rules/no-duplicate-case"
73107 },
73108 schema: [],
73109 messages: {
73110 unexpected: "Duplicate case label."
73111 }
73112 },
73113
73114 create(context) {
73115 const sourceCode = context.getSourceCode();
73116 return {
73117 SwitchStatement(node) {
73118 const previousKeys = new Set();
73119
73120 for (const switchCase of node.cases) {
73121 if (switchCase.test) {
73122 const key = sourceCode.getText(switchCase.test);
73123
73124 if (previousKeys.has(key)) {
73125 context.report({
73126 node: switchCase,
73127 messageId: "unexpected"
73128 });
73129 } else {
73130 previousKeys.add(key);
73131 }
73132 }
73133 }
73134 }
73135
73136 };
73137 }
73138
73139};
73140
73141/***/ }),
73142/* 536 */
73143/***/ (function(module, exports, __webpack_require__) {
73144
73145"use strict";
73146/**
73147 * @fileoverview Restrict usage of duplicate imports.
73148 * @author Simen Bekkhus
73149 */
73150 //------------------------------------------------------------------------------
73151// Rule Definition
73152//------------------------------------------------------------------------------
73153
73154/**
73155 * Returns the name of the module imported or re-exported.
73156 * @param {ASTNode} node A node to get.
73157 * @returns {string} the name of the module, or empty string if no name.
73158 */
73159
73160function getValue(node) {
73161 if (node && node.source && node.source.value) {
73162 return node.source.value.trim();
73163 }
73164
73165 return "";
73166}
73167/**
73168 * Checks if the name of the import or export exists in the given array, and reports if so.
73169 * @param {RuleContext} context The ESLint rule context object.
73170 * @param {ASTNode} node A node to get.
73171 * @param {string} value The name of the imported or exported module.
73172 * @param {string[]} array The array containing other imports or exports in the file.
73173 * @param {string} messageId A messageId to be reported after the name of the module
73174 *
73175 * @returns {void} No return value
73176 */
73177
73178
73179function checkAndReport(context, node, value, array, messageId) {
73180 if (array.indexOf(value) !== -1) {
73181 context.report({
73182 node,
73183 messageId,
73184 data: {
73185 module: value
73186 }
73187 });
73188 }
73189}
73190/**
73191 * @callback nodeCallback
73192 * @param {ASTNode} node A node to handle.
73193 */
73194
73195/**
73196 * Returns a function handling the imports of a given file
73197 * @param {RuleContext} context The ESLint rule context object.
73198 * @param {boolean} includeExports Whether or not to check for exports in addition to imports.
73199 * @param {string[]} importsInFile The array containing other imports in the file.
73200 * @param {string[]} exportsInFile The array containing other exports in the file.
73201 *
73202 * @returns {nodeCallback} A function passed to ESLint to handle the statement.
73203 */
73204
73205
73206function handleImports(context, includeExports, importsInFile, exportsInFile) {
73207 return function (node) {
73208 const value = getValue(node);
73209
73210 if (value) {
73211 checkAndReport(context, node, value, importsInFile, "import");
73212
73213 if (includeExports) {
73214 checkAndReport(context, node, value, exportsInFile, "importAs");
73215 }
73216
73217 importsInFile.push(value);
73218 }
73219 };
73220}
73221/**
73222 * Returns a function handling the exports of a given file
73223 * @param {RuleContext} context The ESLint rule context object.
73224 * @param {string[]} importsInFile The array containing other imports in the file.
73225 * @param {string[]} exportsInFile The array containing other exports in the file.
73226 *
73227 * @returns {nodeCallback} A function passed to ESLint to handle the statement.
73228 */
73229
73230
73231function handleExports(context, importsInFile, exportsInFile) {
73232 return function (node) {
73233 const value = getValue(node);
73234
73235 if (value) {
73236 checkAndReport(context, node, value, exportsInFile, "export");
73237 checkAndReport(context, node, value, importsInFile, "exportAs");
73238 exportsInFile.push(value);
73239 }
73240 };
73241}
73242
73243module.exports = {
73244 meta: {
73245 type: "problem",
73246 docs: {
73247 description: "disallow duplicate module imports",
73248 category: "ECMAScript 6",
73249 recommended: false,
73250 url: "https://eslint.org/docs/rules/no-duplicate-imports"
73251 },
73252 schema: [{
73253 type: "object",
73254 properties: {
73255 includeExports: {
73256 type: "boolean",
73257 default: false
73258 }
73259 },
73260 additionalProperties: false
73261 }],
73262 messages: {
73263 import: "'{{module}}' import is duplicated.",
73264 importAs: "'{{module}}' import is duplicated as export.",
73265 export: "'{{module}}' export is duplicated.",
73266 exportAs: "'{{module}}' export is duplicated as import."
73267 }
73268 },
73269
73270 create(context) {
73271 const includeExports = (context.options[0] || {}).includeExports,
73272 importsInFile = [],
73273 exportsInFile = [];
73274 const handlers = {
73275 ImportDeclaration: handleImports(context, includeExports, importsInFile, exportsInFile)
73276 };
73277
73278 if (includeExports) {
73279 handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile);
73280 handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile);
73281 }
73282
73283 return handlers;
73284 }
73285
73286};
73287
73288/***/ }),
73289/* 537 */
73290/***/ (function(module, exports, __webpack_require__) {
73291
73292"use strict";
73293/**
73294 * @fileoverview Rule to flag `else` after a `return` in `if`
73295 * @author Ian Christian Myers
73296 */
73297 //------------------------------------------------------------------------------
73298// Requirements
73299//------------------------------------------------------------------------------
73300
73301const astUtils = __webpack_require__(426);
73302
73303const FixTracker = __webpack_require__(538); //------------------------------------------------------------------------------
73304// Rule Definition
73305//------------------------------------------------------------------------------
73306
73307
73308module.exports = {
73309 meta: {
73310 type: "suggestion",
73311 docs: {
73312 description: "disallow `else` blocks after `return` statements in `if` statements",
73313 category: "Best Practices",
73314 recommended: false,
73315 url: "https://eslint.org/docs/rules/no-else-return"
73316 },
73317 schema: [{
73318 type: "object",
73319 properties: {
73320 allowElseIf: {
73321 type: "boolean",
73322 default: true
73323 }
73324 },
73325 additionalProperties: false
73326 }],
73327 fixable: "code",
73328 messages: {
73329 unexpected: "Unnecessary 'else' after 'return'."
73330 }
73331 },
73332
73333 create(context) {
73334 //--------------------------------------------------------------------------
73335 // Helpers
73336 //--------------------------------------------------------------------------
73337
73338 /**
73339 * Checks whether the given names can be safely used to declare block-scoped variables
73340 * in the given scope. Name collisions can produce redeclaration syntax errors,
73341 * or silently change references and modify behavior of the original code.
73342 *
73343 * This is not a generic function. In particular, it is assumed that the scope is a function scope or
73344 * a function's inner scope, and that the names can be valid identifiers in the given scope.
73345 * @param {string[]} names Array of variable names.
73346 * @param {eslint-scope.Scope} scope Function scope or a function's inner scope.
73347 * @returns {boolean} True if all names can be safely declared, false otherwise.
73348 */
73349 function isSafeToDeclare(names, scope) {
73350 if (names.length === 0) {
73351 return true;
73352 }
73353
73354 const functionScope = scope.variableScope;
73355 /*
73356 * If this is a function scope, scope.variables will contain parameters, implicit variables such as "arguments",
73357 * all function-scoped variables ('var'), and block-scoped variables defined in the scope.
73358 * If this is an inner scope, scope.variables will contain block-scoped variables defined in the scope.
73359 *
73360 * Redeclaring any of these would cause a syntax error, except for the implicit variables.
73361 */
73362
73363 const declaredVariables = scope.variables.filter(({
73364 defs
73365 }) => defs.length > 0);
73366
73367 if (declaredVariables.some(({
73368 name
73369 }) => names.includes(name))) {
73370 return false;
73371 } // Redeclaring a catch variable would also cause a syntax error.
73372
73373
73374 if (scope !== functionScope && scope.upper.type === "catch") {
73375 if (scope.upper.variables.some(({
73376 name
73377 }) => names.includes(name))) {
73378 return false;
73379 }
73380 }
73381 /*
73382 * Redeclaring an implicit variable, such as "arguments", would not cause a syntax error.
73383 * However, if the variable was used, declaring a new one with the same name would change references
73384 * and modify behavior.
73385 */
73386
73387
73388 const usedImplicitVariables = scope.variables.filter(({
73389 defs,
73390 references
73391 }) => defs.length === 0 && references.length > 0);
73392
73393 if (usedImplicitVariables.some(({
73394 name
73395 }) => names.includes(name))) {
73396 return false;
73397 }
73398 /*
73399 * Declaring a variable with a name that was already used to reference a variable from an upper scope
73400 * would change references and modify behavior.
73401 */
73402
73403
73404 if (scope.through.some(t => names.includes(t.identifier.name))) {
73405 return false;
73406 }
73407 /*
73408 * If the scope is an inner scope (not the function scope), an uninitialized `var` variable declared inside
73409 * the scope node (directly or in one of its descendants) is neither declared nor 'through' in the scope.
73410 *
73411 * For example, this would be a syntax error "Identifier 'a' has already been declared":
73412 * function foo() { if (bar) { let a; if (baz) { var a; } } }
73413 */
73414
73415
73416 if (scope !== functionScope) {
73417 const scopeNodeRange = scope.block.range;
73418 const variablesToCheck = functionScope.variables.filter(({
73419 name
73420 }) => names.includes(name));
73421
73422 if (variablesToCheck.some(v => v.defs.some(({
73423 node: {
73424 range
73425 }
73426 }) => scopeNodeRange[0] <= range[0] && range[1] <= scopeNodeRange[1]))) {
73427 return false;
73428 }
73429 }
73430
73431 return true;
73432 }
73433 /**
73434 * Checks whether the removal of `else` and its braces is safe from variable name collisions.
73435 * @param {Node} node The 'else' node.
73436 * @param {eslint-scope.Scope} scope The scope in which the node and the whole 'if' statement is.
73437 * @returns {boolean} True if it is safe, false otherwise.
73438 */
73439
73440
73441 function isSafeFromNameCollisions(node, scope) {
73442 if (node.type === "FunctionDeclaration") {
73443 // Conditional function declaration. Scope and hoisting are unpredictable, different engines work differently.
73444 return false;
73445 }
73446
73447 if (node.type !== "BlockStatement") {
73448 return true;
73449 }
73450
73451 const elseBlockScope = scope.childScopes.find(({
73452 block
73453 }) => block === node);
73454
73455 if (!elseBlockScope) {
73456 // ecmaVersion < 6, `else` block statement cannot have its own scope, no possible collisions.
73457 return true;
73458 }
73459 /*
73460 * elseBlockScope is supposed to merge into its upper scope. elseBlockScope.variables array contains
73461 * only block-scoped variables (such as let and const variables or class and function declarations)
73462 * defined directly in the elseBlockScope. These are exactly the only names that could cause collisions.
73463 */
73464
73465
73466 const namesToCheck = elseBlockScope.variables.map(({
73467 name
73468 }) => name);
73469 return isSafeToDeclare(namesToCheck, scope);
73470 }
73471 /**
73472 * Display the context report if rule is violated
73473 * @param {Node} node The 'else' node
73474 * @returns {void}
73475 */
73476
73477
73478 function displayReport(node) {
73479 const currentScope = context.getScope();
73480 context.report({
73481 node,
73482 messageId: "unexpected",
73483 fix: fixer => {
73484 if (!isSafeFromNameCollisions(node, currentScope)) {
73485 return null;
73486 }
73487
73488 const sourceCode = context.getSourceCode();
73489 const startToken = sourceCode.getFirstToken(node);
73490 const elseToken = sourceCode.getTokenBefore(startToken);
73491 const source = sourceCode.getText(node);
73492 const lastIfToken = sourceCode.getTokenBefore(elseToken);
73493 let fixedSource, firstTokenOfElseBlock;
73494
73495 if (startToken.type === "Punctuator" && startToken.value === "{") {
73496 firstTokenOfElseBlock = sourceCode.getTokenAfter(startToken);
73497 } else {
73498 firstTokenOfElseBlock = startToken;
73499 }
73500 /*
73501 * If the if block does not have curly braces and does not end in a semicolon
73502 * and the else block starts with (, [, /, +, ` or -, then it is not
73503 * safe to remove the else keyword, because ASI will not add a semicolon
73504 * after the if block
73505 */
73506
73507
73508 const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";";
73509 const elseBlockUnsafe = /^[([/+`-]/u.test(firstTokenOfElseBlock.value);
73510
73511 if (ifBlockMaybeUnsafe && elseBlockUnsafe) {
73512 return null;
73513 }
73514
73515 const endToken = sourceCode.getLastToken(node);
73516 const lastTokenOfElseBlock = sourceCode.getTokenBefore(endToken);
73517
73518 if (lastTokenOfElseBlock.value !== ";") {
73519 const nextToken = sourceCode.getTokenAfter(endToken);
73520 const nextTokenUnsafe = nextToken && /^[([/+`-]/u.test(nextToken.value);
73521 const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line;
73522 /*
73523 * If the else block contents does not end in a semicolon,
73524 * and the else block starts with (, [, /, +, ` or -, then it is not
73525 * safe to remove the else block, because ASI will not add a semicolon
73526 * after the remaining else block contents
73527 */
73528
73529 if (nextTokenUnsafe || nextTokenOnSameLine && nextToken.value !== "}") {
73530 return null;
73531 }
73532 }
73533
73534 if (startToken.type === "Punctuator" && startToken.value === "{") {
73535 fixedSource = source.slice(1, -1);
73536 } else {
73537 fixedSource = source;
73538 }
73539 /*
73540 * Extend the replacement range to include the entire
73541 * function to avoid conflicting with no-useless-return.
73542 * https://github.com/eslint/eslint/issues/8026
73543 *
73544 * Also, to avoid name collisions between two else blocks.
73545 */
73546
73547
73548 return new FixTracker(fixer, sourceCode).retainEnclosingFunction(node).replaceTextRange([elseToken.range[0], node.range[1]], fixedSource);
73549 }
73550 });
73551 }
73552 /**
73553 * Check to see if the node is a ReturnStatement
73554 * @param {Node} node The node being evaluated
73555 * @returns {boolean} True if node is a return
73556 */
73557
73558
73559 function checkForReturn(node) {
73560 return node.type === "ReturnStatement";
73561 }
73562 /**
73563 * Naive return checking, does not iterate through the whole
73564 * BlockStatement because we make the assumption that the ReturnStatement
73565 * will be the last node in the body of the BlockStatement.
73566 * @param {Node} node The consequent/alternate node
73567 * @returns {boolean} True if it has a return
73568 */
73569
73570
73571 function naiveHasReturn(node) {
73572 if (node.type === "BlockStatement") {
73573 const body = node.body,
73574 lastChildNode = body[body.length - 1];
73575 return lastChildNode && checkForReturn(lastChildNode);
73576 }
73577
73578 return checkForReturn(node);
73579 }
73580 /**
73581 * Check to see if the node is valid for evaluation,
73582 * meaning it has an else.
73583 * @param {Node} node The node being evaluated
73584 * @returns {boolean} True if the node is valid
73585 */
73586
73587
73588 function hasElse(node) {
73589 return node.alternate && node.consequent;
73590 }
73591 /**
73592 * If the consequent is an IfStatement, check to see if it has an else
73593 * and both its consequent and alternate path return, meaning this is
73594 * a nested case of rule violation. If-Else not considered currently.
73595 * @param {Node} node The consequent node
73596 * @returns {boolean} True if this is a nested rule violation
73597 */
73598
73599
73600 function checkForIf(node) {
73601 return node.type === "IfStatement" && hasElse(node) && naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent);
73602 }
73603 /**
73604 * Check the consequent/body node to make sure it is not
73605 * a ReturnStatement or an IfStatement that returns on both
73606 * code paths.
73607 * @param {Node} node The consequent or body node
73608 * @returns {boolean} `true` if it is a Return/If node that always returns.
73609 */
73610
73611
73612 function checkForReturnOrIf(node) {
73613 return checkForReturn(node) || checkForIf(node);
73614 }
73615 /**
73616 * Check whether a node returns in every codepath.
73617 * @param {Node} node The node to be checked
73618 * @returns {boolean} `true` if it returns on every codepath.
73619 */
73620
73621
73622 function alwaysReturns(node) {
73623 if (node.type === "BlockStatement") {
73624 // If we have a BlockStatement, check each consequent body node.
73625 return node.body.some(checkForReturnOrIf);
73626 }
73627 /*
73628 * If not a block statement, make sure the consequent isn't a
73629 * ReturnStatement or an IfStatement with returns on both paths.
73630 */
73631
73632
73633 return checkForReturnOrIf(node);
73634 }
73635 /**
73636 * Check the if statement, but don't catch else-if blocks.
73637 * @returns {void}
73638 * @param {Node} node The node for the if statement to check
73639 * @private
73640 */
73641
73642
73643 function checkIfWithoutElse(node) {
73644 const parent = node.parent;
73645 /*
73646 * Fixing this would require splitting one statement into two, so no error should
73647 * be reported if this node is in a position where only one statement is allowed.
73648 */
73649
73650 if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
73651 return;
73652 }
73653
73654 const consequents = [];
73655 let alternate;
73656
73657 for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) {
73658 if (!currentNode.alternate) {
73659 return;
73660 }
73661
73662 consequents.push(currentNode.consequent);
73663 alternate = currentNode.alternate;
73664 }
73665
73666 if (consequents.every(alwaysReturns)) {
73667 displayReport(alternate);
73668 }
73669 }
73670 /**
73671 * Check the if statement
73672 * @returns {void}
73673 * @param {Node} node The node for the if statement to check
73674 * @private
73675 */
73676
73677
73678 function checkIfWithElse(node) {
73679 const parent = node.parent;
73680 /*
73681 * Fixing this would require splitting one statement into two, so no error should
73682 * be reported if this node is in a position where only one statement is allowed.
73683 */
73684
73685 if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
73686 return;
73687 }
73688
73689 const alternate = node.alternate;
73690
73691 if (alternate && alwaysReturns(node.consequent)) {
73692 displayReport(alternate);
73693 }
73694 }
73695
73696 const allowElseIf = !(context.options[0] && context.options[0].allowElseIf === false); //--------------------------------------------------------------------------
73697 // Public API
73698 //--------------------------------------------------------------------------
73699
73700 return {
73701 "IfStatement:exit": allowElseIf ? checkIfWithoutElse : checkIfWithElse
73702 };
73703 }
73704
73705};
73706
73707/***/ }),
73708/* 538 */
73709/***/ (function(module, exports, __webpack_require__) {
73710
73711"use strict";
73712/**
73713 * @fileoverview Helper class to aid in constructing fix commands.
73714 * @author Alan Pierce
73715 */
73716 //------------------------------------------------------------------------------
73717// Requirements
73718//------------------------------------------------------------------------------
73719
73720const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
73721// Public Interface
73722//------------------------------------------------------------------------------
73723
73724/**
73725 * A helper class to combine fix options into a fix command. Currently, it
73726 * exposes some "retain" methods that extend the range of the text being
73727 * replaced so that other fixes won't touch that region in the same pass.
73728 */
73729
73730
73731class FixTracker {
73732 /**
73733 * Create a new FixTracker.
73734 * @param {ruleFixer} fixer A ruleFixer instance.
73735 * @param {SourceCode} sourceCode A SourceCode object for the current code.
73736 */
73737 constructor(fixer, sourceCode) {
73738 this.fixer = fixer;
73739 this.sourceCode = sourceCode;
73740 this.retainedRange = null;
73741 }
73742 /**
73743 * Mark the given range as "retained", meaning that other fixes may not
73744 * may not modify this region in the same pass.
73745 * @param {int[]} range The range to retain.
73746 * @returns {FixTracker} The same RuleFixer, for chained calls.
73747 */
73748
73749
73750 retainRange(range) {
73751 this.retainedRange = range;
73752 return this;
73753 }
73754 /**
73755 * Given a node, find the function containing it (or the entire program) and
73756 * mark it as retained, meaning that other fixes may not modify it in this
73757 * pass. This is useful for avoiding conflicts in fixes that modify control
73758 * flow.
73759 * @param {ASTNode} node The node to use as a starting point.
73760 * @returns {FixTracker} The same RuleFixer, for chained calls.
73761 */
73762
73763
73764 retainEnclosingFunction(node) {
73765 const functionNode = astUtils.getUpperFunction(node);
73766 return this.retainRange(functionNode ? functionNode.range : this.sourceCode.ast.range);
73767 }
73768 /**
73769 * Given a node or token, find the token before and afterward, and mark that
73770 * range as retained, meaning that other fixes may not modify it in this
73771 * pass. This is useful for avoiding conflicts in fixes that make a small
73772 * change to the code where the AST should not be changed.
73773 * @param {ASTNode|Token} nodeOrToken The node or token to use as a starting
73774 * point. The token to the left and right are use in the range.
73775 * @returns {FixTracker} The same RuleFixer, for chained calls.
73776 */
73777
73778
73779 retainSurroundingTokens(nodeOrToken) {
73780 const tokenBefore = this.sourceCode.getTokenBefore(nodeOrToken) || nodeOrToken;
73781 const tokenAfter = this.sourceCode.getTokenAfter(nodeOrToken) || nodeOrToken;
73782 return this.retainRange([tokenBefore.range[0], tokenAfter.range[1]]);
73783 }
73784 /**
73785 * Create a fix command that replaces the given range with the given text,
73786 * accounting for any retained ranges.
73787 * @param {int[]} range The range to remove in the fix.
73788 * @param {string} text The text to insert in place of the range.
73789 * @returns {Object} The fix command.
73790 */
73791
73792
73793 replaceTextRange(range, text) {
73794 let actualRange;
73795
73796 if (this.retainedRange) {
73797 actualRange = [Math.min(this.retainedRange[0], range[0]), Math.max(this.retainedRange[1], range[1])];
73798 } else {
73799 actualRange = range;
73800 }
73801
73802 return this.fixer.replaceTextRange(actualRange, this.sourceCode.text.slice(actualRange[0], range[0]) + text + this.sourceCode.text.slice(range[1], actualRange[1]));
73803 }
73804 /**
73805 * Create a fix command that removes the given node or token, accounting for
73806 * any retained ranges.
73807 * @param {ASTNode|Token} nodeOrToken The node or token to remove.
73808 * @returns {Object} The fix command.
73809 */
73810
73811
73812 remove(nodeOrToken) {
73813 return this.replaceTextRange(nodeOrToken.range, "");
73814 }
73815
73816}
73817
73818module.exports = FixTracker;
73819
73820/***/ }),
73821/* 539 */
73822/***/ (function(module, exports, __webpack_require__) {
73823
73824"use strict";
73825/**
73826 * @fileoverview Rule to flag use of an empty block statement
73827 * @author Nicholas C. Zakas
73828 */
73829 //------------------------------------------------------------------------------
73830// Requirements
73831//------------------------------------------------------------------------------
73832
73833const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
73834// Rule Definition
73835//------------------------------------------------------------------------------
73836
73837
73838module.exports = {
73839 meta: {
73840 type: "suggestion",
73841 docs: {
73842 description: "disallow empty block statements",
73843 category: "Possible Errors",
73844 recommended: true,
73845 url: "https://eslint.org/docs/rules/no-empty"
73846 },
73847 schema: [{
73848 type: "object",
73849 properties: {
73850 allowEmptyCatch: {
73851 type: "boolean",
73852 default: false
73853 }
73854 },
73855 additionalProperties: false
73856 }],
73857 messages: {
73858 unexpected: "Empty {{type}} statement."
73859 }
73860 },
73861
73862 create(context) {
73863 const options = context.options[0] || {},
73864 allowEmptyCatch = options.allowEmptyCatch || false;
73865 const sourceCode = context.getSourceCode();
73866 return {
73867 BlockStatement(node) {
73868 // if the body is not empty, we can just return immediately
73869 if (node.body.length !== 0) {
73870 return;
73871 } // a function is generally allowed to be empty
73872
73873
73874 if (astUtils.isFunction(node.parent)) {
73875 return;
73876 }
73877
73878 if (allowEmptyCatch && node.parent.type === "CatchClause") {
73879 return;
73880 } // any other block is only allowed to be empty, if it contains a comment
73881
73882
73883 if (sourceCode.getCommentsInside(node).length > 0) {
73884 return;
73885 }
73886
73887 context.report({
73888 node,
73889 messageId: "unexpected",
73890 data: {
73891 type: "block"
73892 }
73893 });
73894 },
73895
73896 SwitchStatement(node) {
73897 if (typeof node.cases === "undefined" || node.cases.length === 0) {
73898 context.report({
73899 node,
73900 messageId: "unexpected",
73901 data: {
73902 type: "switch"
73903 }
73904 });
73905 }
73906 }
73907
73908 };
73909 }
73910
73911};
73912
73913/***/ }),
73914/* 540 */
73915/***/ (function(module, exports, __webpack_require__) {
73916
73917"use strict";
73918/**
73919 * @fileoverview Rule to flag the use of empty character classes in regular expressions
73920 * @author Ian Christian Myers
73921 */
73922 //------------------------------------------------------------------------------
73923// Helpers
73924//------------------------------------------------------------------------------
73925
73926/*
73927 * plain-English description of the following regexp:
73928 * 0. `^` fix the match at the beginning of the string
73929 * 1. `\/`: the `/` that begins the regexp
73930 * 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following
73931 * 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes)
73932 * 2.1. `\\.`: an escape sequence
73933 * 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty
73934 * 3. `\/` the `/` that ends the regexp
73935 * 4. `[gimuy]*`: optional regexp flags
73936 * 5. `$`: fix the match at the end of the string
73937 */
73938
73939const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimuys]*$/u; //------------------------------------------------------------------------------
73940// Rule Definition
73941//------------------------------------------------------------------------------
73942
73943module.exports = {
73944 meta: {
73945 type: "problem",
73946 docs: {
73947 description: "disallow empty character classes in regular expressions",
73948 category: "Possible Errors",
73949 recommended: true,
73950 url: "https://eslint.org/docs/rules/no-empty-character-class"
73951 },
73952 schema: [],
73953 messages: {
73954 unexpected: "Empty class."
73955 }
73956 },
73957
73958 create(context) {
73959 const sourceCode = context.getSourceCode();
73960 return {
73961 Literal(node) {
73962 const token = sourceCode.getFirstToken(node);
73963
73964 if (token.type === "RegularExpression" && !regex.test(token.value)) {
73965 context.report({
73966 node,
73967 messageId: "unexpected"
73968 });
73969 }
73970 }
73971
73972 };
73973 }
73974
73975};
73976
73977/***/ }),
73978/* 541 */
73979/***/ (function(module, exports, __webpack_require__) {
73980
73981"use strict";
73982/**
73983 * @fileoverview Rule to disallow empty functions.
73984 * @author Toru Nagashima
73985 */
73986 //------------------------------------------------------------------------------
73987// Requirements
73988//------------------------------------------------------------------------------
73989
73990const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
73991// Helpers
73992//------------------------------------------------------------------------------
73993
73994
73995const ALLOW_OPTIONS = Object.freeze(["functions", "arrowFunctions", "generatorFunctions", "methods", "generatorMethods", "getters", "setters", "constructors", "asyncFunctions", "asyncMethods"]);
73996/**
73997 * Gets the kind of a given function node.
73998 * @param {ASTNode} node A function node to get. This is one of
73999 * an ArrowFunctionExpression, a FunctionDeclaration, or a
74000 * FunctionExpression.
74001 * @returns {string} The kind of the function. This is one of "functions",
74002 * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods",
74003 * "generatorMethods", "asyncMethods", "getters", "setters", and
74004 * "constructors".
74005 */
74006
74007function getKind(node) {
74008 const parent = node.parent;
74009 let kind = "";
74010
74011 if (node.type === "ArrowFunctionExpression") {
74012 return "arrowFunctions";
74013 } // Detects main kind.
74014
74015
74016 if (parent.type === "Property") {
74017 if (parent.kind === "get") {
74018 return "getters";
74019 }
74020
74021 if (parent.kind === "set") {
74022 return "setters";
74023 }
74024
74025 kind = parent.method ? "methods" : "functions";
74026 } else if (parent.type === "MethodDefinition") {
74027 if (parent.kind === "get") {
74028 return "getters";
74029 }
74030
74031 if (parent.kind === "set") {
74032 return "setters";
74033 }
74034
74035 if (parent.kind === "constructor") {
74036 return "constructors";
74037 }
74038
74039 kind = "methods";
74040 } else {
74041 kind = "functions";
74042 } // Detects prefix.
74043
74044
74045 let prefix = "";
74046
74047 if (node.generator) {
74048 prefix = "generator";
74049 } else if (node.async) {
74050 prefix = "async";
74051 } else {
74052 return kind;
74053 }
74054
74055 return prefix + kind[0].toUpperCase() + kind.slice(1);
74056} //------------------------------------------------------------------------------
74057// Rule Definition
74058//------------------------------------------------------------------------------
74059
74060
74061module.exports = {
74062 meta: {
74063 type: "suggestion",
74064 docs: {
74065 description: "disallow empty functions",
74066 category: "Best Practices",
74067 recommended: false,
74068 url: "https://eslint.org/docs/rules/no-empty-function"
74069 },
74070 schema: [{
74071 type: "object",
74072 properties: {
74073 allow: {
74074 type: "array",
74075 items: {
74076 enum: ALLOW_OPTIONS
74077 },
74078 uniqueItems: true
74079 }
74080 },
74081 additionalProperties: false
74082 }],
74083 messages: {
74084 unexpected: "Unexpected empty {{name}}."
74085 }
74086 },
74087
74088 create(context) {
74089 const options = context.options[0] || {};
74090 const allowed = options.allow || [];
74091 const sourceCode = context.getSourceCode();
74092 /**
74093 * Reports a given function node if the node matches the following patterns.
74094 *
74095 * - Not allowed by options.
74096 * - The body is empty.
74097 * - The body doesn't have any comments.
74098 * @param {ASTNode} node A function node to report. This is one of
74099 * an ArrowFunctionExpression, a FunctionDeclaration, or a
74100 * FunctionExpression.
74101 * @returns {void}
74102 */
74103
74104 function reportIfEmpty(node) {
74105 const kind = getKind(node);
74106 const name = astUtils.getFunctionNameWithKind(node);
74107 const innerComments = sourceCode.getTokens(node.body, {
74108 includeComments: true,
74109 filter: astUtils.isCommentToken
74110 });
74111
74112 if (allowed.indexOf(kind) === -1 && node.body.type === "BlockStatement" && node.body.body.length === 0 && innerComments.length === 0) {
74113 context.report({
74114 node,
56c4a2cb 74115 loc: node.body.loc,
eb39fafa
DC
74116 messageId: "unexpected",
74117 data: {
74118 name
74119 }
74120 });
74121 }
74122 }
74123
74124 return {
74125 ArrowFunctionExpression: reportIfEmpty,
74126 FunctionDeclaration: reportIfEmpty,
74127 FunctionExpression: reportIfEmpty
74128 };
74129 }
74130
74131};
74132
74133/***/ }),
74134/* 542 */
74135/***/ (function(module, exports, __webpack_require__) {
74136
74137"use strict";
74138/**
74139 * @fileoverview Rule to disallow an empty pattern
74140 * @author Alberto Rodríguez
74141 */
74142 //------------------------------------------------------------------------------
74143// Rule Definition
74144//------------------------------------------------------------------------------
74145
74146module.exports = {
74147 meta: {
74148 type: "problem",
74149 docs: {
74150 description: "disallow empty destructuring patterns",
74151 category: "Best Practices",
74152 recommended: true,
74153 url: "https://eslint.org/docs/rules/no-empty-pattern"
74154 },
74155 schema: [],
74156 messages: {
74157 unexpected: "Unexpected empty {{type}} pattern."
74158 }
74159 },
74160
74161 create(context) {
74162 return {
74163 ObjectPattern(node) {
74164 if (node.properties.length === 0) {
74165 context.report({
74166 node,
74167 messageId: "unexpected",
74168 data: {
74169 type: "object"
74170 }
74171 });
74172 }
74173 },
74174
74175 ArrayPattern(node) {
74176 if (node.elements.length === 0) {
74177 context.report({
74178 node,
74179 messageId: "unexpected",
74180 data: {
74181 type: "array"
74182 }
74183 });
74184 }
74185 }
74186
74187 };
74188 }
74189
74190};
74191
74192/***/ }),
74193/* 543 */
74194/***/ (function(module, exports, __webpack_require__) {
74195
74196"use strict";
74197/**
74198 * @fileoverview Rule to flag comparisons to null without a type-checking
74199 * operator.
74200 * @author Ian Christian Myers
74201 */
74202 //------------------------------------------------------------------------------
74203// Rule Definition
74204//------------------------------------------------------------------------------
74205
74206module.exports = {
74207 meta: {
74208 type: "suggestion",
74209 docs: {
74210 description: "disallow `null` comparisons without type-checking operators",
74211 category: "Best Practices",
74212 recommended: false,
74213 url: "https://eslint.org/docs/rules/no-eq-null"
74214 },
74215 schema: [],
74216 messages: {
74217 unexpected: "Use '===' to compare with null."
74218 }
74219 },
74220
74221 create(context) {
74222 return {
74223 BinaryExpression(node) {
74224 const badOperator = node.operator === "==" || node.operator === "!=";
74225
74226 if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || node.left.type === "Literal" && node.left.raw === "null" && badOperator) {
74227 context.report({
74228 node,
74229 messageId: "unexpected"
74230 });
74231 }
74232 }
74233
74234 };
74235 }
74236
74237};
74238
74239/***/ }),
74240/* 544 */
74241/***/ (function(module, exports, __webpack_require__) {
74242
74243"use strict";
74244/**
74245 * @fileoverview Rule to flag use of eval() statement
74246 * @author Nicholas C. Zakas
74247 */
74248 //------------------------------------------------------------------------------
74249// Requirements
74250//------------------------------------------------------------------------------
74251
74252const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
74253// Helpers
74254//------------------------------------------------------------------------------
74255
74256
74257const candidatesOfGlobalObject = Object.freeze(["global", "window", "globalThis"]);
74258/**
74259 * Checks a given node is a Identifier node of the specified name.
74260 * @param {ASTNode} node A node to check.
74261 * @param {string} name A name to check.
74262 * @returns {boolean} `true` if the node is a Identifier node of the name.
74263 */
74264
74265function isIdentifier(node, name) {
74266 return node.type === "Identifier" && node.name === name;
74267}
74268/**
74269 * Checks a given node is a Literal node of the specified string value.
74270 * @param {ASTNode} node A node to check.
74271 * @param {string} name A name to check.
74272 * @returns {boolean} `true` if the node is a Literal node of the name.
74273 */
74274
74275
74276function isConstant(node, name) {
74277 switch (node.type) {
74278 case "Literal":
74279 return node.value === name;
74280
74281 case "TemplateLiteral":
74282 return node.expressions.length === 0 && node.quasis[0].value.cooked === name;
74283
74284 default:
74285 return false;
74286 }
74287}
74288/**
74289 * Checks a given node is a MemberExpression node which has the specified name's
74290 * property.
74291 * @param {ASTNode} node A node to check.
74292 * @param {string} name A name to check.
74293 * @returns {boolean} `true` if the node is a MemberExpression node which has
74294 * the specified name's property
74295 */
74296
74297
74298function isMember(node, name) {
74299 return node.type === "MemberExpression" && (node.computed ? isConstant : isIdentifier)(node.property, name);
74300} //------------------------------------------------------------------------------
74301// Rule Definition
74302//------------------------------------------------------------------------------
74303
74304
74305module.exports = {
74306 meta: {
74307 type: "suggestion",
74308 docs: {
74309 description: "disallow the use of `eval()`",
74310 category: "Best Practices",
74311 recommended: false,
74312 url: "https://eslint.org/docs/rules/no-eval"
74313 },
74314 schema: [{
74315 type: "object",
74316 properties: {
74317 allowIndirect: {
74318 type: "boolean",
74319 default: false
74320 }
74321 },
74322 additionalProperties: false
74323 }],
74324 messages: {
74325 unexpected: "eval can be harmful."
74326 }
74327 },
74328
74329 create(context) {
74330 const allowIndirect = Boolean(context.options[0] && context.options[0].allowIndirect);
74331 const sourceCode = context.getSourceCode();
74332 let funcInfo = null;
74333 /**
74334 * Pushs a variable scope (Program or Function) information to the stack.
74335 *
74336 * This is used in order to check whether or not `this` binding is a
74337 * reference to the global object.
74338 * @param {ASTNode} node A node of the scope. This is one of Program,
74339 * FunctionDeclaration, FunctionExpression, and ArrowFunctionExpression.
74340 * @returns {void}
74341 */
74342
74343 function enterVarScope(node) {
74344 const strict = context.getScope().isStrict;
74345 funcInfo = {
74346 upper: funcInfo,
74347 node,
74348 strict,
74349 defaultThis: false,
74350 initialized: strict
74351 };
74352 }
74353 /**
74354 * Pops a variable scope from the stack.
74355 * @returns {void}
74356 */
74357
74358
74359 function exitVarScope() {
74360 funcInfo = funcInfo.upper;
74361 }
74362 /**
74363 * Reports a given node.
74364 *
74365 * `node` is `Identifier` or `MemberExpression`.
74366 * The parent of `node` might be `CallExpression`.
74367 *
74368 * The location of the report is always `eval` `Identifier` (or possibly
74369 * `Literal`). The type of the report is `CallExpression` if the parent is
74370 * `CallExpression`. Otherwise, it's the given node type.
74371 * @param {ASTNode} node A node to report.
74372 * @returns {void}
74373 */
74374
74375
74376 function report(node) {
74377 const parent = node.parent;
74378 const locationNode = node.type === "MemberExpression" ? node.property : node;
74379 const reportNode = parent.type === "CallExpression" && parent.callee === node ? parent : node;
74380 context.report({
74381 node: reportNode,
74382 loc: locationNode.loc,
74383 messageId: "unexpected"
74384 });
74385 }
74386 /**
74387 * Reports accesses of `eval` via the global object.
74388 * @param {eslint-scope.Scope} globalScope The global scope.
74389 * @returns {void}
74390 */
74391
74392
74393 function reportAccessingEvalViaGlobalObject(globalScope) {
74394 for (let i = 0; i < candidatesOfGlobalObject.length; ++i) {
74395 const name = candidatesOfGlobalObject[i];
74396 const variable = astUtils.getVariableByName(globalScope, name);
74397
74398 if (!variable) {
74399 continue;
74400 }
74401
74402 const references = variable.references;
74403
74404 for (let j = 0; j < references.length; ++j) {
74405 const identifier = references[j].identifier;
74406 let node = identifier.parent; // To detect code like `window.window.eval`.
74407
74408 while (isMember(node, name)) {
74409 node = node.parent;
74410 } // Reports.
74411
74412
74413 if (isMember(node, "eval")) {
74414 report(node);
74415 }
74416 }
74417 }
74418 }
74419 /**
74420 * Reports all accesses of `eval` (excludes direct calls to eval).
74421 * @param {eslint-scope.Scope} globalScope The global scope.
74422 * @returns {void}
74423 */
74424
74425
74426 function reportAccessingEval(globalScope) {
74427 const variable = astUtils.getVariableByName(globalScope, "eval");
74428
74429 if (!variable) {
74430 return;
74431 }
74432
74433 const references = variable.references;
74434
74435 for (let i = 0; i < references.length; ++i) {
74436 const reference = references[i];
74437 const id = reference.identifier;
74438
74439 if (id.name === "eval" && !astUtils.isCallee(id)) {
74440 // Is accessing to eval (excludes direct calls to eval)
74441 report(id);
74442 }
74443 }
74444 }
74445
74446 if (allowIndirect) {
74447 // Checks only direct calls to eval. It's simple!
74448 return {
74449 "CallExpression:exit"(node) {
74450 const callee = node.callee;
74451
74452 if (isIdentifier(callee, "eval")) {
74453 report(callee);
74454 }
74455 }
74456
74457 };
74458 }
74459
74460 return {
74461 "CallExpression:exit"(node) {
74462 const callee = node.callee;
74463
74464 if (isIdentifier(callee, "eval")) {
74465 report(callee);
74466 }
74467 },
74468
74469 Program(node) {
74470 const scope = context.getScope(),
74471 features = context.parserOptions.ecmaFeatures || {},
74472 strict = scope.isStrict || node.sourceType === "module" || features.globalReturn && scope.childScopes[0].isStrict;
74473 funcInfo = {
74474 upper: null,
74475 node,
74476 strict,
74477 defaultThis: true,
74478 initialized: true
74479 };
74480 },
74481
74482 "Program:exit"() {
74483 const globalScope = context.getScope();
74484 exitVarScope();
74485 reportAccessingEval(globalScope);
74486 reportAccessingEvalViaGlobalObject(globalScope);
74487 },
74488
74489 FunctionDeclaration: enterVarScope,
74490 "FunctionDeclaration:exit": exitVarScope,
74491 FunctionExpression: enterVarScope,
74492 "FunctionExpression:exit": exitVarScope,
74493 ArrowFunctionExpression: enterVarScope,
74494 "ArrowFunctionExpression:exit": exitVarScope,
74495
74496 ThisExpression(node) {
74497 if (!isMember(node.parent, "eval")) {
74498 return;
74499 }
74500 /*
74501 * `this.eval` is found.
74502 * Checks whether or not the value of `this` is the global object.
74503 */
74504
74505
74506 if (!funcInfo.initialized) {
74507 funcInfo.initialized = true;
74508 funcInfo.defaultThis = astUtils.isDefaultThisBinding(funcInfo.node, sourceCode);
74509 }
74510
74511 if (!funcInfo.strict && funcInfo.defaultThis) {
74512 // `this.eval` is possible built-in `eval`.
74513 report(node.parent);
74514 }
74515 }
74516
74517 };
74518 }
74519
74520};
74521
74522/***/ }),
74523/* 545 */
74524/***/ (function(module, exports, __webpack_require__) {
74525
74526"use strict";
74527/**
74528 * @fileoverview Rule to flag assignment of the exception parameter
74529 * @author Stephen Murray <spmurrayzzz>
74530 */
74531
74532
74533const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
74534// Rule Definition
74535//------------------------------------------------------------------------------
74536
74537
74538module.exports = {
74539 meta: {
74540 type: "problem",
74541 docs: {
74542 description: "disallow reassigning exceptions in `catch` clauses",
74543 category: "Possible Errors",
74544 recommended: true,
74545 url: "https://eslint.org/docs/rules/no-ex-assign"
74546 },
74547 schema: [],
74548 messages: {
74549 unexpected: "Do not assign to the exception parameter."
74550 }
74551 },
74552
74553 create(context) {
74554 /**
74555 * Finds and reports references that are non initializer and writable.
74556 * @param {Variable} variable A variable to check.
74557 * @returns {void}
74558 */
74559 function checkVariable(variable) {
74560 astUtils.getModifyingReferences(variable.references).forEach(reference => {
74561 context.report({
74562 node: reference.identifier,
74563 messageId: "unexpected"
74564 });
74565 });
74566 }
74567
74568 return {
74569 CatchClause(node) {
74570 context.getDeclaredVariables(node).forEach(checkVariable);
74571 }
74572
74573 };
74574 }
74575
74576};
74577
74578/***/ }),
74579/* 546 */
74580/***/ (function(module, exports, __webpack_require__) {
74581
74582"use strict";
74583/**
74584 * @fileoverview Rule to flag adding properties to native object's prototypes.
74585 * @author David Nelson
74586 */
74587 //------------------------------------------------------------------------------
74588// Requirements
74589//------------------------------------------------------------------------------
74590
74591const astUtils = __webpack_require__(426);
74592
74593const globals = __webpack_require__(406); //------------------------------------------------------------------------------
74594// Helpers
74595//------------------------------------------------------------------------------
74596
74597
74598const propertyDefinitionMethods = new Set(["defineProperty", "defineProperties"]); //------------------------------------------------------------------------------
74599// Rule Definition
74600//------------------------------------------------------------------------------
74601
74602module.exports = {
74603 meta: {
74604 type: "suggestion",
74605 docs: {
74606 description: "disallow extending native types",
74607 category: "Best Practices",
74608 recommended: false,
74609 url: "https://eslint.org/docs/rules/no-extend-native"
74610 },
74611 schema: [{
74612 type: "object",
74613 properties: {
74614 exceptions: {
74615 type: "array",
74616 items: {
74617 type: "string"
74618 },
74619 uniqueItems: true
74620 }
74621 },
74622 additionalProperties: false
74623 }],
74624 messages: {
74625 unexpected: "{{builtin}} prototype is read only, properties should not be added."
74626 }
74627 },
74628
74629 create(context) {
74630 const config = context.options[0] || {};
74631 const exceptions = new Set(config.exceptions || []);
74632 const modifiedBuiltins = new Set(Object.keys(globals.builtin).filter(builtin => builtin[0].toUpperCase() === builtin[0]).filter(builtin => !exceptions.has(builtin)));
74633 /**
74634 * Reports a lint error for the given node.
74635 * @param {ASTNode} node The node to report.
74636 * @param {string} builtin The name of the native builtin being extended.
74637 * @returns {void}
74638 */
74639
74640 function reportNode(node, builtin) {
74641 context.report({
74642 node,
74643 messageId: "unexpected",
74644 data: {
74645 builtin
74646 }
74647 });
74648 }
74649 /**
74650 * Check to see if the `prototype` property of the given object
74651 * identifier node is being accessed.
74652 * @param {ASTNode} identifierNode The Identifier representing the object
74653 * to check.
74654 * @returns {boolean} True if the identifier is the object of a
74655 * MemberExpression and its `prototype` property is being accessed,
74656 * false otherwise.
74657 */
74658
74659
74660 function isPrototypePropertyAccessed(identifierNode) {
74661 return Boolean(identifierNode && identifierNode.parent && identifierNode.parent.type === "MemberExpression" && identifierNode.parent.object === identifierNode && astUtils.getStaticPropertyName(identifierNode.parent) === "prototype");
74662 }
74663 /**
74664 * Checks that an identifier is an object of a prototype whose member
74665 * is being assigned in an AssignmentExpression.
74666 * Example: Object.prototype.foo = "bar"
74667 * @param {ASTNode} identifierNode The identifier to check.
74668 * @returns {boolean} True if the identifier's prototype is modified.
74669 */
74670
74671
74672 function isInPrototypePropertyAssignment(identifierNode) {
74673 return Boolean(isPrototypePropertyAccessed(identifierNode) && identifierNode.parent.parent.type === "MemberExpression" && identifierNode.parent.parent.parent.type === "AssignmentExpression" && identifierNode.parent.parent.parent.left === identifierNode.parent.parent);
74674 }
74675 /**
74676 * Checks that an identifier is an object of a prototype whose member
74677 * is being extended via the Object.defineProperty() or
74678 * Object.defineProperties() methods.
74679 * Example: Object.defineProperty(Array.prototype, "foo", ...)
74680 * Example: Object.defineProperties(Array.prototype, ...)
74681 * @param {ASTNode} identifierNode The identifier to check.
74682 * @returns {boolean} True if the identifier's prototype is modified.
74683 */
74684
74685
74686 function isInDefinePropertyCall(identifierNode) {
74687 return Boolean(isPrototypePropertyAccessed(identifierNode) && identifierNode.parent.parent.type === "CallExpression" && identifierNode.parent.parent.arguments[0] === identifierNode.parent && identifierNode.parent.parent.callee.type === "MemberExpression" && identifierNode.parent.parent.callee.object.type === "Identifier" && identifierNode.parent.parent.callee.object.name === "Object" && identifierNode.parent.parent.callee.property.type === "Identifier" && propertyDefinitionMethods.has(identifierNode.parent.parent.callee.property.name));
74688 }
74689 /**
74690 * Check to see if object prototype access is part of a prototype
74691 * extension. There are three ways a prototype can be extended:
74692 * 1. Assignment to prototype property (Object.prototype.foo = 1)
74693 * 2. Object.defineProperty()/Object.defineProperties() on a prototype
74694 * If prototype extension is detected, report the AssignmentExpression
74695 * or CallExpression node.
74696 * @param {ASTNode} identifierNode The Identifier representing the object
74697 * which prototype is being accessed and possibly extended.
74698 * @returns {void}
74699 */
74700
74701
74702 function checkAndReportPrototypeExtension(identifierNode) {
74703 if (isInPrototypePropertyAssignment(identifierNode)) {
74704 // Identifier --> MemberExpression --> MemberExpression --> AssignmentExpression
74705 reportNode(identifierNode.parent.parent.parent, identifierNode.name);
74706 } else if (isInDefinePropertyCall(identifierNode)) {
74707 // Identifier --> MemberExpression --> CallExpression
74708 reportNode(identifierNode.parent.parent, identifierNode.name);
74709 }
74710 }
74711
74712 return {
74713 "Program:exit"() {
74714 const globalScope = context.getScope();
74715 modifiedBuiltins.forEach(builtin => {
74716 const builtinVar = globalScope.set.get(builtin);
74717
74718 if (builtinVar && builtinVar.references) {
74719 builtinVar.references.map(ref => ref.identifier).forEach(checkAndReportPrototypeExtension);
74720 }
74721 });
74722 }
74723
74724 };
74725 }
74726
74727};
74728
74729/***/ }),
74730/* 547 */
74731/***/ (function(module, exports, __webpack_require__) {
74732
74733"use strict";
74734/**
74735 * @fileoverview Rule to flag unnecessary bind calls
74736 * @author Bence Dányi <bence@danyi.me>
74737 */
74738 //------------------------------------------------------------------------------
74739// Requirements
74740//------------------------------------------------------------------------------
74741
74742const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
74743// Helpers
74744//------------------------------------------------------------------------------
74745
74746
74747const SIDE_EFFECT_FREE_NODE_TYPES = new Set(["Literal", "Identifier", "ThisExpression", "FunctionExpression"]); //------------------------------------------------------------------------------
74748// Rule Definition
74749//------------------------------------------------------------------------------
74750
74751module.exports = {
74752 meta: {
74753 type: "suggestion",
74754 docs: {
74755 description: "disallow unnecessary calls to `.bind()`",
74756 category: "Best Practices",
74757 recommended: false,
74758 url: "https://eslint.org/docs/rules/no-extra-bind"
74759 },
74760 schema: [],
74761 fixable: "code",
74762 messages: {
74763 unexpected: "The function binding is unnecessary."
74764 }
74765 },
74766
74767 create(context) {
74768 const sourceCode = context.getSourceCode();
74769 let scopeInfo = null;
74770 /**
74771 * Checks if a node is free of side effects.
74772 *
74773 * This check is stricter than it needs to be, in order to keep the implementation simple.
74774 * @param {ASTNode} node A node to check.
74775 * @returns {boolean} True if the node is known to be side-effect free, false otherwise.
74776 */
74777
74778 function isSideEffectFree(node) {
74779 return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type);
74780 }
74781 /**
74782 * Reports a given function node.
74783 * @param {ASTNode} node A node to report. This is a FunctionExpression or
74784 * an ArrowFunctionExpression.
74785 * @returns {void}
74786 */
74787
74788
74789 function report(node) {
74790 context.report({
74791 node: node.parent.parent,
74792 messageId: "unexpected",
74793 loc: node.parent.property.loc,
74794
74795 fix(fixer) {
74796 if (node.parent.parent.arguments.length && !isSideEffectFree(node.parent.parent.arguments[0])) {
74797 return null;
74798 }
74799
74800 const firstTokenToRemove = sourceCode.getFirstTokenBetween(node.parent.object, node.parent.property, astUtils.isNotClosingParenToken);
74801 const lastTokenToRemove = sourceCode.getLastToken(node.parent.parent);
74802
74803 if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) {
74804 return null;
74805 }
74806
74807 return fixer.removeRange([firstTokenToRemove.range[0], node.parent.parent.range[1]]);
74808 }
74809
74810 });
74811 }
74812 /**
74813 * Checks whether or not a given function node is the callee of `.bind()`
74814 * method.
74815 *
74816 * e.g. `(function() {}.bind(foo))`
74817 * @param {ASTNode} node A node to report. This is a FunctionExpression or
74818 * an ArrowFunctionExpression.
74819 * @returns {boolean} `true` if the node is the callee of `.bind()` method.
74820 */
74821
74822
74823 function isCalleeOfBindMethod(node) {
74824 const parent = node.parent;
74825 const grandparent = parent.parent;
74826 return grandparent && grandparent.type === "CallExpression" && grandparent.callee === parent && grandparent.arguments.length === 1 && grandparent.arguments[0].type !== "SpreadElement" && parent.type === "MemberExpression" && parent.object === node && astUtils.getStaticPropertyName(parent) === "bind";
74827 }
74828 /**
74829 * Adds a scope information object to the stack.
74830 * @param {ASTNode} node A node to add. This node is a FunctionExpression
74831 * or a FunctionDeclaration node.
74832 * @returns {void}
74833 */
74834
74835
74836 function enterFunction(node) {
74837 scopeInfo = {
74838 isBound: isCalleeOfBindMethod(node),
74839 thisFound: false,
74840 upper: scopeInfo
74841 };
74842 }
74843 /**
74844 * Removes the scope information object from the top of the stack.
74845 * At the same time, this reports the function node if the function has
74846 * `.bind()` and the `this` keywords found.
74847 * @param {ASTNode} node A node to remove. This node is a
74848 * FunctionExpression or a FunctionDeclaration node.
74849 * @returns {void}
74850 */
74851
74852
74853 function exitFunction(node) {
74854 if (scopeInfo.isBound && !scopeInfo.thisFound) {
74855 report(node);
74856 }
74857
74858 scopeInfo = scopeInfo.upper;
74859 }
74860 /**
74861 * Reports a given arrow function if the function is callee of `.bind()`
74862 * method.
74863 * @param {ASTNode} node A node to report. This node is an
74864 * ArrowFunctionExpression.
74865 * @returns {void}
74866 */
74867
74868
74869 function exitArrowFunction(node) {
74870 if (isCalleeOfBindMethod(node)) {
74871 report(node);
74872 }
74873 }
74874 /**
74875 * Set the mark as the `this` keyword was found in this scope.
74876 * @returns {void}
74877 */
74878
74879
74880 function markAsThisFound() {
74881 if (scopeInfo) {
74882 scopeInfo.thisFound = true;
74883 }
74884 }
74885
74886 return {
74887 "ArrowFunctionExpression:exit": exitArrowFunction,
74888 FunctionDeclaration: enterFunction,
74889 "FunctionDeclaration:exit": exitFunction,
74890 FunctionExpression: enterFunction,
74891 "FunctionExpression:exit": exitFunction,
74892 ThisExpression: markAsThisFound
74893 };
74894 }
74895
74896};
74897
74898/***/ }),
74899/* 548 */
74900/***/ (function(module, exports, __webpack_require__) {
74901
74902"use strict";
74903/**
74904 * @fileoverview Rule to flag unnecessary double negation in Boolean contexts
74905 * @author Brandon Mills
74906 */
74907 //------------------------------------------------------------------------------
74908// Requirements
74909//------------------------------------------------------------------------------
74910
74911const astUtils = __webpack_require__(426);
74912
74913const eslintUtils = __webpack_require__(549);
74914
74915const precedence = astUtils.getPrecedence; //------------------------------------------------------------------------------
74916// Rule Definition
74917//------------------------------------------------------------------------------
74918
74919module.exports = {
74920 meta: {
74921 type: "suggestion",
74922 docs: {
74923 description: "disallow unnecessary boolean casts",
74924 category: "Possible Errors",
74925 recommended: true,
74926 url: "https://eslint.org/docs/rules/no-extra-boolean-cast"
74927 },
74928 schema: [{
74929 type: "object",
74930 properties: {
74931 enforceForLogicalOperands: {
74932 type: "boolean",
74933 default: false
74934 }
74935 },
74936 additionalProperties: false
74937 }],
74938 fixable: "code",
74939 messages: {
74940 unexpectedCall: "Redundant Boolean call.",
74941 unexpectedNegation: "Redundant double negation."
74942 }
74943 },
74944
74945 create(context) {
74946 const sourceCode = context.getSourceCode(); // Node types which have a test which will coerce values to booleans.
74947
74948 const BOOLEAN_NODE_TYPES = ["IfStatement", "DoWhileStatement", "WhileStatement", "ConditionalExpression", "ForStatement"];
74949 /**
74950 * Check if a node is a Boolean function or constructor.
74951 * @param {ASTNode} node the node
74952 * @returns {boolean} If the node is Boolean function or constructor
74953 */
74954
74955 function isBooleanFunctionOrConstructorCall(node) {
74956 // Boolean(<bool>) and new Boolean(<bool>)
74957 return (node.type === "CallExpression" || node.type === "NewExpression") && node.callee.type === "Identifier" && node.callee.name === "Boolean";
74958 }
74959 /**
74960 * Checks whether the node is a logical expression and that the option is enabled
74961 * @param {ASTNode} node the node
74962 * @returns {boolean} if the node is a logical expression and option is enabled
74963 */
74964
74965
74966 function isLogicalContext(node) {
74967 return node.type === "LogicalExpression" && (node.operator === "||" || node.operator === "&&") && context.options.length && context.options[0].enforceForLogicalOperands === true;
74968 }
74969 /**
74970 * Check if a node is in a context where its value would be coerced to a boolean at runtime.
74971 * @param {ASTNode} node The node
74972 * @returns {boolean} If it is in a boolean context
74973 */
74974
74975
74976 function isInBooleanContext(node) {
74977 return isBooleanFunctionOrConstructorCall(node.parent) && node === node.parent.arguments[0] || BOOLEAN_NODE_TYPES.indexOf(node.parent.type) !== -1 && node === node.parent.test || // !<bool>
74978 node.parent.type === "UnaryExpression" && node.parent.operator === "!";
74979 }
74980 /**
74981 * Checks whether the node is a context that should report an error
74982 * Acts recursively if it is in a logical context
74983 * @param {ASTNode} node the node
74984 * @returns {boolean} If the node is in one of the flagged contexts
74985 */
74986
74987
74988 function isInFlaggedContext(node) {
74989 return isInBooleanContext(node) || isLogicalContext(node.parent) && // For nested logical statements
74990 isInFlaggedContext(node.parent);
74991 }
74992 /**
74993 * Check if a node has comments inside.
74994 * @param {ASTNode} node The node to check.
74995 * @returns {boolean} `true` if it has comments inside.
74996 */
74997
74998
74999 function hasCommentsInside(node) {
75000 return Boolean(sourceCode.getCommentsInside(node).length);
75001 }
75002 /**
75003 * Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count.
75004 * @param {ASTNode} node The node to check.
75005 * @returns {boolean} `true` if the node is parenthesized.
75006 * @private
75007 */
75008
75009
75010 function isParenthesized(node) {
75011 return eslintUtils.isParenthesized(1, node, sourceCode);
75012 }
75013 /**
75014 * Determines whether the given node needs to be parenthesized when replacing the previous node.
75015 * It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list
75016 * of possible parent node types. By the same assumption, the node's role in a particular parent is already known.
75017 * For example, if the parent is `ConditionalExpression`, `previousNode` must be its `test` child.
75018 * @param {ASTNode} previousNode Previous node.
75019 * @param {ASTNode} node The node to check.
75020 * @returns {boolean} `true` if the node needs to be parenthesized.
75021 */
75022
75023
75024 function needsParens(previousNode, node) {
75025 if (isParenthesized(previousNode)) {
75026 // parentheses around the previous node will stay, so there is no need for an additional pair
75027 return false;
75028 } // parent of the previous node will become parent of the replacement node
75029
75030
75031 const parent = previousNode.parent;
75032
75033 switch (parent.type) {
75034 case "CallExpression":
75035 case "NewExpression":
75036 return node.type === "SequenceExpression";
75037
75038 case "IfStatement":
75039 case "DoWhileStatement":
75040 case "WhileStatement":
75041 case "ForStatement":
75042 return false;
75043
75044 case "ConditionalExpression":
75045 return precedence(node) <= precedence(parent);
75046
75047 case "UnaryExpression":
75048 return precedence(node) < precedence(parent);
75049
75050 case "LogicalExpression":
75051 if (previousNode === parent.left) {
75052 return precedence(node) < precedence(parent);
75053 }
75054
75055 return precedence(node) <= precedence(parent);
75056
75057 /* istanbul ignore next */
75058
75059 default:
75060 throw new Error("Unexpected parent type: ".concat(parent.type));
75061 }
75062 }
75063
75064 return {
75065 UnaryExpression(node) {
75066 const parent = node.parent; // Exit early if it's guaranteed not to match
75067
75068 if (node.operator !== "!" || parent.type !== "UnaryExpression" || parent.operator !== "!") {
75069 return;
75070 }
75071
75072 if (isInFlaggedContext(parent)) {
75073 context.report({
75074 node: parent,
75075 messageId: "unexpectedNegation",
75076
75077 fix(fixer) {
75078 if (hasCommentsInside(parent)) {
75079 return null;
75080 }
75081
75082 if (needsParens(parent, node.argument)) {
75083 return fixer.replaceText(parent, "(".concat(sourceCode.getText(node.argument), ")"));
75084 }
75085
75086 let prefix = "";
75087 const tokenBefore = sourceCode.getTokenBefore(parent);
75088 const firstReplacementToken = sourceCode.getFirstToken(node.argument);
75089
75090 if (tokenBefore && tokenBefore.range[1] === parent.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)) {
75091 prefix = " ";
75092 }
75093
75094 return fixer.replaceText(parent, prefix + sourceCode.getText(node.argument));
75095 }
75096
75097 });
75098 }
75099 },
75100
75101 CallExpression(node) {
75102 if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") {
75103 return;
75104 }
75105
75106 if (isInFlaggedContext(node)) {
75107 context.report({
75108 node,
75109 messageId: "unexpectedCall",
75110
75111 fix(fixer) {
75112 const parent = node.parent;
75113
75114 if (node.arguments.length === 0) {
75115 if (parent.type === "UnaryExpression" && parent.operator === "!") {
75116 /*
75117 * !Boolean() -> true
75118 */
75119 if (hasCommentsInside(parent)) {
75120 return null;
75121 }
75122
75123 const replacement = "true";
75124 let prefix = "";
75125 const tokenBefore = sourceCode.getTokenBefore(parent);
75126
75127 if (tokenBefore && tokenBefore.range[1] === parent.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, replacement)) {
75128 prefix = " ";
75129 }
75130
75131 return fixer.replaceText(parent, prefix + replacement);
75132 }
75133 /*
75134 * Boolean() -> false
75135 */
75136
75137
75138 if (hasCommentsInside(node)) {
75139 return null;
75140 }
75141
75142 return fixer.replaceText(node, "false");
75143 }
75144
75145 if (node.arguments.length === 1) {
75146 const argument = node.arguments[0];
75147
75148 if (argument.type === "SpreadElement" || hasCommentsInside(node)) {
75149 return null;
75150 }
75151 /*
75152 * Boolean(expression) -> expression
75153 */
75154
75155
75156 if (needsParens(node, argument)) {
75157 return fixer.replaceText(node, "(".concat(sourceCode.getText(argument), ")"));
75158 }
75159
75160 return fixer.replaceText(node, sourceCode.getText(argument));
75161 } // two or more arguments
75162
75163
75164 return null;
75165 }
75166
75167 });
75168 }
75169 }
75170
75171 };
75172 }
75173
75174};
75175
75176/***/ }),
75177/* 549 */
75178/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) {
75179
75180"use strict";
75181__webpack_require__.r(__webpack_exports__);
75182/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CALL", function() { return CALL; });
75183/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CONSTRUCT", function() { return CONSTRUCT; });
75184/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ESM", function() { return ESM; });
75185/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PatternMatcher", function() { return PatternMatcher; });
75186/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "READ", function() { return READ; });
75187/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferenceTracker", function() { return ReferenceTracker; });
75188/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findVariable", function() { return findVariable; });
75189/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFunctionHeadLocation", function() { return getFunctionHeadLocation; });
75190/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFunctionNameWithKind", function() { return getFunctionNameWithKind; });
75191/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getInnermostScope", function() { return getInnermostScope; });
75192/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPropertyName", function() { return getPropertyName; });
75193/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStaticValue", function() { return getStaticValue; });
75194/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStringIfConstant", function() { return getStringIfConstant; });
75195/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasSideEffect", function() { return hasSideEffect; });
75196/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArrowToken", function() { return isArrowToken; });
75197/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isClosingBraceToken", function() { return isClosingBraceToken; });
75198/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isClosingBracketToken", function() { return isClosingBracketToken; });
75199/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isClosingParenToken", function() { return isClosingParenToken; });
75200/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isColonToken", function() { return isColonToken; });
75201/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCommaToken", function() { return isCommaToken; });
75202/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCommentToken", function() { return isCommentToken; });
75203/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotArrowToken", function() { return isNotArrowToken; });
75204/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotClosingBraceToken", function() { return isNotClosingBraceToken; });
75205/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotClosingBracketToken", function() { return isNotClosingBracketToken; });
75206/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotClosingParenToken", function() { return isNotClosingParenToken; });
75207/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotColonToken", function() { return isNotColonToken; });
75208/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotCommaToken", function() { return isNotCommaToken; });
75209/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotCommentToken", function() { return isNotCommentToken; });
75210/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotOpeningBraceToken", function() { return isNotOpeningBraceToken; });
75211/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotOpeningBracketToken", function() { return isNotOpeningBracketToken; });
75212/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotOpeningParenToken", function() { return isNotOpeningParenToken; });
75213/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNotSemicolonToken", function() { return isNotSemicolonToken; });
75214/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOpeningBraceToken", function() { return isOpeningBraceToken; });
75215/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOpeningBracketToken", function() { return isOpeningBracketToken; });
75216/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isOpeningParenToken", function() { return isOpeningParenToken; });
75217/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isParenthesized", function() { return isParenthesized; });
75218/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSemicolonToken", function() { return isSemicolonToken; });
75219/* harmony import */ var eslint_visitor_keys__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(392);
75220/*! @author Toru Nagashima <https://github.com/mysticatea> */
75221
75222/**
75223 * Get the innermost scope which contains a given location.
75224 * @param {Scope} initialScope The initial scope to search.
75225 * @param {Node} node The location to search.
75226 * @returns {Scope} The innermost scope.
75227 */
75228
75229function getInnermostScope(initialScope, node) {
75230 const location = node.range[0];
75231 let scope = initialScope;
75232 let found = false;
75233
75234 do {
75235 found = false;
75236
75237 for (const childScope of scope.childScopes) {
75238 const range = childScope.block.range;
75239
75240 if (range[0] <= location && location < range[1]) {
75241 scope = childScope;
75242 found = true;
75243 break;
75244 }
75245 }
75246 } while (found);
75247
75248 return scope;
75249}
75250/**
75251 * Find the variable of a given name.
75252 * @param {Scope} initialScope The scope to start finding.
75253 * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
75254 * @returns {Variable|null} The found variable or null.
75255 */
75256
75257
75258function findVariable(initialScope, nameOrNode) {
75259 let name = "";
75260 let scope = initialScope;
75261
75262 if (typeof nameOrNode === "string") {
75263 name = nameOrNode;
75264 } else {
75265 name = nameOrNode.name;
75266 scope = getInnermostScope(scope, nameOrNode);
75267 }
75268
75269 while (scope != null) {
75270 const variable = scope.set.get(name);
75271
75272 if (variable != null) {
75273 return variable;
75274 }
75275
75276 scope = scope.upper;
75277 }
75278
75279 return null;
75280}
75281/**
75282 * Negate the result of `this` calling.
75283 * @param {Token} token The token to check.
75284 * @returns {boolean} `true` if the result of `this(token)` is `false`.
75285 */
75286
75287
75288function negate0(token) {
75289 return !this(token); //eslint-disable-line no-invalid-this
75290}
75291/**
75292 * Creates the negate function of the given function.
75293 * @param {function(Token):boolean} f - The function to negate.
75294 * @returns {function(Token):boolean} Negated function.
75295 */
75296
75297
75298function negate(f) {
75299 return negate0.bind(f);
75300}
75301/**
75302 * Checks if the given token is an arrow token or not.
75303 * @param {Token} token - The token to check.
75304 * @returns {boolean} `true` if the token is an arrow token.
75305 */
75306
75307
75308function isArrowToken(token) {
75309 return token.value === "=>" && token.type === "Punctuator";
75310}
75311/**
75312 * Checks if the given token is a comma token or not.
75313 * @param {Token} token - The token to check.
75314 * @returns {boolean} `true` if the token is a comma token.
75315 */
75316
75317
75318function isCommaToken(token) {
75319 return token.value === "," && token.type === "Punctuator";
75320}
75321/**
75322 * Checks if the given token is a semicolon token or not.
75323 * @param {Token} token - The token to check.
75324 * @returns {boolean} `true` if the token is a semicolon token.
75325 */
75326
75327
75328function isSemicolonToken(token) {
75329 return token.value === ";" && token.type === "Punctuator";
75330}
75331/**
75332 * Checks if the given token is a colon token or not.
75333 * @param {Token} token - The token to check.
75334 * @returns {boolean} `true` if the token is a colon token.
75335 */
75336
75337
75338function isColonToken(token) {
75339 return token.value === ":" && token.type === "Punctuator";
75340}
75341/**
75342 * Checks if the given token is an opening parenthesis token or not.
75343 * @param {Token} token - The token to check.
75344 * @returns {boolean} `true` if the token is an opening parenthesis token.
75345 */
75346
75347
75348function isOpeningParenToken(token) {
75349 return token.value === "(" && token.type === "Punctuator";
75350}
75351/**
75352 * Checks if the given token is a closing parenthesis token or not.
75353 * @param {Token} token - The token to check.
75354 * @returns {boolean} `true` if the token is a closing parenthesis token.
75355 */
75356
75357
75358function isClosingParenToken(token) {
75359 return token.value === ")" && token.type === "Punctuator";
75360}
75361/**
75362 * Checks if the given token is an opening square bracket token or not.
75363 * @param {Token} token - The token to check.
75364 * @returns {boolean} `true` if the token is an opening square bracket token.
75365 */
75366
75367
75368function isOpeningBracketToken(token) {
75369 return token.value === "[" && token.type === "Punctuator";
75370}
75371/**
75372 * Checks if the given token is a closing square bracket token or not.
75373 * @param {Token} token - The token to check.
75374 * @returns {boolean} `true` if the token is a closing square bracket token.
75375 */
75376
75377
75378function isClosingBracketToken(token) {
75379 return token.value === "]" && token.type === "Punctuator";
75380}
75381/**
75382 * Checks if the given token is an opening brace token or not.
75383 * @param {Token} token - The token to check.
75384 * @returns {boolean} `true` if the token is an opening brace token.
75385 */
75386
75387
75388function isOpeningBraceToken(token) {
75389 return token.value === "{" && token.type === "Punctuator";
75390}
75391/**
75392 * Checks if the given token is a closing brace token or not.
75393 * @param {Token} token - The token to check.
75394 * @returns {boolean} `true` if the token is a closing brace token.
75395 */
75396
75397
75398function isClosingBraceToken(token) {
75399 return token.value === "}" && token.type === "Punctuator";
75400}
75401/**
75402 * Checks if the given token is a comment token or not.
75403 * @param {Token} token - The token to check.
75404 * @returns {boolean} `true` if the token is a comment token.
75405 */
75406
75407
75408function isCommentToken(token) {
75409 return token.type === "Line" || token.type === "Block" || token.type === "Shebang";
75410}
75411
75412const isNotArrowToken = negate(isArrowToken);
75413const isNotCommaToken = negate(isCommaToken);
75414const isNotSemicolonToken = negate(isSemicolonToken);
75415const isNotColonToken = negate(isColonToken);
75416const isNotOpeningParenToken = negate(isOpeningParenToken);
75417const isNotClosingParenToken = negate(isClosingParenToken);
75418const isNotOpeningBracketToken = negate(isOpeningBracketToken);
75419const isNotClosingBracketToken = negate(isClosingBracketToken);
75420const isNotOpeningBraceToken = negate(isOpeningBraceToken);
75421const isNotClosingBraceToken = negate(isClosingBraceToken);
75422const isNotCommentToken = negate(isCommentToken);
75423/**
75424 * Get the `(` token of the given function node.
75425 * @param {Node} node - The function node to get.
75426 * @param {SourceCode} sourceCode - The source code object to get tokens.
75427 * @returns {Token} `(` token.
75428 */
75429
75430function getOpeningParenOfParams(node, sourceCode) {
75431 return node.id ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) : sourceCode.getFirstToken(node, isOpeningParenToken);
75432}
75433/**
75434 * Get the location of the given function node for reporting.
75435 * @param {Node} node - The function node to get.
75436 * @param {SourceCode} sourceCode - The source code object to get tokens.
75437 * @returns {string} The location of the function node for reporting.
75438 */
75439
75440
75441function getFunctionHeadLocation(node, sourceCode) {
75442 const parent = node.parent;
75443 let start = null;
75444 let end = null;
75445
75446 if (node.type === "ArrowFunctionExpression") {
75447 const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
75448 start = arrowToken.loc.start;
75449 end = arrowToken.loc.end;
75450 } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
75451 start = parent.loc.start;
75452 end = getOpeningParenOfParams(node, sourceCode).loc.start;
75453 } else {
75454 start = node.loc.start;
75455 end = getOpeningParenOfParams(node, sourceCode).loc.start;
75456 }
75457
75458 return {
75459 start: Object.assign({}, start),
75460 end: Object.assign({}, end)
75461 };
75462}
75463/* globals BigInt, globalThis, global, self, window */
75464
75465
75466const globalObject = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
75467const builtinNames = Object.freeze(new Set(["Array", "ArrayBuffer", "BigInt", "BigInt64Array", "BigUint64Array", "Boolean", "DataView", "Date", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "escape", "Float32Array", "Float64Array", "Function", "Infinity", "Int16Array", "Int32Array", "Int8Array", "isFinite", "isNaN", "isPrototypeOf", "JSON", "Map", "Math", "NaN", "Number", "Object", "parseFloat", "parseInt", "Promise", "Proxy", "Reflect", "RegExp", "Set", "String", "Symbol", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "undefined", "unescape", "WeakMap", "WeakSet"]));
75468const callAllowed = new Set([Array.isArray, typeof BigInt === "function" ? BigInt : undefined, Boolean, Date, Date.parse, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, isFinite, isNaN, isPrototypeOf, ...Object.getOwnPropertyNames(Math).map(k => Math[k]).filter(f => typeof f === "function"), Number, Number.isFinite, Number.isNaN, Number.parseFloat, Number.parseInt, Object, Object.entries, Object.is, Object.isExtensible, Object.isFrozen, Object.isSealed, Object.keys, Object.values, parseFloat, parseInt, RegExp, String, String.fromCharCode, String.fromCodePoint, String.raw, Symbol, Symbol.for, Symbol.keyFor, unescape].filter(f => typeof f === "function"));
75469const callPassThrough = new Set([Object.freeze, Object.preventExtensions, Object.seal]);
75470/**
75471 * Get the property descriptor.
75472 * @param {object} object The object to get.
75473 * @param {string|number|symbol} name The property name to get.
75474 */
75475
75476function getPropertyDescriptor(object, name) {
75477 let x = object;
75478
75479 while ((typeof x === "object" || typeof x === "function") && x !== null) {
75480 const d = Object.getOwnPropertyDescriptor(x, name);
75481
75482 if (d) {
75483 return d;
75484 }
75485
75486 x = Object.getPrototypeOf(x);
75487 }
75488
75489 return null;
75490}
75491/**
75492 * Check if a property is getter or not.
75493 * @param {object} object The object to check.
75494 * @param {string|number|symbol} name The property name to check.
75495 */
75496
75497
75498function isGetter(object, name) {
75499 const d = getPropertyDescriptor(object, name);
75500 return d != null && d.get != null;
75501}
75502/**
75503 * Get the element values of a given node list.
75504 * @param {Node[]} nodeList The node list to get values.
75505 * @param {Scope|undefined} initialScope The initial scope to find variables.
75506 * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
75507 */
75508
75509
75510function getElementValues(nodeList, initialScope) {
75511 const valueList = [];
75512
75513 for (let i = 0; i < nodeList.length; ++i) {
75514 const elementNode = nodeList[i];
75515
75516 if (elementNode == null) {
75517 valueList.length = i + 1;
75518 } else if (elementNode.type === "SpreadElement") {
75519 const argument = getStaticValueR(elementNode.argument, initialScope);
75520
75521 if (argument == null) {
75522 return null;
75523 }
75524
75525 valueList.push(...argument.value);
75526 } else {
75527 const element = getStaticValueR(elementNode, initialScope);
75528
75529 if (element == null) {
75530 return null;
75531 }
75532
75533 valueList.push(element.value);
75534 }
75535 }
75536
75537 return valueList;
75538}
75539
75540const operations = Object.freeze({
75541 ArrayExpression(node, initialScope) {
75542 const elements = getElementValues(node.elements, initialScope);
75543 return elements != null ? {
75544 value: elements
75545 } : null;
75546 },
75547
75548 AssignmentExpression(node, initialScope) {
75549 if (node.operator === "=") {
75550 return getStaticValueR(node.right, initialScope);
75551 }
75552
75553 return null;
75554 },
75555
75556 //eslint-disable-next-line complexity
75557 BinaryExpression(node, initialScope) {
75558 if (node.operator === "in" || node.operator === "instanceof") {
75559 // Not supported.
75560 return null;
75561 }
75562
75563 const left = getStaticValueR(node.left, initialScope);
75564 const right = getStaticValueR(node.right, initialScope);
75565
75566 if (left != null && right != null) {
75567 switch (node.operator) {
75568 case "==":
75569 return {
75570 value: left.value == right.value
75571 };
75572 //eslint-disable-line eqeqeq
75573
75574 case "!=":
75575 return {
75576 value: left.value != right.value
75577 };
75578 //eslint-disable-line eqeqeq
75579
75580 case "===":
75581 return {
75582 value: left.value === right.value
75583 };
75584
75585 case "!==":
75586 return {
75587 value: left.value !== right.value
75588 };
75589
75590 case "<":
75591 return {
75592 value: left.value < right.value
75593 };
75594
75595 case "<=":
75596 return {
75597 value: left.value <= right.value
75598 };
75599
75600 case ">":
75601 return {
75602 value: left.value > right.value
75603 };
75604
75605 case ">=":
75606 return {
75607 value: left.value >= right.value
75608 };
75609
75610 case "<<":
75611 return {
75612 value: left.value << right.value
75613 };
75614
75615 case ">>":
75616 return {
75617 value: left.value >> right.value
75618 };
75619
75620 case ">>>":
75621 return {
75622 value: left.value >>> right.value
75623 };
75624
75625 case "+":
75626 return {
75627 value: left.value + right.value
75628 };
75629
75630 case "-":
75631 return {
75632 value: left.value - right.value
75633 };
75634
75635 case "*":
75636 return {
75637 value: left.value * right.value
75638 };
75639
75640 case "/":
75641 return {
75642 value: left.value / right.value
75643 };
75644
75645 case "%":
75646 return {
75647 value: left.value % right.value
75648 };
75649
75650 case "**":
75651 return {
75652 value: Math.pow(left.value, right.value)
75653 };
75654
75655 case "|":
75656 return {
75657 value: left.value | right.value
75658 };
75659
75660 case "^":
75661 return {
75662 value: left.value ^ right.value
75663 };
75664
75665 case "&":
75666 return {
75667 value: left.value & right.value
75668 };
75669 // no default
75670 }
75671 }
75672
75673 return null;
75674 },
75675
75676 CallExpression(node, initialScope) {
75677 const calleeNode = node.callee;
75678 const args = getElementValues(node.arguments, initialScope);
75679
75680 if (args != null) {
75681 if (calleeNode.type === "MemberExpression") {
75682 const object = getStaticValueR(calleeNode.object, initialScope);
75683 const property = calleeNode.computed ? getStaticValueR(calleeNode.property, initialScope) : {
75684 value: calleeNode.property.name
75685 };
75686
75687 if (object != null && property != null) {
75688 const receiver = object.value;
75689 const methodName = property.value;
75690
75691 if (callAllowed.has(receiver[methodName])) {
75692 return {
75693 value: receiver[methodName](...args)
75694 };
75695 }
75696
75697 if (callPassThrough.has(receiver[methodName])) {
75698 return {
75699 value: args[0]
75700 };
75701 }
75702 }
75703 } else {
75704 const callee = getStaticValueR(calleeNode, initialScope);
75705
75706 if (callee != null) {
75707 const func = callee.value;
75708
75709 if (callAllowed.has(func)) {
75710 return {
75711 value: func(...args)
75712 };
75713 }
75714
75715 if (callPassThrough.has(func)) {
75716 return {
75717 value: args[0]
75718 };
75719 }
75720 }
75721 }
75722 }
75723
75724 return null;
75725 },
75726
75727 ConditionalExpression(node, initialScope) {
75728 const test = getStaticValueR(node.test, initialScope);
75729
75730 if (test != null) {
75731 return test.value ? getStaticValueR(node.consequent, initialScope) : getStaticValueR(node.alternate, initialScope);
75732 }
75733
75734 return null;
75735 },
75736
75737 ExpressionStatement(node, initialScope) {
75738 return getStaticValueR(node.expression, initialScope);
75739 },
75740
75741 Identifier(node, initialScope) {
75742 if (initialScope != null) {
75743 const variable = findVariable(initialScope, node); // Built-in globals.
75744
75745 if (variable != null && variable.defs.length === 0 && builtinNames.has(variable.name) && variable.name in globalObject) {
75746 return {
75747 value: globalObject[variable.name]
75748 };
75749 } // Constants.
75750
75751
75752 if (variable != null && variable.defs.length === 1) {
75753 const def = variable.defs[0];
75754
75755 if (def.parent && def.parent.kind === "const" && // TODO(mysticatea): don't support destructuring here.
75756 def.node.id.type === "Identifier") {
75757 return getStaticValueR(def.node.init, initialScope);
75758 }
75759 }
75760 }
75761
75762 return null;
75763 },
75764
75765 Literal(node) {
75766 //istanbul ignore if : this is implementation-specific behavior.
75767 if ((node.regex != null || node.bigint != null) && node.value == null) {
75768 // It was a RegExp/BigInt literal, but Node.js didn't support it.
75769 return null;
75770 }
75771
75772 return {
75773 value: node.value
75774 };
75775 },
75776
75777 LogicalExpression(node, initialScope) {
75778 const left = getStaticValueR(node.left, initialScope);
75779
75780 if (left != null) {
75781 if (node.operator === "||" && Boolean(left.value) === true || node.operator === "&&" && Boolean(left.value) === false) {
75782 return left;
75783 }
75784
75785 const right = getStaticValueR(node.right, initialScope);
75786
75787 if (right != null) {
75788 return right;
75789 }
75790 }
75791
75792 return null;
75793 },
75794
75795 MemberExpression(node, initialScope) {
75796 const object = getStaticValueR(node.object, initialScope);
75797 const property = node.computed ? getStaticValueR(node.property, initialScope) : {
75798 value: node.property.name
75799 };
75800
75801 if (object != null && property != null && !isGetter(object.value, property.value)) {
75802 return {
75803 value: object.value[property.value]
75804 };
75805 }
75806
75807 return null;
75808 },
75809
75810 NewExpression(node, initialScope) {
75811 const callee = getStaticValueR(node.callee, initialScope);
75812 const args = getElementValues(node.arguments, initialScope);
75813
75814 if (callee != null && args != null) {
75815 const Func = callee.value;
75816
75817 if (callAllowed.has(Func)) {
75818 return {
75819 value: new Func(...args)
75820 };
75821 }
75822 }
75823
75824 return null;
75825 },
75826
75827 ObjectExpression(node, initialScope) {
75828 const object = {};
75829
75830 for (const propertyNode of node.properties) {
75831 if (propertyNode.type === "Property") {
75832 if (propertyNode.kind !== "init") {
75833 return null;
75834 }
75835
75836 const key = propertyNode.computed ? getStaticValueR(propertyNode.key, initialScope) : {
75837 value: propertyNode.key.name
75838 };
75839 const value = getStaticValueR(propertyNode.value, initialScope);
75840
75841 if (key == null || value == null) {
75842 return null;
75843 }
75844
75845 object[key.value] = value.value;
75846 } else if (propertyNode.type === "SpreadElement" || propertyNode.type === "ExperimentalSpreadProperty") {
75847 const argument = getStaticValueR(propertyNode.argument, initialScope);
75848
75849 if (argument == null) {
75850 return null;
75851 }
75852
75853 Object.assign(object, argument.value);
75854 } else {
75855 return null;
75856 }
75857 }
75858
75859 return {
75860 value: object
75861 };
75862 },
75863
75864 SequenceExpression(node, initialScope) {
75865 const last = node.expressions[node.expressions.length - 1];
75866 return getStaticValueR(last, initialScope);
75867 },
75868
75869 TaggedTemplateExpression(node, initialScope) {
75870 const tag = getStaticValueR(node.tag, initialScope);
75871 const expressions = getElementValues(node.quasi.expressions, initialScope);
75872
75873 if (tag != null && expressions != null) {
75874 const func = tag.value;
75875 const strings = node.quasi.quasis.map(q => q.value.cooked);
75876 strings.raw = node.quasi.quasis.map(q => q.value.raw);
75877
75878 if (func === String.raw) {
75879 return {
75880 value: func(strings, ...expressions)
75881 };
75882 }
75883 }
75884
75885 return null;
75886 },
75887
75888 TemplateLiteral(node, initialScope) {
75889 const expressions = getElementValues(node.expressions, initialScope);
75890
75891 if (expressions != null) {
75892 let value = node.quasis[0].value.cooked;
75893
75894 for (let i = 0; i < expressions.length; ++i) {
75895 value += expressions[i];
75896 value += node.quasis[i + 1].value.cooked;
75897 }
75898
75899 return {
75900 value
75901 };
75902 }
75903
75904 return null;
75905 },
75906
75907 UnaryExpression(node, initialScope) {
75908 if (node.operator === "delete") {
75909 // Not supported.
75910 return null;
75911 }
75912
75913 if (node.operator === "void") {
75914 return {
75915 value: undefined
75916 };
75917 }
75918
75919 const arg = getStaticValueR(node.argument, initialScope);
75920
75921 if (arg != null) {
75922 switch (node.operator) {
75923 case "-":
75924 return {
75925 value: -arg.value
75926 };
75927
75928 case "+":
75929 return {
75930 value: +arg.value
75931 };
75932 //eslint-disable-line no-implicit-coercion
75933
75934 case "!":
75935 return {
75936 value: !arg.value
75937 };
75938
75939 case "~":
75940 return {
75941 value: ~arg.value
75942 };
75943
75944 case "typeof":
75945 return {
75946 value: typeof arg.value
75947 };
75948 // no default
75949 }
75950 }
75951
75952 return null;
75953 }
75954
75955});
75956/**
75957 * Get the value of a given node if it's a static value.
75958 * @param {Node} node The node to get.
75959 * @param {Scope|undefined} initialScope The scope to start finding variable.
75960 * @returns {{value:any}|null} The static value of the node, or `null`.
75961 */
75962
75963function getStaticValueR(node, initialScope) {
75964 if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
75965 return operations[node.type](node, initialScope);
75966 }
75967
75968 return null;
75969}
75970/**
75971 * Get the value of a given node if it's a static value.
75972 * @param {Node} node The node to get.
75973 * @param {Scope} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
75974 * @returns {{value:any}|null} The static value of the node, or `null`.
75975 */
75976
75977
75978function getStaticValue(node, initialScope = null) {
75979 try {
75980 return getStaticValueR(node, initialScope);
75981 } catch (_error) {
75982 return null;
75983 }
75984}
75985/**
75986 * Get the value of a given node if it's a literal or a template literal.
75987 * @param {Node} node The node to get.
75988 * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
75989 * @returns {string|null} The value of the node, or `null`.
75990 */
75991
75992
75993function getStringIfConstant(node, initialScope = null) {
75994 // Handle the literals that the platform doesn't support natively.
75995 if (node && node.type === "Literal" && node.value === null) {
75996 if (node.regex) {
75997 return "/".concat(node.regex.pattern, "/").concat(node.regex.flags);
75998 }
75999
76000 if (node.bigint) {
76001 return node.bigint;
76002 }
76003 }
76004
76005 const evaluated = getStaticValue(node, initialScope);
76006 return evaluated && String(evaluated.value);
76007}
76008/**
76009 * Get the property name from a MemberExpression node or a Property node.
76010 * @param {Node} node The node to get.
76011 * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
76012 * @returns {string|null} The property name of the node.
76013 */
76014
76015
76016function getPropertyName(node, initialScope) {
76017 switch (node.type) {
76018 case "MemberExpression":
76019 if (node.computed) {
76020 return getStringIfConstant(node.property, initialScope);
76021 }
76022
76023 return node.property.name;
76024
76025 case "Property":
76026 case "MethodDefinition":
76027 if (node.computed) {
76028 return getStringIfConstant(node.key, initialScope);
76029 }
76030
76031 if (node.key.type === "Literal") {
76032 return String(node.key.value);
76033 }
76034
76035 return node.key.name;
76036 // no default
76037 }
76038
76039 return null;
76040}
76041/**
76042 * Get the name and kind of the given function node.
76043 * @param {ASTNode} node - The function node to get.
76044 * @returns {string} The name and kind of the function node.
76045 */
76046
76047
76048function getFunctionNameWithKind(node) {
76049 const parent = node.parent;
76050 const tokens = [];
76051
76052 if (parent.type === "MethodDefinition" && parent.static) {
76053 tokens.push("static");
76054 }
76055
76056 if (node.async) {
76057 tokens.push("async");
76058 }
76059
76060 if (node.generator) {
76061 tokens.push("generator");
76062 }
76063
76064 if (node.type === "ArrowFunctionExpression") {
76065 tokens.push("arrow", "function");
76066 } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
76067 if (parent.kind === "constructor") {
76068 return "constructor";
76069 }
76070
76071 if (parent.kind === "get") {
76072 tokens.push("getter");
76073 } else if (parent.kind === "set") {
76074 tokens.push("setter");
76075 } else {
76076 tokens.push("method");
76077 }
76078 } else {
76079 tokens.push("function");
76080 }
76081
76082 if (node.id) {
76083 tokens.push("'".concat(node.id.name, "'"));
76084 } else {
76085 const name = getPropertyName(parent);
76086
76087 if (name) {
76088 tokens.push("'".concat(name, "'"));
76089 }
76090 }
76091
76092 return tokens.join(" ");
76093}
76094
76095const typeConversionBinaryOps = Object.freeze(new Set(["==", "!=", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "|", "^", "&", "in"]));
76096const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
76097const visitor = Object.freeze(Object.assign(Object.create(null), {
76098 $visit(node, options, visitorKeys) {
76099 const {
76100 type
76101 } = node;
76102
76103 if (typeof this[type] === "function") {
76104 return this[type](node, options, visitorKeys);
76105 }
76106
76107 return this.$visitChildren(node, options, visitorKeys);
76108 },
76109
76110 $visitChildren(node, options, visitorKeys) {
76111 const {
76112 type
76113 } = node;
76114
76115 for (const key of visitorKeys[type] || eslint_visitor_keys__WEBPACK_IMPORTED_MODULE_0__.getKeys(node)) {
76116 const value = node[key];
76117
76118 if (Array.isArray(value)) {
76119 for (const element of value) {
76120 if (element && this.$visit(element, options, visitorKeys)) {
76121 return true;
76122 }
76123 }
76124 } else if (value && this.$visit(value, options, visitorKeys)) {
76125 return true;
76126 }
76127 }
76128
76129 return false;
76130 },
76131
76132 ArrowFunctionExpression() {
76133 return false;
76134 },
76135
76136 AssignmentExpression() {
76137 return true;
76138 },
76139
76140 AwaitExpression() {
76141 return true;
76142 },
76143
76144 BinaryExpression(node, options, visitorKeys) {
76145 if (options.considerImplicitTypeConversion && typeConversionBinaryOps.has(node.operator) && (node.left.type !== "Literal" || node.right.type !== "Literal")) {
76146 return true;
76147 }
76148
76149 return this.$visitChildren(node, options, visitorKeys);
76150 },
76151
76152 CallExpression() {
76153 return true;
76154 },
76155
76156 FunctionExpression() {
76157 return false;
76158 },
76159
76160 ImportExpression() {
76161 return true;
76162 },
76163
76164 MemberExpression(node, options, visitorKeys) {
76165 if (options.considerGetters) {
76166 return true;
76167 }
76168
76169 if (options.considerImplicitTypeConversion && node.computed && node.property.type !== "Literal") {
76170 return true;
76171 }
76172
76173 return this.$visitChildren(node, options, visitorKeys);
76174 },
76175
76176 MethodDefinition(node, options, visitorKeys) {
76177 if (options.considerImplicitTypeConversion && node.computed && node.key.type !== "Literal") {
76178 return true;
76179 }
76180
76181 return this.$visitChildren(node, options, visitorKeys);
76182 },
76183
76184 NewExpression() {
76185 return true;
76186 },
76187
76188 Property(node, options, visitorKeys) {
76189 if (options.considerImplicitTypeConversion && node.computed && node.key.type !== "Literal") {
76190 return true;
76191 }
76192
76193 return this.$visitChildren(node, options, visitorKeys);
76194 },
76195
76196 UnaryExpression(node, options, visitorKeys) {
76197 if (node.operator === "delete") {
76198 return true;
76199 }
76200
76201 if (options.considerImplicitTypeConversion && typeConversionUnaryOps.has(node.operator) && node.argument.type !== "Literal") {
76202 return true;
76203 }
76204
76205 return this.$visitChildren(node, options, visitorKeys);
76206 },
76207
76208 UpdateExpression() {
76209 return true;
76210 },
76211
76212 YieldExpression() {
76213 return true;
76214 }
76215
76216}));
76217/**
76218 * Check whether a given node has any side effect or not.
76219 * @param {Node} node The node to get.
76220 * @param {SourceCode} sourceCode The source code object.
76221 * @param {object} [options] The option object.
76222 * @param {boolean} [options.considerGetters=false] If `true` then it considers member accesses as the node which has side effects.
76223 * @param {boolean} [options.considerImplicitTypeConversion=false] If `true` then it considers implicit type conversion as the node which has side effects.
76224 * @param {object} [options.visitorKeys=evk.KEYS] The keys to traverse nodes. Use `context.getSourceCode().visitorKeys`.
76225 * @returns {boolean} `true` if the node has a certain side effect.
76226 */
76227
76228function hasSideEffect(node, sourceCode, {
76229 considerGetters = false,
76230 considerImplicitTypeConversion = false
76231} = {}) {
76232 return visitor.$visit(node, {
76233 considerGetters,
76234 considerImplicitTypeConversion
76235 }, sourceCode.visitorKeys || eslint_visitor_keys__WEBPACK_IMPORTED_MODULE_0__.KEYS);
76236}
76237/**
76238 * Get the left parenthesis of the parent node syntax if it exists.
76239 * E.g., `if (a) {}` then the `(`.
76240 * @param {Node} node The AST node to check.
76241 * @param {SourceCode} sourceCode The source code object to get tokens.
76242 * @returns {Token|null} The left parenthesis of the parent node syntax
76243 */
76244
76245
76246function getParentSyntaxParen(node, sourceCode) {
76247 const parent = node.parent;
76248
76249 switch (parent.type) {
76250 case "CallExpression":
76251 case "NewExpression":
76252 if (parent.arguments.length === 1 && parent.arguments[0] === node) {
76253 return sourceCode.getTokenAfter(parent.callee, isOpeningParenToken);
76254 }
76255
76256 return null;
76257
76258 case "DoWhileStatement":
76259 if (parent.test === node) {
76260 return sourceCode.getTokenAfter(parent.body, isOpeningParenToken);
76261 }
76262
76263 return null;
76264
76265 case "IfStatement":
76266 case "WhileStatement":
76267 if (parent.test === node) {
76268 return sourceCode.getFirstToken(parent, 1);
76269 }
76270
76271 return null;
76272
76273 case "ImportExpression":
76274 if (parent.source === node) {
76275 return sourceCode.getFirstToken(parent, 1);
76276 }
76277
76278 return null;
76279
76280 case "SwitchStatement":
76281 if (parent.discriminant === node) {
76282 return sourceCode.getFirstToken(parent, 1);
76283 }
76284
76285 return null;
76286
76287 case "WithStatement":
76288 if (parent.object === node) {
76289 return sourceCode.getFirstToken(parent, 1);
76290 }
76291
76292 return null;
76293
76294 default:
76295 return null;
76296 }
76297}
76298/**
76299 * Check whether a given node is parenthesized or not.
76300 * @param {number} times The number of parantheses.
76301 * @param {Node} node The AST node to check.
76302 * @param {SourceCode} sourceCode The source code object to get tokens.
76303 * @returns {boolean} `true` if the node is parenthesized the given times.
76304 */
76305
76306/**
76307 * Check whether a given node is parenthesized or not.
76308 * @param {Node} node The AST node to check.
76309 * @param {SourceCode} sourceCode The source code object to get tokens.
76310 * @returns {boolean} `true` if the node is parenthesized.
76311 */
76312
76313
76314function isParenthesized(timesOrNode, nodeOrSourceCode, optionalSourceCode) {
76315 let times, node, sourceCode, maybeLeftParen, maybeRightParen;
76316
76317 if (typeof timesOrNode === "number") {
76318 times = timesOrNode | 0;
76319 node = nodeOrSourceCode;
76320 sourceCode = optionalSourceCode;
76321
76322 if (!(times >= 1)) {
76323 throw new TypeError("'times' should be a positive integer.");
76324 }
76325 } else {
76326 times = 1;
76327 node = timesOrNode;
76328 sourceCode = nodeOrSourceCode;
76329 }
76330
76331 if (node == null) {
76332 return false;
76333 }
76334
76335 maybeLeftParen = maybeRightParen = node;
76336
76337 do {
76338 maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
76339 maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
76340 } while (maybeLeftParen != null && maybeRightParen != null && isOpeningParenToken(maybeLeftParen) && isClosingParenToken(maybeRightParen) && // Avoid false positive such as `if (a) {}`
76341 maybeLeftParen !== getParentSyntaxParen(node, sourceCode) && --times > 0);
76342
76343 return times === 0;
76344}
76345/**
76346 * @author Toru Nagashima <https://github.com/mysticatea>
76347 * See LICENSE file in root directory for full license.
76348 */
76349
76350
76351const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
76352/** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
76353
76354const internal = new WeakMap();
76355/**
76356 * Check whether a given character is escaped or not.
76357 * @param {string} str The string to check.
76358 * @param {number} index The location of the character to check.
76359 * @returns {boolean} `true` if the character is escaped.
76360 */
76361
76362function isEscaped(str, index) {
76363 let escaped = false;
76364
76365 for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
76366 escaped = !escaped;
76367 }
76368
76369 return escaped;
76370}
76371/**
76372 * Replace a given string by a given matcher.
76373 * @param {PatternMatcher} matcher The pattern matcher.
76374 * @param {string} str The string to be replaced.
76375 * @param {string} replacement The new substring to replace each matched part.
76376 * @returns {string} The replaced string.
76377 */
76378
76379
76380function replaceS(matcher, str, replacement) {
76381 const chunks = [];
76382 let index = 0;
76383 /** @type {RegExpExecArray} */
76384
76385 let match = null;
76386 /**
76387 * @param {string} key The placeholder.
76388 * @returns {string} The replaced string.
76389 */
76390
76391 function replacer(key) {
76392 switch (key) {
76393 case "$$":
76394 return "$";
76395
76396 case "$&":
76397 return match[0];
76398
76399 case "$`":
76400 return str.slice(0, match.index);
76401
76402 case "$'":
76403 return str.slice(match.index + match[0].length);
76404
76405 default:
76406 {
76407 const i = key.slice(1);
76408
76409 if (i in match) {
76410 return match[i];
76411 }
76412
76413 return key;
76414 }
76415 }
76416 }
76417
76418 for (match of matcher.execAll(str)) {
76419 chunks.push(str.slice(index, match.index));
76420 chunks.push(replacement.replace(placeholder, replacer));
76421 index = match.index + match[0].length;
76422 }
76423
76424 chunks.push(str.slice(index));
76425 return chunks.join("");
76426}
76427/**
76428 * Replace a given string by a given matcher.
76429 * @param {PatternMatcher} matcher The pattern matcher.
76430 * @param {string} str The string to be replaced.
76431 * @param {(...strs[])=>string} replace The function to replace each matched part.
76432 * @returns {string} The replaced string.
76433 */
76434
76435
76436function replaceF(matcher, str, replace) {
76437 const chunks = [];
76438 let index = 0;
76439
76440 for (const match of matcher.execAll(str)) {
76441 chunks.push(str.slice(index, match.index));
76442 chunks.push(String(replace(...match, match.index, match.input)));
76443 index = match.index + match[0].length;
76444 }
76445
76446 chunks.push(str.slice(index));
76447 return chunks.join("");
76448}
76449/**
76450 * The class to find patterns as considering escape sequences.
76451 */
76452
76453
76454class PatternMatcher {
76455 /**
76456 * Initialize this matcher.
76457 * @param {RegExp} pattern The pattern to match.
76458 * @param {{escaped:boolean}} options The options.
76459 */
76460 constructor(pattern, {
76461 escaped = false
76462 } = {}) {
76463 if (!(pattern instanceof RegExp)) {
76464 throw new TypeError("'pattern' should be a RegExp instance.");
76465 }
76466
76467 if (!pattern.flags.includes("g")) {
76468 throw new Error("'pattern' should contains 'g' flag.");
76469 }
76470
76471 internal.set(this, {
76472 pattern: new RegExp(pattern.source, pattern.flags),
76473 escaped: Boolean(escaped)
76474 });
76475 }
76476 /**
76477 * Find the pattern in a given string.
76478 * @param {string} str The string to find.
76479 * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
76480 */
76481
76482
76483 *execAll(str) {
76484 const {
76485 pattern,
76486 escaped
76487 } = internal.get(this);
76488 let match = null;
76489 let lastIndex = 0;
76490 pattern.lastIndex = 0;
76491
76492 while ((match = pattern.exec(str)) != null) {
76493 if (escaped || !isEscaped(str, match.index)) {
76494 lastIndex = pattern.lastIndex;
76495 yield match;
76496 pattern.lastIndex = lastIndex;
76497 }
76498 }
76499 }
76500 /**
76501 * Check whether the pattern is found in a given string.
76502 * @param {string} str The string to check.
76503 * @returns {boolean} `true` if the pattern was found in the string.
76504 */
76505
76506
76507 test(str) {
76508 const it = this.execAll(str);
76509 const ret = it.next();
76510 return !ret.done;
76511 }
76512 /**
76513 * Replace a given string.
76514 * @param {string} str The string to be replaced.
76515 * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
76516 * @returns {string} The replaced string.
76517 */
76518
76519
76520 [Symbol.replace](str, replacer) {
76521 return typeof replacer === "function" ? replaceF(this, String(str), replacer) : replaceS(this, String(str), String(replacer));
76522 }
76523
76524}
76525
76526const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
76527const has = Function.call.bind(Object.hasOwnProperty);
76528const READ = Symbol("read");
76529const CALL = Symbol("call");
76530const CONSTRUCT = Symbol("construct");
76531const ESM = Symbol("esm");
76532const requireCall = {
76533 require: {
76534 [CALL]: true
76535 }
76536};
76537/**
76538 * Check whether a given variable is modified or not.
76539 * @param {Variable} variable The variable to check.
76540 * @returns {boolean} `true` if the variable is modified.
76541 */
76542
76543function isModifiedGlobal(variable) {
76544 return variable == null || variable.defs.length !== 0 || variable.references.some(r => r.isWrite());
76545}
76546/**
76547 * Check if the value of a given node is passed through to the parent syntax as-is.
76548 * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
76549 * @param {Node} node A node to check.
76550 * @returns {boolean} `true` if the node is passed through.
76551 */
76552
76553
76554function isPassThrough(node) {
76555 const parent = node.parent;
76556
76557 switch (parent && parent.type) {
76558 case "ConditionalExpression":
76559 return parent.consequent === node || parent.alternate === node;
76560
76561 case "LogicalExpression":
76562 return true;
76563
76564 case "SequenceExpression":
76565 return parent.expressions[parent.expressions.length - 1] === node;
76566
76567 default:
76568 return false;
76569 }
76570}
76571/**
76572 * The reference tracker.
76573 */
76574
76575
76576class ReferenceTracker {
76577 /**
76578 * Initialize this tracker.
76579 * @param {Scope} globalScope The global scope.
76580 * @param {object} [options] The options.
76581 * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
76582 * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
76583 */
76584 constructor(globalScope, {
76585 mode = "strict",
76586 globalObjectNames = ["global", "globalThis", "self", "window"]
76587 } = {}) {
76588 this.variableStack = [];
76589 this.globalScope = globalScope;
76590 this.mode = mode;
76591 this.globalObjectNames = globalObjectNames.slice(0);
76592 }
76593 /**
76594 * Iterate the references of global variables.
76595 * @param {object} traceMap The trace map.
76596 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76597 */
76598
76599
76600 *iterateGlobalReferences(traceMap) {
76601 for (const key of Object.keys(traceMap)) {
76602 const nextTraceMap = traceMap[key];
76603 const path = [key];
76604 const variable = this.globalScope.set.get(key);
76605
76606 if (isModifiedGlobal(variable)) {
76607 continue;
76608 }
76609
76610 yield* this._iterateVariableReferences(variable, path, nextTraceMap, true);
76611 }
76612
76613 for (const key of this.globalObjectNames) {
76614 const path = [];
76615 const variable = this.globalScope.set.get(key);
76616
76617 if (isModifiedGlobal(variable)) {
76618 continue;
76619 }
76620
76621 yield* this._iterateVariableReferences(variable, path, traceMap, false);
76622 }
76623 }
76624 /**
76625 * Iterate the references of CommonJS modules.
76626 * @param {object} traceMap The trace map.
76627 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76628 */
76629
76630
76631 *iterateCjsReferences(traceMap) {
76632 for (const {
76633 node
76634 } of this.iterateGlobalReferences(requireCall)) {
76635 const key = getStringIfConstant(node.arguments[0]);
76636
76637 if (key == null || !has(traceMap, key)) {
76638 continue;
76639 }
76640
76641 const nextTraceMap = traceMap[key];
76642 const path = [key];
76643
76644 if (nextTraceMap[READ]) {
76645 yield {
76646 node,
76647 path,
76648 type: READ,
76649 info: nextTraceMap[READ]
76650 };
76651 }
76652
76653 yield* this._iteratePropertyReferences(node, path, nextTraceMap);
76654 }
76655 }
76656 /**
76657 * Iterate the references of ES modules.
76658 * @param {object} traceMap The trace map.
76659 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76660 */
76661
76662
76663 *iterateEsmReferences(traceMap) {
76664 const programNode = this.globalScope.block;
76665
76666 for (const node of programNode.body) {
76667 if (!IMPORT_TYPE.test(node.type) || node.source == null) {
76668 continue;
76669 }
76670
76671 const moduleId = node.source.value;
76672
76673 if (!has(traceMap, moduleId)) {
76674 continue;
76675 }
76676
76677 const nextTraceMap = traceMap[moduleId];
76678 const path = [moduleId];
76679
76680 if (nextTraceMap[READ]) {
76681 yield {
76682 node,
76683 path,
76684 type: READ,
76685 info: nextTraceMap[READ]
76686 };
76687 }
76688
76689 if (node.type === "ExportAllDeclaration") {
76690 for (const key of Object.keys(nextTraceMap)) {
76691 const exportTraceMap = nextTraceMap[key];
76692
76693 if (exportTraceMap[READ]) {
76694 yield {
76695 node,
76696 path: path.concat(key),
76697 type: READ,
76698 info: exportTraceMap[READ]
76699 };
76700 }
76701 }
76702 } else {
76703 for (const specifier of node.specifiers) {
76704 const esm = has(nextTraceMap, ESM);
76705
76706 const it = this._iterateImportReferences(specifier, path, esm ? nextTraceMap : this.mode === "legacy" ? Object.assign({
76707 default: nextTraceMap
76708 }, nextTraceMap) : {
76709 default: nextTraceMap
76710 });
76711
76712 if (esm) {
76713 yield* it;
76714 } else {
76715 for (const report of it) {
76716 report.path = report.path.filter(exceptDefault);
76717
76718 if (report.path.length >= 2 || report.type !== READ) {
76719 yield report;
76720 }
76721 }
76722 }
76723 }
76724 }
76725 }
76726 }
76727 /**
76728 * Iterate the references for a given variable.
76729 * @param {Variable} variable The variable to iterate that references.
76730 * @param {string[]} path The current path.
76731 * @param {object} traceMap The trace map.
76732 * @param {boolean} shouldReport = The flag to report those references.
76733 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76734 */
76735
76736
76737 *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
76738 if (this.variableStack.includes(variable)) {
76739 return;
76740 }
76741
76742 this.variableStack.push(variable);
76743
76744 try {
76745 for (const reference of variable.references) {
76746 if (!reference.isRead()) {
76747 continue;
76748 }
76749
76750 const node = reference.identifier;
76751
76752 if (shouldReport && traceMap[READ]) {
76753 yield {
76754 node,
76755 path,
76756 type: READ,
76757 info: traceMap[READ]
76758 };
76759 }
76760
76761 yield* this._iteratePropertyReferences(node, path, traceMap);
76762 }
76763 } finally {
76764 this.variableStack.pop();
76765 }
76766 }
76767 /**
76768 * Iterate the references for a given AST node.
76769 * @param rootNode The AST node to iterate references.
76770 * @param {string[]} path The current path.
76771 * @param {object} traceMap The trace map.
76772 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76773 */
76774 //eslint-disable-next-line complexity
76775
76776
76777 *_iteratePropertyReferences(rootNode, path, traceMap) {
76778 let node = rootNode;
76779
76780 while (isPassThrough(node)) {
76781 node = node.parent;
76782 }
76783
76784 const parent = node.parent;
76785
76786 if (parent.type === "MemberExpression") {
76787 if (parent.object === node) {
76788 const key = getPropertyName(parent);
76789
76790 if (key == null || !has(traceMap, key)) {
76791 return;
76792 }
76793
76794 path = path.concat(key); //eslint-disable-line no-param-reassign
76795
76796 const nextTraceMap = traceMap[key];
76797
76798 if (nextTraceMap[READ]) {
76799 yield {
76800 node: parent,
76801 path,
76802 type: READ,
76803 info: nextTraceMap[READ]
76804 };
76805 }
76806
76807 yield* this._iteratePropertyReferences(parent, path, nextTraceMap);
76808 }
76809
76810 return;
76811 }
76812
76813 if (parent.type === "CallExpression") {
76814 if (parent.callee === node && traceMap[CALL]) {
76815 yield {
76816 node: parent,
76817 path,
76818 type: CALL,
76819 info: traceMap[CALL]
76820 };
76821 }
76822
76823 return;
76824 }
76825
76826 if (parent.type === "NewExpression") {
76827 if (parent.callee === node && traceMap[CONSTRUCT]) {
76828 yield {
76829 node: parent,
76830 path,
76831 type: CONSTRUCT,
76832 info: traceMap[CONSTRUCT]
76833 };
76834 }
76835
76836 return;
76837 }
76838
76839 if (parent.type === "AssignmentExpression") {
76840 if (parent.right === node) {
76841 yield* this._iterateLhsReferences(parent.left, path, traceMap);
76842 yield* this._iteratePropertyReferences(parent, path, traceMap);
76843 }
76844
76845 return;
76846 }
76847
76848 if (parent.type === "AssignmentPattern") {
76849 if (parent.right === node) {
76850 yield* this._iterateLhsReferences(parent.left, path, traceMap);
76851 }
76852
76853 return;
76854 }
76855
76856 if (parent.type === "VariableDeclarator") {
76857 if (parent.init === node) {
76858 yield* this._iterateLhsReferences(parent.id, path, traceMap);
76859 }
76860 }
76861 }
76862 /**
76863 * Iterate the references for a given Pattern node.
76864 * @param {Node} patternNode The Pattern node to iterate references.
76865 * @param {string[]} path The current path.
76866 * @param {object} traceMap The trace map.
76867 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76868 */
76869
76870
76871 *_iterateLhsReferences(patternNode, path, traceMap) {
76872 if (patternNode.type === "Identifier") {
76873 const variable = findVariable(this.globalScope, patternNode);
76874
76875 if (variable != null) {
76876 yield* this._iterateVariableReferences(variable, path, traceMap, false);
76877 }
76878
76879 return;
76880 }
76881
76882 if (patternNode.type === "ObjectPattern") {
76883 for (const property of patternNode.properties) {
76884 const key = getPropertyName(property);
76885
76886 if (key == null || !has(traceMap, key)) {
76887 continue;
76888 }
76889
76890 const nextPath = path.concat(key);
76891 const nextTraceMap = traceMap[key];
76892
76893 if (nextTraceMap[READ]) {
76894 yield {
76895 node: property,
76896 path: nextPath,
76897 type: READ,
76898 info: nextTraceMap[READ]
76899 };
76900 }
76901
76902 yield* this._iterateLhsReferences(property.value, nextPath, nextTraceMap);
76903 }
76904
76905 return;
76906 }
76907
76908 if (patternNode.type === "AssignmentPattern") {
76909 yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
76910 }
76911 }
76912 /**
76913 * Iterate the references for a given ModuleSpecifier node.
76914 * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
76915 * @param {string[]} path The current path.
76916 * @param {object} traceMap The trace map.
76917 * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
76918 */
76919
76920
76921 *_iterateImportReferences(specifierNode, path, traceMap) {
76922 const type = specifierNode.type;
76923
76924 if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
76925 const key = type === "ImportDefaultSpecifier" ? "default" : specifierNode.imported.name;
76926
76927 if (!has(traceMap, key)) {
76928 return;
76929 }
76930
76931 path = path.concat(key); //eslint-disable-line no-param-reassign
76932
76933 const nextTraceMap = traceMap[key];
76934
76935 if (nextTraceMap[READ]) {
76936 yield {
76937 node: specifierNode,
76938 path,
76939 type: READ,
76940 info: nextTraceMap[READ]
76941 };
76942 }
76943
76944 yield* this._iterateVariableReferences(findVariable(this.globalScope, specifierNode.local), path, nextTraceMap, false);
76945 return;
76946 }
76947
76948 if (type === "ImportNamespaceSpecifier") {
76949 yield* this._iterateVariableReferences(findVariable(this.globalScope, specifierNode.local), path, traceMap, false);
76950 return;
76951 }
76952
76953 if (type === "ExportSpecifier") {
76954 const key = specifierNode.local.name;
76955
76956 if (!has(traceMap, key)) {
76957 return;
76958 }
76959
76960 path = path.concat(key); //eslint-disable-line no-param-reassign
76961
76962 const nextTraceMap = traceMap[key];
76963
76964 if (nextTraceMap[READ]) {
76965 yield {
76966 node: specifierNode,
76967 path,
76968 type: READ,
76969 info: nextTraceMap[READ]
76970 };
76971 }
76972 }
76973 }
76974
76975}
76976
76977ReferenceTracker.READ = READ;
76978ReferenceTracker.CALL = CALL;
76979ReferenceTracker.CONSTRUCT = CONSTRUCT;
76980ReferenceTracker.ESM = ESM;
76981/**
76982 * This is a predicate function for Array#filter.
76983 * @param {string} name A name part.
76984 * @param {number} index The index of the name.
76985 * @returns {boolean} `false` if it's default.
76986 */
76987
76988function exceptDefault(name, index) {
76989 return !(index === 1 && name === "default");
76990}
76991
76992var index = {
76993 CALL,
76994 CONSTRUCT,
76995 ESM,
76996 findVariable,
76997 getFunctionHeadLocation,
76998 getFunctionNameWithKind,
76999 getInnermostScope,
77000 getPropertyName,
77001 getStaticValue,
77002 getStringIfConstant,
77003 hasSideEffect,
77004 isArrowToken,
77005 isClosingBraceToken,
77006 isClosingBracketToken,
77007 isClosingParenToken,
77008 isColonToken,
77009 isCommaToken,
77010 isCommentToken,
77011 isNotArrowToken,
77012 isNotClosingBraceToken,
77013 isNotClosingBracketToken,
77014 isNotClosingParenToken,
77015 isNotColonToken,
77016 isNotCommaToken,
77017 isNotCommentToken,
77018 isNotOpeningBraceToken,
77019 isNotOpeningBracketToken,
77020 isNotOpeningParenToken,
77021 isNotSemicolonToken,
77022 isOpeningBraceToken,
77023 isOpeningBracketToken,
77024 isOpeningParenToken,
77025 isParenthesized,
77026 isSemicolonToken,
77027 PatternMatcher,
77028 READ,
77029 ReferenceTracker
77030};
77031/* harmony default export */ __webpack_exports__["default"] = (index);
77032
77033
77034/***/ }),
77035/* 550 */
77036/***/ (function(module, exports, __webpack_require__) {
77037
77038"use strict";
77039/**
77040 * @fileoverview Rule to disallow unnecessary labels
77041 * @author Toru Nagashima
77042 */
77043 //------------------------------------------------------------------------------
77044// Requirements
77045//------------------------------------------------------------------------------
77046
77047const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
77048// Rule Definition
77049//------------------------------------------------------------------------------
77050
77051
77052module.exports = {
77053 meta: {
77054 type: "suggestion",
77055 docs: {
77056 description: "disallow unnecessary labels",
77057 category: "Best Practices",
77058 recommended: false,
77059 url: "https://eslint.org/docs/rules/no-extra-label"
77060 },
77061 schema: [],
77062 fixable: "code",
77063 messages: {
77064 unexpected: "This label '{{name}}' is unnecessary."
77065 }
77066 },
77067
77068 create(context) {
77069 const sourceCode = context.getSourceCode();
77070 let scopeInfo = null;
77071 /**
77072 * Creates a new scope with a breakable statement.
77073 * @param {ASTNode} node A node to create. This is a BreakableStatement.
77074 * @returns {void}
77075 */
77076
77077 function enterBreakableStatement(node) {
77078 scopeInfo = {
77079 label: node.parent.type === "LabeledStatement" ? node.parent.label : null,
77080 breakable: true,
77081 upper: scopeInfo
77082 };
77083 }
77084 /**
77085 * Removes the top scope of the stack.
77086 * @returns {void}
77087 */
77088
77089
77090 function exitBreakableStatement() {
77091 scopeInfo = scopeInfo.upper;
77092 }
77093 /**
77094 * Creates a new scope with a labeled statement.
77095 *
77096 * This ignores it if the body is a breakable statement.
77097 * In this case it's handled in the `enterBreakableStatement` function.
77098 * @param {ASTNode} node A node to create. This is a LabeledStatement.
77099 * @returns {void}
77100 */
77101
77102
77103 function enterLabeledStatement(node) {
77104 if (!astUtils.isBreakableStatement(node.body)) {
77105 scopeInfo = {
77106 label: node.label,
77107 breakable: false,
77108 upper: scopeInfo
77109 };
77110 }
77111 }
77112 /**
77113 * Removes the top scope of the stack.
77114 *
77115 * This ignores it if the body is a breakable statement.
77116 * In this case it's handled in the `exitBreakableStatement` function.
77117 * @param {ASTNode} node A node. This is a LabeledStatement.
77118 * @returns {void}
77119 */
77120
77121
77122 function exitLabeledStatement(node) {
77123 if (!astUtils.isBreakableStatement(node.body)) {
77124 scopeInfo = scopeInfo.upper;
77125 }
77126 }
77127 /**
77128 * Reports a given control node if it's unnecessary.
77129 * @param {ASTNode} node A node. This is a BreakStatement or a
77130 * ContinueStatement.
77131 * @returns {void}
77132 */
77133
77134
77135 function reportIfUnnecessary(node) {
77136 if (!node.label) {
77137 return;
77138 }
77139
77140 const labelNode = node.label;
77141
77142 for (let info = scopeInfo; info !== null; info = info.upper) {
77143 if (info.breakable || info.label && info.label.name === labelNode.name) {
77144 if (info.breakable && info.label && info.label.name === labelNode.name) {
77145 context.report({
77146 node: labelNode,
77147 messageId: "unexpected",
77148 data: labelNode,
77149
77150 fix(fixer) {
77151 const breakOrContinueToken = sourceCode.getFirstToken(node);
77152
77153 if (sourceCode.commentsExistBetween(breakOrContinueToken, labelNode)) {
77154 return null;
77155 }
77156
77157 return fixer.removeRange([breakOrContinueToken.range[1], labelNode.range[1]]);
77158 }
77159
77160 });
77161 }
77162
77163 return;
77164 }
77165 }
77166 }
77167
77168 return {
77169 WhileStatement: enterBreakableStatement,
77170 "WhileStatement:exit": exitBreakableStatement,
77171 DoWhileStatement: enterBreakableStatement,
77172 "DoWhileStatement:exit": exitBreakableStatement,
77173 ForStatement: enterBreakableStatement,
77174 "ForStatement:exit": exitBreakableStatement,
77175 ForInStatement: enterBreakableStatement,
77176 "ForInStatement:exit": exitBreakableStatement,
77177 ForOfStatement: enterBreakableStatement,
77178 "ForOfStatement:exit": exitBreakableStatement,
77179 SwitchStatement: enterBreakableStatement,
77180 "SwitchStatement:exit": exitBreakableStatement,
77181 LabeledStatement: enterLabeledStatement,
77182 "LabeledStatement:exit": exitLabeledStatement,
77183 BreakStatement: reportIfUnnecessary,
77184 ContinueStatement: reportIfUnnecessary
77185 };
77186 }
77187
77188};
77189
77190/***/ }),
77191/* 551 */
77192/***/ (function(module, exports, __webpack_require__) {
77193
77194"use strict";
77195/**
77196 * @fileoverview Disallow parenthesising higher precedence subexpressions.
77197 * @author Michael Ficarra
77198 */
77199 //------------------------------------------------------------------------------
77200// Rule Definition
77201//------------------------------------------------------------------------------
77202
77203const {
77204 isParenthesized: isParenthesizedRaw
77205} = __webpack_require__(549);
77206
77207const astUtils = __webpack_require__(426);
77208
77209module.exports = {
77210 meta: {
77211 type: "layout",
77212 docs: {
77213 description: "disallow unnecessary parentheses",
77214 category: "Possible Errors",
77215 recommended: false,
77216 url: "https://eslint.org/docs/rules/no-extra-parens"
77217 },
77218 fixable: "code",
77219 schema: {
77220 anyOf: [{
77221 type: "array",
77222 items: [{
77223 enum: ["functions"]
77224 }],
77225 minItems: 0,
77226 maxItems: 1
77227 }, {
77228 type: "array",
77229 items: [{
77230 enum: ["all"]
77231 }, {
77232 type: "object",
77233 properties: {
77234 conditionalAssign: {
77235 type: "boolean"
77236 },
77237 nestedBinaryExpressions: {
77238 type: "boolean"
77239 },
77240 returnAssign: {
77241 type: "boolean"
77242 },
77243 ignoreJSX: {
77244 enum: ["none", "all", "single-line", "multi-line"]
77245 },
77246 enforceForArrowConditionals: {
77247 type: "boolean"
77248 },
77249 enforceForSequenceExpressions: {
77250 type: "boolean"
77251 },
77252 enforceForNewInMemberExpressions: {
77253 type: "boolean"
77254 }
77255 },
77256 additionalProperties: false
77257 }],
77258 minItems: 0,
77259 maxItems: 2
77260 }]
77261 },
77262 messages: {
77263 unexpected: "Unnecessary parentheses around expression."
77264 }
77265 },
77266
77267 create(context) {
77268 const sourceCode = context.getSourceCode();
77269 const tokensToIgnore = new WeakSet();
77270 const precedence = astUtils.getPrecedence;
77271 const ALL_NODES = context.options[0] !== "functions";
77272 const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false;
77273 const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false;
77274 const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false;
77275 const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX;
77276 const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] && context.options[1].enforceForArrowConditionals === false;
77277 const IGNORE_SEQUENCE_EXPRESSIONS = ALL_NODES && context.options[1] && context.options[1].enforceForSequenceExpressions === false;
77278 const IGNORE_NEW_IN_MEMBER_EXPR = ALL_NODES && context.options[1] && context.options[1].enforceForNewInMemberExpressions === false;
77279 const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({
77280 type: "AssignmentExpression"
77281 });
77282 const PRECEDENCE_OF_UPDATE_EXPR = precedence({
77283 type: "UpdateExpression"
77284 });
77285 let reportsBuffer;
77286 /**
77287 * Determines if this rule should be enforced for a node given the current configuration.
77288 * @param {ASTNode} node The node to be checked.
77289 * @returns {boolean} True if the rule should be enforced for this node.
77290 * @private
77291 */
77292
77293 function ruleApplies(node) {
77294 if (node.type === "JSXElement" || node.type === "JSXFragment") {
77295 const isSingleLine = node.loc.start.line === node.loc.end.line;
77296
77297 switch (IGNORE_JSX) {
77298 // Exclude this JSX element from linting
77299 case "all":
77300 return false;
77301 // Exclude this JSX element if it is multi-line element
77302
77303 case "multi-line":
77304 return isSingleLine;
77305 // Exclude this JSX element if it is single-line element
77306
77307 case "single-line":
77308 return !isSingleLine;
77309 // Nothing special to be done for JSX elements
77310
77311 case "none":
77312 break;
77313 // no default
77314 }
77315 }
77316
77317 if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) {
77318 return false;
77319 }
77320
77321 return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
77322 }
77323 /**
77324 * Determines if a node is surrounded by parentheses.
77325 * @param {ASTNode} node The node to be checked.
77326 * @returns {boolean} True if the node is parenthesised.
77327 * @private
77328 */
77329
77330
77331 function isParenthesised(node) {
77332 return isParenthesizedRaw(1, node, sourceCode);
77333 }
77334 /**
77335 * Determines if a node is surrounded by parentheses twice.
77336 * @param {ASTNode} node The node to be checked.
77337 * @returns {boolean} True if the node is doubly parenthesised.
77338 * @private
77339 */
77340
77341
77342 function isParenthesisedTwice(node) {
77343 return isParenthesizedRaw(2, node, sourceCode);
77344 }
77345 /**
77346 * Determines if a node is surrounded by (potentially) invalid parentheses.
77347 * @param {ASTNode} node The node to be checked.
77348 * @returns {boolean} True if the node is incorrectly parenthesised.
77349 * @private
77350 */
77351
77352
77353 function hasExcessParens(node) {
77354 return ruleApplies(node) && isParenthesised(node);
77355 }
77356 /**
77357 * Determines if a node that is expected to be parenthesised is surrounded by
77358 * (potentially) invalid extra parentheses.
77359 * @param {ASTNode} node The node to be checked.
77360 * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
77361 * @private
77362 */
77363
77364
77365 function hasDoubleExcessParens(node) {
77366 return ruleApplies(node) && isParenthesisedTwice(node);
77367 }
77368 /**
77369 * Determines if a node that is expected to be parenthesised is surrounded by
77370 * (potentially) invalid extra parentheses with considering precedence level of the node.
77371 * If the preference level of the node is not higher or equal to precedence lower limit, it also checks
77372 * whether the node is surrounded by parentheses twice or not.
77373 * @param {ASTNode} node The node to be checked.
77374 * @param {number} precedenceLowerLimit The lower limit of precedence.
77375 * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
77376 * @private
77377 */
77378
77379
77380 function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
77381 if (ruleApplies(node) && isParenthesised(node)) {
77382 if (precedence(node) >= precedenceLowerLimit || isParenthesisedTwice(node)) {
77383 return true;
77384 }
77385 }
77386
77387 return false;
77388 }
77389 /**
77390 * Determines if a node test expression is allowed to have a parenthesised assignment
77391 * @param {ASTNode} node The node to be checked.
77392 * @returns {boolean} True if the assignment can be parenthesised.
77393 * @private
77394 */
77395
77396
77397 function isCondAssignException(node) {
77398 return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression";
77399 }
77400 /**
77401 * Determines if a node is in a return statement
77402 * @param {ASTNode} node The node to be checked.
77403 * @returns {boolean} True if the node is in a return statement.
77404 * @private
77405 */
77406
77407
77408 function isInReturnStatement(node) {
77409 for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
77410 if (currentNode.type === "ReturnStatement" || currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement") {
77411 return true;
77412 }
77413 }
77414
77415 return false;
77416 }
77417 /**
77418 * Determines if a constructor function is newed-up with parens
77419 * @param {ASTNode} newExpression The NewExpression node to be checked.
77420 * @returns {boolean} True if the constructor is called with parens.
77421 * @private
77422 */
77423
77424
77425 function isNewExpressionWithParens(newExpression) {
77426 const lastToken = sourceCode.getLastToken(newExpression);
77427 const penultimateToken = sourceCode.getTokenBefore(lastToken);
77428 return newExpression.arguments.length > 0 || // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens
77429 astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken) && newExpression.callee.range[1] < newExpression.range[1];
77430 }
77431 /**
77432 * Determines if a node is or contains an assignment expression
77433 * @param {ASTNode} node The node to be checked.
77434 * @returns {boolean} True if the node is or contains an assignment expression.
77435 * @private
77436 */
77437
77438
77439 function containsAssignment(node) {
77440 if (node.type === "AssignmentExpression") {
77441 return true;
77442 }
77443
77444 if (node.type === "ConditionalExpression" && (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) {
77445 return true;
77446 }
77447
77448 if (node.left && node.left.type === "AssignmentExpression" || node.right && node.right.type === "AssignmentExpression") {
77449 return true;
77450 }
77451
77452 return false;
77453 }
77454 /**
77455 * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment
77456 * @param {ASTNode} node The node to be checked.
77457 * @returns {boolean} True if the assignment can be parenthesised.
77458 * @private
77459 */
77460
77461
77462 function isReturnAssignException(node) {
77463 if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
77464 return false;
77465 }
77466
77467 if (node.type === "ReturnStatement") {
77468 return node.argument && containsAssignment(node.argument);
77469 }
77470
77471 if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
77472 return containsAssignment(node.body);
77473 }
77474
77475 return containsAssignment(node);
77476 }
77477 /**
77478 * Determines if a node following a [no LineTerminator here] restriction is
77479 * surrounded by (potentially) invalid extra parentheses.
77480 * @param {Token} token The token preceding the [no LineTerminator here] restriction.
77481 * @param {ASTNode} node The node to be checked.
77482 * @returns {boolean} True if the node is incorrectly parenthesised.
77483 * @private
77484 */
77485
77486
77487 function hasExcessParensNoLineTerminator(token, node) {
77488 if (token.loc.end.line === node.loc.start.line) {
77489 return hasExcessParens(node);
77490 }
77491
77492 return hasDoubleExcessParens(node);
77493 }
77494 /**
77495 * Determines whether a node should be preceded by an additional space when removing parens
77496 * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
77497 * @returns {boolean} `true` if a space should be inserted before the node
77498 * @private
77499 */
77500
77501
77502 function requiresLeadingSpace(node) {
77503 const leftParenToken = sourceCode.getTokenBefore(node);
77504 const tokenBeforeLeftParen = sourceCode.getTokenBefore(leftParenToken, {
77505 includeComments: true
77506 });
77507 const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParenToken, {
77508 includeComments: true
77509 });
77510 return tokenBeforeLeftParen && tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && leftParenToken.range[1] === tokenAfterLeftParen.range[0] && !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen);
77511 }
77512 /**
77513 * Determines whether a node should be followed by an additional space when removing parens
77514 * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
77515 * @returns {boolean} `true` if a space should be inserted after the node
77516 * @private
77517 */
77518
77519
77520 function requiresTrailingSpace(node) {
77521 const nextTwoTokens = sourceCode.getTokensAfter(node, {
77522 count: 2
77523 });
77524 const rightParenToken = nextTwoTokens[0];
77525 const tokenAfterRightParen = nextTwoTokens[1];
77526 const tokenBeforeRightParen = sourceCode.getLastToken(node);
77527 return rightParenToken && tokenAfterRightParen && !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) && !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
77528 }
77529 /**
77530 * Determines if a given expression node is an IIFE
77531 * @param {ASTNode} node The node to check
77532 * @returns {boolean} `true` if the given node is an IIFE
77533 */
77534
77535
77536 function isIIFE(node) {
77537 return node.type === "CallExpression" && node.callee.type === "FunctionExpression";
77538 }
77539 /**
77540 * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment.
77541 * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax,
77542 * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary.
77543 * @param {ASTNode} [node] The node to check
77544 * @returns {boolean} `true` if the given node can be a valid assignment target
77545 */
77546
77547
77548 function canBeAssignmentTarget(node) {
77549 return node && (node.type === "Identifier" || node.type === "MemberExpression");
77550 }
77551 /**
77552 * Report the node
77553 * @param {ASTNode} node node to evaluate
77554 * @returns {void}
77555 * @private
77556 */
77557
77558
77559 function report(node) {
77560 const leftParenToken = sourceCode.getTokenBefore(node);
77561 const rightParenToken = sourceCode.getTokenAfter(node);
77562
77563 if (!isParenthesisedTwice(node)) {
77564 if (tokensToIgnore.has(sourceCode.getFirstToken(node))) {
77565 return;
77566 }
77567
77568 if (isIIFE(node) && !isParenthesised(node.callee)) {
77569 return;
77570 }
77571 }
77572 /**
77573 * Finishes reporting
77574 * @returns {void}
77575 * @private
77576 */
77577
77578
77579 function finishReport() {
77580 context.report({
77581 node,
77582 loc: leftParenToken.loc,
77583 messageId: "unexpected",
77584
77585 fix(fixer) {
77586 const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]);
77587 return fixer.replaceTextRange([leftParenToken.range[0], rightParenToken.range[1]], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : ""));
77588 }
77589
77590 });
77591 }
77592
77593 if (reportsBuffer) {
77594 reportsBuffer.reports.push({
77595 node,
77596 finishReport
77597 });
77598 return;
77599 }
77600
77601 finishReport();
77602 }
77603 /**
77604 * Evaluate a argument of the node.
77605 * @param {ASTNode} node node to evaluate
77606 * @returns {void}
77607 * @private
77608 */
77609
77610
77611 function checkArgumentWithPrecedence(node) {
77612 if (hasExcessParensWithPrecedence(node.argument, precedence(node))) {
77613 report(node.argument);
77614 }
77615 }
77616 /**
77617 * Check if a member expression contains a call expression
77618 * @param {ASTNode} node MemberExpression node to evaluate
77619 * @returns {boolean} true if found, false if not
77620 */
77621
77622
77623 function doesMemberExpressionContainCallExpression(node) {
77624 let currentNode = node.object;
77625 let currentNodeType = node.object.type;
77626
77627 while (currentNodeType === "MemberExpression") {
77628 currentNode = currentNode.object;
77629 currentNodeType = currentNode.type;
77630 }
77631
77632 return currentNodeType === "CallExpression";
77633 }
77634 /**
77635 * Evaluate a new call
77636 * @param {ASTNode} node node to evaluate
77637 * @returns {void}
77638 * @private
77639 */
77640
77641
77642 function checkCallNew(node) {
77643 const callee = node.callee;
77644
77645 if (hasExcessParensWithPrecedence(callee, precedence(node))) {
77646 const hasNewParensException = callee.type === "NewExpression" && !isNewExpressionWithParens(callee);
77647
77648 if (hasDoubleExcessParens(callee) || !isIIFE(node) && !hasNewParensException && !( // Allow extra parens around a new expression if they are intervening parentheses.
77649 node.type === "NewExpression" && callee.type === "MemberExpression" && doesMemberExpressionContainCallExpression(callee))) {
77650 report(node.callee);
77651 }
77652 }
77653
77654 node.arguments.filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR)).forEach(report);
77655 }
77656 /**
77657 * Evaluate binary logicals
77658 * @param {ASTNode} node node to evaluate
77659 * @returns {void}
77660 * @private
77661 */
77662
77663
77664 function checkBinaryLogical(node) {
77665 const prec = precedence(node);
77666 const leftPrecedence = precedence(node.left);
77667 const rightPrecedence = precedence(node.right);
77668 const isExponentiation = node.operator === "**";
77669 const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression");
77670 const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression");
77671
77672 if (!shouldSkipLeft && hasExcessParens(node.left)) {
77673 if (!(node.left.type === "UnaryExpression" && isExponentiation) && (leftPrecedence > prec || leftPrecedence === prec && !isExponentiation) || isParenthesisedTwice(node.left)) {
77674 report(node.left);
77675 }
77676 }
77677
77678 if (!shouldSkipRight && hasExcessParens(node.right)) {
77679 if (rightPrecedence > prec || rightPrecedence === prec && isExponentiation || isParenthesisedTwice(node.right)) {
77680 report(node.right);
77681 }
77682 }
77683 }
77684 /**
77685 * Check the parentheses around the super class of the given class definition.
77686 * @param {ASTNode} node The node of class declarations to check.
77687 * @returns {void}
77688 */
77689
77690
77691 function checkClass(node) {
77692 if (!node.superClass) {
77693 return;
77694 }
77695 /*
77696 * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
77697 * Otherwise, parentheses are needed.
77698 */
77699
77700
77701 const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR ? hasExcessParens(node.superClass) : hasDoubleExcessParens(node.superClass);
77702
77703 if (hasExtraParens) {
77704 report(node.superClass);
77705 }
77706 }
77707 /**
77708 * Check the parentheses around the argument of the given spread operator.
77709 * @param {ASTNode} node The node of spread elements/properties to check.
77710 * @returns {void}
77711 */
77712
77713
77714 function checkSpreadOperator(node) {
77715 if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
77716 report(node.argument);
77717 }
77718 }
77719 /**
77720 * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
77721 * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
77722 * @returns {void}
77723 */
77724
77725
77726 function checkExpressionOrExportStatement(node) {
77727 const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
77728 const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
77729 const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
77730 const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
77731
77732 if (astUtils.isOpeningParenToken(firstToken) && (astUtils.isOpeningBraceToken(secondToken) || secondToken.type === "Keyword" && (secondToken.value === "function" || secondToken.value === "class" || secondToken.value === "let" && tokenAfterClosingParens && (astUtils.isOpeningBracketToken(tokenAfterClosingParens) || tokenAfterClosingParens.type === "Identifier")) || secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function")) {
77733 tokensToIgnore.add(secondToken);
77734 }
77735
56c4a2cb
DC
77736 const hasExtraParens = node.parent.type === "ExportDefaultDeclaration" ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR) : hasExcessParens(node);
77737
77738 if (hasExtraParens) {
eb39fafa
DC
77739 report(node);
77740 }
77741 }
77742 /**
77743 * Finds the path from the given node to the specified ancestor.
77744 * @param {ASTNode} node First node in the path.
77745 * @param {ASTNode} ancestor Last node in the path.
77746 * @returns {ASTNode[]} Path, including both nodes.
77747 * @throws {Error} If the given node does not have the specified ancestor.
77748 */
77749
77750
77751 function pathToAncestor(node, ancestor) {
77752 const path = [node];
77753 let currentNode = node;
77754
77755 while (currentNode !== ancestor) {
77756 currentNode = currentNode.parent;
77757 /* istanbul ignore if */
77758
77759 if (currentNode === null) {
77760 throw new Error("Nodes are not in the ancestor-descendant relationship.");
77761 }
77762
77763 path.push(currentNode);
77764 }
77765
77766 return path;
77767 }
77768 /**
77769 * Finds the path from the given node to the specified descendant.
77770 * @param {ASTNode} node First node in the path.
77771 * @param {ASTNode} descendant Last node in the path.
77772 * @returns {ASTNode[]} Path, including both nodes.
77773 * @throws {Error} If the given node does not have the specified descendant.
77774 */
77775
77776
77777 function pathToDescendant(node, descendant) {
77778 return pathToAncestor(descendant, node).reverse();
77779 }
77780 /**
77781 * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer
77782 * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop.
77783 * @param {ASTNode} node Ancestor of an 'in' expression.
77784 * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself.
77785 * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis.
77786 */
77787
77788
77789 function isSafelyEnclosingInExpression(node, child) {
77790 switch (node.type) {
77791 case "ArrayExpression":
77792 case "ArrayPattern":
77793 case "BlockStatement":
77794 case "ObjectExpression":
77795 case "ObjectPattern":
77796 case "TemplateLiteral":
77797 return true;
77798
77799 case "ArrowFunctionExpression":
77800 case "FunctionExpression":
77801 return node.params.includes(child);
77802
77803 case "CallExpression":
77804 case "NewExpression":
77805 return node.arguments.includes(child);
77806
77807 case "MemberExpression":
77808 return node.computed && node.property === child;
77809
77810 case "ConditionalExpression":
77811 return node.consequent === child;
77812
77813 default:
77814 return false;
77815 }
77816 }
77817 /**
77818 * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately.
77819 * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings.
77820 * @returns {void}
77821 */
77822
77823
77824 function startNewReportsBuffering() {
77825 reportsBuffer = {
77826 upper: reportsBuffer,
77827 inExpressionNodes: [],
77828 reports: []
77829 };
77830 }
77831 /**
77832 * Ends the current reports buffering.
77833 * @returns {void}
77834 */
77835
77836
77837 function endCurrentReportsBuffering() {
77838 const {
77839 upper,
77840 inExpressionNodes,
77841 reports
77842 } = reportsBuffer;
77843
77844 if (upper) {
77845 upper.inExpressionNodes.push(...inExpressionNodes);
77846 upper.reports.push(...reports);
77847 } else {
77848 // flush remaining reports
77849 reports.forEach(({
77850 finishReport
77851 }) => finishReport());
77852 }
77853
77854 reportsBuffer = upper;
77855 }
77856 /**
77857 * Checks whether the given node is in the current reports buffer.
77858 * @param {ASTNode} node Node to check.
77859 * @returns {boolean} True if the node is in the current buffer, false otherwise.
77860 */
77861
77862
77863 function isInCurrentReportsBuffer(node) {
77864 return reportsBuffer.reports.some(r => r.node === node);
77865 }
77866 /**
77867 * Removes the given node from the current reports buffer.
77868 * @param {ASTNode} node Node to remove.
77869 * @returns {void}
77870 */
77871
77872
77873 function removeFromCurrentReportsBuffer(node) {
77874 reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
77875 }
77876
77877 return {
77878 ArrayExpression(node) {
77879 node.elements.filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR)).forEach(report);
77880 },
77881
77882 ArrayPattern(node) {
77883 node.elements.filter(e => canBeAssignmentTarget(e) && hasExcessParens(e)).forEach(report);
77884 },
77885
77886 ArrowFunctionExpression(node) {
77887 if (isReturnAssignException(node)) {
77888 return;
77889 }
77890
77891 if (node.body.type === "ConditionalExpression" && IGNORE_ARROW_CONDITIONALS) {
77892 return;
77893 }
77894
77895 if (node.body.type !== "BlockStatement") {
77896 const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken);
77897 const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken);
77898
77899 if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
77900 tokensToIgnore.add(firstBodyToken);
77901 }
77902
77903 if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
77904 report(node.body);
77905 }
77906 }
77907 },
77908
77909 AssignmentExpression(node) {
77910 if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) {
77911 report(node.left);
77912 }
77913
77914 if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
77915 report(node.right);
77916 }
77917 },
77918
77919 BinaryExpression(node) {
77920 if (reportsBuffer && node.operator === "in") {
77921 reportsBuffer.inExpressionNodes.push(node);
77922 }
77923
77924 checkBinaryLogical(node);
77925 },
77926
77927 CallExpression: checkCallNew,
77928
77929 ClassBody(node) {
77930 node.body.filter(member => member.type === "MethodDefinition" && member.computed && member.key).filter(member => hasExcessParensWithPrecedence(member.key, PRECEDENCE_OF_ASSIGNMENT_EXPR)).forEach(member => report(member.key));
77931 },
77932
77933 ConditionalExpression(node) {
77934 if (isReturnAssignException(node)) {
77935 return;
77936 }
77937
77938 if (!isCondAssignException(node) && hasExcessParensWithPrecedence(node.test, precedence({
77939 type: "LogicalExpression",
77940 operator: "||"
77941 }))) {
77942 report(node.test);
77943 }
77944
77945 if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
77946 report(node.consequent);
77947 }
77948
77949 if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
77950 report(node.alternate);
77951 }
77952 },
77953
77954 DoWhileStatement(node) {
77955 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
77956 report(node.test);
77957 }
77958 },
77959
77960 ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration),
77961 ExpressionStatement: node => checkExpressionOrExportStatement(node.expression),
77962
77963 "ForInStatement, ForOfStatement"(node) {
77964 if (node.left.type !== "VariableDeclarator") {
77965 const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
77966
77967 if (firstLeftToken.value === "let" && (
77968 /*
77969 * If `let` is the only thing on the left side of the loop, it's the loop variable: `for ((let) of foo);`
77970 * Removing it will cause a syntax error, because it will be parsed as the start of a VariableDeclarator.
77971 */
77972 firstLeftToken.range[1] === node.left.range[1] ||
77973 /*
77974 * If `let` is followed by a `[` token, it's a property access on the `let` value: `for ((let[foo]) of bar);`
77975 * Removing it will cause the property access to be parsed as a destructuring declaration of `foo` instead.
77976 */
77977 astUtils.isOpeningBracketToken(sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken)))) {
77978 tokensToIgnore.add(firstLeftToken);
77979 }
77980 }
77981
77982 if (node.type === "ForOfStatement") {
77983 const hasExtraParens = node.right.type === "SequenceExpression" ? hasDoubleExcessParens(node.right) : hasExcessParens(node.right);
77984
77985 if (hasExtraParens) {
77986 report(node.right);
77987 }
77988 } else if (hasExcessParens(node.right)) {
77989 report(node.right);
77990 }
77991
77992 if (hasExcessParens(node.left)) {
77993 report(node.left);
77994 }
77995 },
77996
77997 ForStatement(node) {
77998 if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) {
77999 report(node.test);
78000 }
78001
78002 if (node.update && hasExcessParens(node.update)) {
78003 report(node.update);
78004 }
78005
78006 if (node.init) {
78007 startNewReportsBuffering();
78008
78009 if (hasExcessParens(node.init)) {
78010 report(node.init);
78011 }
78012 }
78013 },
78014
78015 "ForStatement > *.init:exit"(node) {
78016 /*
78017 * Removing parentheses around `in` expressions might change semantics and cause errors.
78018 *
78019 * For example, this valid for loop:
78020 * for (let a = (b in c); ;);
78021 * after removing parentheses would be treated as an invalid for-in loop:
78022 * for (let a = b in c; ;);
78023 */
78024 if (reportsBuffer.reports.length) {
78025 reportsBuffer.inExpressionNodes.forEach(inExpressionNode => {
78026 const path = pathToDescendant(node, inExpressionNode);
78027 let nodeToExclude;
78028
78029 for (let i = 0; i < path.length; i++) {
78030 const pathNode = path[i];
78031
78032 if (i < path.length - 1) {
78033 const nextPathNode = path[i + 1];
78034
78035 if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) {
78036 // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
78037 return;
78038 }
78039 }
78040
78041 if (isParenthesised(pathNode)) {
78042 if (isInCurrentReportsBuffer(pathNode)) {
78043 // This node was supposed to be reported, but parentheses might be necessary.
78044 if (isParenthesisedTwice(pathNode)) {
78045 /*
78046 * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses.
78047 * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses.
78048 * The remaining pair is safely enclosing the 'in' expression.
78049 */
78050 return;
78051 } // Exclude the outermost node only.
78052
78053
78054 if (!nodeToExclude) {
78055 nodeToExclude = pathNode;
78056 } // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
78057
78058 } else {
78059 // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
78060 return;
78061 }
78062 }
78063 } // Exclude the node from the list (i.e. treat parentheses as necessary)
78064
78065
78066 removeFromCurrentReportsBuffer(nodeToExclude);
78067 });
78068 }
78069
78070 endCurrentReportsBuffering();
78071 },
78072
78073 IfStatement(node) {
78074 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
78075 report(node.test);
78076 }
78077 },
78078
78079 ImportExpression(node) {
78080 const {
78081 source
78082 } = node;
78083
78084 if (source.type === "SequenceExpression") {
78085 if (hasDoubleExcessParens(source)) {
78086 report(source);
78087 }
78088 } else if (hasExcessParens(source)) {
78089 report(source);
78090 }
78091 },
78092
78093 LogicalExpression: checkBinaryLogical,
78094
78095 MemberExpression(node) {
78096 const nodeObjHasExcessParens = hasExcessParens(node.object);
78097
78098 if (nodeObjHasExcessParens && precedence(node.object) >= precedence(node) && (node.computed || !(astUtils.isDecimalInteger(node.object) || // RegExp literal is allowed to have parens (#1589)
78099 node.object.type === "Literal" && node.object.regex))) {
78100 report(node.object);
78101 }
78102
78103 if (nodeObjHasExcessParens && node.object.type === "CallExpression" && node.parent.type !== "NewExpression") {
78104 report(node.object);
78105 }
78106
78107 if (nodeObjHasExcessParens && !IGNORE_NEW_IN_MEMBER_EXPR && node.object.type === "NewExpression" && isNewExpressionWithParens(node.object)) {
78108 report(node.object);
78109 }
78110
78111 if (node.computed && hasExcessParens(node.property)) {
78112 report(node.property);
78113 }
78114 },
78115
78116 NewExpression: checkCallNew,
78117
78118 ObjectExpression(node) {
78119 node.properties.filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR)).forEach(property => report(property.value));
78120 },
78121
78122 ObjectPattern(node) {
78123 node.properties.filter(property => {
78124 const value = property.value;
78125 return canBeAssignmentTarget(value) && hasExcessParens(value);
78126 }).forEach(property => report(property.value));
78127 },
78128
78129 Property(node) {
78130 if (node.computed) {
78131 const {
78132 key
78133 } = node;
78134
78135 if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
78136 report(key);
78137 }
78138 }
78139 },
78140
78141 RestElement(node) {
78142 const argument = node.argument;
78143
78144 if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
78145 report(argument);
78146 }
78147 },
78148
78149 ReturnStatement(node) {
78150 const returnToken = sourceCode.getFirstToken(node);
78151
78152 if (isReturnAssignException(node)) {
78153 return;
78154 }
78155
78156 if (node.argument && hasExcessParensNoLineTerminator(returnToken, node.argument) && // RegExp literal is allowed to have parens (#1589)
78157 !(node.argument.type === "Literal" && node.argument.regex)) {
78158 report(node.argument);
78159 }
78160 },
78161
78162 SequenceExpression(node) {
78163 const precedenceOfNode = precedence(node);
78164 node.expressions.filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode)).forEach(report);
78165 },
78166
78167 SwitchCase(node) {
78168 if (node.test && hasExcessParens(node.test)) {
78169 report(node.test);
78170 }
78171 },
78172
78173 SwitchStatement(node) {
78174 if (hasExcessParens(node.discriminant)) {
78175 report(node.discriminant);
78176 }
78177 },
78178
78179 ThrowStatement(node) {
78180 const throwToken = sourceCode.getFirstToken(node);
78181
78182 if (hasExcessParensNoLineTerminator(throwToken, node.argument)) {
78183 report(node.argument);
78184 }
78185 },
78186
78187 UnaryExpression: checkArgumentWithPrecedence,
78188 UpdateExpression: checkArgumentWithPrecedence,
78189 AwaitExpression: checkArgumentWithPrecedence,
78190
78191 VariableDeclarator(node) {
78192 if (node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) && // RegExp literal is allowed to have parens (#1589)
78193 !(node.init.type === "Literal" && node.init.regex)) {
78194 report(node.init);
78195 }
78196 },
78197
78198 WhileStatement(node) {
78199 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
78200 report(node.test);
78201 }
78202 },
78203
78204 WithStatement(node) {
78205 if (hasExcessParens(node.object)) {
78206 report(node.object);
78207 }
78208 },
78209
78210 YieldExpression(node) {
78211 if (node.argument) {
78212 const yieldToken = sourceCode.getFirstToken(node);
78213
78214 if (precedence(node.argument) >= precedence(node) && hasExcessParensNoLineTerminator(yieldToken, node.argument) || hasDoubleExcessParens(node.argument)) {
78215 report(node.argument);
78216 }
78217 }
78218 },
78219
78220 ClassDeclaration: checkClass,
78221 ClassExpression: checkClass,
78222 SpreadElement: checkSpreadOperator,
78223 SpreadProperty: checkSpreadOperator,
78224 ExperimentalSpreadProperty: checkSpreadOperator,
78225
78226 TemplateLiteral(node) {
78227 node.expressions.filter(e => e && hasExcessParens(e)).forEach(report);
78228 },
78229
78230 AssignmentPattern(node) {
78231 const {
78232 left,
78233 right
78234 } = node;
78235
78236 if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
78237 report(left);
78238 }
78239
78240 if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
78241 report(right);
78242 }
78243 }
78244
78245 };
78246 }
78247
78248};
78249
78250/***/ }),
78251/* 552 */
78252/***/ (function(module, exports, __webpack_require__) {
78253
78254"use strict";
78255/**
78256 * @fileoverview Rule to flag use of unnecessary semicolons
78257 * @author Nicholas C. Zakas
78258 */
78259 //------------------------------------------------------------------------------
78260// Requirements
78261//------------------------------------------------------------------------------
78262
78263const FixTracker = __webpack_require__(538);
78264
78265const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
78266// Rule Definition
78267//------------------------------------------------------------------------------
78268
78269
78270module.exports = {
78271 meta: {
78272 type: "suggestion",
78273 docs: {
78274 description: "disallow unnecessary semicolons",
78275 category: "Possible Errors",
78276 recommended: true,
78277 url: "https://eslint.org/docs/rules/no-extra-semi"
78278 },
78279 fixable: "code",
78280 schema: [],
78281 messages: {
78282 unexpected: "Unnecessary semicolon."
78283 }
78284 },
78285
78286 create(context) {
78287 const sourceCode = context.getSourceCode();
78288 /**
78289 * Reports an unnecessary semicolon error.
78290 * @param {Node|Token} nodeOrToken A node or a token to be reported.
78291 * @returns {void}
78292 */
78293
78294 function report(nodeOrToken) {
78295 context.report({
78296 node: nodeOrToken,
78297 messageId: "unexpected",
78298
78299 fix(fixer) {
78300 /*
78301 * Expand the replacement range to include the surrounding
78302 * tokens to avoid conflicting with semi.
78303 * https://github.com/eslint/eslint/issues/7928
78304 */
78305 return new FixTracker(fixer, context.getSourceCode()).retainSurroundingTokens(nodeOrToken).remove(nodeOrToken);
78306 }
78307
78308 });
78309 }
78310 /**
78311 * Checks for a part of a class body.
78312 * This checks tokens from a specified token to a next MethodDefinition or the end of class body.
78313 * @param {Token} firstToken The first token to check.
78314 * @returns {void}
78315 */
78316
78317
78318 function checkForPartOfClassBody(firstToken) {
78319 for (let token = firstToken; token.type === "Punctuator" && !astUtils.isClosingBraceToken(token); token = sourceCode.getTokenAfter(token)) {
78320 if (astUtils.isSemicolonToken(token)) {
78321 report(token);
78322 }
78323 }
78324 }
78325
78326 return {
78327 /**
78328 * Reports this empty statement, except if the parent node is a loop.
78329 * @param {Node} node A EmptyStatement node to be reported.
78330 * @returns {void}
78331 */
78332 EmptyStatement(node) {
78333 const parent = node.parent,
78334 allowedParentTypes = ["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement", "IfStatement", "LabeledStatement", "WithStatement"];
78335
78336 if (allowedParentTypes.indexOf(parent.type) === -1) {
78337 report(node);
78338 }
78339 },
78340
78341 /**
78342 * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body.
78343 * @param {Node} node A ClassBody node to check.
78344 * @returns {void}
78345 */
78346 ClassBody(node) {
78347 checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`.
78348 },
78349
78350 /**
78351 * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body.
78352 * @param {Node} node A MethodDefinition node of the start point.
78353 * @returns {void}
78354 */
78355 MethodDefinition(node) {
78356 checkForPartOfClassBody(sourceCode.getTokenAfter(node));
78357 }
78358
78359 };
78360 }
78361
78362};
78363
78364/***/ }),
78365/* 553 */
78366/***/ (function(module, exports, __webpack_require__) {
78367
78368"use strict";
78369/**
78370 * @fileoverview Rule to flag fall-through cases in switch statements.
78371 * @author Matt DuVall <http://mattduvall.com/>
78372 */
78373 //------------------------------------------------------------------------------
78374// Requirements
78375//------------------------------------------------------------------------------
78376
78377const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
78378// Helpers
78379//------------------------------------------------------------------------------
78380
78381
78382const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu;
78383/**
78384 * Checks whether or not a given node has a fallthrough comment.
78385 * @param {ASTNode} node A SwitchCase node to get comments.
78386 * @param {RuleContext} context A rule context which stores comments.
78387 * @param {RegExp} fallthroughCommentPattern A pattern to match comment to.
78388 * @returns {boolean} `true` if the node has a valid fallthrough comment.
78389 */
78390
78391function hasFallthroughComment(node, context, fallthroughCommentPattern) {
78392 const sourceCode = context.getSourceCode();
78393 const comment = lodash.last(sourceCode.getCommentsBefore(node));
78394 return Boolean(comment && fallthroughCommentPattern.test(comment.value));
78395}
78396/**
78397 * Checks whether or not a given code path segment is reachable.
78398 * @param {CodePathSegment} segment A CodePathSegment to check.
78399 * @returns {boolean} `true` if the segment is reachable.
78400 */
78401
78402
78403function isReachable(segment) {
78404 return segment.reachable;
78405}
78406/**
78407 * Checks whether a node and a token are separated by blank lines
78408 * @param {ASTNode} node The node to check
78409 * @param {Token} token The token to compare against
78410 * @returns {boolean} `true` if there are blank lines between node and token
78411 */
78412
78413
78414function hasBlankLinesBetween(node, token) {
78415 return token.loc.start.line > node.loc.end.line + 1;
78416} //------------------------------------------------------------------------------
78417// Rule Definition
78418//------------------------------------------------------------------------------
78419
78420
78421module.exports = {
78422 meta: {
78423 type: "problem",
78424 docs: {
78425 description: "disallow fallthrough of `case` statements",
78426 category: "Best Practices",
78427 recommended: true,
78428 url: "https://eslint.org/docs/rules/no-fallthrough"
78429 },
78430 schema: [{
78431 type: "object",
78432 properties: {
78433 commentPattern: {
78434 type: "string",
78435 default: ""
78436 }
78437 },
78438 additionalProperties: false
78439 }],
78440 messages: {
78441 case: "Expected a 'break' statement before 'case'.",
78442 default: "Expected a 'break' statement before 'default'."
78443 }
78444 },
78445
78446 create(context) {
78447 const options = context.options[0] || {};
78448 let currentCodePath = null;
78449 const sourceCode = context.getSourceCode();
78450 /*
78451 * We need to use leading comments of the next SwitchCase node because
78452 * trailing comments is wrong if semicolons are omitted.
78453 */
78454
78455 let fallthroughCase = null;
78456 let fallthroughCommentPattern = null;
78457
78458 if (options.commentPattern) {
78459 fallthroughCommentPattern = new RegExp(options.commentPattern, "u");
78460 } else {
78461 fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT;
78462 }
78463
78464 return {
78465 onCodePathStart(codePath) {
78466 currentCodePath = codePath;
78467 },
78468
78469 onCodePathEnd() {
78470 currentCodePath = currentCodePath.upper;
78471 },
78472
78473 SwitchCase(node) {
78474 /*
78475 * Checks whether or not there is a fallthrough comment.
78476 * And reports the previous fallthrough node if that does not exist.
78477 */
78478 if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) {
78479 context.report({
78480 messageId: node.test ? "case" : "default",
78481 node
78482 });
78483 }
78484
78485 fallthroughCase = null;
78486 },
78487
78488 "SwitchCase:exit"(node) {
78489 const nextToken = sourceCode.getTokenAfter(node);
78490 /*
78491 * `reachable` meant fall through because statements preceded by
78492 * `break`, `return`, or `throw` are unreachable.
78493 * And allows empty cases and the last case.
78494 */
78495
78496 if (currentCodePath.currentSegments.some(isReachable) && (node.consequent.length > 0 || hasBlankLinesBetween(node, nextToken)) && lodash.last(node.parent.cases) !== node) {
78497 fallthroughCase = node;
78498 }
78499 }
78500
78501 };
78502 }
78503
78504};
78505
78506/***/ }),
78507/* 554 */
78508/***/ (function(module, exports, __webpack_require__) {
78509
78510"use strict";
78511/**
78512 * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal
78513 * @author James Allardice
78514 */
78515 //------------------------------------------------------------------------------
78516// Requirements
78517//------------------------------------------------------------------------------
78518
78519const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
78520// Rule Definition
78521//------------------------------------------------------------------------------
78522
78523
78524module.exports = {
78525 meta: {
78526 type: "suggestion",
78527 docs: {
78528 description: "disallow leading or trailing decimal points in numeric literals",
78529 category: "Best Practices",
78530 recommended: false,
78531 url: "https://eslint.org/docs/rules/no-floating-decimal"
78532 },
78533 schema: [],
78534 fixable: "code",
78535 messages: {
78536 leading: "A leading decimal point can be confused with a dot.",
78537 trailing: "A trailing decimal point can be confused with a dot."
78538 }
78539 },
78540
78541 create(context) {
78542 const sourceCode = context.getSourceCode();
78543 return {
78544 Literal(node) {
78545 if (typeof node.value === "number") {
78546 if (node.raw.startsWith(".")) {
78547 context.report({
78548 node,
78549 messageId: "leading",
78550
78551 fix(fixer) {
78552 const tokenBefore = sourceCode.getTokenBefore(node);
78553 const needsSpaceBefore = tokenBefore && tokenBefore.range[1] === node.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, "0".concat(node.raw));
78554 return fixer.insertTextBefore(node, needsSpaceBefore ? " 0" : "0");
78555 }
78556
78557 });
78558 }
78559
78560 if (node.raw.indexOf(".") === node.raw.length - 1) {
78561 context.report({
78562 node,
78563 messageId: "trailing",
78564 fix: fixer => fixer.insertTextAfter(node, "0")
78565 });
78566 }
78567 }
78568 }
78569
78570 };
78571 }
78572
78573};
78574
78575/***/ }),
78576/* 555 */
78577/***/ (function(module, exports, __webpack_require__) {
78578
78579"use strict";
78580/**
78581 * @fileoverview Rule to flag use of function declaration identifiers as variables.
78582 * @author Ian Christian Myers
78583 */
78584
78585
78586const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
78587// Rule Definition
78588//------------------------------------------------------------------------------
78589
78590
78591module.exports = {
78592 meta: {
78593 type: "problem",
78594 docs: {
78595 description: "disallow reassigning `function` declarations",
78596 category: "Possible Errors",
78597 recommended: true,
78598 url: "https://eslint.org/docs/rules/no-func-assign"
78599 },
78600 schema: [],
78601 messages: {
78602 isAFunction: "'{{name}}' is a function."
78603 }
78604 },
78605
78606 create(context) {
78607 /**
78608 * Reports a reference if is non initializer and writable.
78609 * @param {References} references Collection of reference to check.
78610 * @returns {void}
78611 */
78612 function checkReference(references) {
78613 astUtils.getModifyingReferences(references).forEach(reference => {
78614 context.report({
78615 node: reference.identifier,
78616 messageId: "isAFunction",
78617 data: {
78618 name: reference.identifier.name
78619 }
78620 });
78621 });
78622 }
78623 /**
78624 * Finds and reports references that are non initializer and writable.
78625 * @param {Variable} variable A variable to check.
78626 * @returns {void}
78627 */
78628
78629
78630 function checkVariable(variable) {
78631 if (variable.defs[0].type === "FunctionName") {
78632 checkReference(variable.references);
78633 }
78634 }
78635 /**
78636 * Checks parameters of a given function node.
78637 * @param {ASTNode} node A function node to check.
78638 * @returns {void}
78639 */
78640
78641
78642 function checkForFunction(node) {
78643 context.getDeclaredVariables(node).forEach(checkVariable);
78644 }
78645
78646 return {
78647 FunctionDeclaration: checkForFunction,
78648 FunctionExpression: checkForFunction
78649 };
78650 }
78651
78652};
78653
78654/***/ }),
78655/* 556 */
78656/***/ (function(module, exports, __webpack_require__) {
78657
78658"use strict";
78659/**
78660 * @fileoverview Rule to disallow assignments to native objects or read-only global variables
78661 * @author Ilya Volodin
78662 */
78663 //------------------------------------------------------------------------------
78664// Rule Definition
78665//------------------------------------------------------------------------------
78666
78667module.exports = {
78668 meta: {
78669 type: "suggestion",
78670 docs: {
78671 description: "disallow assignments to native objects or read-only global variables",
78672 category: "Best Practices",
78673 recommended: true,
78674 url: "https://eslint.org/docs/rules/no-global-assign"
78675 },
78676 schema: [{
78677 type: "object",
78678 properties: {
78679 exceptions: {
78680 type: "array",
78681 items: {
78682 type: "string"
78683 },
78684 uniqueItems: true
78685 }
78686 },
78687 additionalProperties: false
78688 }],
78689 messages: {
78690 globalShouldNotBeModified: "Read-only global '{{name}}' should not be modified."
78691 }
78692 },
78693
78694 create(context) {
78695 const config = context.options[0];
78696 const exceptions = config && config.exceptions || [];
78697 /**
78698 * Reports write references.
78699 * @param {Reference} reference A reference to check.
78700 * @param {int} index The index of the reference in the references.
78701 * @param {Reference[]} references The array that the reference belongs to.
78702 * @returns {void}
78703 */
78704
78705 function checkReference(reference, index, references) {
78706 const identifier = reference.identifier;
78707
78708 if (reference.init === false && reference.isWrite() && (
78709 /*
78710 * Destructuring assignments can have multiple default value,
78711 * so possibly there are multiple writeable references for the same identifier.
78712 */
78713 index === 0 || references[index - 1].identifier !== identifier)) {
78714 context.report({
78715 node: identifier,
78716 messageId: "globalShouldNotBeModified",
78717 data: {
78718 name: identifier.name
78719 }
78720 });
78721 }
78722 }
78723 /**
78724 * Reports write references if a given variable is read-only builtin.
78725 * @param {Variable} variable A variable to check.
78726 * @returns {void}
78727 */
78728
78729
78730 function checkVariable(variable) {
78731 if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
78732 variable.references.forEach(checkReference);
78733 }
78734 }
78735
78736 return {
78737 Program() {
78738 const globalScope = context.getScope();
78739 globalScope.variables.forEach(checkVariable);
78740 }
78741
78742 };
78743 }
78744
78745};
78746
78747/***/ }),
78748/* 557 */
78749/***/ (function(module, exports, __webpack_require__) {
78750
78751"use strict";
78752/**
78753 * @fileoverview A rule to disallow the type conversions with shorter notations.
78754 * @author Toru Nagashima
78755 */
78756
78757
78758const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
78759// Helpers
78760//------------------------------------------------------------------------------
78761
78762
78763const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u;
78764const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"];
78765/**
78766 * Parses and normalizes an option object.
78767 * @param {Object} options An option object to parse.
78768 * @returns {Object} The parsed and normalized option object.
78769 */
78770
78771function parseOptions(options) {
78772 return {
78773 boolean: "boolean" in options ? options.boolean : true,
78774 number: "number" in options ? options.number : true,
78775 string: "string" in options ? options.string : true,
78776 allow: options.allow || []
78777 };
78778}
78779/**
78780 * Checks whether or not a node is a double logical nigating.
78781 * @param {ASTNode} node An UnaryExpression node to check.
78782 * @returns {boolean} Whether or not the node is a double logical nigating.
78783 */
78784
78785
78786function isDoubleLogicalNegating(node) {
78787 return node.operator === "!" && node.argument.type === "UnaryExpression" && node.argument.operator === "!";
78788}
78789/**
78790 * Checks whether or not a node is a binary negating of `.indexOf()` method calling.
78791 * @param {ASTNode} node An UnaryExpression node to check.
78792 * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling.
78793 */
78794
78795
78796function isBinaryNegatingOfIndexOf(node) {
78797 return node.operator === "~" && node.argument.type === "CallExpression" && node.argument.callee.type === "MemberExpression" && node.argument.callee.property.type === "Identifier" && INDEX_OF_PATTERN.test(node.argument.callee.property.name);
78798}
78799/**
78800 * Checks whether or not a node is a multiplying by one.
78801 * @param {BinaryExpression} node A BinaryExpression node to check.
78802 * @returns {boolean} Whether or not the node is a multiplying by one.
78803 */
78804
78805
78806function isMultiplyByOne(node) {
78807 return node.operator === "*" && (node.left.type === "Literal" && node.left.value === 1 || node.right.type === "Literal" && node.right.value === 1);
78808}
78809/**
78810 * Checks whether the result of a node is numeric or not
78811 * @param {ASTNode} node The node to test
78812 * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call
78813 */
78814
78815
78816function isNumeric(node) {
78817 return node.type === "Literal" && typeof node.value === "number" || node.type === "CallExpression" && (node.callee.name === "Number" || node.callee.name === "parseInt" || node.callee.name === "parseFloat");
78818}
78819/**
78820 * Returns the first non-numeric operand in a BinaryExpression. Designed to be
78821 * used from bottom to up since it walks up the BinaryExpression trees using
78822 * node.parent to find the result.
78823 * @param {BinaryExpression} node The BinaryExpression node to be walked up on
78824 * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null
78825 */
78826
78827
78828function getNonNumericOperand(node) {
78829 const left = node.left,
78830 right = node.right;
78831
78832 if (right.type !== "BinaryExpression" && !isNumeric(right)) {
78833 return right;
78834 }
78835
78836 if (left.type !== "BinaryExpression" && !isNumeric(left)) {
78837 return left;
78838 }
78839
78840 return null;
78841}
78842/**
78843 * Checks whether a node is an empty string literal or not.
78844 * @param {ASTNode} node The node to check.
78845 * @returns {boolean} Whether or not the passed in node is an
78846 * empty string literal or not.
78847 */
78848
78849
78850function isEmptyString(node) {
78851 return astUtils.isStringLiteral(node) && (node.value === "" || node.type === "TemplateLiteral" && node.quasis.length === 1 && node.quasis[0].value.cooked === "");
78852}
78853/**
78854 * Checks whether or not a node is a concatenating with an empty string.
78855 * @param {ASTNode} node A BinaryExpression node to check.
78856 * @returns {boolean} Whether or not the node is a concatenating with an empty string.
78857 */
78858
78859
78860function isConcatWithEmptyString(node) {
78861 return node.operator === "+" && (isEmptyString(node.left) && !astUtils.isStringLiteral(node.right) || isEmptyString(node.right) && !astUtils.isStringLiteral(node.left));
78862}
78863/**
78864 * Checks whether or not a node is appended with an empty string.
78865 * @param {ASTNode} node An AssignmentExpression node to check.
78866 * @returns {boolean} Whether or not the node is appended with an empty string.
78867 */
78868
78869
78870function isAppendEmptyString(node) {
78871 return node.operator === "+=" && isEmptyString(node.right);
78872}
78873/**
78874 * Returns the operand that is not an empty string from a flagged BinaryExpression.
78875 * @param {ASTNode} node The flagged BinaryExpression node to check.
78876 * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression.
78877 */
78878
78879
78880function getNonEmptyOperand(node) {
78881 return isEmptyString(node.left) ? node.right : node.left;
78882} //------------------------------------------------------------------------------
78883// Rule Definition
78884//------------------------------------------------------------------------------
78885
78886
78887module.exports = {
78888 meta: {
78889 type: "suggestion",
78890 docs: {
78891 description: "disallow shorthand type conversions",
78892 category: "Best Practices",
78893 recommended: false,
78894 url: "https://eslint.org/docs/rules/no-implicit-coercion"
78895 },
78896 fixable: "code",
78897 schema: [{
78898 type: "object",
78899 properties: {
78900 boolean: {
78901 type: "boolean",
78902 default: true
78903 },
78904 number: {
78905 type: "boolean",
78906 default: true
78907 },
78908 string: {
78909 type: "boolean",
78910 default: true
78911 },
78912 allow: {
78913 type: "array",
78914 items: {
78915 enum: ALLOWABLE_OPERATORS
78916 },
78917 uniqueItems: true
78918 }
78919 },
78920 additionalProperties: false
78921 }],
78922 messages: {
78923 useRecommendation: "use `{{recommendation}}` instead."
78924 }
78925 },
78926
78927 create(context) {
78928 const options = parseOptions(context.options[0] || {});
78929 const sourceCode = context.getSourceCode();
78930 /**
78931 * Reports an error and autofixes the node
78932 * @param {ASTNode} node An ast node to report the error on.
78933 * @param {string} recommendation The recommended code for the issue
78934 * @param {bool} shouldFix Whether this report should fix the node
78935 * @returns {void}
78936 */
78937
78938 function report(node, recommendation, shouldFix) {
78939 context.report({
78940 node,
78941 messageId: "useRecommendation",
78942 data: {
78943 recommendation
78944 },
78945
78946 fix(fixer) {
78947 if (!shouldFix) {
78948 return null;
78949 }
78950
78951 const tokenBefore = sourceCode.getTokenBefore(node);
78952
78953 if (tokenBefore && tokenBefore.range[1] === node.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, recommendation)) {
78954 return fixer.replaceText(node, " ".concat(recommendation));
78955 }
78956
78957 return fixer.replaceText(node, recommendation);
78958 }
78959
78960 });
78961 }
78962
78963 return {
78964 UnaryExpression(node) {
78965 let operatorAllowed; // !!foo
78966
78967 operatorAllowed = options.allow.indexOf("!!") >= 0;
78968
78969 if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) {
78970 const recommendation = "Boolean(".concat(sourceCode.getText(node.argument.argument), ")");
78971 report(node, recommendation, true);
78972 } // ~foo.indexOf(bar)
78973
78974
78975 operatorAllowed = options.allow.indexOf("~") >= 0;
78976
78977 if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) {
78978 const recommendation = "".concat(sourceCode.getText(node.argument), " !== -1");
78979 report(node, recommendation, false);
78980 } // +foo
78981
78982
78983 operatorAllowed = options.allow.indexOf("+") >= 0;
78984
78985 if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) {
78986 const recommendation = "Number(".concat(sourceCode.getText(node.argument), ")");
78987 report(node, recommendation, true);
78988 }
78989 },
78990
78991 // Use `:exit` to prevent double reporting
78992 "BinaryExpression:exit"(node) {
78993 let operatorAllowed; // 1 * foo
78994
78995 operatorAllowed = options.allow.indexOf("*") >= 0;
78996 const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && getNonNumericOperand(node);
78997
78998 if (nonNumericOperand) {
78999 const recommendation = "Number(".concat(sourceCode.getText(nonNumericOperand), ")");
79000 report(node, recommendation, true);
79001 } // "" + foo
79002
79003
79004 operatorAllowed = options.allow.indexOf("+") >= 0;
79005
79006 if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) {
79007 const recommendation = "String(".concat(sourceCode.getText(getNonEmptyOperand(node)), ")");
79008 report(node, recommendation, true);
79009 }
79010 },
79011
79012 AssignmentExpression(node) {
79013 // foo += ""
79014 const operatorAllowed = options.allow.indexOf("+") >= 0;
79015
79016 if (!operatorAllowed && options.string && isAppendEmptyString(node)) {
79017 const code = sourceCode.getText(getNonEmptyOperand(node));
79018 const recommendation = "".concat(code, " = String(").concat(code, ")");
79019 report(node, recommendation, true);
79020 }
79021 }
79022
79023 };
79024 }
79025
79026};
79027
79028/***/ }),
79029/* 558 */
79030/***/ (function(module, exports, __webpack_require__) {
79031
79032"use strict";
79033/**
79034 * @fileoverview Rule to check for implicit global variables, functions and classes.
79035 * @author Joshua Peek
79036 */
79037 //------------------------------------------------------------------------------
79038// Rule Definition
79039//------------------------------------------------------------------------------
79040
79041module.exports = {
79042 meta: {
79043 type: "suggestion",
79044 docs: {
79045 description: "disallow declarations in the global scope",
79046 category: "Best Practices",
79047 recommended: false,
79048 url: "https://eslint.org/docs/rules/no-implicit-globals"
79049 },
79050 schema: [{
79051 type: "object",
79052 properties: {
79053 lexicalBindings: {
79054 type: "boolean",
79055 default: false
79056 }
79057 },
79058 additionalProperties: false
79059 }],
79060 messages: {
79061 globalNonLexicalBinding: "Unexpected {{kind}} declaration in the global scope, wrap in an IIFE for a local variable, assign as global property for a global variable.",
79062 globalLexicalBinding: "Unexpected {{kind}} declaration in the global scope, wrap in a block or in an IIFE.",
79063 globalVariableLeak: "Global variable leak, declare the variable if it is intended to be local.",
79064 assignmentToReadonlyGlobal: "Unexpected assignment to read-only global variable.",
79065 redeclarationOfReadonlyGlobal: "Unexpected redeclaration of read-only global variable."
79066 }
79067 },
79068
79069 create(context) {
79070 const checkLexicalBindings = context.options[0] && context.options[0].lexicalBindings === true;
79071 /**
79072 * Reports the node.
79073 * @param {ASTNode} node Node to report.
79074 * @param {string} messageId Id of the message to report.
79075 * @param {string|undefined} kind Declaration kind, can be 'var', 'const', 'let', function or class.
79076 * @returns {void}
79077 */
79078
79079 function report(node, messageId, kind) {
79080 context.report({
79081 node,
79082 messageId,
79083 data: {
79084 kind
79085 }
79086 });
79087 }
79088
79089 return {
79090 Program() {
79091 const scope = context.getScope();
79092 scope.variables.forEach(variable => {
79093 // Only ESLint global variables have the `writable` key.
79094 const isReadonlyEslintGlobalVariable = variable.writeable === false;
79095 const isWritableEslintGlobalVariable = variable.writeable === true;
79096
79097 if (isWritableEslintGlobalVariable) {
79098 // Everything is allowed with writable ESLint global variables.
79099 return;
79100 }
79101
79102 variable.defs.forEach(def => {
79103 const defNode = def.node;
79104
79105 if (def.type === "FunctionName" || def.type === "Variable" && def.parent.kind === "var") {
79106 if (isReadonlyEslintGlobalVariable) {
79107 report(defNode, "redeclarationOfReadonlyGlobal");
79108 } else {
79109 report(defNode, "globalNonLexicalBinding", def.type === "FunctionName" ? "function" : "'".concat(def.parent.kind, "'"));
79110 }
79111 }
79112
79113 if (checkLexicalBindings) {
79114 if (def.type === "ClassName" || def.type === "Variable" && (def.parent.kind === "let" || def.parent.kind === "const")) {
79115 if (isReadonlyEslintGlobalVariable) {
79116 report(defNode, "redeclarationOfReadonlyGlobal");
79117 } else {
79118 report(defNode, "globalLexicalBinding", def.type === "ClassName" ? "class" : "'".concat(def.parent.kind, "'"));
79119 }
79120 }
79121 }
79122 });
79123 }); // Undeclared assigned variables.
79124
79125 scope.implicit.variables.forEach(variable => {
79126 const scopeVariable = scope.set.get(variable.name);
79127 let messageId;
79128
79129 if (scopeVariable) {
79130 // ESLint global variable
79131 if (scopeVariable.writeable) {
79132 return;
79133 }
79134
79135 messageId = "assignmentToReadonlyGlobal";
79136 } else {
79137 // Reference to an unknown variable, possible global leak.
79138 messageId = "globalVariableLeak";
79139 } // def.node is an AssignmentExpression, ForInStatement or ForOfStatement.
79140
79141
79142 variable.defs.forEach(def => {
79143 report(def.node, messageId);
79144 });
79145 });
79146 }
79147
79148 };
79149 }
79150
79151};
79152
79153/***/ }),
79154/* 559 */
79155/***/ (function(module, exports, __webpack_require__) {
79156
79157"use strict";
79158/**
79159 * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval
79160 * @author James Allardice
79161 */
79162 //------------------------------------------------------------------------------
79163// Requirements
79164//------------------------------------------------------------------------------
79165
79166const astUtils = __webpack_require__(426);
79167
79168const {
79169 getStaticValue
79170} = __webpack_require__(549); //------------------------------------------------------------------------------
79171// Rule Definition
79172//------------------------------------------------------------------------------
79173
79174
79175module.exports = {
79176 meta: {
79177 type: "suggestion",
79178 docs: {
79179 description: "disallow the use of `eval()`-like methods",
79180 category: "Best Practices",
79181 recommended: false,
79182 url: "https://eslint.org/docs/rules/no-implied-eval"
79183 },
79184 schema: [],
79185 messages: {
79186 impliedEval: "Implied eval. Consider passing a function instead of a string."
79187 }
79188 },
79189
79190 create(context) {
79191 const EVAL_LIKE_FUNCS = Object.freeze(["setTimeout", "execScript", "setInterval"]);
79192 const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]);
79193 /**
79194 * Checks whether a node is evaluated as a string or not.
79195 * @param {ASTNode} node A node to check.
79196 * @returns {boolean} True if the node is evaluated as a string.
79197 */
79198
79199 function isEvaluatedString(node) {
79200 if (node.type === "Literal" && typeof node.value === "string" || node.type === "TemplateLiteral") {
79201 return true;
79202 }
79203
79204 if (node.type === "BinaryExpression" && node.operator === "+") {
79205 return isEvaluatedString(node.left) || isEvaluatedString(node.right);
79206 }
79207
79208 return false;
79209 }
79210 /**
79211 * Checks whether a node is an Identifier node named one of the specified names.
79212 * @param {ASTNode} node A node to check.
79213 * @param {string[]} specifiers Array of specified name.
79214 * @returns {boolean} True if the node is a Identifier node which has specified name.
79215 */
79216
79217
79218 function isSpecifiedIdentifier(node, specifiers) {
79219 return node.type === "Identifier" && specifiers.includes(node.name);
79220 }
79221 /**
79222 * Checks a given node is a MemberExpression node which has the specified name's
79223 * property.
79224 * @param {ASTNode} node A node to check.
79225 * @param {string[]} specifiers Array of specified name.
79226 * @returns {boolean} `true` if the node is a MemberExpression node which has
79227 * the specified name's property
79228 */
79229
79230
79231 function isSpecifiedMember(node, specifiers) {
79232 return node.type === "MemberExpression" && specifiers.includes(astUtils.getStaticPropertyName(node));
79233 }
79234 /**
79235 * Reports if the `CallExpression` node has evaluated argument.
79236 * @param {ASTNode} node A CallExpression to check.
79237 * @returns {void}
79238 */
79239
79240
79241 function reportImpliedEvalCallExpression(node) {
79242 const [firstArgument] = node.arguments;
79243
79244 if (firstArgument) {
79245 const staticValue = getStaticValue(firstArgument, context.getScope());
79246 const isStaticString = staticValue && typeof staticValue.value === "string";
79247 const isString = isStaticString || isEvaluatedString(firstArgument);
79248
79249 if (isString) {
79250 context.report({
79251 node,
79252 messageId: "impliedEval"
79253 });
79254 }
79255 }
79256 }
79257 /**
79258 * Reports calls of `implied eval` via the global references.
79259 * @param {Variable} globalVar A global variable to check.
79260 * @returns {void}
79261 */
79262
79263
79264 function reportImpliedEvalViaGlobal(globalVar) {
79265 const {
79266 references,
79267 name
79268 } = globalVar;
79269 references.forEach(ref => {
79270 const identifier = ref.identifier;
79271 let node = identifier.parent;
79272
79273 while (isSpecifiedMember(node, [name])) {
79274 node = node.parent;
79275 }
79276
79277 if (isSpecifiedMember(node, EVAL_LIKE_FUNCS)) {
79278 const parent = node.parent;
79279
79280 if (parent.type === "CallExpression" && parent.callee === node) {
79281 reportImpliedEvalCallExpression(parent);
79282 }
79283 }
79284 });
79285 } //--------------------------------------------------------------------------
79286 // Public
79287 //--------------------------------------------------------------------------
79288
79289
79290 return {
79291 CallExpression(node) {
79292 if (isSpecifiedIdentifier(node.callee, EVAL_LIKE_FUNCS)) {
79293 reportImpliedEvalCallExpression(node);
79294 }
79295 },
79296
79297 "Program:exit"() {
79298 const globalScope = context.getScope();
79299 GLOBAL_CANDIDATES.map(candidate => astUtils.getVariableByName(globalScope, candidate)).filter(globalVar => !!globalVar && globalVar.defs.length === 0).forEach(reportImpliedEvalViaGlobal);
79300 }
79301
79302 };
79303 }
79304
79305};
79306
79307/***/ }),
79308/* 560 */
79309/***/ (function(module, exports, __webpack_require__) {
79310
79311"use strict";
79312/**
79313 * @fileoverview Rule to flag updates of imported bindings.
79314 * @author Toru Nagashima <https://github.com/mysticatea>
79315 */
79316 //------------------------------------------------------------------------------
79317// Helpers
79318//------------------------------------------------------------------------------
79319
79320const {
79321 findVariable,
79322 getPropertyName
79323} = __webpack_require__(549);
79324
79325const MutationMethods = {
79326 Object: new Set(["assign", "defineProperties", "defineProperty", "freeze", "setPrototypeOf"]),
79327 Reflect: new Set(["defineProperty", "deleteProperty", "set", "setPrototypeOf"])
79328};
79329/**
79330 * Check if a given node is LHS of an assignment node.
79331 * @param {ASTNode} node The node to check.
79332 * @returns {boolean} `true` if the node is LHS.
79333 */
79334
79335function isAssignmentLeft(node) {
79336 const {
79337 parent
79338 } = node;
79339 return parent.type === "AssignmentExpression" && parent.left === node || // Destructuring assignments
79340 parent.type === "ArrayPattern" || parent.type === "Property" && parent.value === node && parent.parent.type === "ObjectPattern" || parent.type === "RestElement" || parent.type === "AssignmentPattern" && parent.left === node;
79341}
79342/**
79343 * Check if a given node is the operand of mutation unary operator.
79344 * @param {ASTNode} node The node to check.
79345 * @returns {boolean} `true` if the node is the operand of mutation unary operator.
79346 */
79347
79348
79349function isOperandOfMutationUnaryOperator(node) {
79350 const {
79351 parent
79352 } = node;
79353 return parent.type === "UpdateExpression" && parent.argument === node || parent.type === "UnaryExpression" && parent.operator === "delete" && parent.argument === node;
79354}
79355/**
79356 * Check if a given node is the iteration variable of `for-in`/`for-of` syntax.
79357 * @param {ASTNode} node The node to check.
79358 * @returns {boolean} `true` if the node is the iteration variable.
79359 */
79360
79361
79362function isIterationVariable(node) {
79363 const {
79364 parent
79365 } = node;
79366 return parent.type === "ForInStatement" && parent.left === node || parent.type === "ForOfStatement" && parent.left === node;
79367}
79368/**
79369 * Check if a given node is the iteration variable of `for-in`/`for-of` syntax.
79370 * @param {ASTNode} node The node to check.
79371 * @param {Scope} scope A `escope.Scope` object to find variable (whichever).
79372 * @returns {boolean} `true` if the node is the iteration variable.
79373 */
79374
79375
79376function isArgumentOfWellKnownMutationFunction(node, scope) {
79377 const {
79378 parent
79379 } = node;
79380
79381 if (parent.type === "CallExpression" && parent.arguments[0] === node && parent.callee.type === "MemberExpression" && parent.callee.object.type === "Identifier") {
79382 const {
79383 callee
79384 } = parent;
79385 const {
79386 object
79387 } = callee;
79388
79389 if (Object.keys(MutationMethods).includes(object.name)) {
79390 const variable = findVariable(scope, object);
79391 return variable !== null && variable.scope.type === "global" && MutationMethods[object.name].has(getPropertyName(callee, scope));
79392 }
79393 }
79394
79395 return false;
79396}
79397/**
79398 * Check if the identifier node is placed at to update members.
79399 * @param {ASTNode} id The Identifier node to check.
79400 * @param {Scope} scope A `escope.Scope` object to find variable (whichever).
79401 * @returns {boolean} `true` if the member of `id` was updated.
79402 */
79403
79404
79405function isMemberWrite(id, scope) {
79406 const {
79407 parent
79408 } = id;
79409 return parent.type === "MemberExpression" && parent.object === id && (isAssignmentLeft(parent) || isOperandOfMutationUnaryOperator(parent) || isIterationVariable(parent)) || isArgumentOfWellKnownMutationFunction(id, scope);
79410}
79411/**
79412 * Get the mutation node.
79413 * @param {ASTNode} id The Identifier node to get.
79414 * @returns {ASTNode} The mutation node.
79415 */
79416
79417
79418function getWriteNode(id) {
79419 let node = id.parent;
79420
79421 while (node && node.type !== "AssignmentExpression" && node.type !== "UpdateExpression" && node.type !== "UnaryExpression" && node.type !== "CallExpression" && node.type !== "ForInStatement" && node.type !== "ForOfStatement") {
79422 node = node.parent;
79423 }
79424
79425 return node || id;
79426} //------------------------------------------------------------------------------
79427// Rule Definition
79428//------------------------------------------------------------------------------
79429
79430
79431module.exports = {
79432 meta: {
79433 type: "problem",
79434 docs: {
79435 description: "disallow assigning to imported bindings",
79436 category: "Possible Errors",
79437 recommended: true,
79438 url: "https://eslint.org/docs/rules/no-import-assign"
79439 },
79440 schema: [],
79441 messages: {
79442 readonly: "'{{name}}' is read-only.",
79443 readonlyMember: "The members of '{{name}}' are read-only."
79444 }
79445 },
79446
79447 create(context) {
79448 return {
79449 ImportDeclaration(node) {
79450 const scope = context.getScope();
79451
79452 for (const variable of context.getDeclaredVariables(node)) {
79453 const shouldCheckMembers = variable.defs.some(d => d.node.type === "ImportNamespaceSpecifier");
79454 let prevIdNode = null;
79455
79456 for (const reference of variable.references) {
79457 const idNode = reference.identifier;
79458 /*
79459 * AssignmentPattern (e.g. `[a = 0] = b`) makes two write
79460 * references for the same identifier. This should skip
79461 * the one of the two in order to prevent redundant reports.
79462 */
79463
79464 if (idNode === prevIdNode) {
79465 continue;
79466 }
79467
79468 prevIdNode = idNode;
79469
79470 if (reference.isWrite()) {
79471 context.report({
79472 node: getWriteNode(idNode),
79473 messageId: "readonly",
79474 data: {
79475 name: idNode.name
79476 }
79477 });
79478 } else if (shouldCheckMembers && isMemberWrite(idNode, scope)) {
79479 context.report({
79480 node: getWriteNode(idNode),
79481 messageId: "readonlyMember",
79482 data: {
79483 name: idNode.name
79484 }
79485 });
79486 }
79487 }
79488 }
79489 }
79490
79491 };
79492 }
79493
79494};
79495
79496/***/ }),
79497/* 561 */
79498/***/ (function(module, exports, __webpack_require__) {
79499
79500"use strict";
79501/**
79502 * @fileoverview Enforces or disallows inline comments.
79503 * @author Greg Cochard
79504 */
79505
79506
79507const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
79508// Rule Definition
79509//------------------------------------------------------------------------------
79510
79511
79512module.exports = {
79513 meta: {
79514 type: "suggestion",
79515 docs: {
79516 description: "disallow inline comments after code",
79517 category: "Stylistic Issues",
79518 recommended: false,
79519 url: "https://eslint.org/docs/rules/no-inline-comments"
79520 },
79521 schema: [],
79522 messages: {
79523 unexpectedInlineComment: "Unexpected comment inline with code."
79524 }
79525 },
79526
79527 create(context) {
79528 const sourceCode = context.getSourceCode();
79529 /**
79530 * Will check that comments are not on lines starting with or ending with code
79531 * @param {ASTNode} node The comment node to check
79532 * @private
79533 * @returns {void}
79534 */
79535
79536 function testCodeAroundComment(node) {
79537 const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
79538 endLine = String(sourceCode.lines[node.loc.end.line - 1]),
79539 preamble = startLine.slice(0, node.loc.start.column).trim(),
79540 postamble = endLine.slice(node.loc.end.column).trim(),
79541 isPreambleEmpty = !preamble,
79542 isPostambleEmpty = !postamble; // Nothing on both sides
79543
79544 if (isPreambleEmpty && isPostambleEmpty) {
79545 return;
79546 } // JSX Exception
79547
79548
79549 if ((isPreambleEmpty || preamble === "{") && (isPostambleEmpty || postamble === "}")) {
79550 const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]);
79551
79552 if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") {
79553 return;
79554 }
79555 } // Don't report ESLint directive comments
79556
79557
79558 if (astUtils.isDirectiveComment(node)) {
79559 return;
79560 }
79561
79562 context.report({
79563 node,
79564 messageId: "unexpectedInlineComment"
79565 });
79566 } //--------------------------------------------------------------------------
79567 // Public
79568 //--------------------------------------------------------------------------
79569
79570
79571 return {
79572 Program() {
79573 const comments = sourceCode.getAllComments();
79574 comments.filter(token => token.type !== "Shebang").forEach(testCodeAroundComment);
79575 }
79576
79577 };
79578 }
79579
79580};
79581
79582/***/ }),
79583/* 562 */
79584/***/ (function(module, exports, __webpack_require__) {
79585
79586"use strict";
79587/**
79588 * @fileoverview Rule to enforce declarations in program or function body root.
79589 * @author Brandon Mills
79590 */
79591 //------------------------------------------------------------------------------
56c4a2cb
DC
79592// Requirements
79593//------------------------------------------------------------------------------
79594
79595const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
eb39fafa
DC
79596// Rule Definition
79597//------------------------------------------------------------------------------
79598
56c4a2cb
DC
79599
79600const validParent = new Set(["Program", "ExportNamedDeclaration", "ExportDefaultDeclaration"]);
79601const validBlockStatementParent = new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
eb39fafa
DC
79602module.exports = {
79603 meta: {
79604 type: "problem",
79605 docs: {
79606 description: "disallow variable or `function` declarations in nested blocks",
79607 category: "Possible Errors",
79608 recommended: true,
79609 url: "https://eslint.org/docs/rules/no-inner-declarations"
79610 },
79611 schema: [{
79612 enum: ["functions", "both"]
79613 }],
79614 messages: {
79615 moveDeclToRoot: "Move {{type}} declaration to {{body}} root."
79616 }
79617 },
79618
79619 create(context) {
eb39fafa
DC
79620 /**
79621 * Ensure that a given node is at a program or function body's root.
79622 * @param {ASTNode} node Declaration node to check.
79623 * @returns {void}
79624 */
eb39fafa 79625 function check(node) {
56c4a2cb 79626 const parent = node.parent;
eb39fafa 79627
56c4a2cb
DC
79628 if (parent.type === "BlockStatement" && validBlockStatementParent.has(parent.parent.type)) {
79629 return;
79630 }
79631
79632 if (validParent.has(parent.type)) {
79633 return;
eb39fafa 79634 }
56c4a2cb
DC
79635
79636 const upperFunction = astUtils.getUpperFunction(parent);
79637 context.report({
79638 node,
79639 messageId: "moveDeclToRoot",
79640 data: {
79641 type: node.type === "FunctionDeclaration" ? "function" : "variable",
79642 body: upperFunction === null ? "program" : "function body"
79643 }
79644 });
eb39fafa
DC
79645 }
79646
79647 return {
79648 FunctionDeclaration: check,
79649
79650 VariableDeclaration(node) {
79651 if (context.options[0] === "both" && node.kind === "var") {
79652 check(node);
79653 }
79654 }
79655
79656 };
79657 }
79658
79659};
79660
79661/***/ }),
79662/* 563 */
79663/***/ (function(module, exports, __webpack_require__) {
79664
79665"use strict";
79666/**
79667 * @fileoverview Validate strings passed to the RegExp constructor
79668 * @author Michael Ficarra
79669 */
79670 //------------------------------------------------------------------------------
79671// Requirements
79672//------------------------------------------------------------------------------
79673
79674const RegExpValidator = __webpack_require__(527).RegExpValidator;
79675
79676const validator = new RegExpValidator({
79677 ecmaVersion: 2018
79678});
79679const validFlags = /[gimuys]/gu;
79680const undefined1 = void 0; //------------------------------------------------------------------------------
79681// Rule Definition
79682//------------------------------------------------------------------------------
79683
79684module.exports = {
79685 meta: {
79686 type: "problem",
79687 docs: {
79688 description: "disallow invalid regular expression strings in `RegExp` constructors",
79689 category: "Possible Errors",
79690 recommended: true,
79691 url: "https://eslint.org/docs/rules/no-invalid-regexp"
79692 },
79693 schema: [{
79694 type: "object",
79695 properties: {
79696 allowConstructorFlags: {
79697 type: "array",
79698 items: {
79699 type: "string"
79700 }
79701 }
79702 },
79703 additionalProperties: false
79704 }],
79705 messages: {
79706 regexMessage: "{{message}}."
79707 }
79708 },
79709
79710 create(context) {
79711 const options = context.options[0];
79712 let allowedFlags = null;
79713
79714 if (options && options.allowConstructorFlags) {
79715 const temp = options.allowConstructorFlags.join("").replace(validFlags, "");
79716
79717 if (temp) {
79718 allowedFlags = new RegExp("[".concat(temp, "]"), "giu");
79719 }
79720 }
79721 /**
79722 * Check if node is a string
79723 * @param {ASTNode} node node to evaluate
79724 * @returns {boolean} True if its a string
79725 * @private
79726 */
79727
79728
79729 function isString(node) {
79730 return node && node.type === "Literal" && typeof node.value === "string";
79731 }
79732 /**
79733 * Check syntax error in a given pattern.
79734 * @param {string} pattern The RegExp pattern to validate.
79735 * @param {boolean} uFlag The Unicode flag.
79736 * @returns {string|null} The syntax error.
79737 */
79738
79739
79740 function validateRegExpPattern(pattern, uFlag) {
79741 try {
79742 validator.validatePattern(pattern, undefined1, undefined1, uFlag);
79743 return null;
79744 } catch (err) {
79745 return err.message;
79746 }
79747 }
79748 /**
79749 * Check syntax error in a given flags.
79750 * @param {string} flags The RegExp flags to validate.
79751 * @returns {string|null} The syntax error.
79752 */
79753
79754
79755 function validateRegExpFlags(flags) {
79756 try {
79757 validator.validateFlags(flags);
79758 return null;
79759 } catch (err) {
79760 return "Invalid flags supplied to RegExp constructor '".concat(flags, "'");
79761 }
79762 }
79763
79764 return {
79765 "CallExpression, NewExpression"(node) {
79766 if (node.callee.type !== "Identifier" || node.callee.name !== "RegExp" || !isString(node.arguments[0])) {
79767 return;
79768 }
79769
79770 const pattern = node.arguments[0].value;
79771 let flags = isString(node.arguments[1]) ? node.arguments[1].value : "";
79772
79773 if (allowedFlags) {
79774 flags = flags.replace(allowedFlags, "");
79775 } // If flags are unknown, check both are errored or not.
79776
79777
79778 const message = validateRegExpFlags(flags) || (flags ? validateRegExpPattern(pattern, flags.indexOf("u") !== -1) : validateRegExpPattern(pattern, true) && validateRegExpPattern(pattern, false));
79779
79780 if (message) {
79781 context.report({
79782 node,
79783 messageId: "regexMessage",
79784 data: {
79785 message
79786 }
79787 });
79788 }
79789 }
79790
79791 };
79792 }
79793
79794};
79795
79796/***/ }),
79797/* 564 */
79798/***/ (function(module, exports, __webpack_require__) {
79799
79800"use strict";
79801/**
79802 * @fileoverview A rule to disallow `this` keywords outside of classes or class-like objects.
79803 * @author Toru Nagashima
79804 */
79805 //------------------------------------------------------------------------------
79806// Requirements
79807//------------------------------------------------------------------------------
79808
79809const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
79810// Rule Definition
79811//------------------------------------------------------------------------------
79812
79813
79814module.exports = {
79815 meta: {
79816 type: "suggestion",
79817 docs: {
79818 description: "disallow `this` keywords outside of classes or class-like objects",
79819 category: "Best Practices",
79820 recommended: false,
79821 url: "https://eslint.org/docs/rules/no-invalid-this"
79822 },
79823 schema: [{
79824 type: "object",
79825 properties: {
79826 capIsConstructor: {
79827 type: "boolean",
79828 default: true
79829 }
79830 },
79831 additionalProperties: false
79832 }],
79833 messages: {
79834 unexpectedThis: "Unexpected 'this'."
79835 }
79836 },
79837
79838 create(context) {
79839 const options = context.options[0] || {};
79840 const capIsConstructor = options.capIsConstructor !== false;
79841 const stack = [],
79842 sourceCode = context.getSourceCode();
79843 /**
79844 * Gets the current checking context.
79845 *
79846 * The return value has a flag that whether or not `this` keyword is valid.
79847 * The flag is initialized when got at the first time.
79848 * @returns {{valid: boolean}}
79849 * an object which has a flag that whether or not `this` keyword is valid.
79850 */
79851
79852 stack.getCurrent = function () {
79853 const current = this[this.length - 1];
79854
79855 if (!current.init) {
79856 current.init = true;
79857 current.valid = !astUtils.isDefaultThisBinding(current.node, sourceCode, {
79858 capIsConstructor
79859 });
79860 }
79861
79862 return current;
79863 };
79864 /**
79865 * Pushs new checking context into the stack.
79866 *
79867 * The checking context is not initialized yet.
79868 * Because most functions don't have `this` keyword.
79869 * When `this` keyword was found, the checking context is initialized.
79870 * @param {ASTNode} node A function node that was entered.
79871 * @returns {void}
79872 */
79873
79874
79875 function enterFunction(node) {
79876 // `this` can be invalid only under strict mode.
79877 stack.push({
79878 init: !context.getScope().isStrict,
79879 node,
79880 valid: true
79881 });
79882 }
79883 /**
79884 * Pops the current checking context from the stack.
79885 * @returns {void}
79886 */
79887
79888
79889 function exitFunction() {
79890 stack.pop();
79891 }
79892
79893 return {
79894 /*
79895 * `this` is invalid only under strict mode.
79896 * Modules is always strict mode.
79897 */
79898 Program(node) {
79899 const scope = context.getScope(),
79900 features = context.parserOptions.ecmaFeatures || {};
79901 stack.push({
79902 init: true,
79903 node,
79904 valid: !(scope.isStrict || node.sourceType === "module" || features.globalReturn && scope.childScopes[0].isStrict)
79905 });
79906 },
79907
79908 "Program:exit"() {
79909 stack.pop();
79910 },
79911
79912 FunctionDeclaration: enterFunction,
79913 "FunctionDeclaration:exit": exitFunction,
79914 FunctionExpression: enterFunction,
79915 "FunctionExpression:exit": exitFunction,
79916
79917 // Reports if `this` of the current context is invalid.
79918 ThisExpression(node) {
79919 const current = stack.getCurrent();
79920
79921 if (current && !current.valid) {
79922 context.report({
79923 node,
79924 messageId: "unexpectedThis"
79925 });
79926 }
79927 }
79928
79929 };
79930 }
79931
79932};
79933
79934/***/ }),
79935/* 565 */
79936/***/ (function(module, exports, __webpack_require__) {
79937
79938"use strict";
79939/**
79940 * @fileoverview Rule to disallow whitespace that is not a tab or space, whitespace inside strings and comments are allowed
79941 * @author Jonathan Kingston
79942 * @author Christophe Porteneuve
79943 */
79944 //------------------------------------------------------------------------------
79945// Requirements
79946//------------------------------------------------------------------------------
79947
79948const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
79949// Constants
79950//------------------------------------------------------------------------------
79951
79952
79953const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u;
79954const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mgu;
79955const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mgu;
79956const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); //------------------------------------------------------------------------------
79957// Rule Definition
79958//------------------------------------------------------------------------------
79959
79960module.exports = {
79961 meta: {
79962 type: "problem",
79963 docs: {
79964 description: "disallow irregular whitespace",
79965 category: "Possible Errors",
79966 recommended: true,
79967 url: "https://eslint.org/docs/rules/no-irregular-whitespace"
79968 },
79969 schema: [{
79970 type: "object",
79971 properties: {
79972 skipComments: {
79973 type: "boolean",
79974 default: false
79975 },
79976 skipStrings: {
79977 type: "boolean",
79978 default: true
79979 },
79980 skipTemplates: {
79981 type: "boolean",
79982 default: false
79983 },
79984 skipRegExps: {
79985 type: "boolean",
79986 default: false
79987 }
79988 },
79989 additionalProperties: false
79990 }],
79991 messages: {
79992 noIrregularWhitespace: "Irregular whitespace not allowed."
79993 }
79994 },
79995
79996 create(context) {
79997 // Module store of errors that we have found
79998 let errors = []; // Lookup the `skipComments` option, which defaults to `false`.
79999
80000 const options = context.options[0] || {};
80001 const skipComments = !!options.skipComments;
80002 const skipStrings = options.skipStrings !== false;
80003 const skipRegExps = !!options.skipRegExps;
80004 const skipTemplates = !!options.skipTemplates;
80005 const sourceCode = context.getSourceCode();
80006 const commentNodes = sourceCode.getAllComments();
80007 /**
80008 * Removes errors that occur inside a string node
80009 * @param {ASTNode} node to check for matching errors.
80010 * @returns {void}
80011 * @private
80012 */
80013
80014 function removeWhitespaceError(node) {
80015 const locStart = node.loc.start;
80016 const locEnd = node.loc.end;
80017 errors = errors.filter(({
80018 loc: errorLoc
80019 }) => {
80020 if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) {
80021 if (errorLoc.column >= locStart.column && (errorLoc.column <= locEnd.column || errorLoc.line < locEnd.line)) {
80022 return false;
80023 }
80024 }
80025
80026 return true;
80027 });
80028 }
80029 /**
80030 * Checks identifier or literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
80031 * @param {ASTNode} node to check for matching errors.
80032 * @returns {void}
80033 * @private
80034 */
80035
80036
80037 function removeInvalidNodeErrorsInIdentifierOrLiteral(node) {
80038 const shouldCheckStrings = skipStrings && typeof node.value === "string";
80039 const shouldCheckRegExps = skipRegExps && Boolean(node.regex);
80040
80041 if (shouldCheckStrings || shouldCheckRegExps) {
80042 // If we have irregular characters remove them from the errors list
80043 if (ALL_IRREGULARS.test(node.raw)) {
80044 removeWhitespaceError(node);
80045 }
80046 }
80047 }
80048 /**
80049 * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
80050 * @param {ASTNode} node to check for matching errors.
80051 * @returns {void}
80052 * @private
80053 */
80054
80055
80056 function removeInvalidNodeErrorsInTemplateLiteral(node) {
80057 if (typeof node.value.raw === "string") {
80058 if (ALL_IRREGULARS.test(node.value.raw)) {
80059 removeWhitespaceError(node);
80060 }
80061 }
80062 }
80063 /**
80064 * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
80065 * @param {ASTNode} node to check for matching errors.
80066 * @returns {void}
80067 * @private
80068 */
80069
80070
80071 function removeInvalidNodeErrorsInComment(node) {
80072 if (ALL_IRREGULARS.test(node.value)) {
80073 removeWhitespaceError(node);
80074 }
80075 }
80076 /**
80077 * Checks the program source for irregular whitespace
80078 * @param {ASTNode} node The program node
80079 * @returns {void}
80080 * @private
80081 */
80082
80083
80084 function checkForIrregularWhitespace(node) {
80085 const sourceLines = sourceCode.lines;
80086 sourceLines.forEach((sourceLine, lineIndex) => {
80087 const lineNumber = lineIndex + 1;
80088 let match;
80089
80090 while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) {
80091 const location = {
80092 line: lineNumber,
80093 column: match.index
80094 };
80095 errors.push({
80096 node,
80097 messageId: "noIrregularWhitespace",
80098 loc: location
80099 });
80100 }
80101 });
80102 }
80103 /**
80104 * Checks the program source for irregular line terminators
80105 * @param {ASTNode} node The program node
80106 * @returns {void}
80107 * @private
80108 */
80109
80110
80111 function checkForIrregularLineTerminators(node) {
80112 const source = sourceCode.getText(),
80113 sourceLines = sourceCode.lines,
80114 linebreaks = source.match(LINE_BREAK);
80115 let lastLineIndex = -1,
80116 match;
80117
80118 while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) {
80119 const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0;
80120 const location = {
80121 line: lineIndex + 1,
80122 column: sourceLines[lineIndex].length
80123 };
80124 errors.push({
80125 node,
80126 messageId: "noIrregularWhitespace",
80127 loc: location
80128 });
80129 lastLineIndex = lineIndex;
80130 }
80131 }
80132 /**
80133 * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`.
80134 * @returns {void}
80135 * @private
80136 */
80137
80138
80139 function noop() {}
80140
80141 const nodes = {};
80142
80143 if (ALL_IRREGULARS.test(sourceCode.getText())) {
80144 nodes.Program = function (node) {
80145 /*
80146 * As we can easily fire warnings for all white space issues with
80147 * all the source its simpler to fire them here.
80148 * This means we can check all the application code without having
80149 * to worry about issues caused in the parser tokens.
80150 * When writing this code also evaluating per node was missing out
80151 * connecting tokens in some cases.
80152 * We can later filter the errors when they are found to be not an
80153 * issue in nodes we don't care about.
80154 */
80155 checkForIrregularWhitespace(node);
80156 checkForIrregularLineTerminators(node);
80157 };
80158
80159 nodes.Identifier = removeInvalidNodeErrorsInIdentifierOrLiteral;
80160 nodes.Literal = removeInvalidNodeErrorsInIdentifierOrLiteral;
80161 nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop;
80162
80163 nodes["Program:exit"] = function () {
80164 if (skipComments) {
80165 // First strip errors occurring in comment nodes.
80166 commentNodes.forEach(removeInvalidNodeErrorsInComment);
80167 } // If we have any errors remaining report on them
80168
80169
80170 errors.forEach(error => context.report(error));
80171 };
80172 } else {
80173 nodes.Program = noop;
80174 }
80175
80176 return nodes;
80177 }
80178
80179};
80180
80181/***/ }),
80182/* 566 */
80183/***/ (function(module, exports, __webpack_require__) {
80184
80185"use strict";
80186/**
80187 * @fileoverview Rule to flag usage of __iterator__ property
80188 * @author Ian Christian Myers
80189 */
80190 //------------------------------------------------------------------------------
80191// Requirements
80192//------------------------------------------------------------------------------
80193
80194const {
80195 getStaticPropertyName
80196} = __webpack_require__(426); //------------------------------------------------------------------------------
80197// Rule Definition
80198//------------------------------------------------------------------------------
80199
80200
80201module.exports = {
80202 meta: {
80203 type: "suggestion",
80204 docs: {
80205 description: "disallow the use of the `__iterator__` property",
80206 category: "Best Practices",
80207 recommended: false,
80208 url: "https://eslint.org/docs/rules/no-iterator"
80209 },
80210 schema: [],
80211 messages: {
80212 noIterator: "Reserved name '__iterator__'."
80213 }
80214 },
80215
80216 create(context) {
80217 return {
80218 MemberExpression(node) {
80219 if (getStaticPropertyName(node) === "__iterator__") {
80220 context.report({
80221 node,
80222 messageId: "noIterator"
80223 });
80224 }
80225 }
80226
80227 };
80228 }
80229
80230};
80231
80232/***/ }),
80233/* 567 */
80234/***/ (function(module, exports, __webpack_require__) {
80235
80236"use strict";
80237/**
80238 * @fileoverview Rule to flag labels that are the same as an identifier
80239 * @author Ian Christian Myers
80240 */
80241 //------------------------------------------------------------------------------
80242// Requirements
80243//------------------------------------------------------------------------------
80244
80245const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
80246// Rule Definition
80247//------------------------------------------------------------------------------
80248
80249
80250module.exports = {
80251 meta: {
80252 type: "suggestion",
80253 docs: {
80254 description: "disallow labels that share a name with a variable",
80255 category: "Variables",
80256 recommended: false,
80257 url: "https://eslint.org/docs/rules/no-label-var"
80258 },
80259 schema: [],
80260 messages: {
80261 identifierClashWithLabel: "Found identifier with same name as label."
80262 }
80263 },
80264
80265 create(context) {
80266 //--------------------------------------------------------------------------
80267 // Helpers
80268 //--------------------------------------------------------------------------
80269
80270 /**
80271 * Check if the identifier is present inside current scope
80272 * @param {Object} scope current scope
80273 * @param {string} name To evaluate
80274 * @returns {boolean} True if its present
80275 * @private
80276 */
80277 function findIdentifier(scope, name) {
80278 return astUtils.getVariableByName(scope, name) !== null;
80279 } //--------------------------------------------------------------------------
80280 // Public API
80281 //--------------------------------------------------------------------------
80282
80283
80284 return {
80285 LabeledStatement(node) {
80286 // Fetch the innermost scope.
80287 const scope = context.getScope();
80288 /*
80289 * Recursively find the identifier walking up the scope, starting
80290 * with the innermost scope.
80291 */
80292
80293 if (findIdentifier(scope, node.label.name)) {
80294 context.report({
80295 node,
80296 messageId: "identifierClashWithLabel"
80297 });
80298 }
80299 }
80300
80301 };
80302 }
80303
80304};
80305
80306/***/ }),
80307/* 568 */
80308/***/ (function(module, exports, __webpack_require__) {
80309
80310"use strict";
80311/**
80312 * @fileoverview Disallow Labeled Statements
80313 * @author Nicholas C. Zakas
80314 */
80315 //------------------------------------------------------------------------------
80316// Requirements
80317//------------------------------------------------------------------------------
80318
80319const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
80320// Rule Definition
80321//------------------------------------------------------------------------------
80322
80323
80324module.exports = {
80325 meta: {
80326 type: "suggestion",
80327 docs: {
80328 description: "disallow labeled statements",
80329 category: "Best Practices",
80330 recommended: false,
80331 url: "https://eslint.org/docs/rules/no-labels"
80332 },
80333 schema: [{
80334 type: "object",
80335 properties: {
80336 allowLoop: {
80337 type: "boolean",
80338 default: false
80339 },
80340 allowSwitch: {
80341 type: "boolean",
80342 default: false
80343 }
80344 },
80345 additionalProperties: false
80346 }],
80347 messages: {
80348 unexpectedLabel: "Unexpected labeled statement.",
80349 unexpectedLabelInBreak: "Unexpected label in break statement.",
80350 unexpectedLabelInContinue: "Unexpected label in continue statement."
80351 }
80352 },
80353
80354 create(context) {
80355 const options = context.options[0];
80356 const allowLoop = options && options.allowLoop;
80357 const allowSwitch = options && options.allowSwitch;
80358 let scopeInfo = null;
80359 /**
80360 * Gets the kind of a given node.
80361 * @param {ASTNode} node A node to get.
80362 * @returns {string} The kind of the node.
80363 */
80364
80365 function getBodyKind(node) {
80366 if (astUtils.isLoop(node)) {
80367 return "loop";
80368 }
80369
80370 if (node.type === "SwitchStatement") {
80371 return "switch";
80372 }
80373
80374 return "other";
80375 }
80376 /**
80377 * Checks whether the label of a given kind is allowed or not.
80378 * @param {string} kind A kind to check.
80379 * @returns {boolean} `true` if the kind is allowed.
80380 */
80381
80382
80383 function isAllowed(kind) {
80384 switch (kind) {
80385 case "loop":
80386 return allowLoop;
80387
80388 case "switch":
80389 return allowSwitch;
80390
80391 default:
80392 return false;
80393 }
80394 }
80395 /**
80396 * Checks whether a given name is a label of a loop or not.
80397 * @param {string} label A name of a label to check.
80398 * @returns {boolean} `true` if the name is a label of a loop.
80399 */
80400
80401
80402 function getKind(label) {
80403 let info = scopeInfo;
80404
80405 while (info) {
80406 if (info.label === label) {
80407 return info.kind;
80408 }
80409
80410 info = info.upper;
80411 }
80412 /* istanbul ignore next: syntax error */
80413
80414
80415 return "other";
80416 } //--------------------------------------------------------------------------
80417 // Public
80418 //--------------------------------------------------------------------------
80419
80420
80421 return {
80422 LabeledStatement(node) {
80423 scopeInfo = {
80424 label: node.label.name,
80425 kind: getBodyKind(node.body),
80426 upper: scopeInfo
80427 };
80428 },
80429
80430 "LabeledStatement:exit"(node) {
80431 if (!isAllowed(scopeInfo.kind)) {
80432 context.report({
80433 node,
80434 messageId: "unexpectedLabel"
80435 });
80436 }
80437
80438 scopeInfo = scopeInfo.upper;
80439 },
80440
80441 BreakStatement(node) {
80442 if (node.label && !isAllowed(getKind(node.label.name))) {
80443 context.report({
80444 node,
80445 messageId: "unexpectedLabelInBreak"
80446 });
80447 }
80448 },
80449
80450 ContinueStatement(node) {
80451 if (node.label && !isAllowed(getKind(node.label.name))) {
80452 context.report({
80453 node,
80454 messageId: "unexpectedLabelInContinue"
80455 });
80456 }
80457 }
80458
80459 };
80460 }
80461
80462};
80463
80464/***/ }),
80465/* 569 */
80466/***/ (function(module, exports, __webpack_require__) {
80467
80468"use strict";
80469/**
80470 * @fileoverview Rule to flag blocks with no reason to exist
80471 * @author Brandon Mills
80472 */
80473 //------------------------------------------------------------------------------
80474// Rule Definition
80475//------------------------------------------------------------------------------
80476
80477module.exports = {
80478 meta: {
80479 type: "suggestion",
80480 docs: {
80481 description: "disallow unnecessary nested blocks",
80482 category: "Best Practices",
80483 recommended: false,
80484 url: "https://eslint.org/docs/rules/no-lone-blocks"
80485 },
80486 schema: [],
80487 messages: {
80488 redundantBlock: "Block is redundant.",
80489 redundantNestedBlock: "Nested block is redundant."
80490 }
80491 },
80492
80493 create(context) {
80494 // A stack of lone blocks to be checked for block-level bindings
80495 const loneBlocks = [];
80496 let ruleDef;
80497 /**
80498 * Reports a node as invalid.
80499 * @param {ASTNode} node The node to be reported.
80500 * @returns {void}
80501 */
80502
80503 function report(node) {
80504 const messageId = node.parent.type === "BlockStatement" ? "redundantNestedBlock" : "redundantBlock";
80505 context.report({
80506 node,
80507 messageId
80508 });
80509 }
80510 /**
56c4a2cb 80511 * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear
eb39fafa
DC
80512 * @param {ASTNode} node The node to check
80513 * @returns {boolean} True if the node is a lone block.
80514 */
80515
80516
80517 function isLoneBlock(node) {
80518 return node.parent.type === "BlockStatement" || node.parent.type === "Program" || // Don't report blocks in switch cases if the block is the only statement of the case.
80519 node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
80520 }
80521 /**
80522 * Checks the enclosing block of the current node for block-level bindings,
80523 * and "marks it" as valid if any.
80524 * @returns {void}
80525 */
80526
80527
80528 function markLoneBlock() {
80529 if (loneBlocks.length === 0) {
80530 return;
80531 }
80532
80533 const block = context.getAncestors().pop();
80534
80535 if (loneBlocks[loneBlocks.length - 1] === block) {
80536 loneBlocks.pop();
80537 }
80538 } // Default rule definition: report all lone blocks
80539
80540
80541 ruleDef = {
80542 BlockStatement(node) {
80543 if (isLoneBlock(node)) {
80544 report(node);
80545 }
80546 }
80547
80548 }; // ES6: report blocks without block-level bindings, or that's only child of another block
80549
80550 if (context.parserOptions.ecmaVersion >= 6) {
80551 ruleDef = {
80552 BlockStatement(node) {
80553 if (isLoneBlock(node)) {
80554 loneBlocks.push(node);
80555 }
80556 },
80557
80558 "BlockStatement:exit"(node) {
80559 if (loneBlocks.length > 0 && loneBlocks[loneBlocks.length - 1] === node) {
80560 loneBlocks.pop();
80561 report(node);
80562 } else if (node.parent.type === "BlockStatement" && node.parent.body.length === 1) {
80563 report(node);
80564 }
80565 }
80566
80567 };
80568
80569 ruleDef.VariableDeclaration = function (node) {
80570 if (node.kind === "let" || node.kind === "const") {
80571 markLoneBlock();
80572 }
80573 };
80574
80575 ruleDef.FunctionDeclaration = function () {
80576 if (context.getScope().isStrict) {
80577 markLoneBlock();
80578 }
80579 };
80580
80581 ruleDef.ClassDeclaration = markLoneBlock;
80582 }
80583
80584 return ruleDef;
80585 }
80586
80587};
80588
80589/***/ }),
80590/* 570 */
80591/***/ (function(module, exports, __webpack_require__) {
80592
80593"use strict";
80594/**
80595 * @fileoverview Rule to disallow if as the only statement in an else block
80596 * @author Brandon Mills
80597 */
80598 //------------------------------------------------------------------------------
80599// Rule Definition
80600//------------------------------------------------------------------------------
80601
80602module.exports = {
80603 meta: {
80604 type: "suggestion",
80605 docs: {
80606 description: "disallow `if` statements as the only statement in `else` blocks",
80607 category: "Stylistic Issues",
80608 recommended: false,
80609 url: "https://eslint.org/docs/rules/no-lonely-if"
80610 },
80611 schema: [],
80612 fixable: "code",
80613 messages: {
80614 unexpectedLonelyIf: "Unexpected if as the only statement in an else block."
80615 }
80616 },
80617
80618 create(context) {
80619 const sourceCode = context.getSourceCode();
80620 return {
80621 IfStatement(node) {
80622 const ancestors = context.getAncestors(),
80623 parent = ancestors.pop(),
80624 grandparent = ancestors.pop();
80625
80626 if (parent && parent.type === "BlockStatement" && parent.body.length === 1 && grandparent && grandparent.type === "IfStatement" && parent === grandparent.alternate) {
80627 context.report({
80628 node,
80629 messageId: "unexpectedLonelyIf",
80630
80631 fix(fixer) {
80632 const openingElseCurly = sourceCode.getFirstToken(parent);
80633 const closingElseCurly = sourceCode.getLastToken(parent);
80634 const elseKeyword = sourceCode.getTokenBefore(openingElseCurly);
80635 const tokenAfterElseBlock = sourceCode.getTokenAfter(closingElseCurly);
80636 const lastIfToken = sourceCode.getLastToken(node.consequent);
80637 const sourceText = sourceCode.getText();
80638
80639 if (sourceText.slice(openingElseCurly.range[1], node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) {
80640 // Don't fix if there are any non-whitespace characters interfering (e.g. comments)
80641 return null;
80642 }
80643
80644 if (node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && (node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || /^[([/+`-]/u.test(tokenAfterElseBlock.value) || lastIfToken.value === "++" || lastIfToken.value === "--")) {
80645 /*
80646 * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing
80647 * the issue would not change semantics due to ASI. If this would happen, don't do a fix.
80648 */
80649 return null;
80650 }
80651
80652 return fixer.replaceTextRange([openingElseCurly.range[0], closingElseCurly.range[1]], (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node));
80653 }
80654
80655 });
80656 }
80657 }
80658
80659 };
80660 }
80661
80662};
80663
80664/***/ }),
80665/* 571 */
80666/***/ (function(module, exports, __webpack_require__) {
80667
80668"use strict";
80669/**
80670 * @fileoverview Rule to flag creation of function inside a loop
80671 * @author Ilya Volodin
80672 */
80673 //------------------------------------------------------------------------------
80674// Helpers
80675//------------------------------------------------------------------------------
80676
80677/**
80678 * Gets the containing loop node of a specified node.
80679 *
80680 * We don't need to check nested functions, so this ignores those.
80681 * `Scope.through` contains references of nested functions.
80682 * @param {ASTNode} node An AST node to get.
80683 * @returns {ASTNode|null} The containing loop node of the specified node, or
80684 * `null`.
80685 */
80686
80687function getContainingLoopNode(node) {
80688 for (let currentNode = node; currentNode.parent; currentNode = currentNode.parent) {
80689 const parent = currentNode.parent;
80690
80691 switch (parent.type) {
80692 case "WhileStatement":
80693 case "DoWhileStatement":
80694 return parent;
80695
80696 case "ForStatement":
80697 // `init` is outside of the loop.
80698 if (parent.init !== currentNode) {
80699 return parent;
80700 }
80701
80702 break;
80703
80704 case "ForInStatement":
80705 case "ForOfStatement":
80706 // `right` is outside of the loop.
80707 if (parent.right !== currentNode) {
80708 return parent;
80709 }
80710
80711 break;
80712
80713 case "ArrowFunctionExpression":
80714 case "FunctionExpression":
80715 case "FunctionDeclaration":
80716 // We don't need to check nested functions.
80717 return null;
80718
80719 default:
80720 break;
80721 }
80722 }
80723
80724 return null;
80725}
80726/**
80727 * Gets the containing loop node of a given node.
80728 * If the loop was nested, this returns the most outer loop.
80729 * @param {ASTNode} node A node to get. This is a loop node.
80730 * @param {ASTNode|null} excludedNode A node that the result node should not
80731 * include.
80732 * @returns {ASTNode} The most outer loop node.
80733 */
80734
80735
80736function getTopLoopNode(node, excludedNode) {
80737 const border = excludedNode ? excludedNode.range[1] : 0;
80738 let retv = node;
80739 let containingLoopNode = node;
80740
80741 while (containingLoopNode && containingLoopNode.range[0] >= border) {
80742 retv = containingLoopNode;
80743 containingLoopNode = getContainingLoopNode(containingLoopNode);
80744 }
80745
80746 return retv;
80747}
80748/**
80749 * Checks whether a given reference which refers to an upper scope's variable is
80750 * safe or not.
80751 * @param {ASTNode} loopNode A containing loop node.
80752 * @param {eslint-scope.Reference} reference A reference to check.
80753 * @returns {boolean} `true` if the reference is safe or not.
80754 */
80755
80756
80757function isSafe(loopNode, reference) {
80758 const variable = reference.resolved;
80759 const definition = variable && variable.defs[0];
80760 const declaration = definition && definition.parent;
80761 const kind = declaration && declaration.type === "VariableDeclaration" ? declaration.kind : ""; // Variables which are declared by `const` is safe.
80762
80763 if (kind === "const") {
80764 return true;
80765 }
80766 /*
80767 * Variables which are declared by `let` in the loop is safe.
80768 * It's a different instance from the next loop step's.
80769 */
80770
80771
80772 if (kind === "let" && declaration.range[0] > loopNode.range[0] && declaration.range[1] < loopNode.range[1]) {
80773 return true;
80774 }
80775 /*
80776 * WriteReferences which exist after this border are unsafe because those
80777 * can modify the variable.
80778 */
80779
80780
80781 const border = getTopLoopNode(loopNode, kind === "let" ? declaration : null).range[0];
80782 /**
80783 * Checks whether a given reference is safe or not.
80784 * The reference is every reference of the upper scope's variable we are
80785 * looking now.
80786 *
80787 * It's safeafe if the reference matches one of the following condition.
80788 * - is readonly.
80789 * - doesn't exist inside a local function and after the border.
80790 * @param {eslint-scope.Reference} upperRef A reference to check.
80791 * @returns {boolean} `true` if the reference is safe.
80792 */
80793
80794 function isSafeReference(upperRef) {
80795 const id = upperRef.identifier;
80796 return !upperRef.isWrite() || variable.scope.variableScope === upperRef.from.variableScope && id.range[0] < border;
80797 }
80798
80799 return Boolean(variable) && variable.references.every(isSafeReference);
80800} //------------------------------------------------------------------------------
80801// Rule Definition
80802//------------------------------------------------------------------------------
80803
80804
80805module.exports = {
80806 meta: {
80807 type: "suggestion",
80808 docs: {
80809 description: "disallow function declarations that contain unsafe references inside loop statements",
80810 category: "Best Practices",
80811 recommended: false,
80812 url: "https://eslint.org/docs/rules/no-loop-func"
80813 },
80814 schema: [],
80815 messages: {
80816 unsafeRefs: "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}."
80817 }
80818 },
80819
80820 create(context) {
80821 /**
80822 * Reports functions which match the following condition:
80823 *
80824 * - has a loop node in ancestors.
80825 * - has any references which refers to an unsafe variable.
80826 * @param {ASTNode} node The AST node to check.
80827 * @returns {boolean} Whether or not the node is within a loop.
80828 */
80829 function checkForLoops(node) {
80830 const loopNode = getContainingLoopNode(node);
80831
80832 if (!loopNode) {
80833 return;
80834 }
80835
80836 const references = context.getScope().through;
80837 const unsafeRefs = references.filter(r => !isSafe(loopNode, r)).map(r => r.identifier.name);
80838
80839 if (unsafeRefs.length > 0) {
80840 context.report({
80841 node,
80842 messageId: "unsafeRefs",
80843 data: {
80844 varNames: "'".concat(unsafeRefs.join("', '"), "'")
80845 }
80846 });
80847 }
80848 }
80849
80850 return {
80851 ArrowFunctionExpression: checkForLoops,
80852 FunctionExpression: checkForLoops,
80853 FunctionDeclaration: checkForLoops
80854 };
80855 }
80856
80857};
80858
80859/***/ }),
80860/* 572 */
80861/***/ (function(module, exports, __webpack_require__) {
80862
6a5a0f88
TL
80863"use strict";
80864/**
80865 * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime
80866 * @author Jacob Moore
80867 */
80868 //------------------------------------------------------------------------------
80869// Rule Definition
80870//------------------------------------------------------------------------------
80871
80872module.exports = {
80873 meta: {
80874 type: "problem",
80875 docs: {
80876 description: "disallow literal numbers that lose precision",
80877 category: "Possible Errors",
80878 recommended: false,
80879 url: "https://eslint.org/docs/rules/no-loss-of-precision"
80880 },
80881 schema: [],
80882 messages: {
80883 noLossOfPrecision: "This number literal will lose precision at runtime."
80884 }
80885 },
80886
80887 create(context) {
80888 /**
80889 * Returns whether the node is number literal
80890 * @param {Node} node the node literal being evaluated
80891 * @returns {boolean} true if the node is a number literal
80892 */
80893 function isNumber(node) {
80894 return typeof node.value === "number";
80895 }
80896 /**
80897 * Checks whether the number is base ten
80898 * @param {ASTNode} node the node being evaluated
80899 * @returns {boolean} true if the node is in base ten
80900 */
80901
80902
80903 function isBaseTen(node) {
80904 const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"];
80905 return prefixes.every(prefix => !node.raw.startsWith(prefix)) && !/^0[0-7]+$/u.test(node.raw);
80906 }
80907 /**
80908 * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type
80909 * @param {Node} node the node being evaluated
80910 * @returns {boolean} true if they do not match
80911 */
80912
80913
80914 function notBaseTenLosesPrecision(node) {
80915 const rawString = node.raw.toUpperCase();
80916 let base = 0;
80917
80918 if (rawString.startsWith("0B")) {
80919 base = 2;
80920 } else if (rawString.startsWith("0X")) {
80921 base = 16;
80922 } else {
80923 base = 8;
80924 }
80925
80926 return !rawString.endsWith(node.value.toString(base).toUpperCase());
80927 }
80928 /**
80929 * Adds a decimal point to the numeric string at index 1
80930 * @param {string} stringNumber the numeric string without any decimal point
80931 * @returns {string} the numeric string with a decimal point in the proper place
80932 */
80933
80934
80935 function addDecimalPointToNumber(stringNumber) {
80936 return "".concat(stringNumber.slice(0, 1), ".").concat(stringNumber.slice(1));
80937 }
80938 /**
80939 * Returns the number stripped of leading zeros
80940 * @param {string} numberAsString the string representation of the number
80941 * @returns {string} the stripped string
80942 */
80943
80944
80945 function removeLeadingZeros(numberAsString) {
80946 return numberAsString.replace(/^0*/u, "");
80947 }
80948 /**
80949 * Returns the number stripped of trailing zeros
80950 * @param {string} numberAsString the string representation of the number
80951 * @returns {string} the stripped string
80952 */
80953
80954
80955 function removeTrailingZeros(numberAsString) {
80956 return numberAsString.replace(/0*$/u, "");
80957 }
80958 /**
80959 * Converts an integer to to an object containing the the integer's coefficient and order of magnitude
80960 * @param {string} stringInteger the string representation of the integer being converted
80961 * @returns {Object} the object containing the the integer's coefficient and order of magnitude
80962 */
80963
80964
80965 function normalizeInteger(stringInteger) {
80966 const significantDigits = removeTrailingZeros(removeLeadingZeros(stringInteger));
80967 return {
80968 magnitude: stringInteger.startsWith("0") ? stringInteger.length - 2 : stringInteger.length - 1,
80969 coefficient: addDecimalPointToNumber(significantDigits)
80970 };
80971 }
80972 /**
80973 *
80974 * Converts a float to to an object containing the the floats's coefficient and order of magnitude
80975 * @param {string} stringFloat the string representation of the float being converted
80976 * @returns {Object} the object containing the the integer's coefficient and order of magnitude
80977 */
80978
80979
80980 function normalizeFloat(stringFloat) {
80981 const trimmedFloat = removeLeadingZeros(stringFloat);
80982
80983 if (trimmedFloat.startsWith(".")) {
80984 const decimalDigits = trimmedFloat.split(".").pop();
80985 const significantDigits = removeLeadingZeros(decimalDigits);
80986 return {
80987 magnitude: significantDigits.length - decimalDigits.length - 1,
80988 coefficient: addDecimalPointToNumber(significantDigits)
80989 };
80990 }
80991
80992 return {
80993 magnitude: trimmedFloat.indexOf(".") - 1,
80994 coefficient: addDecimalPointToNumber(trimmedFloat.replace(".", ""))
80995 };
80996 }
80997 /**
80998 * Converts a base ten number to proper scientific notation
80999 * @param {string} stringNumber the string representation of the base ten number to be converted
81000 * @returns {string} the number converted to scientific notation
81001 */
81002
81003
81004 function convertNumberToScientificNotation(stringNumber) {
81005 const splitNumber = stringNumber.replace("E", "e").split("e");
81006 const originalCoefficient = splitNumber[0];
81007 const normalizedNumber = stringNumber.includes(".") ? normalizeFloat(originalCoefficient) : normalizeInteger(originalCoefficient);
81008 const normalizedCoefficient = normalizedNumber.coefficient;
81009 const magnitude = splitNumber.length > 1 ? parseInt(splitNumber[1], 10) + normalizedNumber.magnitude : normalizedNumber.magnitude;
81010 return "".concat(normalizedCoefficient, "e").concat(magnitude);
81011 }
81012 /**
81013 * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type
81014 * @param {Node} node the node being evaluated
81015 * @returns {boolean} true if they do not match
81016 */
81017
81018
81019 function baseTenLosesPrecision(node) {
81020 const normalizedRawNumber = convertNumberToScientificNotation(node.raw);
81021 const requestedPrecision = normalizedRawNumber.split("e")[0].replace(".", "").length;
81022
81023 if (requestedPrecision > 100) {
81024 return true;
81025 }
81026
81027 const storedNumber = node.value.toPrecision(requestedPrecision);
81028 const normalizedStoredNumber = convertNumberToScientificNotation(storedNumber);
81029 return normalizedRawNumber !== normalizedStoredNumber;
81030 }
81031 /**
81032 * Checks that the user-intended number equals the actual number after is has been converted to the Number type
81033 * @param {Node} node the node being evaluated
81034 * @returns {boolean} true if they do not match
81035 */
81036
81037
81038 function losesPrecision(node) {
81039 return isBaseTen(node) ? baseTenLosesPrecision(node) : notBaseTenLosesPrecision(node);
81040 }
81041
81042 return {
81043 Literal(node) {
81044 if (node.value && isNumber(node) && losesPrecision(node)) {
81045 context.report({
81046 messageId: "noLossOfPrecision",
81047 node
81048 });
81049 }
81050 }
81051
81052 };
81053 }
81054
81055};
81056
81057/***/ }),
81058/* 573 */
81059/***/ (function(module, exports, __webpack_require__) {
81060
eb39fafa
DC
81061"use strict";
81062/**
81063 * @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js)
81064 * @author Vincent Lemeunier
81065 */
81066
81067
81068const {
81069 isNumericLiteral
81070} = __webpack_require__(426); // Maximum array length by the ECMAScript Specification.
81071
81072
81073const MAX_ARRAY_LENGTH = 2 ** 32 - 1; //------------------------------------------------------------------------------
81074// Rule Definition
81075//------------------------------------------------------------------------------
81076
81077/**
81078 * Convert the value to bigint if it's a string. Otherwise return the value as-is.
81079 * @param {bigint|number|string} x The value to normalize.
81080 * @returns {bigint|number} The normalized value.
81081 */
81082
81083function normalizeIgnoreValue(x) {
81084 if (typeof x === "string") {
81085 return BigInt(x.slice(0, -1));
81086 }
81087
81088 return x;
81089}
81090
81091module.exports = {
81092 meta: {
81093 type: "suggestion",
81094 docs: {
81095 description: "disallow magic numbers",
81096 category: "Best Practices",
81097 recommended: false,
81098 url: "https://eslint.org/docs/rules/no-magic-numbers"
81099 },
81100 schema: [{
81101 type: "object",
81102 properties: {
81103 detectObjects: {
81104 type: "boolean",
81105 default: false
81106 },
81107 enforceConst: {
81108 type: "boolean",
81109 default: false
81110 },
81111 ignore: {
81112 type: "array",
81113 items: {
81114 anyOf: [{
81115 type: "number"
81116 }, {
81117 type: "string",
81118 pattern: "^[+-]?(?:0|[1-9][0-9]*)n$"
81119 }]
81120 },
81121 uniqueItems: true
81122 },
81123 ignoreArrayIndexes: {
81124 type: "boolean",
81125 default: false
81126 }
81127 },
81128 additionalProperties: false
81129 }],
81130 messages: {
81131 useConst: "Number constants declarations must use 'const'.",
81132 noMagic: "No magic number: {{raw}}."
81133 }
81134 },
81135
81136 create(context) {
81137 const config = context.options[0] || {},
81138 detectObjects = !!config.detectObjects,
81139 enforceConst = !!config.enforceConst,
81140 ignore = (config.ignore || []).map(normalizeIgnoreValue),
81141 ignoreArrayIndexes = !!config.ignoreArrayIndexes;
81142 const okTypes = detectObjects ? [] : ["ObjectExpression", "Property", "AssignmentExpression"];
81143 /**
81144 * Returns whether the rule is configured to ignore the given value
81145 * @param {bigint|number} value The value to check
81146 * @returns {boolean} true if the value is ignored
81147 */
81148
81149 function isIgnoredValue(value) {
81150 return ignore.indexOf(value) !== -1;
81151 }
81152 /**
81153 * Returns whether the given node is used as a radix within parseInt() or Number.parseInt()
81154 * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node
81155 * @returns {boolean} true if the node is radix
81156 */
81157
81158
81159 function isParseIntRadix(fullNumberNode) {
81160 const parent = fullNumberNode.parent;
81161 return parent.type === "CallExpression" && fullNumberNode === parent.arguments[1] && (parent.callee.name === "parseInt" || parent.callee.type === "MemberExpression" && parent.callee.object.name === "Number" && parent.callee.property.name === "parseInt");
81162 }
81163 /**
81164 * Returns whether the given node is a direct child of a JSX node.
81165 * In particular, it aims to detect numbers used as prop values in JSX tags.
81166 * Example: <input maxLength={10} />
81167 * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node
81168 * @returns {boolean} true if the node is a JSX number
81169 */
81170
81171
81172 function isJSXNumber(fullNumberNode) {
81173 return fullNumberNode.parent.type.indexOf("JSX") === 0;
81174 }
81175 /**
81176 * Returns whether the given node is used as an array index.
81177 * Value must coerce to a valid array index name: "0", "1", "2" ... "4294967294".
81178 *
81179 * All other values, like "-1", "2.5", or "4294967295", are just "normal" object properties,
81180 * which can be created and accessed on an array in addition to the array index properties,
81181 * but they don't affect array's length and are not considered by methods such as .map(), .forEach() etc.
81182 *
81183 * The maximum array length by the specification is 2 ** 32 - 1 = 4294967295,
81184 * thus the maximum valid index is 2 ** 32 - 2 = 4294967294.
81185 *
81186 * All notations are allowed, as long as the value coerces to one of "0", "1", "2" ... "4294967294".
81187 *
81188 * Valid examples:
81189 * a[0], a[1], a[1.2e1], a[0xAB], a[0n], a[1n]
81190 * a[-0] (same as a[0] because -0 coerces to "0")
81191 * a[-0n] (-0n evaluates to 0n)
81192 *
81193 * Invalid examples:
81194 * a[-1], a[-0xAB], a[-1n], a[2.5], a[1.23e1], a[12e-1]
81195 * a[4294967295] (above the max index, it's an access to a regular property a["4294967295"])
81196 * a[999999999999999999999] (even if it wasn't above the max index, it would be a["1e+21"])
81197 * a[1e310] (same as a["Infinity"])
81198 * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node
81199 * @param {bigint|number} value Value expressed by the fullNumberNode
81200 * @returns {boolean} true if the node is a valid array index
81201 */
81202
81203
81204 function isArrayIndex(fullNumberNode, value) {
81205 const parent = fullNumberNode.parent;
81206 return parent.type === "MemberExpression" && parent.property === fullNumberNode && (Number.isInteger(value) || typeof value === "bigint") && value >= 0 && value < MAX_ARRAY_LENGTH;
81207 }
81208
81209 return {
81210 Literal(node) {
81211 if (!isNumericLiteral(node)) {
81212 return;
81213 }
81214
81215 let fullNumberNode;
81216 let value;
81217 let raw; // Treat unary minus as a part of the number
81218
81219 if (node.parent.type === "UnaryExpression" && node.parent.operator === "-") {
81220 fullNumberNode = node.parent;
81221 value = -node.value;
81222 raw = "-".concat(node.raw);
81223 } else {
81224 fullNumberNode = node;
81225 value = node.value;
81226 raw = node.raw;
81227 } // Always allow radix arguments and JSX props
81228
81229
81230 if (isIgnoredValue(value) || isParseIntRadix(fullNumberNode) || isJSXNumber(fullNumberNode) || ignoreArrayIndexes && isArrayIndex(fullNumberNode, value)) {
81231 return;
81232 }
81233
81234 const parent = fullNumberNode.parent;
81235
81236 if (parent.type === "VariableDeclarator") {
81237 if (enforceConst && parent.parent.kind !== "const") {
81238 context.report({
81239 node: fullNumberNode,
81240 messageId: "useConst"
81241 });
81242 }
81243 } else if (okTypes.indexOf(parent.type) === -1 || parent.type === "AssignmentExpression" && parent.left.type === "Identifier") {
81244 context.report({
81245 node: fullNumberNode,
81246 messageId: "noMagic",
81247 data: {
81248 raw
81249 }
81250 });
81251 }
81252 }
81253
81254 };
81255 }
81256
81257};
81258
81259/***/ }),
6a5a0f88 81260/* 574 */
eb39fafa
DC
81261/***/ (function(module, exports, __webpack_require__) {
81262
81263"use strict";
81264/**
81265 * @author Toru Nagashima <https://github.com/mysticatea>
81266 */
81267
81268
81269const {
81270 CALL,
81271 CONSTRUCT,
81272 ReferenceTracker,
81273 getStringIfConstant
81274} = __webpack_require__(549);
81275
81276const {
81277 RegExpParser,
81278 visitRegExpAST
81279} = __webpack_require__(527);
81280
81281const {
81282 isCombiningCharacter,
81283 isEmojiModifier,
81284 isRegionalIndicatorSymbol,
81285 isSurrogatePair
6a5a0f88 81286} = __webpack_require__(575); //------------------------------------------------------------------------------
eb39fafa
DC
81287// Helpers
81288//------------------------------------------------------------------------------
81289
81290/**
81291 * Iterate character sequences of a given nodes.
81292 *
81293 * CharacterClassRange syntax can steal a part of character sequence,
81294 * so this function reverts CharacterClassRange syntax and restore the sequence.
81295 * @param {regexpp.AST.CharacterClassElement[]} nodes The node list to iterate character sequences.
81296 * @returns {IterableIterator<number[]>} The list of character sequences.
81297 */
81298
81299
81300function* iterateCharacterSequence(nodes) {
81301 let seq = [];
81302
81303 for (const node of nodes) {
81304 switch (node.type) {
81305 case "Character":
81306 seq.push(node.value);
81307 break;
81308
81309 case "CharacterClassRange":
81310 seq.push(node.min.value);
81311 yield seq;
81312 seq = [node.max.value];
81313 break;
81314
81315 case "CharacterSet":
81316 if (seq.length > 0) {
81317 yield seq;
81318 seq = [];
81319 }
81320
81321 break;
81322 // no default
81323 }
81324 }
81325
81326 if (seq.length > 0) {
81327 yield seq;
81328 }
81329}
81330
81331const hasCharacterSequence = {
81332 surrogatePairWithoutUFlag(chars) {
81333 return chars.some((c, i) => i !== 0 && isSurrogatePair(chars[i - 1], c));
81334 },
81335
81336 combiningClass(chars) {
81337 return chars.some((c, i) => i !== 0 && isCombiningCharacter(c) && !isCombiningCharacter(chars[i - 1]));
81338 },
81339
81340 emojiModifier(chars) {
81341 return chars.some((c, i) => i !== 0 && isEmojiModifier(c) && !isEmojiModifier(chars[i - 1]));
81342 },
81343
81344 regionalIndicatorSymbol(chars) {
81345 return chars.some((c, i) => i !== 0 && isRegionalIndicatorSymbol(c) && isRegionalIndicatorSymbol(chars[i - 1]));
81346 },
81347
81348 zwj(chars) {
81349 const lastIndex = chars.length - 1;
81350 return chars.some((c, i) => i !== 0 && i !== lastIndex && c === 0x200d && chars[i - 1] !== 0x200d && chars[i + 1] !== 0x200d);
81351 }
81352
81353};
81354const kinds = Object.keys(hasCharacterSequence); //------------------------------------------------------------------------------
81355// Rule Definition
81356//------------------------------------------------------------------------------
81357
81358module.exports = {
81359 meta: {
81360 type: "problem",
81361 docs: {
81362 description: "disallow characters which are made with multiple code points in character class syntax",
81363 category: "Possible Errors",
81364 recommended: true,
81365 url: "https://eslint.org/docs/rules/no-misleading-character-class"
81366 },
81367 schema: [],
81368 messages: {
81369 surrogatePairWithoutUFlag: "Unexpected surrogate pair in character class. Use 'u' flag.",
81370 combiningClass: "Unexpected combined character in character class.",
81371 emojiModifier: "Unexpected modified Emoji in character class.",
81372 regionalIndicatorSymbol: "Unexpected national flag in character class.",
81373 zwj: "Unexpected joined character sequence in character class."
81374 }
81375 },
81376
81377 create(context) {
81378 const parser = new RegExpParser();
81379 /**
81380 * Verify a given regular expression.
81381 * @param {Node} node The node to report.
81382 * @param {string} pattern The regular expression pattern to verify.
81383 * @param {string} flags The flags of the regular expression.
81384 * @returns {void}
81385 */
81386
81387 function verify(node, pattern, flags) {
81388 const has = {
81389 surrogatePairWithoutUFlag: false,
81390 combiningClass: false,
81391 variationSelector: false,
81392 emojiModifier: false,
81393 regionalIndicatorSymbol: false,
81394 zwj: false
81395 };
81396 let patternNode;
81397
81398 try {
81399 patternNode = parser.parsePattern(pattern, 0, pattern.length, flags.includes("u"));
81400 } catch (e) {
81401 // Ignore regular expressions with syntax errors
81402 return;
81403 }
81404
81405 visitRegExpAST(patternNode, {
81406 onCharacterClassEnter(ccNode) {
81407 for (const chars of iterateCharacterSequence(ccNode.elements)) {
81408 for (const kind of kinds) {
81409 has[kind] = has[kind] || hasCharacterSequence[kind](chars);
81410 }
81411 }
81412 }
81413
81414 });
81415
81416 for (const kind of kinds) {
81417 if (has[kind]) {
81418 context.report({
81419 node,
81420 messageId: kind
81421 });
81422 }
81423 }
81424 }
81425
81426 return {
81427 "Literal[regex]"(node) {
81428 verify(node, node.regex.pattern, node.regex.flags);
81429 },
81430
81431 "Program"() {
81432 const scope = context.getScope();
81433 const tracker = new ReferenceTracker(scope);
81434 /*
81435 * Iterate calls of RegExp.
81436 * E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`,
81437 * `const {RegExp: a} = window; new a()`, etc...
81438 */
81439
81440 for (const {
81441 node
81442 } of tracker.iterateGlobalReferences({
81443 RegExp: {
81444 [CALL]: true,
81445 [CONSTRUCT]: true
81446 }
81447 })) {
81448 const [patternNode, flagsNode] = node.arguments;
81449 const pattern = getStringIfConstant(patternNode, scope);
81450 const flags = getStringIfConstant(flagsNode, scope);
81451
81452 if (typeof pattern === "string") {
81453 verify(node, pattern, flags || "");
81454 }
81455 }
81456 }
81457
81458 };
81459 }
81460
81461};
81462
81463/***/ }),
6a5a0f88 81464/* 575 */
eb39fafa
DC
81465/***/ (function(module, exports, __webpack_require__) {
81466
81467"use strict";
81468/**
81469 * @author Toru Nagashima <https://github.com/mysticatea>
81470 */
81471
81472
81473module.exports = {
6a5a0f88
TL
81474 isCombiningCharacter: __webpack_require__(576),
81475 isEmojiModifier: __webpack_require__(577),
81476 isRegionalIndicatorSymbol: __webpack_require__(578),
81477 isSurrogatePair: __webpack_require__(579)
eb39fafa
DC
81478};
81479
81480/***/ }),
6a5a0f88 81481/* 576 */
eb39fafa
DC
81482/***/ (function(module, exports, __webpack_require__) {
81483
81484"use strict";
81485/**
81486 * @author Toru Nagashima <https://github.com/mysticatea>
81487 */
81488
81489/**
81490 * Check whether a given character is a combining mark or not.
81491 * @param {number} codePoint The character code to check.
81492 * @returns {boolean} `true` if the character belongs to the category, any of `Mc`, `Me`, and `Mn`.
81493 */
81494
81495module.exports = function isCombiningCharacter(codePoint) {
81496 return /^[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1AC0\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]$/u.test(String.fromCodePoint(codePoint));
81497};
81498
81499/***/ }),
6a5a0f88 81500/* 577 */
eb39fafa
DC
81501/***/ (function(module, exports, __webpack_require__) {
81502
81503"use strict";
81504/**
81505 * @author Toru Nagashima <https://github.com/mysticatea>
81506 */
81507
81508/**
81509 * Check whether a given character is an emoji modifier.
81510 * @param {number} code The character code to check.
81511 * @returns {boolean} `true` if the character is an emoji modifier.
81512 */
81513
81514module.exports = function isEmojiModifier(code) {
81515 return code >= 0x1F3FB && code <= 0x1F3FF;
81516};
81517
81518/***/ }),
6a5a0f88 81519/* 578 */
eb39fafa
DC
81520/***/ (function(module, exports, __webpack_require__) {
81521
81522"use strict";
81523/**
81524 * @author Toru Nagashima <https://github.com/mysticatea>
81525 */
81526
81527/**
81528 * Check whether a given character is a regional indicator symbol.
81529 * @param {number} code The character code to check.
81530 * @returns {boolean} `true` if the character is a regional indicator symbol.
81531 */
81532
81533module.exports = function isRegionalIndicatorSymbol(code) {
81534 return code >= 0x1F1E6 && code <= 0x1F1FF;
81535};
81536
81537/***/ }),
6a5a0f88 81538/* 579 */
eb39fafa
DC
81539/***/ (function(module, exports, __webpack_require__) {
81540
81541"use strict";
81542/**
81543 * @author Toru Nagashima <https://github.com/mysticatea>
81544 */
81545
81546/**
81547 * Check whether given two characters are a surrogate pair.
81548 * @param {number} lead The code of the lead character.
81549 * @param {number} tail The code of the tail character.
81550 * @returns {boolean} `true` if the character pair is a surrogate pair.
81551 */
81552
81553module.exports = function isSurrogatePair(lead, tail) {
81554 return lead >= 0xD800 && lead < 0xDC00 && tail >= 0xDC00 && tail < 0xE000;
81555};
81556
81557/***/ }),
6a5a0f88 81558/* 580 */
eb39fafa
DC
81559/***/ (function(module, exports, __webpack_require__) {
81560
81561"use strict";
81562/**
81563 * @fileoverview Rule to disallow mixed binary operators.
81564 * @author Toru Nagashima
81565 */
81566 //------------------------------------------------------------------------------
81567// Requirements
81568//------------------------------------------------------------------------------
81569
81570const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
81571// Helpers
81572//------------------------------------------------------------------------------
81573
81574
81575const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"];
81576const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"];
81577const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="];
81578const LOGICAL_OPERATORS = ["&&", "||"];
81579const RELATIONAL_OPERATORS = ["in", "instanceof"];
81580const TERNARY_OPERATOR = ["?:"];
81581const ALL_OPERATORS = [].concat(ARITHMETIC_OPERATORS, BITWISE_OPERATORS, COMPARISON_OPERATORS, LOGICAL_OPERATORS, RELATIONAL_OPERATORS, TERNARY_OPERATOR);
81582const DEFAULT_GROUPS = [ARITHMETIC_OPERATORS, BITWISE_OPERATORS, COMPARISON_OPERATORS, LOGICAL_OPERATORS, RELATIONAL_OPERATORS];
81583const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u;
81584/**
81585 * Normalizes options.
81586 * @param {Object|undefined} options A options object to normalize.
81587 * @returns {Object} Normalized option object.
81588 */
81589
81590function normalizeOptions(options = {}) {
81591 const hasGroups = options.groups && options.groups.length > 0;
81592 const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
81593 const allowSamePrecedence = options.allowSamePrecedence !== false;
81594 return {
81595 groups,
81596 allowSamePrecedence
81597 };
81598}
81599/**
81600 * Checks whether any group which includes both given operator exists or not.
81601 * @param {Array.<string[]>} groups A list of groups to check.
81602 * @param {string} left An operator.
81603 * @param {string} right Another operator.
81604 * @returns {boolean} `true` if such group existed.
81605 */
81606
81607
81608function includesBothInAGroup(groups, left, right) {
81609 return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
81610}
81611/**
81612 * Checks whether the given node is a conditional expression and returns the test node else the left node.
81613 * @param {ASTNode} node A node which can be a BinaryExpression or a LogicalExpression node.
81614 * This parent node can be BinaryExpression, LogicalExpression
81615 * , or a ConditionalExpression node
81616 * @returns {ASTNode} node the appropriate node(left or test).
81617 */
81618
81619
81620function getChildNode(node) {
81621 return node.type === "ConditionalExpression" ? node.test : node.left;
81622} //------------------------------------------------------------------------------
81623// Rule Definition
81624//------------------------------------------------------------------------------
81625
81626
81627module.exports = {
81628 meta: {
81629 type: "suggestion",
81630 docs: {
81631 description: "disallow mixed binary operators",
81632 category: "Stylistic Issues",
81633 recommended: false,
81634 url: "https://eslint.org/docs/rules/no-mixed-operators"
81635 },
81636 schema: [{
81637 type: "object",
81638 properties: {
81639 groups: {
81640 type: "array",
81641 items: {
81642 type: "array",
81643 items: {
81644 enum: ALL_OPERATORS
81645 },
81646 minItems: 2,
81647 uniqueItems: true
81648 },
81649 uniqueItems: true
81650 },
81651 allowSamePrecedence: {
81652 type: "boolean",
81653 default: true
81654 }
81655 },
81656 additionalProperties: false
81657 }],
81658 messages: {
81659 unexpectedMixedOperator: "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'."
81660 }
81661 },
81662
81663 create(context) {
81664 const sourceCode = context.getSourceCode();
81665 const options = normalizeOptions(context.options[0]);
81666 /**
81667 * Checks whether a given node should be ignored by options or not.
81668 * @param {ASTNode} node A node to check. This is a BinaryExpression
81669 * node or a LogicalExpression node. This parent node is one of
81670 * them, too.
81671 * @returns {boolean} `true` if the node should be ignored.
81672 */
81673
81674 function shouldIgnore(node) {
81675 const a = node;
81676 const b = node.parent;
81677 return !includesBothInAGroup(options.groups, a.operator, b.type === "ConditionalExpression" ? "?:" : b.operator) || options.allowSamePrecedence && astUtils.getPrecedence(a) === astUtils.getPrecedence(b);
81678 }
81679 /**
81680 * Checks whether the operator of a given node is mixed with parent
81681 * node's operator or not.
81682 * @param {ASTNode} node A node to check. This is a BinaryExpression
81683 * node or a LogicalExpression node. This parent node is one of
81684 * them, too.
81685 * @returns {boolean} `true` if the node was mixed.
81686 */
81687
81688
81689 function isMixedWithParent(node) {
81690 return node.operator !== node.parent.operator && !astUtils.isParenthesised(sourceCode, node);
81691 }
81692 /**
81693 * Checks whether the operator of a given node is mixed with a
81694 * conditional expression.
81695 * @param {ASTNode} node A node to check. This is a conditional
81696 * expression node
81697 * @returns {boolean} `true` if the node was mixed.
81698 */
81699
81700
81701 function isMixedWithConditionalParent(node) {
81702 return !astUtils.isParenthesised(sourceCode, node) && !astUtils.isParenthesised(sourceCode, node.test);
81703 }
81704 /**
81705 * Gets the operator token of a given node.
81706 * @param {ASTNode} node A node to check. This is a BinaryExpression
81707 * node or a LogicalExpression node.
81708 * @returns {Token} The operator token of the node.
81709 */
81710
81711
81712 function getOperatorToken(node) {
81713 return sourceCode.getTokenAfter(getChildNode(node), astUtils.isNotClosingParenToken);
81714 }
81715 /**
81716 * Reports both the operator of a given node and the operator of the
81717 * parent node.
81718 * @param {ASTNode} node A node to check. This is a BinaryExpression
81719 * node or a LogicalExpression node. This parent node is one of
81720 * them, too.
81721 * @returns {void}
81722 */
81723
81724
81725 function reportBothOperators(node) {
81726 const parent = node.parent;
81727 const left = getChildNode(parent) === node ? node : parent;
81728 const right = getChildNode(parent) !== node ? node : parent;
81729 const data = {
81730 leftOperator: left.operator || "?:",
81731 rightOperator: right.operator || "?:"
81732 };
81733 context.report({
81734 node: left,
81735 loc: getOperatorToken(left).loc,
81736 messageId: "unexpectedMixedOperator",
81737 data
81738 });
81739 context.report({
81740 node: right,
81741 loc: getOperatorToken(right).loc,
81742 messageId: "unexpectedMixedOperator",
81743 data
81744 });
81745 }
81746 /**
81747 * Checks between the operator of this node and the operator of the
81748 * parent node.
81749 * @param {ASTNode} node A node to check.
81750 * @returns {void}
81751 */
81752
81753
81754 function check(node) {
81755 if (TARGET_NODE_TYPE.test(node.parent.type)) {
81756 if (node.parent.type === "ConditionalExpression" && !shouldIgnore(node) && isMixedWithConditionalParent(node.parent)) {
81757 reportBothOperators(node);
81758 } else {
81759 if (TARGET_NODE_TYPE.test(node.parent.type) && isMixedWithParent(node) && !shouldIgnore(node)) {
81760 reportBothOperators(node);
81761 }
81762 }
81763 }
81764 }
81765
81766 return {
81767 BinaryExpression: check,
81768 LogicalExpression: check
81769 };
81770 }
81771
81772};
81773
81774/***/ }),
6a5a0f88 81775/* 581 */
eb39fafa
DC
81776/***/ (function(module, exports, __webpack_require__) {
81777
81778"use strict";
81779/**
81780 * @fileoverview Rule to enforce grouped require statements for Node.JS
81781 * @author Raphael Pigulla
81782 */
81783 //------------------------------------------------------------------------------
81784// Rule Definition
81785//------------------------------------------------------------------------------
81786
81787module.exports = {
81788 meta: {
56c4a2cb 81789 deprecated: true,
6a5a0f88 81790 replacedBy: [],
eb39fafa
DC
81791 type: "suggestion",
81792 docs: {
81793 description: "disallow `require` calls to be mixed with regular variable declarations",
81794 category: "Node.js and CommonJS",
81795 recommended: false,
81796 url: "https://eslint.org/docs/rules/no-mixed-requires"
81797 },
81798 schema: [{
81799 oneOf: [{
81800 type: "boolean"
81801 }, {
81802 type: "object",
81803 properties: {
81804 grouping: {
81805 type: "boolean"
81806 },
81807 allowCall: {
81808 type: "boolean"
81809 }
81810 },
81811 additionalProperties: false
81812 }]
81813 }],
81814 messages: {
81815 noMixRequire: "Do not mix 'require' and other declarations.",
81816 noMixCoreModuleFileComputed: "Do not mix core, module, file and computed requires."
81817 }
81818 },
81819
81820 create(context) {
81821 const options = context.options[0];
81822 let grouping = false,
81823 allowCall = false;
81824
81825 if (typeof options === "object") {
81826 grouping = options.grouping;
81827 allowCall = options.allowCall;
81828 } else {
81829 grouping = !!options;
81830 }
81831 /**
81832 * Returns the list of built-in modules.
81833 * @returns {string[]} An array of built-in Node.js modules.
81834 */
81835
81836
81837 function getBuiltinModules() {
81838 /*
81839 * This list is generated using:
81840 * `require("repl")._builtinLibs.concat('repl').sort()`
81841 * This particular list is as per nodejs v0.12.2 and iojs v0.7.1
81842 */
81843 return ["assert", "buffer", "child_process", "cluster", "crypto", "dgram", "dns", "domain", "events", "fs", "http", "https", "net", "os", "path", "punycode", "querystring", "readline", "repl", "smalloc", "stream", "string_decoder", "tls", "tty", "url", "util", "v8", "vm", "zlib"];
81844 }
81845
81846 const BUILTIN_MODULES = getBuiltinModules();
81847 const DECL_REQUIRE = "require",
81848 DECL_UNINITIALIZED = "uninitialized",
81849 DECL_OTHER = "other";
81850 const REQ_CORE = "core",
81851 REQ_FILE = "file",
81852 REQ_MODULE = "module",
81853 REQ_COMPUTED = "computed";
81854 /**
81855 * Determines the type of a declaration statement.
81856 * @param {ASTNode} initExpression The init node of the VariableDeclarator.
81857 * @returns {string} The type of declaration represented by the expression.
81858 */
81859
81860 function getDeclarationType(initExpression) {
81861 if (!initExpression) {
81862 // "var x;"
81863 return DECL_UNINITIALIZED;
81864 }
81865
81866 if (initExpression.type === "CallExpression" && initExpression.callee.type === "Identifier" && initExpression.callee.name === "require") {
81867 // "var x = require('util');"
81868 return DECL_REQUIRE;
81869 }
81870
81871 if (allowCall && initExpression.type === "CallExpression" && initExpression.callee.type === "CallExpression") {
81872 // "var x = require('diagnose')('sub-module');"
81873 return getDeclarationType(initExpression.callee);
81874 }
81875
81876 if (initExpression.type === "MemberExpression") {
81877 // "var x = require('glob').Glob;"
81878 return getDeclarationType(initExpression.object);
81879 } // "var x = 42;"
81880
81881
81882 return DECL_OTHER;
81883 }
81884 /**
81885 * Determines the type of module that is loaded via require.
81886 * @param {ASTNode} initExpression The init node of the VariableDeclarator.
81887 * @returns {string} The module type.
81888 */
81889
81890
81891 function inferModuleType(initExpression) {
81892 if (initExpression.type === "MemberExpression") {
81893 // "var x = require('glob').Glob;"
81894 return inferModuleType(initExpression.object);
81895 }
81896
81897 if (initExpression.arguments.length === 0) {
81898 // "var x = require();"
81899 return REQ_COMPUTED;
81900 }
81901
81902 const arg = initExpression.arguments[0];
81903
81904 if (arg.type !== "Literal" || typeof arg.value !== "string") {
81905 // "var x = require(42);"
81906 return REQ_COMPUTED;
81907 }
81908
81909 if (BUILTIN_MODULES.indexOf(arg.value) !== -1) {
81910 // "var fs = require('fs');"
81911 return REQ_CORE;
81912 }
81913
81914 if (/^\.{0,2}\//u.test(arg.value)) {
81915 // "var utils = require('./utils');"
81916 return REQ_FILE;
81917 } // "var async = require('async');"
81918
81919
81920 return REQ_MODULE;
81921 }
81922 /**
81923 * Check if the list of variable declarations is mixed, i.e. whether it
81924 * contains both require and other declarations.
81925 * @param {ASTNode} declarations The list of VariableDeclarators.
81926 * @returns {boolean} True if the declarations are mixed, false if not.
81927 */
81928
81929
81930 function isMixed(declarations) {
81931 const contains = {};
81932 declarations.forEach(declaration => {
81933 const type = getDeclarationType(declaration.init);
81934 contains[type] = true;
81935 });
81936 return !!(contains[DECL_REQUIRE] && (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]));
81937 }
81938 /**
81939 * Check if all require declarations in the given list are of the same
81940 * type.
81941 * @param {ASTNode} declarations The list of VariableDeclarators.
81942 * @returns {boolean} True if the declarations are grouped, false if not.
81943 */
81944
81945
81946 function isGrouped(declarations) {
81947 const found = {};
81948 declarations.forEach(declaration => {
81949 if (getDeclarationType(declaration.init) === DECL_REQUIRE) {
81950 found[inferModuleType(declaration.init)] = true;
81951 }
81952 });
81953 return Object.keys(found).length <= 1;
81954 }
81955
81956 return {
81957 VariableDeclaration(node) {
81958 if (isMixed(node.declarations)) {
81959 context.report({
81960 node,
81961 messageId: "noMixRequire"
81962 });
81963 } else if (grouping && !isGrouped(node.declarations)) {
81964 context.report({
81965 node,
81966 messageId: "noMixCoreModuleFileComputed"
81967 });
81968 }
81969 }
81970
81971 };
81972 }
81973
81974};
81975
81976/***/ }),
6a5a0f88 81977/* 582 */
eb39fafa
DC
81978/***/ (function(module, exports, __webpack_require__) {
81979
81980"use strict";
81981/**
81982 * @fileoverview Disallow mixed spaces and tabs for indentation
81983 * @author Jary Niebur
81984 */
81985 //------------------------------------------------------------------------------
81986// Rule Definition
81987//------------------------------------------------------------------------------
81988
81989module.exports = {
81990 meta: {
81991 type: "layout",
81992 docs: {
81993 description: "disallow mixed spaces and tabs for indentation",
81994 category: "Stylistic Issues",
81995 recommended: true,
81996 url: "https://eslint.org/docs/rules/no-mixed-spaces-and-tabs"
81997 },
81998 schema: [{
81999 enum: ["smart-tabs", true, false]
82000 }],
82001 messages: {
82002 mixedSpacesAndTabs: "Mixed spaces and tabs."
82003 }
82004 },
82005
82006 create(context) {
82007 const sourceCode = context.getSourceCode();
82008 let smartTabs;
82009
82010 switch (context.options[0]) {
82011 case true: // Support old syntax, maybe add deprecation warning here
82012
82013 case "smart-tabs":
82014 smartTabs = true;
82015 break;
82016
82017 default:
82018 smartTabs = false;
82019 } //--------------------------------------------------------------------------
82020 // Public
82021 //--------------------------------------------------------------------------
82022
82023
82024 return {
82025 "Program:exit"(node) {
82026 const lines = sourceCode.lines,
82027 comments = sourceCode.getAllComments(),
82028 ignoredCommentLines = new Set(); // Add all lines except the first ones.
82029
82030 comments.forEach(comment => {
82031 for (let i = comment.loc.start.line + 1; i <= comment.loc.end.line; i++) {
82032 ignoredCommentLines.add(i);
82033 }
82034 });
82035 /*
82036 * At least one space followed by a tab
82037 * or the reverse before non-tab/-space
82038 * characters begin.
82039 */
82040
82041 let regex = /^(?=[\t ]*(\t | \t))/u;
82042
82043 if (smartTabs) {
82044 /*
82045 * At least one space followed by a tab
82046 * before non-tab/-space characters begin.
82047 */
82048 regex = /^(?=[\t ]* \t)/u;
82049 }
82050
82051 lines.forEach((line, i) => {
82052 const match = regex.exec(line);
82053
82054 if (match) {
82055 const lineNumber = i + 1,
82056 column = match.index + 1,
82057 loc = {
82058 line: lineNumber,
82059 column
82060 };
82061
82062 if (!ignoredCommentLines.has(lineNumber)) {
82063 const containingNode = sourceCode.getNodeByRangeIndex(sourceCode.getIndexFromLoc(loc));
82064
82065 if (!(containingNode && ["Literal", "TemplateElement"].includes(containingNode.type))) {
82066 context.report({
82067 node,
82068 loc,
82069 messageId: "mixedSpacesAndTabs"
82070 });
82071 }
82072 }
82073 }
82074 });
82075 }
82076
82077 };
82078 }
82079
82080};
82081
82082/***/ }),
6a5a0f88 82083/* 583 */
eb39fafa
DC
82084/***/ (function(module, exports, __webpack_require__) {
82085
82086"use strict";
82087/**
82088 * @fileoverview Rule to check use of chained assignment expressions
82089 * @author Stewart Rand
82090 */
82091 //------------------------------------------------------------------------------
82092// Rule Definition
82093//------------------------------------------------------------------------------
82094
82095module.exports = {
82096 meta: {
82097 type: "suggestion",
82098 docs: {
82099 description: "disallow use of chained assignment expressions",
82100 category: "Stylistic Issues",
82101 recommended: false,
82102 url: "https://eslint.org/docs/rules/no-multi-assign"
82103 },
82104 schema: [],
82105 messages: {
82106 unexpectedChain: "Unexpected chained assignment."
82107 }
82108 },
82109
82110 create(context) {
82111 //--------------------------------------------------------------------------
82112 // Public
82113 //--------------------------------------------------------------------------
82114 return {
82115 AssignmentExpression(node) {
82116 if (["AssignmentExpression", "VariableDeclarator"].indexOf(node.parent.type) !== -1) {
82117 context.report({
82118 node,
82119 messageId: "unexpectedChain"
82120 });
82121 }
82122 }
82123
82124 };
82125 }
82126
82127};
82128
82129/***/ }),
6a5a0f88 82130/* 584 */
eb39fafa
DC
82131/***/ (function(module, exports, __webpack_require__) {
82132
82133"use strict";
82134/**
82135 * @fileoverview Disallow use of multiple spaces.
82136 * @author Nicholas C. Zakas
82137 */
82138
82139
82140const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
82141// Rule Definition
82142//------------------------------------------------------------------------------
82143
82144
82145module.exports = {
82146 meta: {
82147 type: "layout",
82148 docs: {
82149 description: "disallow multiple spaces",
82150 category: "Best Practices",
82151 recommended: false,
82152 url: "https://eslint.org/docs/rules/no-multi-spaces"
82153 },
82154 fixable: "whitespace",
82155 schema: [{
82156 type: "object",
82157 properties: {
82158 exceptions: {
82159 type: "object",
82160 patternProperties: {
82161 "^([A-Z][a-z]*)+$": {
82162 type: "boolean"
82163 }
82164 },
82165 additionalProperties: false
82166 },
82167 ignoreEOLComments: {
82168 type: "boolean",
82169 default: false
82170 }
82171 },
82172 additionalProperties: false
82173 }],
82174 messages: {
82175 multipleSpaces: "Multiple spaces found before '{{displayValue}}'."
82176 }
82177 },
82178
82179 create(context) {
82180 const sourceCode = context.getSourceCode();
82181 const options = context.options[0] || {};
82182 const ignoreEOLComments = options.ignoreEOLComments;
82183 const exceptions = Object.assign({
82184 Property: true
82185 }, options.exceptions);
82186 const hasExceptions = Object.keys(exceptions).filter(key => exceptions[key]).length > 0;
82187 /**
82188 * Formats value of given comment token for error message by truncating its length.
82189 * @param {Token} token comment token
82190 * @returns {string} formatted value
82191 * @private
82192 */
82193
82194 function formatReportedCommentValue(token) {
82195 const valueLines = token.value.split("\n");
82196 const value = valueLines[0];
82197 const formattedValue = "".concat(value.slice(0, 12), "...");
82198 return valueLines.length === 1 && value.length <= 12 ? value : formattedValue;
82199 } //--------------------------------------------------------------------------
82200 // Public
82201 //--------------------------------------------------------------------------
82202
82203
82204 return {
82205 Program() {
82206 sourceCode.tokensAndComments.forEach((leftToken, leftIndex, tokensAndComments) => {
82207 if (leftIndex === tokensAndComments.length - 1) {
82208 return;
82209 }
82210
82211 const rightToken = tokensAndComments[leftIndex + 1]; // Ignore tokens that don't have 2 spaces between them or are on different lines
82212
82213 if (!sourceCode.text.slice(leftToken.range[1], rightToken.range[0]).includes(" ") || leftToken.loc.end.line < rightToken.loc.start.line) {
82214 return;
82215 } // Ignore comments that are the last token on their line if `ignoreEOLComments` is active.
82216
82217
82218 if (ignoreEOLComments && astUtils.isCommentToken(rightToken) && (leftIndex === tokensAndComments.length - 2 || rightToken.loc.end.line < tokensAndComments[leftIndex + 2].loc.start.line)) {
82219 return;
82220 } // Ignore tokens that are in a node in the "exceptions" object
82221
82222
82223 if (hasExceptions) {
82224 const parentNode = sourceCode.getNodeByRangeIndex(rightToken.range[0] - 1);
82225
82226 if (parentNode && exceptions[parentNode.type]) {
82227 return;
82228 }
82229 }
82230
82231 let displayValue;
82232
82233 if (rightToken.type === "Block") {
82234 displayValue = "/*".concat(formatReportedCommentValue(rightToken), "*/");
82235 } else if (rightToken.type === "Line") {
82236 displayValue = "//".concat(formatReportedCommentValue(rightToken));
82237 } else {
82238 displayValue = rightToken.value;
82239 }
82240
82241 context.report({
82242 node: rightToken,
82243 loc: {
82244 start: leftToken.loc.end,
82245 end: rightToken.loc.start
82246 },
82247 messageId: "multipleSpaces",
82248 data: {
82249 displayValue
82250 },
82251 fix: fixer => fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ")
82252 });
82253 });
82254 }
82255
82256 };
82257 }
82258
82259};
82260
82261/***/ }),
6a5a0f88 82262/* 585 */
eb39fafa
DC
82263/***/ (function(module, exports, __webpack_require__) {
82264
82265"use strict";
82266/**
82267 * @fileoverview Rule to flag when using multiline strings
82268 * @author Ilya Volodin
82269 */
82270 //------------------------------------------------------------------------------
82271// Requirements
82272//------------------------------------------------------------------------------
82273
82274const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
82275// Rule Definition
82276//------------------------------------------------------------------------------
82277
82278
82279module.exports = {
82280 meta: {
82281 type: "suggestion",
82282 docs: {
82283 description: "disallow multiline strings",
82284 category: "Best Practices",
82285 recommended: false,
82286 url: "https://eslint.org/docs/rules/no-multi-str"
82287 },
82288 schema: [],
82289 messages: {
82290 multilineString: "Multiline support is limited to browsers supporting ES5 only."
82291 }
82292 },
82293
82294 create(context) {
82295 /**
82296 * Determines if a given node is part of JSX syntax.
82297 * @param {ASTNode} node The node to check.
82298 * @returns {boolean} True if the node is a JSX node, false if not.
82299 * @private
82300 */
82301 function isJSXElement(node) {
82302 return node.type.indexOf("JSX") === 0;
82303 } //--------------------------------------------------------------------------
82304 // Public API
82305 //--------------------------------------------------------------------------
82306
82307
82308 return {
82309 Literal(node) {
82310 if (astUtils.LINEBREAK_MATCHER.test(node.raw) && !isJSXElement(node.parent)) {
82311 context.report({
82312 node,
82313 messageId: "multilineString"
82314 });
82315 }
82316 }
82317
82318 };
82319 }
82320
82321};
82322
82323/***/ }),
6a5a0f88 82324/* 586 */
eb39fafa
DC
82325/***/ (function(module, exports, __webpack_require__) {
82326
82327"use strict";
82328/**
82329 * @fileoverview Disallows multiple blank lines.
82330 * implementation adapted from the no-trailing-spaces rule.
82331 * @author Greg Cochard
82332 */
82333 //------------------------------------------------------------------------------
82334// Rule Definition
82335//------------------------------------------------------------------------------
82336
82337module.exports = {
82338 meta: {
82339 type: "layout",
82340 docs: {
82341 description: "disallow multiple empty lines",
82342 category: "Stylistic Issues",
82343 recommended: false,
82344 url: "https://eslint.org/docs/rules/no-multiple-empty-lines"
82345 },
82346 fixable: "whitespace",
82347 schema: [{
82348 type: "object",
82349 properties: {
82350 max: {
82351 type: "integer",
82352 minimum: 0
82353 },
82354 maxEOF: {
82355 type: "integer",
82356 minimum: 0
82357 },
82358 maxBOF: {
82359 type: "integer",
82360 minimum: 0
82361 }
82362 },
82363 required: ["max"],
82364 additionalProperties: false
82365 }],
82366 messages: {
82367 blankBeginningOfFile: "Too many blank lines at the beginning of file. Max of {{max}} allowed.",
82368 blankEndOfFile: "Too many blank lines at the end of file. Max of {{max}} allowed.",
82369 consecutiveBlank: "More than {{max}} blank {{pluralizedLines}} not allowed."
82370 }
82371 },
82372
82373 create(context) {
82374 // Use options.max or 2 as default
82375 let max = 2,
82376 maxEOF = max,
82377 maxBOF = max;
82378
82379 if (context.options.length) {
82380 max = context.options[0].max;
82381 maxEOF = typeof context.options[0].maxEOF !== "undefined" ? context.options[0].maxEOF : max;
82382 maxBOF = typeof context.options[0].maxBOF !== "undefined" ? context.options[0].maxBOF : max;
82383 }
82384
82385 const sourceCode = context.getSourceCode(); // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue
82386
82387 const allLines = sourceCode.lines[sourceCode.lines.length - 1] === "" ? sourceCode.lines.slice(0, -1) : sourceCode.lines;
82388 const templateLiteralLines = new Set(); //--------------------------------------------------------------------------
82389 // Public
82390 //--------------------------------------------------------------------------
82391
82392 return {
82393 TemplateLiteral(node) {
82394 node.quasis.forEach(literalPart => {
82395 // Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines.
82396 for (let ignoredLine = literalPart.loc.start.line; ignoredLine < literalPart.loc.end.line; ignoredLine++) {
82397 templateLiteralLines.add(ignoredLine);
82398 }
82399 });
82400 },
82401
82402 "Program:exit"(node) {
82403 return allLines // Given a list of lines, first get a list of line numbers that are non-empty.
82404 .reduce((nonEmptyLineNumbers, line, index) => {
82405 if (line.trim() || templateLiteralLines.has(index + 1)) {
82406 nonEmptyLineNumbers.push(index + 1);
82407 }
82408
82409 return nonEmptyLineNumbers;
82410 }, []) // Add a value at the end to allow trailing empty lines to be checked.
82411 .concat(allLines.length + 1) // Given two line numbers of non-empty lines, report the lines between if the difference is too large.
82412 .reduce((lastLineNumber, lineNumber) => {
82413 let messageId, maxAllowed;
82414
82415 if (lastLineNumber === 0) {
82416 messageId = "blankBeginningOfFile";
82417 maxAllowed = maxBOF;
82418 } else if (lineNumber === allLines.length + 1) {
82419 messageId = "blankEndOfFile";
82420 maxAllowed = maxEOF;
82421 } else {
82422 messageId = "consecutiveBlank";
82423 maxAllowed = max;
82424 }
82425
82426 if (lineNumber - lastLineNumber - 1 > maxAllowed) {
82427 context.report({
82428 node,
82429 loc: {
82430 start: {
82431 line: lastLineNumber + maxAllowed + 1,
82432 column: 0
82433 },
82434 end: {
82435 line: lineNumber,
82436 column: 0
82437 }
82438 },
82439 messageId,
82440 data: {
82441 max: maxAllowed,
82442 pluralizedLines: maxAllowed === 1 ? "line" : "lines"
82443 },
82444
82445 fix(fixer) {
82446 const rangeStart = sourceCode.getIndexFromLoc({
82447 line: lastLineNumber + 1,
82448 column: 0
82449 });
82450 /*
82451 * The end of the removal range is usually the start index of the next line.
82452 * However, at the end of the file there is no next line, so the end of the
82453 * range is just the length of the text.
82454 */
82455
82456 const lineNumberAfterRemovedLines = lineNumber - maxAllowed;
82457 const rangeEnd = lineNumberAfterRemovedLines <= allLines.length ? sourceCode.getIndexFromLoc({
82458 line: lineNumberAfterRemovedLines,
82459 column: 0
82460 }) : sourceCode.text.length;
82461 return fixer.removeRange([rangeStart, rangeEnd]);
82462 }
82463
82464 });
82465 }
82466
82467 return lineNumber;
82468 }, 0);
82469 }
82470
82471 };
82472 }
82473
82474};
82475
82476/***/ }),
6a5a0f88 82477/* 587 */
eb39fafa
DC
82478/***/ (function(module, exports, __webpack_require__) {
82479
82480"use strict";
82481/**
82482 * @fileoverview Rule to disallow assignments to native objects or read-only global variables
82483 * @author Ilya Volodin
82484 * @deprecated in ESLint v3.3.0
82485 */
82486 //------------------------------------------------------------------------------
82487// Rule Definition
82488//------------------------------------------------------------------------------
82489
82490module.exports = {
82491 meta: {
82492 type: "suggestion",
82493 docs: {
82494 description: "disallow assignments to native objects or read-only global variables",
82495 category: "Best Practices",
82496 recommended: false,
82497 url: "https://eslint.org/docs/rules/no-native-reassign"
82498 },
82499 deprecated: true,
82500 replacedBy: ["no-global-assign"],
82501 schema: [{
82502 type: "object",
82503 properties: {
82504 exceptions: {
82505 type: "array",
82506 items: {
82507 type: "string"
82508 },
82509 uniqueItems: true
82510 }
82511 },
82512 additionalProperties: false
82513 }],
82514 messages: {
82515 nativeReassign: "Read-only global '{{name}}' should not be modified."
82516 }
82517 },
82518
82519 create(context) {
82520 const config = context.options[0];
82521 const exceptions = config && config.exceptions || [];
82522 /**
82523 * Reports write references.
82524 * @param {Reference} reference A reference to check.
82525 * @param {int} index The index of the reference in the references.
82526 * @param {Reference[]} references The array that the reference belongs to.
82527 * @returns {void}
82528 */
82529
82530 function checkReference(reference, index, references) {
82531 const identifier = reference.identifier;
82532
82533 if (reference.init === false && reference.isWrite() && (
82534 /*
82535 * Destructuring assignments can have multiple default value,
82536 * so possibly there are multiple writeable references for the same identifier.
82537 */
82538 index === 0 || references[index - 1].identifier !== identifier)) {
82539 context.report({
82540 node: identifier,
82541 messageId: "nativeReassign",
82542 data: identifier
82543 });
82544 }
82545 }
82546 /**
82547 * Reports write references if a given variable is read-only builtin.
82548 * @param {Variable} variable A variable to check.
82549 * @returns {void}
82550 */
82551
82552
82553 function checkVariable(variable) {
82554 if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
82555 variable.references.forEach(checkReference);
82556 }
82557 }
82558
82559 return {
82560 Program() {
82561 const globalScope = context.getScope();
82562 globalScope.variables.forEach(checkVariable);
82563 }
82564
82565 };
82566 }
82567
82568};
82569
82570/***/ }),
6a5a0f88 82571/* 588 */
eb39fafa
DC
82572/***/ (function(module, exports, __webpack_require__) {
82573
82574"use strict";
82575/**
82576 * @fileoverview Rule to disallow a negated condition
82577 * @author Alberto Rodríguez
82578 */
82579 //------------------------------------------------------------------------------
82580// Rule Definition
82581//------------------------------------------------------------------------------
82582
82583module.exports = {
82584 meta: {
82585 type: "suggestion",
82586 docs: {
82587 description: "disallow negated conditions",
82588 category: "Stylistic Issues",
82589 recommended: false,
82590 url: "https://eslint.org/docs/rules/no-negated-condition"
82591 },
82592 schema: [],
82593 messages: {
82594 unexpectedNegated: "Unexpected negated condition."
82595 }
82596 },
82597
82598 create(context) {
82599 /**
82600 * Determines if a given node is an if-else without a condition on the else
82601 * @param {ASTNode} node The node to check.
82602 * @returns {boolean} True if the node has an else without an if.
82603 * @private
82604 */
82605 function hasElseWithoutCondition(node) {
82606 return node.alternate && node.alternate.type !== "IfStatement";
82607 }
82608 /**
82609 * Determines if a given node is a negated unary expression
82610 * @param {Object} test The test object to check.
82611 * @returns {boolean} True if the node is a negated unary expression.
82612 * @private
82613 */
82614
82615
82616 function isNegatedUnaryExpression(test) {
82617 return test.type === "UnaryExpression" && test.operator === "!";
82618 }
82619 /**
82620 * Determines if a given node is a negated binary expression
82621 * @param {Test} test The test to check.
82622 * @returns {boolean} True if the node is a negated binary expression.
82623 * @private
82624 */
82625
82626
82627 function isNegatedBinaryExpression(test) {
82628 return test.type === "BinaryExpression" && (test.operator === "!=" || test.operator === "!==");
82629 }
82630 /**
82631 * Determines if a given node has a negated if expression
82632 * @param {ASTNode} node The node to check.
82633 * @returns {boolean} True if the node has a negated if expression.
82634 * @private
82635 */
82636
82637
82638 function isNegatedIf(node) {
82639 return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test);
82640 }
82641
82642 return {
82643 IfStatement(node) {
82644 if (!hasElseWithoutCondition(node)) {
82645 return;
82646 }
82647
82648 if (isNegatedIf(node)) {
82649 context.report({
82650 node,
82651 messageId: "unexpectedNegated"
82652 });
82653 }
82654 },
82655
82656 ConditionalExpression(node) {
82657 if (isNegatedIf(node)) {
82658 context.report({
82659 node,
82660 messageId: "unexpectedNegated"
82661 });
82662 }
82663 }
82664
82665 };
82666 }
82667
82668};
82669
82670/***/ }),
6a5a0f88 82671/* 589 */
eb39fafa
DC
82672/***/ (function(module, exports, __webpack_require__) {
82673
82674"use strict";
82675/**
82676 * @fileoverview A rule to disallow negated left operands of the `in` operator
82677 * @author Michael Ficarra
82678 * @deprecated in ESLint v3.3.0
82679 */
82680 //------------------------------------------------------------------------------
82681// Rule Definition
82682//------------------------------------------------------------------------------
82683
82684module.exports = {
82685 meta: {
82686 type: "problem",
82687 docs: {
82688 description: "disallow negating the left operand in `in` expressions",
82689 category: "Possible Errors",
82690 recommended: false,
82691 url: "https://eslint.org/docs/rules/no-negated-in-lhs"
82692 },
82693 replacedBy: ["no-unsafe-negation"],
82694 deprecated: true,
82695 schema: [],
82696 messages: {
82697 negatedLHS: "The 'in' expression's left operand is negated."
82698 }
82699 },
82700
82701 create(context) {
82702 return {
82703 BinaryExpression(node) {
82704 if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") {
82705 context.report({
82706 node,
82707 messageId: "negatedLHS"
82708 });
82709 }
82710 }
82711
82712 };
82713 }
82714
82715};
82716
82717/***/ }),
6a5a0f88 82718/* 590 */
eb39fafa
DC
82719/***/ (function(module, exports, __webpack_require__) {
82720
82721"use strict";
82722/**
82723 * @fileoverview Rule to flag nested ternary expressions
82724 * @author Ian Christian Myers
82725 */
82726 //------------------------------------------------------------------------------
82727// Rule Definition
82728//------------------------------------------------------------------------------
82729
82730module.exports = {
82731 meta: {
82732 type: "suggestion",
82733 docs: {
82734 description: "disallow nested ternary expressions",
82735 category: "Stylistic Issues",
82736 recommended: false,
82737 url: "https://eslint.org/docs/rules/no-nested-ternary"
82738 },
82739 schema: [],
82740 messages: {
82741 noNestedTernary: "Do not nest ternary expressions."
82742 }
82743 },
82744
82745 create(context) {
82746 return {
82747 ConditionalExpression(node) {
82748 if (node.alternate.type === "ConditionalExpression" || node.consequent.type === "ConditionalExpression") {
82749 context.report({
82750 node,
82751 messageId: "noNestedTernary"
82752 });
82753 }
82754 }
82755
82756 };
82757 }
82758
82759};
82760
82761/***/ }),
6a5a0f88 82762/* 591 */
eb39fafa
DC
82763/***/ (function(module, exports, __webpack_require__) {
82764
82765"use strict";
82766/**
82767 * @fileoverview Rule to flag statements with function invocation preceded by
82768 * "new" and not part of assignment
82769 * @author Ilya Volodin
82770 */
82771 //------------------------------------------------------------------------------
82772// Rule Definition
82773//------------------------------------------------------------------------------
82774
82775module.exports = {
82776 meta: {
82777 type: "suggestion",
82778 docs: {
82779 description: "disallow `new` operators outside of assignments or comparisons",
82780 category: "Best Practices",
82781 recommended: false,
82782 url: "https://eslint.org/docs/rules/no-new"
82783 },
82784 schema: [],
82785 messages: {
82786 noNewStatement: "Do not use 'new' for side effects."
82787 }
82788 },
82789
82790 create(context) {
82791 return {
82792 "ExpressionStatement > NewExpression"(node) {
82793 context.report({
82794 node: node.parent,
82795 messageId: "noNewStatement"
82796 });
82797 }
82798
82799 };
82800 }
82801
82802};
82803
82804/***/ }),
6a5a0f88 82805/* 592 */
eb39fafa
DC
82806/***/ (function(module, exports, __webpack_require__) {
82807
82808"use strict";
82809/**
82810 * @fileoverview Rule to flag when using new Function
82811 * @author Ilya Volodin
82812 */
82813 //------------------------------------------------------------------------------
82814// Rule Definition
82815//------------------------------------------------------------------------------
82816
82817module.exports = {
82818 meta: {
82819 type: "suggestion",
82820 docs: {
82821 description: "disallow `new` operators with the `Function` object",
82822 category: "Best Practices",
82823 recommended: false,
82824 url: "https://eslint.org/docs/rules/no-new-func"
82825 },
82826 schema: [],
82827 messages: {
82828 noFunctionConstructor: "The Function constructor is eval."
82829 }
82830 },
82831
82832 create(context) {
6a5a0f88
TL
82833 return {
82834 "Program:exit"() {
82835 const globalScope = context.getScope();
82836 const variable = globalScope.set.get("Function");
eb39fafa 82837
6a5a0f88
TL
82838 if (variable && variable.defs.length === 0) {
82839 variable.references.forEach(ref => {
82840 const node = ref.identifier;
82841 const {
82842 parent
82843 } = node;
82844
82845 if (parent && (parent.type === "NewExpression" || parent.type === "CallExpression") && node === parent.callee) {
82846 context.report({
82847 node: parent,
82848 messageId: "noFunctionConstructor"
82849 });
82850 }
82851 });
82852 }
82853 }
eb39fafa 82854
eb39fafa
DC
82855 };
82856 }
82857
82858};
82859
82860/***/ }),
6a5a0f88 82861/* 593 */
eb39fafa
DC
82862/***/ (function(module, exports, __webpack_require__) {
82863
82864"use strict";
82865/**
82866 * @fileoverview A rule to disallow calls to the Object constructor
82867 * @author Matt DuVall <http://www.mattduvall.com/>
82868 */
82869 //------------------------------------------------------------------------------
56c4a2cb
DC
82870// Requirements
82871//------------------------------------------------------------------------------
82872
82873const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
eb39fafa
DC
82874// Rule Definition
82875//------------------------------------------------------------------------------
82876
56c4a2cb 82877
eb39fafa
DC
82878module.exports = {
82879 meta: {
82880 type: "suggestion",
82881 docs: {
82882 description: "disallow `Object` constructors",
82883 category: "Stylistic Issues",
82884 recommended: false,
82885 url: "https://eslint.org/docs/rules/no-new-object"
82886 },
82887 schema: [],
82888 messages: {
82889 preferLiteral: "The object literal notation {} is preferrable."
82890 }
82891 },
82892
82893 create(context) {
82894 return {
82895 NewExpression(node) {
56c4a2cb
DC
82896 const variable = astUtils.getVariableByName(context.getScope(), node.callee.name);
82897
82898 if (variable && variable.identifiers.length > 0) {
82899 return;
82900 }
82901
eb39fafa
DC
82902 if (node.callee.name === "Object") {
82903 context.report({
82904 node,
82905 messageId: "preferLiteral"
82906 });
82907 }
82908 }
82909
82910 };
82911 }
82912
82913};
82914
82915/***/ }),
6a5a0f88 82916/* 594 */
eb39fafa
DC
82917/***/ (function(module, exports, __webpack_require__) {
82918
82919"use strict";
82920/**
82921 * @fileoverview Rule to disallow use of new operator with the `require` function
82922 * @author Wil Moore III
82923 */
82924 //------------------------------------------------------------------------------
82925// Rule Definition
82926//------------------------------------------------------------------------------
82927
82928module.exports = {
82929 meta: {
56c4a2cb 82930 deprecated: true,
6a5a0f88 82931 replacedBy: [],
eb39fafa
DC
82932 type: "suggestion",
82933 docs: {
82934 description: "disallow `new` operators with calls to `require`",
82935 category: "Node.js and CommonJS",
82936 recommended: false,
82937 url: "https://eslint.org/docs/rules/no-new-require"
82938 },
82939 schema: [],
82940 messages: {
82941 noNewRequire: "Unexpected use of new with require."
82942 }
82943 },
82944
82945 create(context) {
82946 return {
82947 NewExpression(node) {
82948 if (node.callee.type === "Identifier" && node.callee.name === "require") {
82949 context.report({
82950 node,
82951 messageId: "noNewRequire"
82952 });
82953 }
82954 }
82955
82956 };
82957 }
82958
82959};
82960
82961/***/ }),
6a5a0f88 82962/* 595 */
eb39fafa
DC
82963/***/ (function(module, exports, __webpack_require__) {
82964
82965"use strict";
82966/**
82967 * @fileoverview Rule to disallow use of the new operator with the `Symbol` object
82968 * @author Alberto Rodríguez
82969 */
82970 //------------------------------------------------------------------------------
82971// Rule Definition
82972//------------------------------------------------------------------------------
82973
82974module.exports = {
82975 meta: {
82976 type: "problem",
82977 docs: {
82978 description: "disallow `new` operators with the `Symbol` object",
82979 category: "ECMAScript 6",
82980 recommended: true,
82981 url: "https://eslint.org/docs/rules/no-new-symbol"
82982 },
82983 schema: [],
82984 messages: {
82985 noNewSymbol: "`Symbol` cannot be called as a constructor."
82986 }
82987 },
82988
82989 create(context) {
82990 return {
82991 "Program:exit"() {
82992 const globalScope = context.getScope();
82993 const variable = globalScope.set.get("Symbol");
82994
82995 if (variable && variable.defs.length === 0) {
82996 variable.references.forEach(ref => {
82997 const node = ref.identifier;
6a5a0f88 82998 const parent = node.parent;
eb39fafa 82999
6a5a0f88 83000 if (parent && parent.type === "NewExpression" && parent.callee === node) {
eb39fafa
DC
83001 context.report({
83002 node,
83003 messageId: "noNewSymbol"
83004 });
83005 }
83006 });
83007 }
83008 }
83009
83010 };
83011 }
83012
83013};
83014
83015/***/ }),
6a5a0f88 83016/* 596 */
eb39fafa
DC
83017/***/ (function(module, exports, __webpack_require__) {
83018
83019"use strict";
83020/**
83021 * @fileoverview Rule to flag when using constructor for wrapper objects
83022 * @author Ilya Volodin
83023 */
83024 //------------------------------------------------------------------------------
83025// Rule Definition
83026//------------------------------------------------------------------------------
83027
83028module.exports = {
83029 meta: {
83030 type: "suggestion",
83031 docs: {
83032 description: "disallow `new` operators with the `String`, `Number`, and `Boolean` objects",
83033 category: "Best Practices",
83034 recommended: false,
83035 url: "https://eslint.org/docs/rules/no-new-wrappers"
83036 },
83037 schema: [],
83038 messages: {
83039 noConstructor: "Do not use {{fn}} as a constructor."
83040 }
83041 },
83042
83043 create(context) {
83044 return {
83045 NewExpression(node) {
83046 const wrapperObjects = ["String", "Number", "Boolean"];
83047
83048 if (wrapperObjects.indexOf(node.callee.name) > -1) {
83049 context.report({
83050 node,
83051 messageId: "noConstructor",
83052 data: {
83053 fn: node.callee.name
83054 }
83055 });
83056 }
83057 }
83058
83059 };
83060 }
83061
83062};
83063
83064/***/ }),
6a5a0f88 83065/* 597 */
eb39fafa
DC
83066/***/ (function(module, exports, __webpack_require__) {
83067
83068"use strict";
83069/**
83070 * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function
83071 * @author James Allardice
83072 */
83073 //------------------------------------------------------------------------------
83074// Requirements
83075//------------------------------------------------------------------------------
83076
83077const {
83078 CALL,
83079 CONSTRUCT,
83080 ReferenceTracker
83081} = __webpack_require__(549);
83082
83083const getPropertyName = __webpack_require__(426).getStaticPropertyName; //------------------------------------------------------------------------------
83084// Helpers
83085//------------------------------------------------------------------------------
83086
83087
83088const nonCallableGlobals = ["Atomics", "JSON", "Math", "Reflect"];
83089/**
83090 * Returns the name of the node to report
83091 * @param {ASTNode} node A node to report
83092 * @returns {string} name to report
83093 */
83094
83095function getReportNodeName(node) {
83096 if (node.callee.type === "MemberExpression") {
83097 return getPropertyName(node.callee);
83098 }
83099
83100 return node.callee.name;
83101} //------------------------------------------------------------------------------
83102// Rule Definition
83103//------------------------------------------------------------------------------
83104
83105
83106module.exports = {
83107 meta: {
83108 type: "problem",
83109 docs: {
83110 description: "disallow calling global object properties as functions",
83111 category: "Possible Errors",
83112 recommended: true,
83113 url: "https://eslint.org/docs/rules/no-obj-calls"
83114 },
83115 schema: [],
83116 messages: {
83117 unexpectedCall: "'{{name}}' is not a function.",
83118 unexpectedRefCall: "'{{name}}' is reference to '{{ref}}', which is not a function."
83119 }
83120 },
83121
83122 create(context) {
83123 return {
83124 Program() {
83125 const scope = context.getScope();
83126 const tracker = new ReferenceTracker(scope);
83127 const traceMap = {};
83128
83129 for (const g of nonCallableGlobals) {
83130 traceMap[g] = {
83131 [CALL]: true,
83132 [CONSTRUCT]: true
83133 };
83134 }
83135
83136 for (const {
83137 node,
83138 path
83139 } of tracker.iterateGlobalReferences(traceMap)) {
83140 const name = getReportNodeName(node);
83141 const ref = path[0];
83142 const messageId = name === ref ? "unexpectedCall" : "unexpectedRefCall";
83143 context.report({
83144 node,
83145 messageId,
83146 data: {
83147 name,
83148 ref
83149 }
83150 });
83151 }
83152 }
83153
83154 };
83155 }
83156
83157};
83158
83159/***/ }),
6a5a0f88 83160/* 598 */
eb39fafa
DC
83161/***/ (function(module, exports, __webpack_require__) {
83162
83163"use strict";
83164/**
83165 * @fileoverview Rule to flag when initializing octal literal
83166 * @author Ilya Volodin
83167 */
83168 //------------------------------------------------------------------------------
83169// Rule Definition
83170//------------------------------------------------------------------------------
83171
83172module.exports = {
83173 meta: {
83174 type: "suggestion",
83175 docs: {
83176 description: "disallow octal literals",
83177 category: "Best Practices",
83178 recommended: true,
83179 url: "https://eslint.org/docs/rules/no-octal"
83180 },
83181 schema: [],
83182 messages: {
83183 noOcatal: "Octal literals should not be used."
83184 }
83185 },
83186
83187 create(context) {
83188 return {
83189 Literal(node) {
83190 if (typeof node.value === "number" && /^0[0-9]/u.test(node.raw)) {
83191 context.report({
83192 node,
83193 messageId: "noOcatal"
83194 });
83195 }
83196 }
83197
83198 };
83199 }
83200
83201};
83202
83203/***/ }),
6a5a0f88 83204/* 599 */
eb39fafa
DC
83205/***/ (function(module, exports, __webpack_require__) {
83206
83207"use strict";
83208/**
83209 * @fileoverview Rule to flag octal escape sequences in string literals.
83210 * @author Ian Christian Myers
83211 */
83212 //------------------------------------------------------------------------------
83213// Rule Definition
83214//------------------------------------------------------------------------------
83215
83216module.exports = {
83217 meta: {
83218 type: "suggestion",
83219 docs: {
83220 description: "disallow octal escape sequences in string literals",
83221 category: "Best Practices",
83222 recommended: false,
83223 url: "https://eslint.org/docs/rules/no-octal-escape"
83224 },
83225 schema: [],
83226 messages: {
83227 octalEscapeSequence: "Don't use octal: '\\{{sequence}}'. Use '\\u....' instead."
83228 }
83229 },
83230
83231 create(context) {
83232 return {
83233 Literal(node) {
83234 if (typeof node.value !== "string") {
83235 return;
83236 } // \0 represents a valid NULL character if it isn't followed by a digit.
83237
83238
83239 const match = node.raw.match(/^(?:[\0-\[\]-\u{10FFFF}]|\\[\0-\u{10FFFF}])*?\\([0-3][0-7]{1,2}|[4-7][0-7]|0(?=[89])|[1-7])/u);
83240
83241 if (match) {
83242 context.report({
83243 node,
83244 messageId: "octalEscapeSequence",
83245 data: {
83246 sequence: match[1]
83247 }
83248 });
83249 }
83250 }
83251
83252 };
83253 }
83254
83255};
83256
83257/***/ }),
6a5a0f88 83258/* 600 */
eb39fafa
DC
83259/***/ (function(module, exports, __webpack_require__) {
83260
83261"use strict";
83262/**
83263 * @fileoverview Disallow reassignment of function parameters.
83264 * @author Nat Burns
83265 */
83266 //------------------------------------------------------------------------------
83267// Rule Definition
83268//------------------------------------------------------------------------------
83269
83270const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u;
83271module.exports = {
83272 meta: {
83273 type: "suggestion",
83274 docs: {
83275 description: "disallow reassigning `function` parameters",
83276 category: "Best Practices",
83277 recommended: false,
83278 url: "https://eslint.org/docs/rules/no-param-reassign"
83279 },
83280 schema: [{
83281 oneOf: [{
83282 type: "object",
83283 properties: {
83284 props: {
83285 enum: [false]
83286 }
83287 },
83288 additionalProperties: false
83289 }, {
83290 type: "object",
83291 properties: {
83292 props: {
83293 enum: [true]
83294 },
83295 ignorePropertyModificationsFor: {
83296 type: "array",
83297 items: {
83298 type: "string"
83299 },
83300 uniqueItems: true
83301 },
83302 ignorePropertyModificationsForRegex: {
83303 type: "array",
83304 items: {
83305 type: "string"
83306 },
83307 uniqueItems: true
83308 }
83309 },
83310 additionalProperties: false
83311 }]
83312 }],
83313 messages: {
83314 assignmentToFunctionParam: "Assignment to function parameter '{{name}}'.",
83315 assignmentToFunctionParamProp: "Assignment to property of function parameter '{{name}}'."
83316 }
83317 },
83318
83319 create(context) {
83320 const props = context.options[0] && context.options[0].props;
83321 const ignoredPropertyAssignmentsFor = context.options[0] && context.options[0].ignorePropertyModificationsFor || [];
83322 const ignoredPropertyAssignmentsForRegex = context.options[0] && context.options[0].ignorePropertyModificationsForRegex || [];
83323 /**
83324 * Checks whether or not the reference modifies properties of its variable.
83325 * @param {Reference} reference A reference to check.
83326 * @returns {boolean} Whether or not the reference modifies properties of its variable.
83327 */
83328
83329 function isModifyingProp(reference) {
83330 let node = reference.identifier;
83331 let parent = node.parent;
83332
83333 while (parent && (!stopNodePattern.test(parent.type) || parent.type === "ForInStatement" || parent.type === "ForOfStatement")) {
83334 switch (parent.type) {
83335 // e.g. foo.a = 0;
83336 case "AssignmentExpression":
83337 return parent.left === node;
83338 // e.g. ++foo.a;
83339
83340 case "UpdateExpression":
83341 return true;
83342 // e.g. delete foo.a;
83343
83344 case "UnaryExpression":
83345 if (parent.operator === "delete") {
83346 return true;
83347 }
83348
83349 break;
83350 // e.g. for (foo.a in b) {}
83351
83352 case "ForInStatement":
83353 case "ForOfStatement":
83354 if (parent.left === node) {
83355 return true;
83356 } // this is a stop node for parent.right and parent.body
83357
83358
83359 return false;
83360 // EXCLUDES: e.g. cache.get(foo.a).b = 0;
83361
83362 case "CallExpression":
83363 if (parent.callee !== node) {
83364 return false;
83365 }
83366
83367 break;
83368 // EXCLUDES: e.g. cache[foo.a] = 0;
83369
83370 case "MemberExpression":
83371 if (parent.property === node) {
83372 return false;
83373 }
83374
83375 break;
83376 // EXCLUDES: e.g. ({ [foo]: a }) = bar;
83377
83378 case "Property":
83379 if (parent.key === node) {
83380 return false;
83381 }
83382
83383 break;
83384 // EXCLUDES: e.g. (foo ? a : b).c = bar;
83385
83386 case "ConditionalExpression":
83387 if (parent.test === node) {
83388 return false;
83389 }
83390
83391 break;
83392 // no default
83393 }
83394
83395 node = parent;
83396 parent = node.parent;
83397 }
83398
83399 return false;
83400 }
83401 /**
83402 * Tests that an identifier name matches any of the ignored property assignments.
83403 * First we test strings in ignoredPropertyAssignmentsFor.
83404 * Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings.
83405 * @param {string} identifierName A string that describes the name of an identifier to
83406 * ignore property assignments for.
83407 * @returns {boolean} Whether the string matches an ignored property assignment regular expression or not.
83408 */
83409
83410
83411 function isIgnoredPropertyAssignment(identifierName) {
83412 return ignoredPropertyAssignmentsFor.includes(identifierName) || ignoredPropertyAssignmentsForRegex.some(ignored => new RegExp(ignored, "u").test(identifierName));
83413 }
83414 /**
83415 * Reports a reference if is non initializer and writable.
83416 * @param {Reference} reference A reference to check.
83417 * @param {int} index The index of the reference in the references.
83418 * @param {Reference[]} references The array that the reference belongs to.
83419 * @returns {void}
83420 */
83421
83422
83423 function checkReference(reference, index, references) {
83424 const identifier = reference.identifier;
83425
83426 if (identifier && !reference.init && (
83427 /*
83428 * Destructuring assignments can have multiple default value,
83429 * so possibly there are multiple writeable references for the same identifier.
83430 */
83431 index === 0 || references[index - 1].identifier !== identifier)) {
83432 if (reference.isWrite()) {
83433 context.report({
83434 node: identifier,
83435 messageId: "assignmentToFunctionParam",
83436 data: {
83437 name: identifier.name
83438 }
83439 });
83440 } else if (props && isModifyingProp(reference) && !isIgnoredPropertyAssignment(identifier.name)) {
83441 context.report({
83442 node: identifier,
83443 messageId: "assignmentToFunctionParamProp",
83444 data: {
83445 name: identifier.name
83446 }
83447 });
83448 }
83449 }
83450 }
83451 /**
83452 * Finds and reports references that are non initializer and writable.
83453 * @param {Variable} variable A variable to check.
83454 * @returns {void}
83455 */
83456
83457
83458 function checkVariable(variable) {
83459 if (variable.defs[0].type === "Parameter") {
83460 variable.references.forEach(checkReference);
83461 }
83462 }
83463 /**
83464 * Checks parameters of a given function node.
83465 * @param {ASTNode} node A function node to check.
83466 * @returns {void}
83467 */
83468
83469
83470 function checkForFunction(node) {
83471 context.getDeclaredVariables(node).forEach(checkVariable);
83472 }
83473
83474 return {
83475 // `:exit` is needed for the `node.parent` property of identifier nodes.
83476 "FunctionDeclaration:exit": checkForFunction,
83477 "FunctionExpression:exit": checkForFunction,
83478 "ArrowFunctionExpression:exit": checkForFunction
83479 };
83480 }
83481
83482};
83483
83484/***/ }),
6a5a0f88 83485/* 601 */
eb39fafa
DC
83486/***/ (function(module, exports, __webpack_require__) {
83487
83488"use strict";
83489/**
83490 * @fileoverview Disallow string concatenation when using __dirname and __filename
83491 * @author Nicholas C. Zakas
83492 */
83493 //------------------------------------------------------------------------------
83494// Rule Definition
83495//------------------------------------------------------------------------------
83496
83497module.exports = {
83498 meta: {
56c4a2cb 83499 deprecated: true,
6a5a0f88 83500 replacedBy: [],
eb39fafa
DC
83501 type: "suggestion",
83502 docs: {
83503 description: "disallow string concatenation with `__dirname` and `__filename`",
83504 category: "Node.js and CommonJS",
83505 recommended: false,
83506 url: "https://eslint.org/docs/rules/no-path-concat"
83507 },
83508 schema: [],
83509 messages: {
83510 usePathFunctions: "Use path.join() or path.resolve() instead of + to create paths."
83511 }
83512 },
83513
83514 create(context) {
83515 const MATCHER = /^__(?:dir|file)name$/u; //--------------------------------------------------------------------------
83516 // Public
83517 //--------------------------------------------------------------------------
83518
83519 return {
83520 BinaryExpression(node) {
83521 const left = node.left,
83522 right = node.right;
83523
83524 if (node.operator === "+" && (left.type === "Identifier" && MATCHER.test(left.name) || right.type === "Identifier" && MATCHER.test(right.name))) {
83525 context.report({
83526 node,
83527 messageId: "usePathFunctions"
83528 });
83529 }
83530 }
83531
83532 };
83533 }
83534
83535};
83536
83537/***/ }),
6a5a0f88 83538/* 602 */
eb39fafa
DC
83539/***/ (function(module, exports, __webpack_require__) {
83540
83541"use strict";
83542/**
83543 * @fileoverview Rule to flag use of unary increment and decrement operators.
83544 * @author Ian Christian Myers
83545 * @author Brody McKee (github.com/mrmckeb)
83546 */
83547 //------------------------------------------------------------------------------
83548// Helpers
83549//------------------------------------------------------------------------------
83550
83551/**
83552 * Determines whether the given node is the update node of a `ForStatement`.
83553 * @param {ASTNode} node The node to check.
83554 * @returns {boolean} `true` if the node is `ForStatement` update.
83555 */
83556
83557function isForStatementUpdate(node) {
83558 const parent = node.parent;
83559 return parent.type === "ForStatement" && parent.update === node;
83560}
83561/**
83562 * Determines whether the given node is considered to be a for loop "afterthought" by the logic of this rule.
83563 * In particular, it returns `true` if the given node is either:
83564 * - The update node of a `ForStatement`: for (;; i++) {}
83565 * - An operand of a sequence expression that is the update node: for (;; foo(), i++) {}
83566 * - An operand of a sequence expression that is child of another sequence expression, etc.,
83567 * up to the sequence expression that is the update node: for (;; foo(), (bar(), (baz(), i++))) {}
83568 * @param {ASTNode} node The node to check.
83569 * @returns {boolean} `true` if the node is a for loop afterthought.
83570 */
83571
83572
83573function isForLoopAfterthought(node) {
83574 const parent = node.parent;
83575
83576 if (parent.type === "SequenceExpression") {
83577 return isForLoopAfterthought(parent);
83578 }
83579
83580 return isForStatementUpdate(node);
83581} //------------------------------------------------------------------------------
83582// Rule Definition
83583//------------------------------------------------------------------------------
83584
83585
83586module.exports = {
83587 meta: {
83588 type: "suggestion",
83589 docs: {
83590 description: "disallow the unary operators `++` and `--`",
83591 category: "Stylistic Issues",
83592 recommended: false,
83593 url: "https://eslint.org/docs/rules/no-plusplus"
83594 },
83595 schema: [{
83596 type: "object",
83597 properties: {
83598 allowForLoopAfterthoughts: {
83599 type: "boolean",
83600 default: false
83601 }
83602 },
83603 additionalProperties: false
83604 }],
83605 messages: {
83606 unexpectedUnaryOp: "Unary operator '{{operator}}' used."
83607 }
83608 },
83609
83610 create(context) {
83611 const config = context.options[0];
83612 let allowForLoopAfterthoughts = false;
83613
83614 if (typeof config === "object") {
83615 allowForLoopAfterthoughts = config.allowForLoopAfterthoughts === true;
83616 }
83617
83618 return {
83619 UpdateExpression(node) {
83620 if (allowForLoopAfterthoughts && isForLoopAfterthought(node)) {
83621 return;
83622 }
83623
83624 context.report({
83625 node,
83626 messageId: "unexpectedUnaryOp",
83627 data: {
83628 operator: node.operator
83629 }
83630 });
83631 }
83632
83633 };
83634 }
83635
83636};
83637
83638/***/ }),
6a5a0f88 83639/* 603 */
eb39fafa
DC
83640/***/ (function(module, exports, __webpack_require__) {
83641
83642"use strict";
83643/**
83644 * @fileoverview Disallow the use of process.env()
83645 * @author Vignesh Anand
83646 */
83647 //------------------------------------------------------------------------------
83648// Rule Definition
83649//------------------------------------------------------------------------------
83650
83651module.exports = {
83652 meta: {
56c4a2cb 83653 deprecated: true,
6a5a0f88 83654 replacedBy: [],
eb39fafa
DC
83655 type: "suggestion",
83656 docs: {
83657 description: "disallow the use of `process.env`",
83658 category: "Node.js and CommonJS",
83659 recommended: false,
83660 url: "https://eslint.org/docs/rules/no-process-env"
83661 },
83662 schema: [],
83663 messages: {
83664 unexpectedProcessEnv: "Unexpected use of process.env."
83665 }
83666 },
83667
83668 create(context) {
83669 return {
83670 MemberExpression(node) {
83671 const objectName = node.object.name,
83672 propertyName = node.property.name;
83673
83674 if (objectName === "process" && !node.computed && propertyName && propertyName === "env") {
83675 context.report({
83676 node,
83677 messageId: "unexpectedProcessEnv"
83678 });
83679 }
83680 }
83681
83682 };
83683 }
83684
83685};
83686
83687/***/ }),
6a5a0f88 83688/* 604 */
eb39fafa
DC
83689/***/ (function(module, exports, __webpack_require__) {
83690
83691"use strict";
83692/**
83693 * @fileoverview Disallow the use of process.exit()
83694 * @author Nicholas C. Zakas
83695 */
83696 //------------------------------------------------------------------------------
83697// Rule Definition
83698//------------------------------------------------------------------------------
83699
83700module.exports = {
83701 meta: {
56c4a2cb 83702 deprecated: true,
6a5a0f88 83703 replacedBy: [],
eb39fafa
DC
83704 type: "suggestion",
83705 docs: {
83706 description: "disallow the use of `process.exit()`",
83707 category: "Node.js and CommonJS",
83708 recommended: false,
83709 url: "https://eslint.org/docs/rules/no-process-exit"
83710 },
83711 schema: [],
83712 messages: {
83713 noProcessExit: "Don't use process.exit(); throw an error instead."
83714 }
83715 },
83716
83717 create(context) {
83718 //--------------------------------------------------------------------------
83719 // Public
83720 //--------------------------------------------------------------------------
83721 return {
83722 "CallExpression > MemberExpression.callee[object.name = 'process'][property.name = 'exit']"(node) {
83723 context.report({
83724 node: node.parent,
83725 messageId: "noProcessExit"
83726 });
83727 }
83728
83729 };
83730 }
83731
83732};
83733
83734/***/ }),
6a5a0f88 83735/* 605 */
eb39fafa
DC
83736/***/ (function(module, exports, __webpack_require__) {
83737
83738"use strict";
83739/**
83740 * @fileoverview Rule to flag usage of __proto__ property
83741 * @author Ilya Volodin
83742 */
83743 //------------------------------------------------------------------------------
83744// Requirements
83745//------------------------------------------------------------------------------
83746
83747const {
83748 getStaticPropertyName
83749} = __webpack_require__(426); //------------------------------------------------------------------------------
83750// Rule Definition
83751//------------------------------------------------------------------------------
83752
83753
83754module.exports = {
83755 meta: {
83756 type: "suggestion",
83757 docs: {
83758 description: "disallow the use of the `__proto__` property",
83759 category: "Best Practices",
83760 recommended: false,
83761 url: "https://eslint.org/docs/rules/no-proto"
83762 },
83763 schema: [],
83764 messages: {
83765 unexpectedProto: "The '__proto__' property is deprecated."
83766 }
83767 },
83768
83769 create(context) {
83770 return {
83771 MemberExpression(node) {
83772 if (getStaticPropertyName(node) === "__proto__") {
83773 context.report({
83774 node,
83775 messageId: "unexpectedProto"
83776 });
83777 }
83778 }
83779
83780 };
83781 }
83782
83783};
83784
83785/***/ }),
6a5a0f88 83786/* 606 */
eb39fafa
DC
83787/***/ (function(module, exports, __webpack_require__) {
83788
83789"use strict";
83790/**
83791 * @fileoverview Rule to disallow use of Object.prototype builtins on objects
83792 * @author Andrew Levine
83793 */
83794 //------------------------------------------------------------------------------
83795// Rule Definition
83796//------------------------------------------------------------------------------
83797
83798module.exports = {
83799 meta: {
83800 type: "problem",
83801 docs: {
83802 description: "disallow calling some `Object.prototype` methods directly on objects",
83803 category: "Possible Errors",
83804 recommended: true,
83805 url: "https://eslint.org/docs/rules/no-prototype-builtins"
83806 },
83807 schema: [],
83808 messages: {
83809 prototypeBuildIn: "Do not access Object.prototype method '{{prop}}' from target object."
83810 }
83811 },
83812
83813 create(context) {
83814 const DISALLOWED_PROPS = ["hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable"];
83815 /**
83816 * Reports if a disallowed property is used in a CallExpression
83817 * @param {ASTNode} node The CallExpression node.
83818 * @returns {void}
83819 */
83820
83821 function disallowBuiltIns(node) {
83822 if (node.callee.type !== "MemberExpression" || node.callee.computed) {
83823 return;
83824 }
83825
83826 const propName = node.callee.property.name;
83827
83828 if (DISALLOWED_PROPS.indexOf(propName) > -1) {
83829 context.report({
83830 messageId: "prototypeBuildIn",
83831 loc: node.callee.property.loc,
83832 data: {
83833 prop: propName
83834 },
83835 node
83836 });
83837 }
83838 }
83839
83840 return {
83841 CallExpression: disallowBuiltIns
83842 };
83843 }
83844
83845};
83846
83847/***/ }),
6a5a0f88 83848/* 607 */
eb39fafa
DC
83849/***/ (function(module, exports, __webpack_require__) {
83850
83851"use strict";
83852/**
83853 * @fileoverview Rule to flag when the same variable is declared more then once.
83854 * @author Ilya Volodin
83855 */
83856 //------------------------------------------------------------------------------
83857// Requirements
83858//------------------------------------------------------------------------------
83859
83860const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
83861// Rule Definition
83862//------------------------------------------------------------------------------
83863
83864
83865module.exports = {
83866 meta: {
83867 type: "suggestion",
83868 docs: {
83869 description: "disallow variable redeclaration",
83870 category: "Best Practices",
83871 recommended: true,
83872 url: "https://eslint.org/docs/rules/no-redeclare"
83873 },
83874 messages: {
83875 redeclared: "'{{id}}' is already defined.",
83876 redeclaredAsBuiltin: "'{{id}}' is already defined as a built-in global variable.",
83877 redeclaredBySyntax: "'{{id}}' is already defined by a variable declaration."
83878 },
83879 schema: [{
83880 type: "object",
83881 properties: {
83882 builtinGlobals: {
83883 type: "boolean",
83884 default: true
83885 }
83886 },
83887 additionalProperties: false
83888 }]
83889 },
83890
83891 create(context) {
83892 const options = {
83893 builtinGlobals: Boolean(context.options.length === 0 || context.options[0].builtinGlobals)
83894 };
83895 const sourceCode = context.getSourceCode();
83896 /**
83897 * Iterate declarations of a given variable.
83898 * @param {escope.variable} variable The variable object to iterate declarations.
83899 * @returns {IterableIterator<{type:string,node:ASTNode,loc:SourceLocation}>} The declarations.
83900 */
83901
83902 function* iterateDeclarations(variable) {
83903 if (options.builtinGlobals && (variable.eslintImplicitGlobalSetting === "readonly" || variable.eslintImplicitGlobalSetting === "writable")) {
83904 yield {
83905 type: "builtin"
83906 };
83907 }
83908
83909 for (const id of variable.identifiers) {
83910 yield {
83911 type: "syntax",
83912 node: id,
83913 loc: id.loc
83914 };
83915 }
83916
83917 if (variable.eslintExplicitGlobalComments) {
83918 for (const comment of variable.eslintExplicitGlobalComments) {
83919 yield {
83920 type: "comment",
83921 node: comment,
83922 loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, comment, variable.name)
83923 };
83924 }
83925 }
83926 }
83927 /**
83928 * Find variables in a given scope and flag redeclared ones.
83929 * @param {Scope} scope An eslint-scope scope object.
83930 * @returns {void}
83931 * @private
83932 */
83933
83934
83935 function findVariablesInScope(scope) {
83936 for (const variable of scope.variables) {
83937 const [declaration, ...extraDeclarations] = iterateDeclarations(variable);
83938
83939 if (extraDeclarations.length === 0) {
83940 continue;
83941 }
83942 /*
83943 * If the type of a declaration is different from the type of
83944 * the first declaration, it shows the location of the first
83945 * declaration.
83946 */
83947
83948
83949 const detailMessageId = declaration.type === "builtin" ? "redeclaredAsBuiltin" : "redeclaredBySyntax";
83950 const data = {
83951 id: variable.name
83952 }; // Report extra declarations.
83953
83954 for (const {
83955 type,
83956 node,
83957 loc
83958 } of extraDeclarations) {
83959 const messageId = type === declaration.type ? "redeclared" : detailMessageId;
83960 context.report({
83961 node,
83962 loc,
83963 messageId,
83964 data
83965 });
83966 }
83967 }
83968 }
83969 /**
83970 * Find variables in the current scope.
83971 * @param {ASTNode} node The node of the current scope.
83972 * @returns {void}
83973 * @private
83974 */
83975
83976
83977 function checkForBlock(node) {
83978 const scope = context.getScope();
83979 /*
83980 * In ES5, some node type such as `BlockStatement` doesn't have that scope.
83981 * `scope.block` is a different node in such a case.
83982 */
83983
83984 if (scope.block === node) {
83985 findVariablesInScope(scope);
83986 }
83987 }
83988
83989 return {
83990 Program() {
83991 const scope = context.getScope();
83992 findVariablesInScope(scope); // Node.js or ES modules has a special scope.
83993
83994 if (scope.type === "global" && scope.childScopes[0] && // The special scope's block is the Program node.
83995 scope.block === scope.childScopes[0].block) {
83996 findVariablesInScope(scope.childScopes[0]);
83997 }
83998 },
83999
84000 FunctionDeclaration: checkForBlock,
84001 FunctionExpression: checkForBlock,
84002 ArrowFunctionExpression: checkForBlock,
84003 BlockStatement: checkForBlock,
84004 ForStatement: checkForBlock,
84005 ForInStatement: checkForBlock,
84006 ForOfStatement: checkForBlock,
84007 SwitchStatement: checkForBlock
84008 };
84009 }
84010
84011};
84012
84013/***/ }),
6a5a0f88 84014/* 608 */
eb39fafa
DC
84015/***/ (function(module, exports, __webpack_require__) {
84016
84017"use strict";
84018/**
84019 * @fileoverview Rule to count multiple spaces in regular expressions
84020 * @author Matt DuVall <http://www.mattduvall.com/>
84021 */
84022 //------------------------------------------------------------------------------
84023// Requirements
84024//------------------------------------------------------------------------------
84025
84026const astUtils = __webpack_require__(426);
84027
84028const regexpp = __webpack_require__(527); //------------------------------------------------------------------------------
84029// Helpers
84030//------------------------------------------------------------------------------
84031
84032
84033const regExpParser = new regexpp.RegExpParser();
84034const DOUBLE_SPACE = / {2}/u;
84035/**
84036 * Check if node is a string
84037 * @param {ASTNode} node node to evaluate
84038 * @returns {boolean} True if its a string
84039 * @private
84040 */
84041
84042function isString(node) {
84043 return node && node.type === "Literal" && typeof node.value === "string";
84044} //------------------------------------------------------------------------------
84045// Rule Definition
84046//------------------------------------------------------------------------------
84047
84048
84049module.exports = {
84050 meta: {
84051 type: "suggestion",
84052 docs: {
84053 description: "disallow multiple spaces in regular expressions",
84054 category: "Possible Errors",
84055 recommended: true,
84056 url: "https://eslint.org/docs/rules/no-regex-spaces"
84057 },
84058 schema: [],
84059 fixable: "code",
84060 messages: {
84061 multipleSpaces: "Spaces are hard to count. Use {{{length}}}."
84062 }
84063 },
84064
84065 create(context) {
84066 /**
84067 * Validate regular expression
84068 * @param {ASTNode} nodeToReport Node to report.
84069 * @param {string} pattern Regular expression pattern to validate.
84070 * @param {string} rawPattern Raw representation of the pattern in the source code.
84071 * @param {number} rawPatternStartRange Start range of the pattern in the source code.
84072 * @param {string} flags Regular expression flags.
84073 * @returns {void}
84074 * @private
84075 */
84076 function checkRegex(nodeToReport, pattern, rawPattern, rawPatternStartRange, flags) {
84077 // Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ ').
84078 if (!DOUBLE_SPACE.test(rawPattern)) {
84079 return;
84080 }
84081
84082 const characterClassNodes = [];
84083 let regExpAST;
84084
84085 try {
84086 regExpAST = regExpParser.parsePattern(pattern, 0, pattern.length, flags.includes("u"));
84087 } catch (e) {
84088 // Ignore regular expressions with syntax errors
84089 return;
84090 }
84091
84092 regexpp.visitRegExpAST(regExpAST, {
84093 onCharacterClassEnter(ccNode) {
84094 characterClassNodes.push(ccNode);
84095 }
84096
84097 });
84098 const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu;
84099 let match;
84100
84101 while (match = spacesPattern.exec(pattern)) {
84102 const {
84103 1: {
84104 length
84105 },
84106 index
84107 } = match; // Report only consecutive spaces that are not in character classes.
84108
84109 if (characterClassNodes.every(({
84110 start,
84111 end
84112 }) => index < start || end <= index)) {
84113 context.report({
84114 node: nodeToReport,
84115 messageId: "multipleSpaces",
84116 data: {
84117 length
84118 },
84119
84120 fix(fixer) {
84121 if (pattern !== rawPattern) {
84122 return null;
84123 }
84124
84125 return fixer.replaceTextRange([rawPatternStartRange + index, rawPatternStartRange + index + length], " {".concat(length, "}"));
84126 }
84127
84128 }); // Report only the first occurrence of consecutive spaces
84129
84130 return;
84131 }
84132 }
84133 }
84134 /**
84135 * Validate regular expression literals
84136 * @param {ASTNode} node node to validate
84137 * @returns {void}
84138 * @private
84139 */
84140
84141
84142 function checkLiteral(node) {
84143 if (node.regex) {
84144 const pattern = node.regex.pattern;
84145 const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/"));
84146 const rawPatternStartRange = node.range[0] + 1;
84147 const flags = node.regex.flags;
84148 checkRegex(node, pattern, rawPattern, rawPatternStartRange, flags);
84149 }
84150 }
84151 /**
84152 * Validate strings passed to the RegExp constructor
84153 * @param {ASTNode} node node to validate
84154 * @returns {void}
84155 * @private
84156 */
84157
84158
84159 function checkFunction(node) {
84160 const scope = context.getScope();
84161 const regExpVar = astUtils.getVariableByName(scope, "RegExp");
84162 const shadowed = regExpVar && regExpVar.defs.length > 0;
84163 const patternNode = node.arguments[0];
84164 const flagsNode = node.arguments[1];
84165
84166 if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(patternNode) && !shadowed) {
84167 const pattern = patternNode.value;
84168 const rawPattern = patternNode.raw.slice(1, -1);
84169 const rawPatternStartRange = patternNode.range[0] + 1;
84170 const flags = isString(flagsNode) ? flagsNode.value : "";
84171 checkRegex(node, pattern, rawPattern, rawPatternStartRange, flags);
84172 }
84173 }
84174
84175 return {
84176 Literal: checkLiteral,
84177 CallExpression: checkFunction,
84178 NewExpression: checkFunction
84179 };
84180 }
84181
84182};
84183
84184/***/ }),
6a5a0f88 84185/* 609 */
eb39fafa
DC
84186/***/ (function(module, exports, __webpack_require__) {
84187
84188"use strict";
84189/**
84190 * @fileoverview Rule to disallow specified names in exports
84191 * @author Milos Djermanovic
84192 */
84193 //------------------------------------------------------------------------------
84194// Rule Definition
84195//------------------------------------------------------------------------------
84196
84197module.exports = {
84198 meta: {
84199 type: "suggestion",
84200 docs: {
84201 description: "disallow specified names in exports",
84202 category: "ECMAScript 6",
84203 recommended: false,
84204 url: "https://eslint.org/docs/rules/no-restricted-exports"
84205 },
84206 schema: [{
84207 type: "object",
84208 properties: {
84209 restrictedNamedExports: {
84210 type: "array",
84211 items: {
84212 type: "string"
84213 },
84214 uniqueItems: true
84215 }
84216 },
84217 additionalProperties: false
84218 }],
84219 messages: {
84220 restrictedNamed: "'{{name}}' is restricted from being used as an exported name."
84221 }
84222 },
84223
84224 create(context) {
84225 const restrictedNames = new Set(context.options[0] && context.options[0].restrictedNamedExports);
84226 /**
84227 * Checks and reports given exported identifier.
84228 * @param {ASTNode} node exported `Identifer` node to check.
84229 * @returns {void}
84230 */
84231
84232 function checkExportedName(node) {
84233 const name = node.name;
84234
84235 if (restrictedNames.has(name)) {
84236 context.report({
84237 node,
84238 messageId: "restrictedNamed",
84239 data: {
84240 name
84241 }
84242 });
84243 }
84244 }
84245
84246 return {
84247 ExportNamedDeclaration(node) {
84248 const declaration = node.declaration;
84249
84250 if (declaration) {
84251 if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") {
84252 checkExportedName(declaration.id);
84253 } else if (declaration.type === "VariableDeclaration") {
84254 context.getDeclaredVariables(declaration).map(v => v.defs.find(d => d.parent === declaration)).map(d => d.name) // Identifier nodes
84255 .forEach(checkExportedName);
84256 }
84257 } else {
84258 node.specifiers.map(s => s.exported).forEach(checkExportedName);
84259 }
84260 }
84261
84262 };
84263 }
84264
84265};
84266
84267/***/ }),
6a5a0f88 84268/* 610 */
eb39fafa
DC
84269/***/ (function(module, exports, __webpack_require__) {
84270
84271"use strict";
84272/**
84273 * @fileoverview Restrict usage of specified globals.
84274 * @author Benoît Zugmeyer
84275 */
84276 //------------------------------------------------------------------------------
84277// Rule Definition
84278//------------------------------------------------------------------------------
84279
84280module.exports = {
84281 meta: {
84282 type: "suggestion",
84283 docs: {
84284 description: "disallow specified global variables",
84285 category: "Variables",
84286 recommended: false,
84287 url: "https://eslint.org/docs/rules/no-restricted-globals"
84288 },
84289 schema: {
84290 type: "array",
84291 items: {
84292 oneOf: [{
84293 type: "string"
84294 }, {
84295 type: "object",
84296 properties: {
84297 name: {
84298 type: "string"
84299 },
84300 message: {
84301 type: "string"
84302 }
84303 },
84304 required: ["name"],
84305 additionalProperties: false
84306 }]
84307 },
84308 uniqueItems: true,
84309 minItems: 0
84310 },
84311 messages: {
84312 defaultMessage: "Unexpected use of '{{name}}'.",
84313 // eslint-disable-next-line eslint-plugin/report-message-format
84314 customMessage: "Unexpected use of '{{name}}'. {{customMessage}}"
84315 }
84316 },
84317
84318 create(context) {
84319 // If no globals are restricted, we don't need to do anything
84320 if (context.options.length === 0) {
84321 return {};
84322 }
84323
84324 const restrictedGlobalMessages = context.options.reduce((memo, option) => {
84325 if (typeof option === "string") {
84326 memo[option] = null;
84327 } else {
84328 memo[option.name] = option.message;
84329 }
84330
84331 return memo;
84332 }, {});
84333 /**
84334 * Report a variable to be used as a restricted global.
84335 * @param {Reference} reference the variable reference
84336 * @returns {void}
84337 * @private
84338 */
84339
84340 function reportReference(reference) {
84341 const name = reference.identifier.name,
84342 customMessage = restrictedGlobalMessages[name],
84343 messageId = customMessage ? "customMessage" : "defaultMessage";
84344 context.report({
84345 node: reference.identifier,
84346 messageId,
84347 data: {
84348 name,
84349 customMessage
84350 }
84351 });
84352 }
84353 /**
84354 * Check if the given name is a restricted global name.
84355 * @param {string} name name of a variable
84356 * @returns {boolean} whether the variable is a restricted global or not
84357 * @private
84358 */
84359
84360
84361 function isRestricted(name) {
84362 return Object.prototype.hasOwnProperty.call(restrictedGlobalMessages, name);
84363 }
84364
84365 return {
84366 Program() {
84367 const scope = context.getScope(); // Report variables declared elsewhere (ex: variables defined as "global" by eslint)
84368
84369 scope.variables.forEach(variable => {
84370 if (!variable.defs.length && isRestricted(variable.name)) {
84371 variable.references.forEach(reportReference);
84372 }
84373 }); // Report variables not declared at all
84374
84375 scope.through.forEach(reference => {
84376 if (isRestricted(reference.identifier.name)) {
84377 reportReference(reference);
84378 }
84379 });
84380 }
84381
84382 };
84383 }
84384
84385};
84386
84387/***/ }),
6a5a0f88 84388/* 611 */
eb39fafa
DC
84389/***/ (function(module, exports, __webpack_require__) {
84390
84391"use strict";
84392/**
84393 * @fileoverview Restrict usage of specified node imports.
84394 * @author Guy Ellis
84395 */
84396 //------------------------------------------------------------------------------
84397// Rule Definition
84398//------------------------------------------------------------------------------
84399
6a5a0f88 84400const ignore = __webpack_require__(612);
eb39fafa
DC
84401
84402const arrayOfStrings = {
84403 type: "array",
84404 items: {
84405 type: "string"
84406 },
84407 uniqueItems: true
84408};
84409const arrayOfStringsOrObjects = {
84410 type: "array",
84411 items: {
84412 anyOf: [{
84413 type: "string"
84414 }, {
84415 type: "object",
84416 properties: {
84417 name: {
84418 type: "string"
84419 },
84420 message: {
84421 type: "string",
84422 minLength: 1
84423 },
84424 importNames: {
84425 type: "array",
84426 items: {
84427 type: "string"
84428 }
84429 }
84430 },
84431 additionalProperties: false,
84432 required: ["name"]
84433 }]
84434 },
84435 uniqueItems: true
84436};
84437module.exports = {
84438 meta: {
84439 type: "suggestion",
84440 docs: {
84441 description: "disallow specified modules when loaded by `import`",
84442 category: "ECMAScript 6",
84443 recommended: false,
84444 url: "https://eslint.org/docs/rules/no-restricted-imports"
84445 },
84446 messages: {
84447 path: "'{{importSource}}' import is restricted from being used.",
84448 // eslint-disable-next-line eslint-plugin/report-message-format
84449 pathWithCustomMessage: "'{{importSource}}' import is restricted from being used. {{customMessage}}",
84450 patterns: "'{{importSource}}' import is restricted from being used by a pattern.",
84451 everything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.",
84452 // eslint-disable-next-line eslint-plugin/report-message-format
84453 everythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}",
84454 importName: "'{{importName}}' import from '{{importSource}}' is restricted.",
84455 // eslint-disable-next-line eslint-plugin/report-message-format
84456 importNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}"
84457 },
84458 schema: {
84459 anyOf: [arrayOfStringsOrObjects, {
84460 type: "array",
84461 items: [{
84462 type: "object",
84463 properties: {
84464 paths: arrayOfStringsOrObjects,
84465 patterns: arrayOfStrings
84466 },
84467 additionalProperties: false
84468 }],
84469 additionalItems: false
84470 }]
84471 }
84472 },
84473
84474 create(context) {
84475 const sourceCode = context.getSourceCode();
84476 const options = Array.isArray(context.options) ? context.options : [];
84477 const isPathAndPatternsObject = typeof options[0] === "object" && (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns"));
84478 const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || [];
84479 const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; // if no imports are restricted we don"t need to check
84480
84481 if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) {
84482 return {};
84483 }
84484
84485 const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => {
84486 if (typeof importSource === "string") {
84487 memo[importSource] = {
84488 message: null
84489 };
84490 } else {
84491 memo[importSource.name] = {
84492 message: importSource.message,
84493 importNames: importSource.importNames
84494 };
84495 }
84496
84497 return memo;
84498 }, {});
84499 const restrictedPatternsMatcher = ignore().add(restrictedPatterns);
84500 /**
84501 * Report a restricted path.
84502 * @param {string} importSource path of the import
84503 * @param {Map<string,Object[]>} importNames Map of import names that are being imported
84504 * @param {node} node representing the restricted path reference
84505 * @returns {void}
84506 * @private
84507 */
84508
84509 function checkRestrictedPathAndReport(importSource, importNames, node) {
84510 if (!Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) {
84511 return;
84512 }
84513
84514 const customMessage = restrictedPathMessages[importSource].message;
84515 const restrictedImportNames = restrictedPathMessages[importSource].importNames;
84516
84517 if (restrictedImportNames) {
84518 if (importNames.has("*")) {
84519 const specifierData = importNames.get("*")[0];
84520 context.report({
84521 node,
84522 messageId: customMessage ? "everythingWithCustomMessage" : "everything",
84523 loc: specifierData.loc,
84524 data: {
84525 importSource,
84526 importNames: restrictedImportNames,
84527 customMessage
84528 }
84529 });
84530 }
84531
84532 restrictedImportNames.forEach(importName => {
84533 if (importNames.has(importName)) {
84534 const specifiers = importNames.get(importName);
84535 specifiers.forEach(specifier => {
84536 context.report({
84537 node,
84538 messageId: customMessage ? "importNameWithCustomMessage" : "importName",
84539 loc: specifier.loc,
84540 data: {
84541 importSource,
84542 customMessage,
84543 importName
84544 }
84545 });
84546 });
84547 }
84548 });
84549 } else {
84550 context.report({
84551 node,
84552 messageId: customMessage ? "pathWithCustomMessage" : "path",
84553 data: {
84554 importSource,
84555 customMessage
84556 }
84557 });
84558 }
84559 }
84560 /**
84561 * Report a restricted path specifically for patterns.
84562 * @param {node} node representing the restricted path reference
84563 * @returns {void}
84564 * @private
84565 */
84566
84567
84568 function reportPathForPatterns(node) {
84569 const importSource = node.source.value.trim();
84570 context.report({
84571 node,
84572 messageId: "patterns",
84573 data: {
84574 importSource
84575 }
84576 });
84577 }
84578 /**
84579 * Check if the given importSource is restricted by a pattern.
84580 * @param {string} importSource path of the import
84581 * @returns {boolean} whether the variable is a restricted pattern or not
84582 * @private
84583 */
84584
84585
84586 function isRestrictedPattern(importSource) {
84587 return restrictedPatterns.length > 0 && restrictedPatternsMatcher.ignores(importSource);
84588 }
84589 /**
84590 * Checks a node to see if any problems should be reported.
84591 * @param {ASTNode} node The node to check.
84592 * @returns {void}
84593 * @private
84594 */
84595
84596
84597 function checkNode(node) {
84598 const importSource = node.source.value.trim();
84599 const importNames = new Map();
84600
84601 if (node.type === "ExportAllDeclaration") {
84602 const starToken = sourceCode.getFirstToken(node, 1);
84603 importNames.set("*", [{
84604 loc: starToken.loc
84605 }]);
84606 } else if (node.specifiers) {
84607 for (const specifier of node.specifiers) {
84608 let name;
84609 const specifierData = {
84610 loc: specifier.loc
84611 };
84612
84613 if (specifier.type === "ImportDefaultSpecifier") {
84614 name = "default";
84615 } else if (specifier.type === "ImportNamespaceSpecifier") {
84616 name = "*";
84617 } else if (specifier.imported) {
84618 name = specifier.imported.name;
84619 } else if (specifier.local) {
84620 name = specifier.local.name;
84621 }
84622
84623 if (name) {
84624 if (importNames.has(name)) {
84625 importNames.get(name).push(specifierData);
84626 } else {
84627 importNames.set(name, [specifierData]);
84628 }
84629 }
84630 }
84631 }
84632
84633 checkRestrictedPathAndReport(importSource, importNames, node);
84634
84635 if (isRestrictedPattern(importSource)) {
84636 reportPathForPatterns(node);
84637 }
84638 }
84639
84640 return {
84641 ImportDeclaration: checkNode,
84642
84643 ExportNamedDeclaration(node) {
84644 if (node.source) {
84645 checkNode(node);
84646 }
84647 },
84648
84649 ExportAllDeclaration: checkNode
84650 };
84651 }
84652
84653};
84654
84655/***/ }),
6a5a0f88 84656/* 612 */
eb39fafa
DC
84657/***/ (function(module, exports) {
84658
84659// A simple implementation of make-array
84660function make_array(subject) {
84661 return Array.isArray(subject) ? subject : [subject];
84662}
84663
84664const REGEX_BLANK_LINE = /^\s+$/;
84665const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
84666const REGEX_LEADING_EXCAPED_HASH = /^\\#/;
84667const SLASH = '/';
84668const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
84669/* istanbul ignore next */
84670: 'node-ignore';
84671
84672const define = (object, key, value) => Object.defineProperty(object, key, {
84673 value
84674});
84675
84676const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
84677// The cases are complicated, see test cases for details
84678
84679const sanitizeRange = range => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
84680// fatal for JavaScript regular expression, so eliminate it.
84681: ''); // > If the pattern ends with a slash,
84682// > it is removed for the purpose of the following description,
84683// > but it would only find a match with a directory.
84684// > In other words, foo/ will match a directory foo and paths underneath it,
84685// > but will not match a regular file or a symbolic link foo
84686// > (this is consistent with the way how pathspec works in general in Git).
84687// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
84688// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
84689// you could use option `mark: true` with `glob`
84690// '`foo/`' should not continue with the '`..`'
84691
84692
84693const DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
84694[// (a\ ) -> (a )
84695// (a ) -> (a)
84696// (a \ ) -> (a )
84697/\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
84698[/\\\s/g, () => ' '], // Escape metacharacters
84699// which is written down by users but means special for regular expressions.
84700// > There are 12 characters with special meanings:
84701// > - the backslash \,
84702// > - the caret ^,
84703// > - the dollar sign $,
84704// > - the period or dot .,
84705// > - the vertical bar or pipe symbol |,
84706// > - the question mark ?,
84707// > - the asterisk or star *,
84708// > - the plus sign +,
84709// > - the opening parenthesis (,
84710// > - the closing parenthesis ),
84711// > - and the opening square bracket [,
84712// > - the opening curly brace {,
84713// > These special characters are often called "metacharacters".
84714[/[\\^$.|*+(){]/g, match => "\\".concat(match)], [// > [abc] matches any character inside the brackets
84715// > (in this case a, b, or c);
84716/\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? "[".concat(sanitizeRange(p1), "]") : "\\".concat(match)], [// > a question mark (?) matches a single character
84717/(?!\\)\?/g, () => '[^/]'], // leading slash
84718[// > A leading slash matches the beginning of the pathname.
84719// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
84720// A leading slash matches the beginning of the pathname
84721/^\//, () => '^'], // replace special metacharacter slash after the leading slash
84722[/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
84723// > For example, "**/foo" matches file or directory "foo" anywhere,
84724// > the same as pattern "foo".
84725// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
84726// > under directory "foo".
84727// Notice that the '*'s have been replaced as '\\*'
84728/^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
84729() => '^(?:.*\\/)?']];
84730const DEFAULT_REPLACER_SUFFIX = [// starting
84731[// there will be no leading '/'
84732// (which has been replaced by section "leading slash")
84733// If starts with '**', adding a '^' to the regular expression also works
84734/^(?=[^^])/, function startingReplacer() {
84735 return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
84736 // > Git treats it as a shell glob pattern
84737 // Actually, if there is only a trailing slash,
84738 // git also treats it as a shell glob pattern
84739 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
84740 // > consumption by fnmatch(3)
84741 : '^';
84742}], // two globstars
84743[// Use lookahead assertions so that we could match more than one `'/**'`
84744/\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
84745// should not use '*', or it will be replaced by the next replacer
84746// Check if it is not the last `'/**'`
84747(match, index, str) => index + 6 < str.length // case: /**/
84748// > A slash followed by two consecutive asterisks then a slash matches
84749// > zero or more directories.
84750// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
84751// '/**/'
84752? '(?:\\/[^\\/]+)*' // case: /**
84753// > A trailing `"/**"` matches everything inside.
84754// #21: everything inside but it should not include the current folder
84755: '\\/.+'], // intermediate wildcards
84756[// Never replace escaped '*'
84757// ignore rule '\*' will match the path '*'
84758// 'abc.*/' -> go
84759// 'abc.*' -> skip this rule
84760/(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
84761// '*.js' doesn't match 'abc'
84762(match, p1) => "".concat(p1, "[^\\/]*")], // trailing wildcard
84763[/(\^|\\\/)?\\\*$/, (match, p1) => {
84764 const prefix = p1 // '\^':
84765 // '/*' does not match ''
84766 // '/*' does not match everything
84767 // '\\\/':
84768 // 'abc/*' does not match 'abc/'
84769 ? "".concat(p1, "[^/]+") // 'a*' matches 'a'
84770 // 'a*' matches 'aa'
84771 : '[^/]*';
84772 return "".concat(prefix, "(?=$|\\/$)");
84773}], [// unescape
84774/\\\\\\/g, () => '\\']];
84775const POSITIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // 'f'
84776// matches
84777// - /f(end)
84778// - /f/
84779// - (start)f(end)
84780// - (start)f/
84781// doesn't match
84782// - oof
84783// - foo
84784// pseudo:
84785// -> (^|/)f(/|$)
84786// ending
84787[// 'js' will not match 'js.'
84788// 'ab' will not match 'abc'
84789/(?:[^*/])$/, // 'js*' will not match 'a.js'
84790// 'js/' will not match 'a.js'
84791// 'js' will match 'a.js' and 'a.js/'
84792match => "".concat(match, "(?=$|\\/)")], ...DEFAULT_REPLACER_SUFFIX];
84793const NEGATIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // #24, #38
84794// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
84795// A negative pattern without a trailing wildcard should not
84796// re-include the things inside that directory.
84797// eg:
84798// ['node_modules/*', '!node_modules']
84799// should ignore `node_modules/a.js`
84800[/(?:[^*])$/, match => "".concat(match, "(?=$|\\/$)")], ...DEFAULT_REPLACER_SUFFIX]; // A simple cache, because an ignore rule only has only one certain meaning
84801
84802const cache = Object.create(null); // @param {pattern}
84803
84804const make_regex = (pattern, negative, ignorecase) => {
84805 const r = cache[pattern];
84806
84807 if (r) {
84808 return r;
84809 }
84810
84811 const replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
84812 const source = replacers.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
84813 return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
84814}; // > A blank line matches no files, so it can serve as a separator for readability.
84815
84816
84817const checkPattern = pattern => pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
84818&& pattern.indexOf('#') !== 0;
84819
84820const createRule = (pattern, ignorecase) => {
84821 const origin = pattern;
84822 let negative = false; // > An optional prefix "!" which negates the pattern;
84823
84824 if (pattern.indexOf('!') === 0) {
84825 negative = true;
84826 pattern = pattern.substr(1);
84827 }
84828
84829 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
84830 // > begin with a literal "!", for example, `"\!important!.txt"`.
84831 .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
84832 // > begin with a hash.
84833 .replace(REGEX_LEADING_EXCAPED_HASH, '#');
84834 const regex = make_regex(pattern, negative, ignorecase);
84835 return {
84836 origin,
84837 pattern,
84838 negative,
84839 regex
84840 };
84841};
84842
84843class IgnoreBase {
84844 constructor({
84845 ignorecase = true
84846 } = {}) {
84847 this._rules = [];
84848 this._ignorecase = ignorecase;
84849 define(this, KEY_IGNORE, true);
84850
84851 this._initCache();
84852 }
84853
84854 _initCache() {
84855 this._cache = Object.create(null);
84856 } // @param {Array.<string>|string|Ignore} pattern
84857
84858
84859 add(pattern) {
84860 this._added = false;
84861
84862 if (typeof pattern === 'string') {
84863 pattern = pattern.split(/\r?\n/g);
84864 }
84865
84866 make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
84867 // making the behavior changed.
84868
84869 if (this._added) {
84870 this._initCache();
84871 }
84872
84873 return this;
84874 } // legacy
84875
84876
84877 addPattern(pattern) {
84878 return this.add(pattern);
84879 }
84880
84881 _addPattern(pattern) {
84882 // #32
84883 if (pattern && pattern[KEY_IGNORE]) {
84884 this._rules = this._rules.concat(pattern._rules);
84885 this._added = true;
84886 return;
84887 }
84888
84889 if (checkPattern(pattern)) {
84890 const rule = createRule(pattern, this._ignorecase);
84891 this._added = true;
84892
84893 this._rules.push(rule);
84894 }
84895 }
84896
84897 filter(paths) {
84898 return make_array(paths).filter(path => this._filter(path));
84899 }
84900
84901 createFilter() {
84902 return path => this._filter(path);
84903 }
84904
84905 ignores(path) {
84906 return !this._filter(path);
84907 } // @returns `Boolean` true if the `path` is NOT ignored
84908
84909
84910 _filter(path, slices) {
84911 if (!path) {
84912 return false;
84913 }
84914
84915 if (path in this._cache) {
84916 return this._cache[path];
84917 }
84918
84919 if (!slices) {
84920 // path/to/a.js
84921 // ['path', 'to', 'a.js']
84922 slices = path.split(SLASH);
84923 }
84924
84925 slices.pop();
84926 return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
84927 // > that file is excluded.
84928 // If the path contains a parent directory, check the parent first
84929 ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
84930 : this._test(path);
84931 } // @returns {Boolean} true if a file is NOT ignored
84932
84933
84934 _test(path) {
84935 // Explicitly define variable type by setting matched to `0`
84936 let matched = 0;
84937
84938 this._rules.forEach(rule => {
84939 // if matched = true, then we only test negative rules
84940 // if matched = false, then we test non-negative rules
84941 if (!(matched ^ rule.negative)) {
84942 matched = rule.negative ^ rule.regex.test(path);
84943 }
84944 });
84945
84946 return !matched;
84947 }
84948
84949} // Windows
84950// --------------------------------------------------------------
84951
84952/* istanbul ignore if */
84953
84954
84955if ( // Detect `process` so that it can run in browsers.
84956typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
84957 const filter = IgnoreBase.prototype._filter;
84958 /* eslint no-control-regex: "off" */
84959
84960 const make_posix = str => /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
84961
84962 IgnoreBase.prototype._filter = function filterWin32(path, slices) {
84963 path = make_posix(path);
84964 return filter.call(this, path, slices);
84965 };
84966}
84967
84968module.exports = options => new IgnoreBase(options);
84969
84970/***/ }),
6a5a0f88 84971/* 613 */
eb39fafa
DC
84972/***/ (function(module, exports, __webpack_require__) {
84973
84974"use strict";
84975/**
84976 * @fileoverview Restrict usage of specified node modules.
84977 * @author Christian Schulz
84978 */
84979 //------------------------------------------------------------------------------
84980// Rule Definition
84981//------------------------------------------------------------------------------
84982
6a5a0f88 84983const ignore = __webpack_require__(612);
eb39fafa
DC
84984
84985const arrayOfStrings = {
84986 type: "array",
84987 items: {
84988 type: "string"
84989 },
84990 uniqueItems: true
84991};
84992const arrayOfStringsOrObjects = {
84993 type: "array",
84994 items: {
84995 anyOf: [{
84996 type: "string"
84997 }, {
84998 type: "object",
84999 properties: {
85000 name: {
85001 type: "string"
85002 },
85003 message: {
85004 type: "string",
85005 minLength: 1
85006 }
85007 },
85008 additionalProperties: false,
85009 required: ["name"]
85010 }]
85011 },
85012 uniqueItems: true
85013};
85014module.exports = {
85015 meta: {
56c4a2cb 85016 deprecated: true,
6a5a0f88 85017 replacedBy: [],
eb39fafa
DC
85018 type: "suggestion",
85019 docs: {
85020 description: "disallow specified modules when loaded by `require`",
85021 category: "Node.js and CommonJS",
85022 recommended: false,
85023 url: "https://eslint.org/docs/rules/no-restricted-modules"
85024 },
85025 schema: {
85026 anyOf: [arrayOfStringsOrObjects, {
85027 type: "array",
85028 items: {
85029 type: "object",
85030 properties: {
85031 paths: arrayOfStringsOrObjects,
85032 patterns: arrayOfStrings
85033 },
85034 additionalProperties: false
85035 },
85036 additionalItems: false
85037 }]
85038 },
85039 messages: {
85040 defaultMessage: "'{{name}}' module is restricted from being used.",
85041 // eslint-disable-next-line eslint-plugin/report-message-format
85042 customMessage: "'{{name}}' module is restricted from being used. {{customMessage}}",
85043 patternMessage: "'{{name}}' module is restricted from being used by a pattern."
85044 }
85045 },
85046
85047 create(context) {
85048 const options = Array.isArray(context.options) ? context.options : [];
85049 const isPathAndPatternsObject = typeof options[0] === "object" && (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns"));
85050 const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || [];
85051 const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || [];
85052 const restrictedPathMessages = restrictedPaths.reduce((memo, importName) => {
85053 if (typeof importName === "string") {
85054 memo[importName] = null;
85055 } else {
85056 memo[importName.name] = importName.message;
85057 }
85058
85059 return memo;
85060 }, {}); // if no imports are restricted we don"t need to check
85061
85062 if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) {
85063 return {};
85064 }
85065
85066 const ig = ignore().add(restrictedPatterns);
85067 /**
85068 * Function to check if a node is a string literal.
85069 * @param {ASTNode} node The node to check.
85070 * @returns {boolean} If the node is a string literal.
85071 */
85072
85073 function isStringLiteral(node) {
85074 return node && node.type === "Literal" && typeof node.value === "string";
85075 }
85076 /**
85077 * Function to check if a node is a static string template literal.
85078 * @param {ASTNode} node The node to check.
85079 * @returns {boolean} If the node is a string template literal.
85080 */
85081
85082
85083 function isStaticTemplateLiteral(node) {
85084 return node && node.type === "TemplateLiteral" && node.expressions.length === 0;
85085 }
85086 /**
85087 * Function to check if a node is a require call.
85088 * @param {ASTNode} node The node to check.
85089 * @returns {boolean} If the node is a require call.
85090 */
85091
85092
85093 function isRequireCall(node) {
85094 return node.callee.type === "Identifier" && node.callee.name === "require";
85095 }
85096 /**
85097 * Extract string from Literal or TemplateLiteral node
85098 * @param {ASTNode} node The node to extract from
85099 * @returns {string|null} Extracted string or null if node doesn't represent a string
85100 */
85101
85102
85103 function getFirstArgumentString(node) {
85104 if (isStringLiteral(node)) {
85105 return node.value.trim();
85106 }
85107
85108 if (isStaticTemplateLiteral(node)) {
85109 return node.quasis[0].value.cooked.trim();
85110 }
85111
85112 return null;
85113 }
85114 /**
85115 * Report a restricted path.
85116 * @param {node} node representing the restricted path reference
85117 * @param {string} name restricted path
85118 * @returns {void}
85119 * @private
85120 */
85121
85122
85123 function reportPath(node, name) {
85124 const customMessage = restrictedPathMessages[name];
85125 const messageId = customMessage ? "customMessage" : "defaultMessage";
85126 context.report({
85127 node,
85128 messageId,
85129 data: {
85130 name,
85131 customMessage
85132 }
85133 });
85134 }
85135 /**
85136 * Check if the given name is a restricted path name
85137 * @param {string} name name of a variable
85138 * @returns {boolean} whether the variable is a restricted path or not
85139 * @private
85140 */
85141
85142
85143 function isRestrictedPath(name) {
85144 return Object.prototype.hasOwnProperty.call(restrictedPathMessages, name);
85145 }
85146
85147 return {
85148 CallExpression(node) {
85149 if (isRequireCall(node)) {
85150 // node has arguments
85151 if (node.arguments.length) {
85152 const name = getFirstArgumentString(node.arguments[0]); // if first argument is a string literal or a static string template literal
85153
85154 if (name) {
85155 // check if argument value is in restricted modules array
85156 if (isRestrictedPath(name)) {
85157 reportPath(node, name);
85158 }
85159
85160 if (restrictedPatterns.length > 0 && ig.ignores(name)) {
85161 context.report({
85162 node,
85163 messageId: "patternMessage",
85164 data: {
85165 name
85166 }
85167 });
85168 }
85169 }
85170 }
85171 }
85172 }
85173
85174 };
85175 }
85176
85177};
85178
85179/***/ }),
6a5a0f88 85180/* 614 */
eb39fafa
DC
85181/***/ (function(module, exports, __webpack_require__) {
85182
85183"use strict";
85184/**
85185 * @fileoverview Rule to disallow certain object properties
85186 * @author Will Klein & Eli White
85187 */
85188
85189
85190const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
85191// Rule Definition
85192//------------------------------------------------------------------------------
85193
85194
85195module.exports = {
85196 meta: {
85197 type: "suggestion",
85198 docs: {
85199 description: "disallow certain properties on certain objects",
85200 category: "Best Practices",
85201 recommended: false,
85202 url: "https://eslint.org/docs/rules/no-restricted-properties"
85203 },
85204 schema: {
85205 type: "array",
85206 items: {
85207 anyOf: [// `object` and `property` are both optional, but at least one of them must be provided.
85208 {
85209 type: "object",
85210 properties: {
85211 object: {
85212 type: "string"
85213 },
85214 property: {
85215 type: "string"
85216 },
85217 message: {
85218 type: "string"
85219 }
85220 },
85221 additionalProperties: false,
85222 required: ["object"]
85223 }, {
85224 type: "object",
85225 properties: {
85226 object: {
85227 type: "string"
85228 },
85229 property: {
85230 type: "string"
85231 },
85232 message: {
85233 type: "string"
85234 }
85235 },
85236 additionalProperties: false,
85237 required: ["property"]
85238 }]
85239 },
85240 uniqueItems: true
85241 },
85242 messages: {
85243 // eslint-disable-next-line eslint-plugin/report-message-format
85244 restrictedObjectProperty: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}",
85245 // eslint-disable-next-line eslint-plugin/report-message-format
85246 restrictedProperty: "'{{propertyName}}' is restricted from being used.{{message}}"
85247 }
85248 },
85249
85250 create(context) {
85251 const restrictedCalls = context.options;
85252
85253 if (restrictedCalls.length === 0) {
85254 return {};
85255 }
85256
85257 const restrictedProperties = new Map();
85258 const globallyRestrictedObjects = new Map();
85259 const globallyRestrictedProperties = new Map();
85260 restrictedCalls.forEach(option => {
85261 const objectName = option.object;
85262 const propertyName = option.property;
85263
85264 if (typeof objectName === "undefined") {
85265 globallyRestrictedProperties.set(propertyName, {
85266 message: option.message
85267 });
85268 } else if (typeof propertyName === "undefined") {
85269 globallyRestrictedObjects.set(objectName, {
85270 message: option.message
85271 });
85272 } else {
85273 if (!restrictedProperties.has(objectName)) {
85274 restrictedProperties.set(objectName, new Map());
85275 }
85276
85277 restrictedProperties.get(objectName).set(propertyName, {
85278 message: option.message
85279 });
85280 }
85281 });
85282 /**
85283 * Checks to see whether a property access is restricted, and reports it if so.
85284 * @param {ASTNode} node The node to report
85285 * @param {string} objectName The name of the object
85286 * @param {string} propertyName The name of the property
85287 * @returns {undefined}
85288 */
85289
85290 function checkPropertyAccess(node, objectName, propertyName) {
85291 if (propertyName === null) {
85292 return;
85293 }
85294
85295 const matchedObject = restrictedProperties.get(objectName);
85296 const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName);
85297 const globalMatchedProperty = globallyRestrictedProperties.get(propertyName);
85298
85299 if (matchedObjectProperty) {
85300 const message = matchedObjectProperty.message ? " ".concat(matchedObjectProperty.message) : "";
85301 context.report({
85302 node,
85303 messageId: "restrictedObjectProperty",
85304 data: {
85305 objectName,
85306 propertyName,
85307 message
85308 }
85309 });
85310 } else if (globalMatchedProperty) {
85311 const message = globalMatchedProperty.message ? " ".concat(globalMatchedProperty.message) : "";
85312 context.report({
85313 node,
85314 messageId: "restrictedProperty",
85315 data: {
85316 propertyName,
85317 message
85318 }
85319 });
85320 }
85321 }
85322 /**
85323 * Checks property accesses in a destructuring assignment expression, e.g. `var foo; ({foo} = bar);`
85324 * @param {ASTNode} node An AssignmentExpression or AssignmentPattern node
85325 * @returns {undefined}
85326 */
85327
85328
85329 function checkDestructuringAssignment(node) {
85330 if (node.right.type === "Identifier") {
85331 const objectName = node.right.name;
85332
85333 if (node.left.type === "ObjectPattern") {
85334 node.left.properties.forEach(property => {
85335 checkPropertyAccess(node.left, objectName, astUtils.getStaticPropertyName(property));
85336 });
85337 }
85338 }
85339 }
85340
85341 return {
85342 MemberExpression(node) {
85343 checkPropertyAccess(node, node.object && node.object.name, astUtils.getStaticPropertyName(node));
85344 },
85345
85346 VariableDeclarator(node) {
85347 if (node.init && node.init.type === "Identifier") {
85348 const objectName = node.init.name;
85349
85350 if (node.id.type === "ObjectPattern") {
85351 node.id.properties.forEach(property => {
85352 checkPropertyAccess(node.id, objectName, astUtils.getStaticPropertyName(property));
85353 });
85354 }
85355 }
85356 },
85357
85358 AssignmentExpression: checkDestructuringAssignment,
85359 AssignmentPattern: checkDestructuringAssignment
85360 };
85361 }
85362
85363};
85364
85365/***/ }),
6a5a0f88 85366/* 615 */
eb39fafa
DC
85367/***/ (function(module, exports, __webpack_require__) {
85368
85369"use strict";
85370/**
85371 * @fileoverview Rule to flag use of certain node types
85372 * @author Burak Yigit Kaya
85373 */
85374 //------------------------------------------------------------------------------
85375// Rule Definition
85376//------------------------------------------------------------------------------
85377
85378module.exports = {
85379 meta: {
85380 type: "suggestion",
85381 docs: {
85382 description: "disallow specified syntax",
85383 category: "Stylistic Issues",
85384 recommended: false,
85385 url: "https://eslint.org/docs/rules/no-restricted-syntax"
85386 },
85387 schema: {
85388 type: "array",
85389 items: {
85390 oneOf: [{
85391 type: "string"
85392 }, {
85393 type: "object",
85394 properties: {
85395 selector: {
85396 type: "string"
85397 },
85398 message: {
85399 type: "string"
85400 }
85401 },
85402 required: ["selector"],
85403 additionalProperties: false
85404 }]
85405 },
85406 uniqueItems: true,
85407 minItems: 0
85408 },
85409 messages: {
85410 // eslint-disable-next-line eslint-plugin/report-message-format
85411 restrictedSyntax: "{{message}}"
85412 }
85413 },
85414
85415 create(context) {
85416 return context.options.reduce((result, selectorOrObject) => {
85417 const isStringFormat = typeof selectorOrObject === "string";
85418 const hasCustomMessage = !isStringFormat && Boolean(selectorOrObject.message);
85419 const selector = isStringFormat ? selectorOrObject : selectorOrObject.selector;
85420 const message = hasCustomMessage ? selectorOrObject.message : "Using '".concat(selector, "' is not allowed.");
85421 return Object.assign(result, {
85422 [selector](node) {
85423 context.report({
85424 node,
85425 messageId: "restrictedSyntax",
85426 data: {
85427 message
85428 }
85429 });
85430 }
85431
85432 });
85433 }, {});
85434 }
85435
85436};
85437
85438/***/ }),
6a5a0f88 85439/* 616 */
eb39fafa
DC
85440/***/ (function(module, exports, __webpack_require__) {
85441
85442"use strict";
85443/**
85444 * @fileoverview Rule to flag when return statement contains assignment
85445 * @author Ilya Volodin
85446 */
85447 //------------------------------------------------------------------------------
85448// Requirements
85449//------------------------------------------------------------------------------
85450
85451const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
85452// Helpers
85453//------------------------------------------------------------------------------
85454
85455
85456const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u; //------------------------------------------------------------------------------
85457// Rule Definition
85458//------------------------------------------------------------------------------
85459
85460module.exports = {
85461 meta: {
85462 type: "suggestion",
85463 docs: {
85464 description: "disallow assignment operators in `return` statements",
85465 category: "Best Practices",
85466 recommended: false,
85467 url: "https://eslint.org/docs/rules/no-return-assign"
85468 },
85469 schema: [{
85470 enum: ["except-parens", "always"]
85471 }],
85472 messages: {
85473 returnAssignment: "Return statement should not contain assignment.",
85474 arrowAssignment: "Arrow function should not return assignment."
85475 }
85476 },
85477
85478 create(context) {
85479 const always = (context.options[0] || "except-parens") !== "except-parens";
85480 const sourceCode = context.getSourceCode();
85481 return {
85482 AssignmentExpression(node) {
85483 if (!always && astUtils.isParenthesised(sourceCode, node)) {
85484 return;
85485 }
85486
85487 let currentChild = node;
85488 let parent = currentChild.parent; // Find ReturnStatement or ArrowFunctionExpression in ancestors.
85489
85490 while (parent && !SENTINEL_TYPE.test(parent.type)) {
85491 currentChild = parent;
85492 parent = parent.parent;
85493 } // Reports.
85494
85495
85496 if (parent && parent.type === "ReturnStatement") {
85497 context.report({
85498 node: parent,
85499 messageId: "returnAssignment"
85500 });
85501 } else if (parent && parent.type === "ArrowFunctionExpression" && parent.body === currentChild) {
85502 context.report({
85503 node: parent,
85504 messageId: "arrowAssignment"
85505 });
85506 }
85507 }
85508
85509 };
85510 }
85511
85512};
85513
85514/***/ }),
6a5a0f88 85515/* 617 */
eb39fafa
DC
85516/***/ (function(module, exports, __webpack_require__) {
85517
85518"use strict";
85519/**
85520 * @fileoverview Disallows unnecessary `return await`
85521 * @author Jordan Harband
85522 */
85523
85524
85525const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
85526// Rule Definition
85527//------------------------------------------------------------------------------
85528
85529
85530module.exports = {
85531 meta: {
85532 type: "suggestion",
85533 docs: {
85534 description: "disallow unnecessary `return await`",
85535 category: "Best Practices",
85536 recommended: false,
85537 url: "https://eslint.org/docs/rules/no-return-await"
85538 },
85539 fixable: null,
85540 schema: [],
85541 messages: {
85542 redundantUseOfAwait: "Redundant use of `await` on a return value."
85543 }
85544 },
85545
85546 create(context) {
85547 /**
85548 * Reports a found unnecessary `await` expression.
85549 * @param {ASTNode} node The node representing the `await` expression to report
85550 * @returns {void}
85551 */
85552 function reportUnnecessaryAwait(node) {
85553 context.report({
85554 node: context.getSourceCode().getFirstToken(node),
85555 loc: node.loc,
85556 messageId: "redundantUseOfAwait"
85557 });
85558 }
85559 /**
85560 * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting
85561 * this function. For example, a statement in a `try` block will always have an error handler. A statement in
85562 * a `catch` block will only have an error handler if there is also a `finally` block.
85563 * @param {ASTNode} node A node representing a location where an could be thrown
85564 * @returns {boolean} `true` if a thrown error will be caught/handled in this function
85565 */
85566
85567
85568 function hasErrorHandler(node) {
85569 let ancestor = node;
85570
85571 while (!astUtils.isFunction(ancestor) && ancestor.type !== "Program") {
85572 if (ancestor.parent.type === "TryStatement" && (ancestor === ancestor.parent.block || ancestor === ancestor.parent.handler && ancestor.parent.finalizer)) {
85573 return true;
85574 }
85575
85576 ancestor = ancestor.parent;
85577 }
85578
85579 return false;
85580 }
85581 /**
85582 * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression,
85583 * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position.
85584 * @param {ASTNode} node A node representing the `await` expression to check
85585 * @returns {boolean} The checking result
85586 */
85587
85588
85589 function isInTailCallPosition(node) {
85590 if (node.parent.type === "ArrowFunctionExpression") {
85591 return true;
85592 }
85593
85594 if (node.parent.type === "ReturnStatement") {
85595 return !hasErrorHandler(node.parent);
85596 }
85597
85598 if (node.parent.type === "ConditionalExpression" && (node === node.parent.consequent || node === node.parent.alternate)) {
85599 return isInTailCallPosition(node.parent);
85600 }
85601
85602 if (node.parent.type === "LogicalExpression" && node === node.parent.right) {
85603 return isInTailCallPosition(node.parent);
85604 }
85605
85606 if (node.parent.type === "SequenceExpression" && node === node.parent.expressions[node.parent.expressions.length - 1]) {
85607 return isInTailCallPosition(node.parent);
85608 }
85609
85610 return false;
85611 }
85612
85613 return {
85614 AwaitExpression(node) {
85615 if (isInTailCallPosition(node) && !hasErrorHandler(node)) {
85616 reportUnnecessaryAwait(node);
85617 }
85618 }
85619
85620 };
85621 }
85622
85623};
85624
85625/***/ }),
6a5a0f88 85626/* 618 */
eb39fafa
DC
85627/***/ (function(module, exports, __webpack_require__) {
85628
85629"use strict";
85630/**
85631 * @fileoverview Rule to flag when using javascript: urls
85632 * @author Ilya Volodin
85633 */
85634
85635/* jshint scripturl: true */
85636
85637/* eslint no-script-url: 0 */
85638 //------------------------------------------------------------------------------
85639// Rule Definition
85640//------------------------------------------------------------------------------
85641
85642module.exports = {
85643 meta: {
85644 type: "suggestion",
85645 docs: {
85646 description: "disallow `javascript:` urls",
85647 category: "Best Practices",
85648 recommended: false,
85649 url: "https://eslint.org/docs/rules/no-script-url"
85650 },
85651 schema: [],
85652 messages: {
85653 unexpectedScriptURL: "Script URL is a form of eval."
85654 }
85655 },
85656
85657 create(context) {
85658 return {
85659 Literal(node) {
85660 if (node.value && typeof node.value === "string") {
85661 const value = node.value.toLowerCase();
85662
85663 if (value.indexOf("javascript:") === 0) {
85664 context.report({
85665 node,
85666 messageId: "unexpectedScriptURL"
85667 });
85668 }
85669 }
85670 }
85671
85672 };
85673 }
85674
85675};
85676
85677/***/ }),
6a5a0f88 85678/* 619 */
eb39fafa
DC
85679/***/ (function(module, exports, __webpack_require__) {
85680
85681"use strict";
85682/**
85683 * @fileoverview Rule to disallow assignments where both sides are exactly the same
85684 * @author Toru Nagashima
85685 */
85686 //------------------------------------------------------------------------------
85687// Requirements
85688//------------------------------------------------------------------------------
85689
85690const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
85691// Helpers
85692//------------------------------------------------------------------------------
85693
85694
85695const SPACES = /\s+/gu;
85696/**
85697 * Checks whether the property of 2 given member expression nodes are the same
85698 * property or not.
85699 * @param {ASTNode} left A member expression node to check.
85700 * @param {ASTNode} right Another member expression node to check.
85701 * @returns {boolean} `true` if the member expressions have the same property.
85702 */
85703
85704function isSameProperty(left, right) {
85705 if (left.property.type === "Identifier" && left.property.type === right.property.type && left.property.name === right.property.name && left.computed === right.computed) {
85706 return true;
85707 }
85708
85709 const lname = astUtils.getStaticPropertyName(left);
85710 const rname = astUtils.getStaticPropertyName(right);
85711 return lname !== null && lname === rname;
85712}
85713/**
85714 * Checks whether 2 given member expression nodes are the reference to the same
85715 * property or not.
85716 * @param {ASTNode} left A member expression node to check.
85717 * @param {ASTNode} right Another member expression node to check.
85718 * @returns {boolean} `true` if the member expressions are the reference to the
85719 * same property or not.
85720 */
85721
85722
85723function isSameMember(left, right) {
85724 if (!isSameProperty(left, right)) {
85725 return false;
85726 }
85727
85728 const lobj = left.object;
85729 const robj = right.object;
85730
85731 if (lobj.type !== robj.type) {
85732 return false;
85733 }
85734
85735 if (lobj.type === "MemberExpression") {
85736 return isSameMember(lobj, robj);
85737 }
85738
85739 if (lobj.type === "ThisExpression") {
85740 return true;
85741 }
85742
85743 return lobj.type === "Identifier" && lobj.name === robj.name;
85744}
85745/**
85746 * Traverses 2 Pattern nodes in parallel, then reports self-assignments.
85747 * @param {ASTNode|null} left A left node to traverse. This is a Pattern or
85748 * a Property.
85749 * @param {ASTNode|null} right A right node to traverse. This is a Pattern or
85750 * a Property.
85751 * @param {boolean} props The flag to check member expressions as well.
85752 * @param {Function} report A callback function to report.
85753 * @returns {void}
85754 */
85755
85756
85757function eachSelfAssignment(left, right, props, report) {
85758 if (!left || !right) {// do nothing
85759 } else if (left.type === "Identifier" && right.type === "Identifier" && left.name === right.name) {
85760 report(right);
85761 } else if (left.type === "ArrayPattern" && right.type === "ArrayExpression") {
85762 const end = Math.min(left.elements.length, right.elements.length);
85763
85764 for (let i = 0; i < end; ++i) {
85765 const leftElement = left.elements[i];
85766 const rightElement = right.elements[i]; // Avoid cases such as [...a] = [...a, 1]
85767
85768 if (leftElement && leftElement.type === "RestElement" && i < right.elements.length - 1) {
85769 break;
85770 }
85771
85772 eachSelfAssignment(leftElement, rightElement, props, report); // After a spread element, those indices are unknown.
85773
85774 if (rightElement && rightElement.type === "SpreadElement") {
85775 break;
85776 }
85777 }
85778 } else if (left.type === "RestElement" && right.type === "SpreadElement") {
85779 eachSelfAssignment(left.argument, right.argument, props, report);
85780 } else if (left.type === "ObjectPattern" && right.type === "ObjectExpression" && right.properties.length >= 1) {
85781 /*
85782 * Gets the index of the last spread property.
85783 * It's possible to overwrite properties followed by it.
85784 */
85785 let startJ = 0;
85786
85787 for (let i = right.properties.length - 1; i >= 0; --i) {
85788 const propType = right.properties[i].type;
85789
85790 if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") {
85791 startJ = i + 1;
85792 break;
85793 }
85794 }
85795
85796 for (let i = 0; i < left.properties.length; ++i) {
85797 for (let j = startJ; j < right.properties.length; ++j) {
85798 eachSelfAssignment(left.properties[i], right.properties[j], props, report);
85799 }
85800 }
85801 } else if (left.type === "Property" && right.type === "Property" && right.kind === "init" && !right.method) {
85802 const leftName = astUtils.getStaticPropertyName(left);
85803
85804 if (leftName !== null && leftName === astUtils.getStaticPropertyName(right)) {
85805 eachSelfAssignment(left.value, right.value, props, report);
85806 }
85807 } else if (props && left.type === "MemberExpression" && right.type === "MemberExpression" && isSameMember(left, right)) {
85808 report(right);
85809 }
85810} //------------------------------------------------------------------------------
85811// Rule Definition
85812//------------------------------------------------------------------------------
85813
85814
85815module.exports = {
85816 meta: {
85817 type: "problem",
85818 docs: {
85819 description: "disallow assignments where both sides are exactly the same",
85820 category: "Best Practices",
85821 recommended: true,
85822 url: "https://eslint.org/docs/rules/no-self-assign"
85823 },
85824 schema: [{
85825 type: "object",
85826 properties: {
85827 props: {
85828 type: "boolean",
85829 default: true
85830 }
85831 },
85832 additionalProperties: false
85833 }],
85834 messages: {
85835 selfAssignment: "'{{name}}' is assigned to itself."
85836 }
85837 },
85838
85839 create(context) {
85840 const sourceCode = context.getSourceCode();
85841 const [{
85842 props = true
85843 } = {}] = context.options;
85844 /**
85845 * Reports a given node as self assignments.
85846 * @param {ASTNode} node A node to report. This is an Identifier node.
85847 * @returns {void}
85848 */
85849
85850 function report(node) {
85851 context.report({
85852 node,
85853 messageId: "selfAssignment",
85854 data: {
85855 name: sourceCode.getText(node).replace(SPACES, "")
85856 }
85857 });
85858 }
85859
85860 return {
85861 AssignmentExpression(node) {
85862 if (node.operator === "=") {
85863 eachSelfAssignment(node.left, node.right, props, report);
85864 }
85865 }
85866
85867 };
85868 }
85869
85870};
85871
85872/***/ }),
6a5a0f88 85873/* 620 */
eb39fafa
DC
85874/***/ (function(module, exports, __webpack_require__) {
85875
85876"use strict";
85877/**
85878 * @fileoverview Rule to flag comparison where left part is the same as the right
85879 * part.
85880 * @author Ilya Volodin
85881 */
85882 //------------------------------------------------------------------------------
85883// Rule Definition
85884//------------------------------------------------------------------------------
85885
85886module.exports = {
85887 meta: {
85888 type: "problem",
85889 docs: {
85890 description: "disallow comparisons where both sides are exactly the same",
85891 category: "Best Practices",
85892 recommended: false,
85893 url: "https://eslint.org/docs/rules/no-self-compare"
85894 },
85895 schema: [],
85896 messages: {
85897 comparingToSelf: "Comparing to itself is potentially pointless."
85898 }
85899 },
85900
85901 create(context) {
85902 const sourceCode = context.getSourceCode();
85903 /**
85904 * Determines whether two nodes are composed of the same tokens.
85905 * @param {ASTNode} nodeA The first node
85906 * @param {ASTNode} nodeB The second node
85907 * @returns {boolean} true if the nodes have identical token representations
85908 */
85909
85910 function hasSameTokens(nodeA, nodeB) {
85911 const tokensA = sourceCode.getTokens(nodeA);
85912 const tokensB = sourceCode.getTokens(nodeB);
85913 return tokensA.length === tokensB.length && tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value);
85914 }
85915
85916 return {
85917 BinaryExpression(node) {
85918 const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]);
85919
85920 if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) {
85921 context.report({
85922 node,
85923 messageId: "comparingToSelf"
85924 });
85925 }
85926 }
85927
85928 };
85929 }
85930
85931};
85932
85933/***/ }),
6a5a0f88 85934/* 621 */
eb39fafa
DC
85935/***/ (function(module, exports, __webpack_require__) {
85936
85937"use strict";
85938/**
85939 * @fileoverview Rule to flag use of comma operator
85940 * @author Brandon Mills
85941 */
85942 //------------------------------------------------------------------------------
85943// Requirements
85944//------------------------------------------------------------------------------
85945
85946const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
85947// Rule Definition
85948//------------------------------------------------------------------------------
85949
85950
85951module.exports = {
85952 meta: {
85953 type: "suggestion",
85954 docs: {
85955 description: "disallow comma operators",
85956 category: "Best Practices",
85957 recommended: false,
85958 url: "https://eslint.org/docs/rules/no-sequences"
85959 },
85960 schema: [],
85961 messages: {
85962 unexpectedCommaExpression: "Unexpected use of comma operator."
85963 }
85964 },
85965
85966 create(context) {
85967 const sourceCode = context.getSourceCode();
85968 /**
85969 * Parts of the grammar that are required to have parens.
85970 */
85971
85972 const parenthesized = {
85973 DoWhileStatement: "test",
85974 IfStatement: "test",
85975 SwitchStatement: "discriminant",
85976 WhileStatement: "test",
85977 WithStatement: "object",
85978 ArrowFunctionExpression: "body"
85979 /*
85980 * Omitting CallExpression - commas are parsed as argument separators
85981 * Omitting NewExpression - commas are parsed as argument separators
85982 * Omitting ForInStatement - parts aren't individually parenthesised
85983 * Omitting ForStatement - parts aren't individually parenthesised
85984 */
85985
85986 };
85987 /**
85988 * Determines whether a node is required by the grammar to be wrapped in
85989 * parens, e.g. the test of an if statement.
85990 * @param {ASTNode} node The AST node
85991 * @returns {boolean} True if parens around node belong to parent node.
85992 */
85993
85994 function requiresExtraParens(node) {
85995 return node.parent && parenthesized[node.parent.type] && node === node.parent[parenthesized[node.parent.type]];
85996 }
85997 /**
85998 * Check if a node is wrapped in parens.
85999 * @param {ASTNode} node The AST node
86000 * @returns {boolean} True if the node has a paren on each side.
86001 */
86002
86003
86004 function isParenthesised(node) {
86005 return astUtils.isParenthesised(sourceCode, node);
86006 }
86007 /**
86008 * Check if a node is wrapped in two levels of parens.
86009 * @param {ASTNode} node The AST node
86010 * @returns {boolean} True if two parens surround the node on each side.
86011 */
86012
86013
86014 function isParenthesisedTwice(node) {
86015 const previousToken = sourceCode.getTokenBefore(node, 1),
86016 nextToken = sourceCode.getTokenAfter(node, 1);
86017 return isParenthesised(node) && previousToken && nextToken && astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1];
86018 }
86019
86020 return {
86021 SequenceExpression(node) {
86022 // Always allow sequences in for statement update
86023 if (node.parent.type === "ForStatement" && (node === node.parent.init || node === node.parent.update)) {
86024 return;
86025 } // Wrapping a sequence in extra parens indicates intent
86026
86027
86028 if (requiresExtraParens(node)) {
86029 if (isParenthesisedTwice(node)) {
86030 return;
86031 }
86032 } else {
86033 if (isParenthesised(node)) {
86034 return;
86035 }
86036 }
86037
86038 const firstCommaToken = sourceCode.getTokenAfter(node.expressions[0], astUtils.isCommaToken);
86039 context.report({
86040 node,
86041 loc: firstCommaToken.loc,
86042 messageId: "unexpectedCommaExpression"
86043 });
86044 }
86045
86046 };
86047 }
86048
86049};
86050
86051/***/ }),
6a5a0f88 86052/* 622 */
eb39fafa
DC
86053/***/ (function(module, exports, __webpack_require__) {
86054
86055"use strict";
86056/**
86057 * @fileoverview Rule to disallow returning values from setters
86058 * @author Milos Djermanovic
86059 */
86060 //------------------------------------------------------------------------------
86061// Requirements
86062//------------------------------------------------------------------------------
86063
86064const astUtils = __webpack_require__(426);
86065
86066const {
86067 findVariable
86068} = __webpack_require__(549); //------------------------------------------------------------------------------
86069// Helpers
86070//------------------------------------------------------------------------------
86071
86072/**
86073 * Determines whether the given identifier node is a reference to a global variable.
86074 * @param {ASTNode} node `Identifier` node to check.
86075 * @param {Scope} scope Scope to which the node belongs.
86076 * @returns {boolean} True if the identifier is a reference to a global variable.
86077 */
86078
86079
86080function isGlobalReference(node, scope) {
86081 const variable = findVariable(scope, node);
86082 return variable !== null && variable.scope.type === "global" && variable.defs.length === 0;
86083}
86084/**
86085 * Determines whether the given node is an argument of the specified global method call, at the given `index` position.
86086 * E.g., for given `index === 1`, this function checks for `objectName.methodName(foo, node)`, where objectName is a global variable.
86087 * @param {ASTNode} node The node to check.
86088 * @param {Scope} scope Scope to which the node belongs.
86089 * @param {string} objectName Name of the global object.
86090 * @param {string} methodName Name of the method.
86091 * @param {number} index The given position.
86092 * @returns {boolean} `true` if the node is argument at the given position.
86093 */
86094
86095
86096function isArgumentOfGlobalMethodCall(node, scope, objectName, methodName, index) {
86097 const parent = node.parent;
86098 return parent.type === "CallExpression" && parent.arguments[index] === node && parent.callee.type === "MemberExpression" && astUtils.getStaticPropertyName(parent.callee) === methodName && parent.callee.object.type === "Identifier" && parent.callee.object.name === objectName && isGlobalReference(parent.callee.object, scope);
86099}
86100/**
86101 * Determines whether the given node is used as a property descriptor.
86102 * @param {ASTNode} node The node to check.
86103 * @param {Scope} scope Scope to which the node belongs.
86104 * @returns {boolean} `true` if the node is a property descriptor.
86105 */
86106
86107
86108function isPropertyDescriptor(node, scope) {
86109 if (isArgumentOfGlobalMethodCall(node, scope, "Object", "defineProperty", 2) || isArgumentOfGlobalMethodCall(node, scope, "Reflect", "defineProperty", 2)) {
86110 return true;
86111 }
86112
86113 const parent = node.parent;
86114
86115 if (parent.type === "Property" && parent.value === node) {
86116 const grandparent = parent.parent;
86117
86118 if (grandparent.type === "ObjectExpression" && (isArgumentOfGlobalMethodCall(grandparent, scope, "Object", "create", 1) || isArgumentOfGlobalMethodCall(grandparent, scope, "Object", "defineProperties", 1))) {
86119 return true;
86120 }
86121 }
86122
86123 return false;
86124}
86125/**
86126 * Determines whether the given function node is used as a setter function.
86127 * @param {ASTNode} node The node to check.
86128 * @param {Scope} scope Scope to which the node belongs.
86129 * @returns {boolean} `true` if the node is a setter.
86130 */
86131
86132
86133function isSetter(node, scope) {
86134 const parent = node.parent;
86135
86136 if (parent.kind === "set" && parent.value === node) {
86137 // Setter in an object literal or in a class
86138 return true;
86139 }
86140
86141 if (parent.type === "Property" && parent.value === node && astUtils.getStaticPropertyName(parent) === "set" && parent.parent.type === "ObjectExpression" && isPropertyDescriptor(parent.parent, scope)) {
86142 // Setter in a property descriptor
86143 return true;
86144 }
86145
86146 return false;
86147}
86148/**
86149 * Finds function's outer scope.
86150 * @param {Scope} scope Function's own scope.
86151 * @returns {Scope} Function's outer scope.
86152 */
86153
86154
86155function getOuterScope(scope) {
86156 const upper = scope.upper;
86157
86158 if (upper.type === "function-expression-name") {
86159 return upper.upper;
86160 }
86161
86162 return upper;
86163} //------------------------------------------------------------------------------
86164// Rule Definition
86165//------------------------------------------------------------------------------
86166
86167
86168module.exports = {
86169 meta: {
86170 type: "problem",
86171 docs: {
86172 description: "disallow returning values from setters",
86173 category: "Possible Errors",
86174 recommended: true,
86175 url: "https://eslint.org/docs/rules/no-setter-return"
86176 },
86177 schema: [],
86178 messages: {
86179 returnsValue: "Setter cannot return a value."
86180 }
86181 },
86182
86183 create(context) {
86184 let funcInfo = null;
86185 /**
86186 * Creates and pushes to the stack a function info object for the given function node.
86187 * @param {ASTNode} node The function node.
86188 * @returns {void}
86189 */
86190
86191 function enterFunction(node) {
86192 const outerScope = getOuterScope(context.getScope());
86193 funcInfo = {
86194 upper: funcInfo,
86195 isSetter: isSetter(node, outerScope)
86196 };
86197 }
86198 /**
86199 * Pops the current function info object from the stack.
86200 * @returns {void}
86201 */
86202
86203
86204 function exitFunction() {
86205 funcInfo = funcInfo.upper;
86206 }
86207 /**
86208 * Reports the given node.
86209 * @param {ASTNode} node Node to report.
86210 * @returns {void}
86211 */
86212
86213
86214 function report(node) {
86215 context.report({
86216 node,
86217 messageId: "returnsValue"
86218 });
86219 }
86220
86221 return {
86222 /*
86223 * Function declarations cannot be setters, but we still have to track them in the `funcInfo` stack to avoid
86224 * false positives, because a ReturnStatement node can belong to a function declaration inside a setter.
86225 *
86226 * Note: A previously declared function can be referenced and actually used as a setter in a property descriptor,
86227 * but that's out of scope for this rule.
86228 */
86229 FunctionDeclaration: enterFunction,
86230 FunctionExpression: enterFunction,
86231
86232 ArrowFunctionExpression(node) {
86233 enterFunction(node);
86234
86235 if (funcInfo.isSetter && node.expression) {
86236 // { set: foo => bar } property descriptor. Report implicit return 'bar' as the equivalent for a return statement.
86237 report(node.body);
86238 }
86239 },
86240
86241 "FunctionDeclaration:exit": exitFunction,
86242 "FunctionExpression:exit": exitFunction,
86243 "ArrowFunctionExpression:exit": exitFunction,
86244
86245 ReturnStatement(node) {
86246 // Global returns (e.g., at the top level of a Node module) don't have `funcInfo`.
86247 if (funcInfo && funcInfo.isSetter && node.argument) {
86248 report(node);
86249 }
86250 }
86251
86252 };
86253 }
86254
86255};
86256
86257/***/ }),
6a5a0f88 86258/* 623 */
eb39fafa
DC
86259/***/ (function(module, exports, __webpack_require__) {
86260
86261"use strict";
86262/**
86263 * @fileoverview Rule to flag on declaring variables already declared in the outer scope
86264 * @author Ilya Volodin
86265 */
86266 //------------------------------------------------------------------------------
86267// Requirements
86268//------------------------------------------------------------------------------
86269
86270const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
86271// Rule Definition
86272//------------------------------------------------------------------------------
86273
86274
86275module.exports = {
86276 meta: {
86277 type: "suggestion",
86278 docs: {
86279 description: "disallow variable declarations from shadowing variables declared in the outer scope",
86280 category: "Variables",
86281 recommended: false,
86282 url: "https://eslint.org/docs/rules/no-shadow"
86283 },
86284 schema: [{
86285 type: "object",
86286 properties: {
86287 builtinGlobals: {
86288 type: "boolean",
86289 default: false
86290 },
86291 hoist: {
86292 enum: ["all", "functions", "never"],
86293 default: "functions"
86294 },
86295 allow: {
86296 type: "array",
86297 items: {
86298 type: "string"
86299 }
86300 }
86301 },
86302 additionalProperties: false
86303 }],
86304 messages: {
86305 noShadow: "'{{name}}' is already declared in the upper scope."
86306 }
86307 },
86308
86309 create(context) {
86310 const options = {
86311 builtinGlobals: context.options[0] && context.options[0].builtinGlobals,
86312 hoist: context.options[0] && context.options[0].hoist || "functions",
86313 allow: context.options[0] && context.options[0].allow || []
86314 };
86315 /**
86316 * Check if variable name is allowed.
86317 * @param {ASTNode} variable The variable to check.
86318 * @returns {boolean} Whether or not the variable name is allowed.
86319 */
86320
86321 function isAllowed(variable) {
86322 return options.allow.indexOf(variable.name) !== -1;
86323 }
86324 /**
86325 * Checks if a variable of the class name in the class scope of ClassDeclaration.
86326 *
86327 * ClassDeclaration creates two variables of its name into its outer scope and its class scope.
86328 * So we should ignore the variable in the class scope.
86329 * @param {Object} variable The variable to check.
86330 * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
86331 */
86332
86333
86334 function isDuplicatedClassNameVariable(variable) {
86335 const block = variable.scope.block;
86336 return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
86337 }
86338 /**
86339 * Checks if a variable is inside the initializer of scopeVar.
86340 *
86341 * To avoid reporting at declarations such as `var a = function a() {};`.
86342 * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
86343 * @param {Object} variable The variable to check.
86344 * @param {Object} scopeVar The scope variable to look for.
86345 * @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
86346 */
86347
86348
86349 function isOnInitializer(variable, scopeVar) {
86350 const outerScope = scopeVar.scope;
86351 const outerDef = scopeVar.defs[0];
86352 const outer = outerDef && outerDef.parent && outerDef.parent.range;
86353 const innerScope = variable.scope;
86354 const innerDef = variable.defs[0];
86355 const inner = innerDef && innerDef.name.range;
86356 return outer && inner && outer[0] < inner[0] && inner[1] < outer[1] && (innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression" || innerDef.node.type === "ClassExpression") && outerScope === innerScope.upper;
86357 }
86358 /**
86359 * Get a range of a variable's identifier node.
86360 * @param {Object} variable The variable to get.
86361 * @returns {Array|undefined} The range of the variable's identifier node.
86362 */
86363
86364
86365 function getNameRange(variable) {
86366 const def = variable.defs[0];
86367 return def && def.name.range;
86368 }
86369 /**
86370 * Checks if a variable is in TDZ of scopeVar.
86371 * @param {Object} variable The variable to check.
86372 * @param {Object} scopeVar The variable of TDZ.
86373 * @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
86374 */
86375
86376
86377 function isInTdz(variable, scopeVar) {
86378 const outerDef = scopeVar.defs[0];
86379 const inner = getNameRange(variable);
86380 const outer = getNameRange(scopeVar);
86381 return inner && outer && inner[1] < outer[0] && ( // Excepts FunctionDeclaration if is {"hoist":"function"}.
86382 options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration");
86383 }
86384 /**
86385 * Checks the current context for shadowed variables.
86386 * @param {Scope} scope Fixme
86387 * @returns {void}
86388 */
86389
86390
86391 function checkForShadows(scope) {
86392 const variables = scope.variables;
86393
86394 for (let i = 0; i < variables.length; ++i) {
86395 const variable = variables[i]; // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration.
86396
86397 if (variable.identifiers.length === 0 || isDuplicatedClassNameVariable(variable) || isAllowed(variable)) {
86398 continue;
86399 } // Gets shadowed variable.
86400
86401
86402 const shadowed = astUtils.getVariableByName(scope.upper, variable.name);
86403
86404 if (shadowed && (shadowed.identifiers.length > 0 || options.builtinGlobals && "writeable" in shadowed) && !isOnInitializer(variable, shadowed) && !(options.hoist !== "all" && isInTdz(variable, shadowed))) {
86405 context.report({
86406 node: variable.identifiers[0],
86407 messageId: "noShadow",
86408 data: variable
86409 });
86410 }
86411 }
86412 }
86413
86414 return {
86415 "Program:exit"() {
86416 const globalScope = context.getScope();
86417 const stack = globalScope.childScopes.slice();
86418
86419 while (stack.length) {
86420 const scope = stack.pop();
86421 stack.push(...scope.childScopes);
86422 checkForShadows(scope);
86423 }
86424 }
86425
86426 };
86427 }
86428
86429};
86430
86431/***/ }),
6a5a0f88 86432/* 624 */
eb39fafa
DC
86433/***/ (function(module, exports, __webpack_require__) {
86434
86435"use strict";
86436/**
86437 * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1)
86438 * @author Michael Ficarra
86439 */
86440
86441/**
86442 * Determines if a variable safely shadows undefined.
86443 * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value
86444 * as the global).
86445 * @param {eslintScope.Variable} variable The variable to check
86446 * @returns {boolean} true if this variable safely shadows `undefined`
86447 */
86448
86449function safelyShadowsUndefined(variable) {
86450 return variable.name === "undefined" && variable.references.every(ref => !ref.isWrite()) && variable.defs.every(def => def.node.type === "VariableDeclarator" && def.node.init === null);
86451} //------------------------------------------------------------------------------
86452// Rule Definition
86453//------------------------------------------------------------------------------
86454
86455
86456module.exports = {
86457 meta: {
86458 type: "suggestion",
86459 docs: {
86460 description: "disallow identifiers from shadowing restricted names",
86461 category: "Variables",
86462 recommended: true,
86463 url: "https://eslint.org/docs/rules/no-shadow-restricted-names"
86464 },
86465 schema: [],
86466 messages: {
86467 shadowingRestrictedName: "Shadowing of global property '{{name}}'."
86468 }
86469 },
86470
86471 create(context) {
86472 const RESTRICTED = new Set(["undefined", "NaN", "Infinity", "arguments", "eval"]);
86473 return {
86474 "VariableDeclaration, :function, CatchClause"(node) {
86475 for (const variable of context.getDeclaredVariables(node)) {
86476 if (variable.defs.length > 0 && RESTRICTED.has(variable.name) && !safelyShadowsUndefined(variable)) {
86477 context.report({
86478 node: variable.defs[0].name,
86479 messageId: "shadowingRestrictedName",
86480 data: {
86481 name: variable.name
86482 }
86483 });
86484 }
86485 }
86486 }
86487
86488 };
86489 }
86490
86491};
86492
86493/***/ }),
6a5a0f88 86494/* 625 */
eb39fafa
DC
86495/***/ (function(module, exports, __webpack_require__) {
86496
86497"use strict";
86498/**
86499 * @fileoverview Rule to check that spaced function application
86500 * @author Matt DuVall <http://www.mattduvall.com>
86501 * @deprecated in ESLint v3.3.0
86502 */
86503 //------------------------------------------------------------------------------
86504// Rule Definition
86505//------------------------------------------------------------------------------
86506
86507module.exports = {
86508 meta: {
86509 type: "layout",
86510 docs: {
86511 description: "disallow spacing between function identifiers and their applications (deprecated)",
86512 category: "Stylistic Issues",
86513 recommended: false,
86514 url: "https://eslint.org/docs/rules/no-spaced-func"
86515 },
86516 deprecated: true,
86517 replacedBy: ["func-call-spacing"],
86518 fixable: "whitespace",
86519 schema: [],
86520 messages: {
86521 noSpacedFunction: "Unexpected space between function name and paren."
86522 }
86523 },
86524
86525 create(context) {
86526 const sourceCode = context.getSourceCode();
86527 /**
86528 * Check if open space is present in a function name
86529 * @param {ASTNode} node node to evaluate
86530 * @returns {void}
86531 * @private
86532 */
86533
86534 function detectOpenSpaces(node) {
86535 const lastCalleeToken = sourceCode.getLastToken(node.callee);
86536 let prevToken = lastCalleeToken,
86537 parenToken = sourceCode.getTokenAfter(lastCalleeToken); // advances to an open parenthesis.
86538
86539 while (parenToken && parenToken.range[1] < node.range[1] && parenToken.value !== "(") {
86540 prevToken = parenToken;
86541 parenToken = sourceCode.getTokenAfter(parenToken);
86542 } // look for a space between the callee and the open paren
86543
86544
86545 if (parenToken && parenToken.range[1] < node.range[1] && sourceCode.isSpaceBetweenTokens(prevToken, parenToken)) {
86546 context.report({
86547 node,
86548 loc: lastCalleeToken.loc.start,
86549 messageId: "noSpacedFunction",
86550
86551 fix(fixer) {
86552 return fixer.removeRange([prevToken.range[1], parenToken.range[0]]);
86553 }
86554
86555 });
86556 }
86557 }
86558
86559 return {
86560 CallExpression: detectOpenSpaces,
86561 NewExpression: detectOpenSpaces
86562 };
86563 }
86564
86565};
86566
86567/***/ }),
6a5a0f88 86568/* 626 */
eb39fafa
DC
86569/***/ (function(module, exports, __webpack_require__) {
86570
86571"use strict";
86572/**
86573 * @fileoverview Disallow sparse arrays
86574 * @author Nicholas C. Zakas
86575 */
86576 //------------------------------------------------------------------------------
86577// Rule Definition
86578//------------------------------------------------------------------------------
86579
86580module.exports = {
86581 meta: {
86582 type: "problem",
86583 docs: {
86584 description: "disallow sparse arrays",
86585 category: "Possible Errors",
86586 recommended: true,
86587 url: "https://eslint.org/docs/rules/no-sparse-arrays"
86588 },
86589 schema: [],
86590 messages: {
86591 unexpectedSparseArray: "Unexpected comma in middle of array."
86592 }
86593 },
86594
86595 create(context) {
86596 //--------------------------------------------------------------------------
86597 // Public
86598 //--------------------------------------------------------------------------
86599 return {
86600 ArrayExpression(node) {
86601 const emptySpot = node.elements.indexOf(null) > -1;
86602
86603 if (emptySpot) {
86604 context.report({
86605 node,
86606 messageId: "unexpectedSparseArray"
86607 });
86608 }
86609 }
86610
86611 };
86612 }
86613
86614};
86615
86616/***/ }),
6a5a0f88 86617/* 627 */
eb39fafa
DC
86618/***/ (function(module, exports, __webpack_require__) {
86619
86620"use strict";
86621/**
86622 * @fileoverview Rule to check for properties whose identifier ends with the string Sync
86623 * @author Matt DuVall<http://mattduvall.com/>
86624 */
86625
86626/* jshint node:true */
86627 //------------------------------------------------------------------------------
86628// Rule Definition
86629//------------------------------------------------------------------------------
86630
86631module.exports = {
86632 meta: {
56c4a2cb 86633 deprecated: true,
6a5a0f88 86634 replacedBy: [],
eb39fafa
DC
86635 type: "suggestion",
86636 docs: {
86637 description: "disallow synchronous methods",
86638 category: "Node.js and CommonJS",
86639 recommended: false,
86640 url: "https://eslint.org/docs/rules/no-sync"
86641 },
86642 schema: [{
86643 type: "object",
86644 properties: {
86645 allowAtRootLevel: {
86646 type: "boolean",
86647 default: false
86648 }
86649 },
86650 additionalProperties: false
86651 }],
86652 messages: {
86653 noSync: "Unexpected sync method: '{{propertyName}}'."
86654 }
86655 },
86656
86657 create(context) {
86658 const selector = context.options[0] && context.options[0].allowAtRootLevel ? ":function MemberExpression[property.name=/.*Sync$/]" : "MemberExpression[property.name=/.*Sync$/]";
86659 return {
86660 [selector](node) {
86661 context.report({
86662 node,
86663 messageId: "noSync",
86664 data: {
86665 propertyName: node.property.name
86666 }
86667 });
86668 }
86669
86670 };
86671 }
86672
86673};
86674
86675/***/ }),
6a5a0f88 86676/* 628 */
eb39fafa
DC
86677/***/ (function(module, exports, __webpack_require__) {
86678
86679"use strict";
86680/**
86681 * @fileoverview Rule to check for tabs inside a file
86682 * @author Gyandeep Singh
86683 */
86684 //------------------------------------------------------------------------------
86685// Helpers
86686//------------------------------------------------------------------------------
86687
86688const tabRegex = /\t+/gu;
86689const anyNonWhitespaceRegex = /\S/u; //------------------------------------------------------------------------------
86690// Public Interface
86691//------------------------------------------------------------------------------
86692
86693module.exports = {
86694 meta: {
86695 type: "layout",
86696 docs: {
86697 description: "disallow all tabs",
86698 category: "Stylistic Issues",
86699 recommended: false,
86700 url: "https://eslint.org/docs/rules/no-tabs"
86701 },
86702 schema: [{
86703 type: "object",
86704 properties: {
86705 allowIndentationTabs: {
86706 type: "boolean",
86707 default: false
86708 }
86709 },
86710 additionalProperties: false
86711 }],
86712 messages: {
86713 unexpectedTab: "Unexpected tab character."
86714 }
86715 },
86716
86717 create(context) {
86718 const sourceCode = context.getSourceCode();
86719 const allowIndentationTabs = context.options && context.options[0] && context.options[0].allowIndentationTabs;
86720 return {
86721 Program(node) {
86722 sourceCode.getLines().forEach((line, index) => {
86723 let match;
86724
86725 while ((match = tabRegex.exec(line)) !== null) {
86726 if (allowIndentationTabs && !anyNonWhitespaceRegex.test(line.slice(0, match.index))) {
86727 continue;
86728 }
86729
86730 context.report({
86731 node,
86732 loc: {
86733 start: {
86734 line: index + 1,
86735 column: match.index
86736 },
86737 end: {
86738 line: index + 1,
86739 column: match.index + match[0].length
86740 }
86741 },
86742 messageId: "unexpectedTab"
86743 });
86744 }
86745 });
86746 }
86747
86748 };
86749 }
86750
86751};
86752
86753/***/ }),
6a5a0f88 86754/* 629 */
eb39fafa
DC
86755/***/ (function(module, exports, __webpack_require__) {
86756
86757"use strict";
86758/**
86759 * @fileoverview Warn when using template string syntax in regular strings
86760 * @author Jeroen Engels
86761 */
86762 //------------------------------------------------------------------------------
86763// Rule Definition
86764//------------------------------------------------------------------------------
86765
86766module.exports = {
86767 meta: {
86768 type: "problem",
86769 docs: {
86770 description: "disallow template literal placeholder syntax in regular strings",
86771 category: "Possible Errors",
86772 recommended: false,
86773 url: "https://eslint.org/docs/rules/no-template-curly-in-string"
86774 },
86775 schema: [],
86776 messages: {
86777 unexpectedTemplateExpression: "Unexpected template string expression."
86778 }
86779 },
86780
86781 create(context) {
86782 const regex = /\$\{[^}]+\}/u;
86783 return {
86784 Literal(node) {
86785 if (typeof node.value === "string" && regex.test(node.value)) {
86786 context.report({
86787 node,
86788 messageId: "unexpectedTemplateExpression"
86789 });
86790 }
86791 }
86792
86793 };
86794 }
86795
86796};
86797
86798/***/ }),
6a5a0f88 86799/* 630 */
eb39fafa
DC
86800/***/ (function(module, exports, __webpack_require__) {
86801
86802"use strict";
86803/**
86804 * @fileoverview Rule to flag use of ternary operators.
86805 * @author Ian Christian Myers
86806 */
86807 //------------------------------------------------------------------------------
86808// Rule Definition
86809//------------------------------------------------------------------------------
86810
86811module.exports = {
86812 meta: {
86813 type: "suggestion",
86814 docs: {
86815 description: "disallow ternary operators",
86816 category: "Stylistic Issues",
86817 recommended: false,
86818 url: "https://eslint.org/docs/rules/no-ternary"
86819 },
86820 schema: [],
86821 messages: {
86822 noTernaryOperator: "Ternary operator used."
86823 }
86824 },
86825
86826 create(context) {
86827 return {
86828 ConditionalExpression(node) {
86829 context.report({
86830 node,
86831 messageId: "noTernaryOperator"
86832 });
86833 }
86834
86835 };
86836 }
86837
86838};
86839
86840/***/ }),
6a5a0f88 86841/* 631 */
eb39fafa
DC
86842/***/ (function(module, exports, __webpack_require__) {
86843
86844"use strict";
86845/**
86846 * @fileoverview A rule to disallow using `this`/`super` before `super()`.
86847 * @author Toru Nagashima
86848 */
86849 //------------------------------------------------------------------------------
86850// Requirements
86851//------------------------------------------------------------------------------
86852
86853const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
86854// Helpers
86855//------------------------------------------------------------------------------
86856
86857/**
86858 * Checks whether or not a given node is a constructor.
86859 * @param {ASTNode} node A node to check. This node type is one of
86860 * `Program`, `FunctionDeclaration`, `FunctionExpression`, and
86861 * `ArrowFunctionExpression`.
86862 * @returns {boolean} `true` if the node is a constructor.
86863 */
86864
86865
86866function isConstructorFunction(node) {
86867 return node.type === "FunctionExpression" && node.parent.type === "MethodDefinition" && node.parent.kind === "constructor";
86868} //------------------------------------------------------------------------------
86869// Rule Definition
86870//------------------------------------------------------------------------------
86871
86872
86873module.exports = {
86874 meta: {
86875 type: "problem",
86876 docs: {
86877 description: "disallow `this`/`super` before calling `super()` in constructors",
86878 category: "ECMAScript 6",
86879 recommended: true,
86880 url: "https://eslint.org/docs/rules/no-this-before-super"
86881 },
86882 schema: [],
86883 messages: {
86884 noBeforeSuper: "'{{kind}}' is not allowed before 'super()'."
86885 }
86886 },
86887
86888 create(context) {
86889 /*
86890 * Information for each constructor.
86891 * - upper: Information of the upper constructor.
86892 * - hasExtends: A flag which shows whether the owner class has a valid
86893 * `extends` part.
86894 * - scope: The scope of the owner class.
86895 * - codePath: The code path of this constructor.
86896 */
86897 let funcInfo = null;
86898 /*
86899 * Information for each code path segment.
86900 * Each key is the id of a code path segment.
86901 * Each value is an object:
86902 * - superCalled: The flag which shows `super()` called in all code paths.
86903 * - invalidNodes: The array of invalid ThisExpression and Super nodes.
86904 */
86905
86906 let segInfoMap = Object.create(null);
86907 /**
86908 * Gets whether or not `super()` is called in a given code path segment.
86909 * @param {CodePathSegment} segment A code path segment to get.
86910 * @returns {boolean} `true` if `super()` is called.
86911 */
86912
86913 function isCalled(segment) {
86914 return !segment.reachable || segInfoMap[segment.id].superCalled;
86915 }
86916 /**
86917 * Checks whether or not this is in a constructor.
86918 * @returns {boolean} `true` if this is in a constructor.
86919 */
86920
86921
86922 function isInConstructorOfDerivedClass() {
86923 return Boolean(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends);
86924 }
86925 /**
86926 * Checks whether or not this is before `super()` is called.
86927 * @returns {boolean} `true` if this is before `super()` is called.
86928 */
86929
86930
86931 function isBeforeCallOfSuper() {
86932 return isInConstructorOfDerivedClass() && !funcInfo.codePath.currentSegments.every(isCalled);
86933 }
86934 /**
86935 * Sets a given node as invalid.
86936 * @param {ASTNode} node A node to set as invalid. This is one of
86937 * a ThisExpression and a Super.
86938 * @returns {void}
86939 */
86940
86941
86942 function setInvalid(node) {
86943 const segments = funcInfo.codePath.currentSegments;
86944
86945 for (let i = 0; i < segments.length; ++i) {
86946 const segment = segments[i];
86947
86948 if (segment.reachable) {
86949 segInfoMap[segment.id].invalidNodes.push(node);
86950 }
86951 }
86952 }
86953 /**
86954 * Sets the current segment as `super` was called.
86955 * @returns {void}
86956 */
86957
86958
86959 function setSuperCalled() {
86960 const segments = funcInfo.codePath.currentSegments;
86961
86962 for (let i = 0; i < segments.length; ++i) {
86963 const segment = segments[i];
86964
86965 if (segment.reachable) {
86966 segInfoMap[segment.id].superCalled = true;
86967 }
86968 }
86969 }
86970
86971 return {
86972 /**
86973 * Adds information of a constructor into the stack.
86974 * @param {CodePath} codePath A code path which was started.
86975 * @param {ASTNode} node The current node.
86976 * @returns {void}
86977 */
86978 onCodePathStart(codePath, node) {
86979 if (isConstructorFunction(node)) {
86980 // Class > ClassBody > MethodDefinition > FunctionExpression
86981 const classNode = node.parent.parent.parent;
86982 funcInfo = {
86983 upper: funcInfo,
86984 isConstructor: true,
86985 hasExtends: Boolean(classNode.superClass && !astUtils.isNullOrUndefined(classNode.superClass)),
86986 codePath
86987 };
86988 } else {
86989 funcInfo = {
86990 upper: funcInfo,
86991 isConstructor: false,
86992 hasExtends: false,
86993 codePath
86994 };
86995 }
86996 },
86997
86998 /**
86999 * Removes the top of stack item.
87000 *
87001 * And this treverses all segments of this code path then reports every
87002 * invalid node.
87003 * @param {CodePath} codePath A code path which was ended.
87004 * @returns {void}
87005 */
87006 onCodePathEnd(codePath) {
87007 const isDerivedClass = funcInfo.hasExtends;
87008 funcInfo = funcInfo.upper;
87009
87010 if (!isDerivedClass) {
87011 return;
87012 }
87013
87014 codePath.traverseSegments((segment, controller) => {
87015 const info = segInfoMap[segment.id];
87016
87017 for (let i = 0; i < info.invalidNodes.length; ++i) {
87018 const invalidNode = info.invalidNodes[i];
87019 context.report({
87020 messageId: "noBeforeSuper",
87021 node: invalidNode,
87022 data: {
87023 kind: invalidNode.type === "Super" ? "super" : "this"
87024 }
87025 });
87026 }
87027
87028 if (info.superCalled) {
87029 controller.skip();
87030 }
87031 });
87032 },
87033
87034 /**
87035 * Initialize information of a given code path segment.
87036 * @param {CodePathSegment} segment A code path segment to initialize.
87037 * @returns {void}
87038 */
87039 onCodePathSegmentStart(segment) {
87040 if (!isInConstructorOfDerivedClass()) {
87041 return;
87042 } // Initialize info.
87043
87044
87045 segInfoMap[segment.id] = {
87046 superCalled: segment.prevSegments.length > 0 && segment.prevSegments.every(isCalled),
87047 invalidNodes: []
87048 };
87049 },
87050
87051 /**
87052 * Update information of the code path segment when a code path was
87053 * looped.
87054 * @param {CodePathSegment} fromSegment The code path segment of the
87055 * end of a loop.
87056 * @param {CodePathSegment} toSegment A code path segment of the head
87057 * of a loop.
87058 * @returns {void}
87059 */
87060 onCodePathSegmentLoop(fromSegment, toSegment) {
87061 if (!isInConstructorOfDerivedClass()) {
87062 return;
87063 } // Update information inside of the loop.
87064
87065
87066 funcInfo.codePath.traverseSegments({
87067 first: toSegment,
87068 last: fromSegment
87069 }, (segment, controller) => {
87070 const info = segInfoMap[segment.id];
87071
87072 if (info.superCalled) {
87073 info.invalidNodes = [];
87074 controller.skip();
87075 } else if (segment.prevSegments.length > 0 && segment.prevSegments.every(isCalled)) {
87076 info.superCalled = true;
87077 info.invalidNodes = [];
87078 }
87079 });
87080 },
87081
87082 /**
87083 * Reports if this is before `super()`.
87084 * @param {ASTNode} node A target node.
87085 * @returns {void}
87086 */
87087 ThisExpression(node) {
87088 if (isBeforeCallOfSuper()) {
87089 setInvalid(node);
87090 }
87091 },
87092
87093 /**
87094 * Reports if this is before `super()`.
87095 * @param {ASTNode} node A target node.
87096 * @returns {void}
87097 */
87098 Super(node) {
87099 if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) {
87100 setInvalid(node);
87101 }
87102 },
87103
87104 /**
87105 * Marks `super()` called.
87106 * @param {ASTNode} node A target node.
87107 * @returns {void}
87108 */
87109 "CallExpression:exit"(node) {
87110 if (node.callee.type === "Super" && isBeforeCallOfSuper()) {
87111 setSuperCalled();
87112 }
87113 },
87114
87115 /**
87116 * Resets state.
87117 * @returns {void}
87118 */
87119 "Program:exit"() {
87120 segInfoMap = Object.create(null);
87121 }
87122
87123 };
87124 }
87125
87126};
87127
87128/***/ }),
6a5a0f88 87129/* 632 */
eb39fafa
DC
87130/***/ (function(module, exports, __webpack_require__) {
87131
87132"use strict";
87133/**
87134 * @fileoverview Rule to restrict what can be thrown as an exception.
87135 * @author Dieter Oberkofler
87136 */
87137
87138
87139const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
87140// Rule Definition
87141//------------------------------------------------------------------------------
87142
87143
87144module.exports = {
87145 meta: {
87146 type: "suggestion",
87147 docs: {
87148 description: "disallow throwing literals as exceptions",
87149 category: "Best Practices",
87150 recommended: false,
87151 url: "https://eslint.org/docs/rules/no-throw-literal"
87152 },
87153 schema: [],
87154 messages: {
87155 object: "Expected an error object to be thrown.",
87156 undef: "Do not throw undefined."
87157 }
87158 },
87159
87160 create(context) {
87161 return {
87162 ThrowStatement(node) {
87163 if (!astUtils.couldBeError(node.argument)) {
87164 context.report({
87165 node,
87166 messageId: "object"
87167 });
87168 } else if (node.argument.type === "Identifier") {
87169 if (node.argument.name === "undefined") {
87170 context.report({
87171 node,
87172 messageId: "undef"
87173 });
87174 }
87175 }
87176 }
87177
87178 };
87179 }
87180
87181};
87182
87183/***/ }),
6a5a0f88 87184/* 633 */
eb39fafa
DC
87185/***/ (function(module, exports, __webpack_require__) {
87186
87187"use strict";
87188/**
87189 * @fileoverview Disallow trailing spaces at the end of lines.
87190 * @author Nodeca Team <https://github.com/nodeca>
87191 */
87192 //------------------------------------------------------------------------------
87193// Requirements
87194//------------------------------------------------------------------------------
87195
87196const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
87197// Rule Definition
87198//------------------------------------------------------------------------------
87199
87200
87201module.exports = {
87202 meta: {
87203 type: "layout",
87204 docs: {
87205 description: "disallow trailing whitespace at the end of lines",
87206 category: "Stylistic Issues",
87207 recommended: false,
87208 url: "https://eslint.org/docs/rules/no-trailing-spaces"
87209 },
87210 fixable: "whitespace",
87211 schema: [{
87212 type: "object",
87213 properties: {
87214 skipBlankLines: {
87215 type: "boolean",
87216 default: false
87217 },
87218 ignoreComments: {
87219 type: "boolean",
87220 default: false
87221 }
87222 },
87223 additionalProperties: false
87224 }],
87225 messages: {
87226 trailingSpace: "Trailing spaces not allowed."
87227 }
87228 },
87229
87230 create(context) {
87231 const sourceCode = context.getSourceCode();
87232 const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]",
87233 SKIP_BLANK = "^".concat(BLANK_CLASS, "*$"),
87234 NONBLANK = "".concat(BLANK_CLASS, "+$");
87235 const options = context.options[0] || {},
87236 skipBlankLines = options.skipBlankLines || false,
87237 ignoreComments = options.ignoreComments || false;
87238 /**
87239 * Report the error message
87240 * @param {ASTNode} node node to report
87241 * @param {int[]} location range information
87242 * @param {int[]} fixRange Range based on the whole program
87243 * @returns {void}
87244 */
87245
87246 function report(node, location, fixRange) {
87247 /*
87248 * Passing node is a bit dirty, because message data will contain big
87249 * text in `source`. But... who cares :) ?
87250 * One more kludge will not make worse the bloody wizardry of this
87251 * plugin.
87252 */
87253 context.report({
87254 node,
87255 loc: location,
87256 messageId: "trailingSpace",
87257
87258 fix(fixer) {
87259 return fixer.removeRange(fixRange);
87260 }
87261
87262 });
87263 }
87264 /**
87265 * Given a list of comment nodes, return the line numbers for those comments.
87266 * @param {Array} comments An array of comment nodes.
87267 * @returns {number[]} An array of line numbers containing comments.
87268 */
87269
87270
87271 function getCommentLineNumbers(comments) {
87272 const lines = new Set();
87273 comments.forEach(comment => {
87274 const endLine = comment.type === "Block" ? comment.loc.end.line - 1 : comment.loc.end.line;
87275
87276 for (let i = comment.loc.start.line; i <= endLine; i++) {
87277 lines.add(i);
87278 }
87279 });
87280 return lines;
87281 } //--------------------------------------------------------------------------
87282 // Public
87283 //--------------------------------------------------------------------------
87284
87285
87286 return {
87287 Program: function checkTrailingSpaces(node) {
87288 /*
87289 * Let's hack. Since Espree does not return whitespace nodes,
87290 * fetch the source code and do matching via regexps.
87291 */
87292 const re = new RegExp(NONBLANK, "u"),
87293 skipMatch = new RegExp(SKIP_BLANK, "u"),
87294 lines = sourceCode.lines,
87295 linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()),
87296 comments = sourceCode.getAllComments(),
87297 commentLineNumbers = getCommentLineNumbers(comments);
87298 let totalLength = 0,
87299 fixRange = [];
87300
87301 for (let i = 0, ii = lines.length; i < ii; i++) {
87302 const lineNumber = i + 1;
87303 /*
87304 * Always add linebreak length to line length to accommodate for line break (\n or \r\n)
87305 * Because during the fix time they also reserve one spot in the array.
87306 * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF)
87307 */
87308
87309 const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1;
87310 const lineLength = lines[i].length + linebreakLength;
87311 const matches = re.exec(lines[i]);
87312
87313 if (matches) {
87314 const location = {
87315 start: {
87316 line: lineNumber,
87317 column: matches.index
87318 },
87319 end: {
87320 line: lineNumber,
87321 column: lineLength - linebreakLength
87322 }
87323 };
87324 const rangeStart = totalLength + location.start.column;
87325 const rangeEnd = totalLength + location.end.column;
87326 const containingNode = sourceCode.getNodeByRangeIndex(rangeStart);
87327
87328 if (containingNode && containingNode.type === "TemplateElement" && rangeStart > containingNode.parent.range[0] && rangeEnd < containingNode.parent.range[1]) {
87329 totalLength += lineLength;
87330 continue;
87331 }
87332 /*
87333 * If the line has only whitespace, and skipBlankLines
87334 * is true, don't report it
87335 */
87336
87337
87338 if (skipBlankLines && skipMatch.test(lines[i])) {
87339 totalLength += lineLength;
87340 continue;
87341 }
87342
87343 fixRange = [rangeStart, rangeEnd];
87344
87345 if (!ignoreComments || !commentLineNumbers.has(lineNumber)) {
87346 report(node, location, fixRange);
87347 }
87348 }
87349
87350 totalLength += lineLength;
87351 }
87352 }
87353 };
87354 }
87355
87356};
87357
87358/***/ }),
6a5a0f88 87359/* 634 */
eb39fafa
DC
87360/***/ (function(module, exports, __webpack_require__) {
87361
87362"use strict";
87363/**
87364 * @fileoverview Rule to flag references to undeclared variables.
87365 * @author Mark Macdonald
87366 */
87367 //------------------------------------------------------------------------------
87368// Helpers
87369//------------------------------------------------------------------------------
87370
87371/**
87372 * Checks if the given node is the argument of a typeof operator.
87373 * @param {ASTNode} node The AST node being checked.
87374 * @returns {boolean} Whether or not the node is the argument of a typeof operator.
87375 */
87376
87377function hasTypeOfOperator(node) {
87378 const parent = node.parent;
87379 return parent.type === "UnaryExpression" && parent.operator === "typeof";
87380} //------------------------------------------------------------------------------
87381// Rule Definition
87382//------------------------------------------------------------------------------
87383
87384
87385module.exports = {
87386 meta: {
87387 type: "problem",
87388 docs: {
87389 description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments",
87390 category: "Variables",
87391 recommended: true,
87392 url: "https://eslint.org/docs/rules/no-undef"
87393 },
87394 schema: [{
87395 type: "object",
87396 properties: {
87397 typeof: {
87398 type: "boolean",
87399 default: false
87400 }
87401 },
87402 additionalProperties: false
87403 }],
87404 messages: {
87405 undef: "'{{name}}' is not defined."
87406 }
87407 },
87408
87409 create(context) {
87410 const options = context.options[0];
87411 const considerTypeOf = options && options.typeof === true || false;
87412 return {
87413 "Program:exit"()
87414 /* node */
87415 {
87416 const globalScope = context.getScope();
87417 globalScope.through.forEach(ref => {
87418 const identifier = ref.identifier;
87419
87420 if (!considerTypeOf && hasTypeOfOperator(identifier)) {
87421 return;
87422 }
87423
87424 context.report({
87425 node: identifier,
87426 messageId: "undef",
87427 data: identifier
87428 });
87429 });
87430 }
87431
87432 };
87433 }
87434
87435};
87436
87437/***/ }),
6a5a0f88 87438/* 635 */
eb39fafa
DC
87439/***/ (function(module, exports, __webpack_require__) {
87440
87441"use strict";
87442/**
87443 * @fileoverview Rule to flag when initializing to undefined
87444 * @author Ilya Volodin
87445 */
87446
87447
87448const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
87449// Rule Definition
87450//------------------------------------------------------------------------------
87451
87452
87453module.exports = {
87454 meta: {
87455 type: "suggestion",
87456 docs: {
87457 description: "disallow initializing variables to `undefined`",
87458 category: "Variables",
87459 recommended: false,
87460 url: "https://eslint.org/docs/rules/no-undef-init"
87461 },
87462 schema: [],
87463 fixable: "code",
87464 messages: {
87465 unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined."
87466 }
87467 },
87468
87469 create(context) {
87470 const sourceCode = context.getSourceCode();
87471 return {
87472 VariableDeclarator(node) {
87473 const name = sourceCode.getText(node.id),
87474 init = node.init && node.init.name,
87475 scope = context.getScope(),
87476 undefinedVar = astUtils.getVariableByName(scope, "undefined"),
87477 shadowed = undefinedVar && undefinedVar.defs.length > 0,
87478 lastToken = sourceCode.getLastToken(node);
87479
87480 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
87481 context.report({
87482 node,
87483 messageId: "unnecessaryUndefinedInit",
87484 data: {
87485 name
87486 },
87487
87488 fix(fixer) {
87489 if (node.parent.kind === "var") {
87490 return null;
87491 }
87492
87493 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
87494 // Don't fix destructuring assignment to `undefined`.
87495 return null;
87496 }
87497
87498 if (sourceCode.commentsExistBetween(node.id, lastToken)) {
87499 return null;
87500 }
87501
87502 return fixer.removeRange([node.id.range[1], node.range[1]]);
87503 }
87504
87505 });
87506 }
87507 }
87508
87509 };
87510 }
87511
87512};
87513
87514/***/ }),
6a5a0f88 87515/* 636 */
eb39fafa
DC
87516/***/ (function(module, exports, __webpack_require__) {
87517
87518"use strict";
87519/**
87520 * @fileoverview Rule to flag references to the undefined variable.
87521 * @author Michael Ficarra
87522 */
87523 //------------------------------------------------------------------------------
87524// Rule Definition
87525//------------------------------------------------------------------------------
87526
87527module.exports = {
87528 meta: {
87529 type: "suggestion",
87530 docs: {
87531 description: "disallow the use of `undefined` as an identifier",
87532 category: "Variables",
87533 recommended: false,
87534 url: "https://eslint.org/docs/rules/no-undefined"
87535 },
87536 schema: [],
87537 messages: {
87538 unexpectedUndefined: "Unexpected use of undefined."
87539 }
87540 },
87541
87542 create(context) {
87543 /**
87544 * Report an invalid "undefined" identifier node.
87545 * @param {ASTNode} node The node to report.
87546 * @returns {void}
87547 */
87548 function report(node) {
87549 context.report({
87550 node,
87551 messageId: "unexpectedUndefined"
87552 });
87553 }
87554 /**
87555 * Checks the given scope for references to `undefined` and reports
87556 * all references found.
87557 * @param {eslint-scope.Scope} scope The scope to check.
87558 * @returns {void}
87559 */
87560
87561
87562 function checkScope(scope) {
87563 const undefinedVar = scope.set.get("undefined");
87564
87565 if (!undefinedVar) {
87566 return;
87567 }
87568
87569 const references = undefinedVar.references;
87570 const defs = undefinedVar.defs; // Report non-initializing references (those are covered in defs below)
87571
87572 references.filter(ref => !ref.init).forEach(ref => report(ref.identifier));
87573 defs.forEach(def => report(def.name));
87574 }
87575
87576 return {
87577 "Program:exit"() {
87578 const globalScope = context.getScope();
87579 const stack = [globalScope];
87580
87581 while (stack.length) {
87582 const scope = stack.pop();
87583 stack.push(...scope.childScopes);
87584 checkScope(scope);
87585 }
87586 }
87587
87588 };
87589 }
87590
87591};
87592
87593/***/ }),
6a5a0f88 87594/* 637 */
eb39fafa
DC
87595/***/ (function(module, exports, __webpack_require__) {
87596
87597"use strict";
87598/**
87599 * @fileoverview Rule to flag trailing underscores in variable declarations.
87600 * @author Matt DuVall <http://www.mattduvall.com>
87601 */
87602 //------------------------------------------------------------------------------
87603// Rule Definition
87604//------------------------------------------------------------------------------
87605
87606module.exports = {
87607 meta: {
87608 type: "suggestion",
87609 docs: {
87610 description: "disallow dangling underscores in identifiers",
87611 category: "Stylistic Issues",
87612 recommended: false,
87613 url: "https://eslint.org/docs/rules/no-underscore-dangle"
87614 },
87615 schema: [{
87616 type: "object",
87617 properties: {
87618 allow: {
87619 type: "array",
87620 items: {
87621 type: "string"
87622 }
87623 },
87624 allowAfterThis: {
87625 type: "boolean",
87626 default: false
87627 },
87628 allowAfterSuper: {
87629 type: "boolean",
87630 default: false
87631 },
87632 allowAfterThisConstructor: {
87633 type: "boolean",
87634 default: false
87635 },
87636 enforceInMethodNames: {
87637 type: "boolean",
87638 default: false
87639 }
87640 },
87641 additionalProperties: false
87642 }],
87643 messages: {
87644 unexpectedUnderscore: "Unexpected dangling '_' in '{{identifier}}'."
87645 }
87646 },
87647
87648 create(context) {
87649 const options = context.options[0] || {};
87650 const ALLOWED_VARIABLES = options.allow ? options.allow : [];
87651 const allowAfterThis = typeof options.allowAfterThis !== "undefined" ? options.allowAfterThis : false;
87652 const allowAfterSuper = typeof options.allowAfterSuper !== "undefined" ? options.allowAfterSuper : false;
87653 const allowAfterThisConstructor = typeof options.allowAfterThisConstructor !== "undefined" ? options.allowAfterThisConstructor : false;
87654 const enforceInMethodNames = typeof options.enforceInMethodNames !== "undefined" ? options.enforceInMethodNames : false; //-------------------------------------------------------------------------
87655 // Helpers
87656 //-------------------------------------------------------------------------
87657
87658 /**
87659 * Check if identifier is present inside the allowed option
87660 * @param {string} identifier name of the node
87661 * @returns {boolean} true if its is present
87662 * @private
87663 */
87664
87665 function isAllowed(identifier) {
87666 return ALLOWED_VARIABLES.some(ident => ident === identifier);
87667 }
87668 /**
87669 * Check if identifier has a underscore at the end
87670 * @param {string} identifier name of the node
87671 * @returns {boolean} true if its is present
87672 * @private
87673 */
87674
87675
87676 function hasTrailingUnderscore(identifier) {
87677 const len = identifier.length;
87678 return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_");
87679 }
87680 /**
87681 * Check if identifier is a special case member expression
87682 * @param {string} identifier name of the node
87683 * @returns {boolean} true if its is a special case
87684 * @private
87685 */
87686
87687
87688 function isSpecialCaseIdentifierForMemberExpression(identifier) {
87689 return identifier === "__proto__";
87690 }
87691 /**
87692 * Check if identifier is a special case variable expression
87693 * @param {string} identifier name of the node
87694 * @returns {boolean} true if its is a special case
87695 * @private
87696 */
87697
87698
87699 function isSpecialCaseIdentifierInVariableExpression(identifier) {
87700 // Checks for the underscore library usage here
87701 return identifier === "_";
87702 }
87703 /**
87704 * Check if a node is a member reference of this.constructor
87705 * @param {ASTNode} node node to evaluate
87706 * @returns {boolean} true if it is a reference on this.constructor
87707 * @private
87708 */
87709
87710
87711 function isThisConstructorReference(node) {
87712 return node.object.type === "MemberExpression" && node.object.property.name === "constructor" && node.object.object.type === "ThisExpression";
87713 }
87714 /**
87715 * Check if function has a underscore at the end
87716 * @param {ASTNode} node node to evaluate
87717 * @returns {void}
87718 * @private
87719 */
87720
87721
87722 function checkForTrailingUnderscoreInFunctionDeclaration(node) {
87723 if (node.id) {
87724 const identifier = node.id.name;
87725
87726 if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && !isAllowed(identifier)) {
87727 context.report({
87728 node,
87729 messageId: "unexpectedUnderscore",
87730 data: {
87731 identifier
87732 }
87733 });
87734 }
87735 }
87736 }
87737 /**
87738 * Check if variable expression has a underscore at the end
87739 * @param {ASTNode} node node to evaluate
87740 * @returns {void}
87741 * @private
87742 */
87743
87744
87745 function checkForTrailingUnderscoreInVariableExpression(node) {
87746 const identifier = node.id.name;
87747
87748 if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && !isSpecialCaseIdentifierInVariableExpression(identifier) && !isAllowed(identifier)) {
87749 context.report({
87750 node,
87751 messageId: "unexpectedUnderscore",
87752 data: {
87753 identifier
87754 }
87755 });
87756 }
87757 }
87758 /**
87759 * Check if member expression has a underscore at the end
87760 * @param {ASTNode} node node to evaluate
87761 * @returns {void}
87762 * @private
87763 */
87764
87765
87766 function checkForTrailingUnderscoreInMemberExpression(node) {
87767 const identifier = node.property.name,
87768 isMemberOfThis = node.object.type === "ThisExpression",
87769 isMemberOfSuper = node.object.type === "Super",
87770 isMemberOfThisConstructor = isThisConstructorReference(node);
87771
87772 if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && !(isMemberOfThis && allowAfterThis) && !(isMemberOfSuper && allowAfterSuper) && !(isMemberOfThisConstructor && allowAfterThisConstructor) && !isSpecialCaseIdentifierForMemberExpression(identifier) && !isAllowed(identifier)) {
87773 context.report({
87774 node,
87775 messageId: "unexpectedUnderscore",
87776 data: {
87777 identifier
87778 }
87779 });
87780 }
87781 }
87782 /**
87783 * Check if method declaration or method property has a underscore at the end
87784 * @param {ASTNode} node node to evaluate
87785 * @returns {void}
87786 * @private
87787 */
87788
87789
87790 function checkForTrailingUnderscoreInMethod(node) {
87791 const identifier = node.key.name;
87792 const isMethod = node.type === "MethodDefinition" || node.type === "Property" && node.method;
87793
87794 if (typeof identifier !== "undefined" && enforceInMethodNames && isMethod && hasTrailingUnderscore(identifier) && !isAllowed(identifier)) {
87795 context.report({
87796 node,
87797 messageId: "unexpectedUnderscore",
87798 data: {
87799 identifier
87800 }
87801 });
87802 }
87803 } //--------------------------------------------------------------------------
87804 // Public API
87805 //--------------------------------------------------------------------------
87806
87807
87808 return {
87809 FunctionDeclaration: checkForTrailingUnderscoreInFunctionDeclaration,
87810 VariableDeclarator: checkForTrailingUnderscoreInVariableExpression,
87811 MemberExpression: checkForTrailingUnderscoreInMemberExpression,
87812 MethodDefinition: checkForTrailingUnderscoreInMethod,
87813 Property: checkForTrailingUnderscoreInMethod
87814 };
87815 }
87816
87817};
87818
87819/***/ }),
6a5a0f88 87820/* 638 */
eb39fafa
DC
87821/***/ (function(module, exports, __webpack_require__) {
87822
87823"use strict";
87824/**
87825 * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not.
87826 * @author Glen Mailer
87827 */
87828 //------------------------------------------------------------------------------
87829// Requirements
87830//------------------------------------------------------------------------------
87831
87832const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
87833// Rule Definition
87834//------------------------------------------------------------------------------
87835
87836
87837module.exports = {
87838 meta: {
87839 type: "problem",
87840 docs: {
87841 description: "disallow confusing multiline expressions",
87842 category: "Possible Errors",
87843 recommended: true,
87844 url: "https://eslint.org/docs/rules/no-unexpected-multiline"
87845 },
87846 schema: [],
87847 messages: {
87848 function: "Unexpected newline between function and ( of function call.",
87849 property: "Unexpected newline between object and [ of property access.",
87850 taggedTemplate: "Unexpected newline between template tag and template literal.",
87851 division: "Unexpected newline between numerator and division operator."
87852 }
87853 },
87854
87855 create(context) {
87856 const REGEX_FLAG_MATCHER = /^[gimsuy]+$/u;
87857 const sourceCode = context.getSourceCode();
87858 /**
87859 * Check to see if there is a newline between the node and the following open bracket
87860 * line's expression
87861 * @param {ASTNode} node The node to check.
87862 * @param {string} messageId The error messageId to use.
87863 * @returns {void}
87864 * @private
87865 */
87866
87867 function checkForBreakAfter(node, messageId) {
87868 const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken);
87869 const nodeExpressionEnd = sourceCode.getTokenBefore(openParen);
87870
87871 if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) {
87872 context.report({
87873 node,
56c4a2cb
DC
87874 loc: openParen.loc,
87875 messageId
eb39fafa
DC
87876 });
87877 }
87878 } //--------------------------------------------------------------------------
87879 // Public API
87880 //--------------------------------------------------------------------------
87881
87882
87883 return {
87884 MemberExpression(node) {
87885 if (!node.computed) {
87886 return;
87887 }
87888
87889 checkForBreakAfter(node.object, "property");
87890 },
87891
87892 TaggedTemplateExpression(node) {
56c4a2cb
DC
87893 const {
87894 quasi
87895 } = node; // handles common tags, parenthesized tags, and typescript's generic type arguments
eb39fafa 87896
56c4a2cb 87897 const tokenBefore = sourceCode.getTokenBefore(quasi);
eb39fafa 87898
56c4a2cb
DC
87899 if (tokenBefore.loc.end.line !== quasi.loc.start.line) {
87900 context.report({
87901 node,
87902 loc: {
87903 start: quasi.loc.start,
87904 end: {
87905 line: quasi.loc.start.line,
87906 column: quasi.loc.start.column + 1
87907 }
87908 },
87909 messageId: "taggedTemplate"
87910 });
eb39fafa 87911 }
eb39fafa
DC
87912 },
87913
87914 CallExpression(node) {
87915 if (node.arguments.length === 0) {
87916 return;
87917 }
87918
87919 checkForBreakAfter(node.callee, "function");
87920 },
87921
87922 "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"(node) {
87923 const secondSlash = sourceCode.getTokenAfter(node, token => token.value === "/");
87924 const tokenAfterOperator = sourceCode.getTokenAfter(secondSlash);
87925
87926 if (tokenAfterOperator.type === "Identifier" && REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && secondSlash.range[1] === tokenAfterOperator.range[0]) {
87927 checkForBreakAfter(node.left, "division");
87928 }
87929 }
87930
87931 };
87932 }
87933
87934};
87935
87936/***/ }),
6a5a0f88 87937/* 639 */
eb39fafa
DC
87938/***/ (function(module, exports, __webpack_require__) {
87939
87940"use strict";
87941/**
87942 * @fileoverview Rule to disallow use of unmodified expressions in loop conditions
87943 * @author Toru Nagashima
87944 */
87945 //------------------------------------------------------------------------------
87946// Requirements
87947//------------------------------------------------------------------------------
87948
6a5a0f88 87949const Traverser = __webpack_require__(640),
eb39fafa
DC
87950 astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
87951// Helpers
87952//------------------------------------------------------------------------------
87953
87954
87955const SENTINEL_PATTERN = /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/u;
87956const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/u; // for-in/of statements don't have `test` property.
87957
87958const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/u;
87959const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/u;
87960const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/u;
87961/**
87962 * @typedef {Object} LoopConditionInfo
87963 * @property {eslint-scope.Reference} reference - The reference.
87964 * @property {ASTNode} group - BinaryExpression or ConditionalExpression nodes
87965 * that the reference is belonging to.
87966 * @property {Function} isInLoop - The predicate which checks a given reference
87967 * is in this loop.
87968 * @property {boolean} modified - The flag that the reference is modified in
87969 * this loop.
87970 */
87971
87972/**
87973 * Checks whether or not a given reference is a write reference.
87974 * @param {eslint-scope.Reference} reference A reference to check.
87975 * @returns {boolean} `true` if the reference is a write reference.
87976 */
87977
87978function isWriteReference(reference) {
87979 if (reference.init) {
87980 const def = reference.resolved && reference.resolved.defs[0];
87981
87982 if (!def || def.type !== "Variable" || def.parent.kind !== "var") {
87983 return false;
87984 }
87985 }
87986
87987 return reference.isWrite();
87988}
87989/**
87990 * Checks whether or not a given loop condition info does not have the modified
87991 * flag.
87992 * @param {LoopConditionInfo} condition A loop condition info to check.
87993 * @returns {boolean} `true` if the loop condition info is "unmodified".
87994 */
87995
87996
87997function isUnmodified(condition) {
87998 return !condition.modified;
87999}
88000/**
88001 * Checks whether or not a given loop condition info does not have the modified
88002 * flag and does not have the group this condition belongs to.
88003 * @param {LoopConditionInfo} condition A loop condition info to check.
88004 * @returns {boolean} `true` if the loop condition info is "unmodified".
88005 */
88006
88007
88008function isUnmodifiedAndNotBelongToGroup(condition) {
88009 return !(condition.modified || condition.group);
88010}
88011/**
88012 * Checks whether or not a given reference is inside of a given node.
88013 * @param {ASTNode} node A node to check.
88014 * @param {eslint-scope.Reference} reference A reference to check.
88015 * @returns {boolean} `true` if the reference is inside of the node.
88016 */
88017
88018
88019function isInRange(node, reference) {
88020 const or = node.range;
88021 const ir = reference.identifier.range;
88022 return or[0] <= ir[0] && ir[1] <= or[1];
88023}
88024/**
88025 * Checks whether or not a given reference is inside of a loop node's condition.
88026 * @param {ASTNode} node A node to check.
88027 * @param {eslint-scope.Reference} reference A reference to check.
88028 * @returns {boolean} `true` if the reference is inside of the loop node's
88029 * condition.
88030 */
88031
88032
88033const isInLoop = {
88034 WhileStatement: isInRange,
88035 DoWhileStatement: isInRange,
88036
88037 ForStatement(node, reference) {
88038 return isInRange(node, reference) && !(node.init && isInRange(node.init, reference));
88039 }
88040
88041};
88042/**
88043 * Gets the function which encloses a given reference.
88044 * This supports only FunctionDeclaration.
88045 * @param {eslint-scope.Reference} reference A reference to get.
88046 * @returns {ASTNode|null} The function node or null.
88047 */
88048
88049function getEncloseFunctionDeclaration(reference) {
88050 let node = reference.identifier;
88051
88052 while (node) {
88053 if (node.type === "FunctionDeclaration") {
88054 return node.id ? node : null;
88055 }
88056
88057 node = node.parent;
88058 }
88059
88060 return null;
88061}
88062/**
88063 * Updates the "modified" flags of given loop conditions with given modifiers.
88064 * @param {LoopConditionInfo[]} conditions The loop conditions to be updated.
88065 * @param {eslint-scope.Reference[]} modifiers The references to update.
88066 * @returns {void}
88067 */
88068
88069
88070function updateModifiedFlag(conditions, modifiers) {
88071 for (let i = 0; i < conditions.length; ++i) {
88072 const condition = conditions[i];
88073
88074 for (let j = 0; !condition.modified && j < modifiers.length; ++j) {
88075 const modifier = modifiers[j];
88076 let funcNode, funcVar;
88077 /*
88078 * Besides checking for the condition being in the loop, we want to
88079 * check the function that this modifier is belonging to is called
88080 * in the loop.
88081 * FIXME: This should probably be extracted to a function.
88082 */
88083
88084 const inLoop = condition.isInLoop(modifier) || Boolean((funcNode = getEncloseFunctionDeclaration(modifier)) && (funcVar = astUtils.getVariableByName(modifier.from.upper, funcNode.id.name)) && funcVar.references.some(condition.isInLoop));
88085 condition.modified = inLoop;
88086 }
88087 }
88088} //------------------------------------------------------------------------------
88089// Rule Definition
88090//------------------------------------------------------------------------------
88091
88092
88093module.exports = {
88094 meta: {
88095 type: "problem",
88096 docs: {
88097 description: "disallow unmodified loop conditions",
88098 category: "Best Practices",
88099 recommended: false,
88100 url: "https://eslint.org/docs/rules/no-unmodified-loop-condition"
88101 },
88102 schema: [],
88103 messages: {
88104 loopConditionNotModified: "'{{name}}' is not modified in this loop."
88105 }
88106 },
88107
88108 create(context) {
88109 const sourceCode = context.getSourceCode();
88110 let groupMap = null;
88111 /**
88112 * Reports a given condition info.
88113 * @param {LoopConditionInfo} condition A loop condition info to report.
88114 * @returns {void}
88115 */
88116
88117 function report(condition) {
88118 const node = condition.reference.identifier;
88119 context.report({
88120 node,
88121 messageId: "loopConditionNotModified",
88122 data: node
88123 });
88124 }
88125 /**
88126 * Registers given conditions to the group the condition belongs to.
88127 * @param {LoopConditionInfo[]} conditions A loop condition info to
88128 * register.
88129 * @returns {void}
88130 */
88131
88132
88133 function registerConditionsToGroup(conditions) {
88134 for (let i = 0; i < conditions.length; ++i) {
88135 const condition = conditions[i];
88136
88137 if (condition.group) {
88138 let group = groupMap.get(condition.group);
88139
88140 if (!group) {
88141 group = [];
88142 groupMap.set(condition.group, group);
88143 }
88144
88145 group.push(condition);
88146 }
88147 }
88148 }
88149 /**
88150 * Reports references which are inside of unmodified groups.
88151 * @param {LoopConditionInfo[]} conditions A loop condition info to report.
88152 * @returns {void}
88153 */
88154
88155
88156 function checkConditionsInGroup(conditions) {
88157 if (conditions.every(isUnmodified)) {
88158 conditions.forEach(report);
88159 }
88160 }
88161 /**
88162 * Checks whether or not a given group node has any dynamic elements.
88163 * @param {ASTNode} root A node to check.
88164 * This node is one of BinaryExpression or ConditionalExpression.
88165 * @returns {boolean} `true` if the node is dynamic.
88166 */
88167
88168
88169 function hasDynamicExpressions(root) {
88170 let retv = false;
88171 Traverser.traverse(root, {
88172 visitorKeys: sourceCode.visitorKeys,
88173
88174 enter(node) {
88175 if (DYNAMIC_PATTERN.test(node.type)) {
88176 retv = true;
88177 this.break();
88178 } else if (SKIP_PATTERN.test(node.type)) {
88179 this.skip();
88180 }
88181 }
88182
88183 });
88184 return retv;
88185 }
88186 /**
88187 * Creates the loop condition information from a given reference.
88188 * @param {eslint-scope.Reference} reference A reference to create.
88189 * @returns {LoopConditionInfo|null} Created loop condition info, or null.
88190 */
88191
88192
88193 function toLoopCondition(reference) {
88194 if (reference.init) {
88195 return null;
88196 }
88197
88198 let group = null;
88199 let child = reference.identifier;
88200 let node = child.parent;
88201
88202 while (node) {
88203 if (SENTINEL_PATTERN.test(node.type)) {
88204 if (LOOP_PATTERN.test(node.type) && node.test === child) {
88205 // This reference is inside of a loop condition.
88206 return {
88207 reference,
88208 group,
88209 isInLoop: isInLoop[node.type].bind(null, node),
88210 modified: false
88211 };
88212 } // This reference is outside of a loop condition.
88213
88214
88215 break;
88216 }
88217 /*
88218 * If it's inside of a group, OK if either operand is modified.
88219 * So stores the group this reference belongs to.
88220 */
88221
88222
88223 if (GROUP_PATTERN.test(node.type)) {
88224 // If this expression is dynamic, no need to check.
88225 if (hasDynamicExpressions(node)) {
88226 break;
88227 } else {
88228 group = node;
88229 }
88230 }
88231
88232 child = node;
88233 node = node.parent;
88234 }
88235
88236 return null;
88237 }
88238 /**
88239 * Finds unmodified references which are inside of a loop condition.
88240 * Then reports the references which are outside of groups.
88241 * @param {eslint-scope.Variable} variable A variable to report.
88242 * @returns {void}
88243 */
88244
88245
88246 function checkReferences(variable) {
88247 // Gets references that exist in loop conditions.
88248 const conditions = variable.references.map(toLoopCondition).filter(Boolean);
88249
88250 if (conditions.length === 0) {
88251 return;
88252 } // Registers the conditions to belonging groups.
88253
88254
88255 registerConditionsToGroup(conditions); // Check the conditions are modified.
88256
88257 const modifiers = variable.references.filter(isWriteReference);
88258
88259 if (modifiers.length > 0) {
88260 updateModifiedFlag(conditions, modifiers);
88261 }
88262 /*
88263 * Reports the conditions which are not belonging to groups.
88264 * Others will be reported after all variables are done.
88265 */
88266
88267
88268 conditions.filter(isUnmodifiedAndNotBelongToGroup).forEach(report);
88269 }
88270
88271 return {
88272 "Program:exit"() {
88273 const queue = [context.getScope()];
88274 groupMap = new Map();
88275 let scope;
88276
88277 while (scope = queue.pop()) {
88278 queue.push(...scope.childScopes);
88279 scope.variables.forEach(checkReferences);
88280 }
88281
88282 groupMap.forEach(checkConditionsInGroup);
88283 groupMap = null;
88284 }
88285
88286 };
88287 }
88288
88289};
88290
88291/***/ }),
6a5a0f88 88292/* 640 */
eb39fafa
DC
88293/***/ (function(module, exports, __webpack_require__) {
88294
88295"use strict";
88296/**
88297 * @fileoverview Traverser to traverse AST trees.
88298 * @author Nicholas C. Zakas
88299 * @author Toru Nagashima
88300 */
88301 //------------------------------------------------------------------------------
88302// Requirements
88303//------------------------------------------------------------------------------
88304
88305const vk = __webpack_require__(392);
88306
88307const debug = __webpack_require__(416)("eslint:traverser"); //------------------------------------------------------------------------------
88308// Helpers
88309//------------------------------------------------------------------------------
88310
88311/**
88312 * Do nothing.
88313 * @returns {void}
88314 */
88315
88316
88317function noop() {} // do nothing.
88318
88319/**
88320 * Check whether the given value is an ASTNode or not.
88321 * @param {any} x The value to check.
88322 * @returns {boolean} `true` if the value is an ASTNode.
88323 */
88324
88325
88326function isNode(x) {
88327 return x !== null && typeof x === "object" && typeof x.type === "string";
88328}
88329/**
88330 * Get the visitor keys of a given node.
88331 * @param {Object} visitorKeys The map of visitor keys.
88332 * @param {ASTNode} node The node to get their visitor keys.
88333 * @returns {string[]} The visitor keys of the node.
88334 */
88335
88336
88337function getVisitorKeys(visitorKeys, node) {
88338 let keys = visitorKeys[node.type];
88339
88340 if (!keys) {
88341 keys = vk.getKeys(node);
88342 debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys);
88343 }
88344
88345 return keys;
88346}
88347/**
88348 * The traverser class to traverse AST trees.
88349 */
88350
88351
88352class Traverser {
88353 constructor() {
88354 this._current = null;
88355 this._parents = [];
88356 this._skipped = false;
88357 this._broken = false;
88358 this._visitorKeys = null;
88359 this._enter = null;
88360 this._leave = null;
88361 } // eslint-disable-next-line jsdoc/require-description
88362
88363 /**
88364 * @returns {ASTNode} The current node.
88365 */
88366
88367
88368 current() {
88369 return this._current;
88370 } // eslint-disable-next-line jsdoc/require-description
88371
88372 /**
88373 * @returns {ASTNode[]} The ancestor nodes.
88374 */
88375
88376
88377 parents() {
88378 return this._parents.slice(0);
88379 }
88380 /**
88381 * Break the current traversal.
88382 * @returns {void}
88383 */
88384
88385
88386 break() {
88387 this._broken = true;
88388 }
88389 /**
88390 * Skip child nodes for the current traversal.
88391 * @returns {void}
88392 */
88393
88394
88395 skip() {
88396 this._skipped = true;
88397 }
88398 /**
88399 * Traverse the given AST tree.
88400 * @param {ASTNode} node The root node to traverse.
88401 * @param {Object} options The option object.
88402 * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`.
88403 * @param {Function} [options.enter=noop] The callback function which is called on entering each node.
88404 * @param {Function} [options.leave=noop] The callback function which is called on leaving each node.
88405 * @returns {void}
88406 */
88407
88408
88409 traverse(node, options) {
88410 this._current = null;
88411 this._parents = [];
88412 this._skipped = false;
88413 this._broken = false;
88414 this._visitorKeys = options.visitorKeys || vk.KEYS;
88415 this._enter = options.enter || noop;
88416 this._leave = options.leave || noop;
88417
88418 this._traverse(node, null);
88419 }
88420 /**
88421 * Traverse the given AST tree recursively.
88422 * @param {ASTNode} node The current node.
88423 * @param {ASTNode|null} parent The parent node.
88424 * @returns {void}
88425 * @private
88426 */
88427
88428
88429 _traverse(node, parent) {
88430 if (!isNode(node)) {
88431 return;
88432 }
88433
88434 this._current = node;
88435 this._skipped = false;
88436
88437 this._enter(node, parent);
88438
88439 if (!this._skipped && !this._broken) {
88440 const keys = getVisitorKeys(this._visitorKeys, node);
88441
88442 if (keys.length >= 1) {
88443 this._parents.push(node);
88444
88445 for (let i = 0; i < keys.length && !this._broken; ++i) {
88446 const child = node[keys[i]];
88447
88448 if (Array.isArray(child)) {
88449 for (let j = 0; j < child.length && !this._broken; ++j) {
88450 this._traverse(child[j], node);
88451 }
88452 } else {
88453 this._traverse(child, node);
88454 }
88455 }
88456
88457 this._parents.pop();
88458 }
88459 }
88460
88461 if (!this._broken) {
88462 this._leave(node, parent);
88463 }
88464
88465 this._current = parent;
88466 }
88467 /**
88468 * Calculates the keys to use for traversal.
88469 * @param {ASTNode} node The node to read keys from.
88470 * @returns {string[]} An array of keys to visit on the node.
88471 * @private
88472 */
88473
88474
88475 static getKeys(node) {
88476 return vk.getKeys(node);
88477 }
88478 /**
88479 * Traverse the given AST tree.
88480 * @param {ASTNode} node The root node to traverse.
88481 * @param {Object} options The option object.
88482 * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`.
88483 * @param {Function} [options.enter=noop] The callback function which is called on entering each node.
88484 * @param {Function} [options.leave=noop] The callback function which is called on leaving each node.
88485 * @returns {void}
88486 */
88487
88488
88489 static traverse(node, options) {
88490 new Traverser().traverse(node, options);
88491 }
88492 /**
88493 * The default visitor keys.
88494 * @type {Object}
88495 */
88496
88497
88498 static get DEFAULT_VISITOR_KEYS() {
88499 return vk.KEYS;
88500 }
88501
88502}
88503
88504module.exports = Traverser;
88505
88506/***/ }),
6a5a0f88 88507/* 641 */
eb39fafa
DC
88508/***/ (function(module, exports, __webpack_require__) {
88509
88510"use strict";
88511/**
88512 * @fileoverview Rule to flag no-unneeded-ternary
88513 * @author Gyandeep Singh
88514 */
88515
88516
88517const astUtils = __webpack_require__(426); // Operators that always result in a boolean value
88518
88519
88520const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]);
88521const OPERATOR_INVERSES = {
88522 "==": "!=",
88523 "!=": "==",
88524 "===": "!==",
88525 "!==": "===" // Operators like < and >= are not true inverses, since both will return false with NaN.
88526
88527};
88528const OR_PRECEDENCE = astUtils.getPrecedence({
88529 type: "LogicalExpression",
88530 operator: "||"
88531}); //------------------------------------------------------------------------------
88532// Rule Definition
88533//------------------------------------------------------------------------------
88534
88535module.exports = {
88536 meta: {
88537 type: "suggestion",
88538 docs: {
88539 description: "disallow ternary operators when simpler alternatives exist",
88540 category: "Stylistic Issues",
88541 recommended: false,
88542 url: "https://eslint.org/docs/rules/no-unneeded-ternary"
88543 },
88544 schema: [{
88545 type: "object",
88546 properties: {
88547 defaultAssignment: {
88548 type: "boolean",
88549 default: true
88550 }
88551 },
88552 additionalProperties: false
88553 }],
88554 fixable: "code",
88555 messages: {
88556 unnecessaryConditionalExpression: "Unnecessary use of boolean literals in conditional expression.",
88557 unnecessaryConditionalAssignment: "Unnecessary use of conditional expression for default assignment."
88558 }
88559 },
88560
88561 create(context) {
88562 const options = context.options[0] || {};
88563 const defaultAssignment = options.defaultAssignment !== false;
88564 const sourceCode = context.getSourceCode();
88565 /**
88566 * Test if the node is a boolean literal
88567 * @param {ASTNode} node The node to report.
88568 * @returns {boolean} True if the its a boolean literal
88569 * @private
88570 */
88571
88572 function isBooleanLiteral(node) {
88573 return node.type === "Literal" && typeof node.value === "boolean";
88574 }
88575 /**
88576 * Creates an expression that represents the boolean inverse of the expression represented by the original node
88577 * @param {ASTNode} node A node representing an expression
88578 * @returns {string} A string representing an inverted expression
88579 */
88580
88581
88582 function invertExpression(node) {
88583 if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) {
88584 const operatorToken = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
88585 const text = sourceCode.getText();
88586 return text.slice(node.range[0], operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]);
88587 }
88588
88589 if (astUtils.getPrecedence(node) < astUtils.getPrecedence({
88590 type: "UnaryExpression"
88591 })) {
88592 return "!(".concat(astUtils.getParenthesisedText(sourceCode, node), ")");
88593 }
88594
88595 return "!".concat(astUtils.getParenthesisedText(sourceCode, node));
88596 }
88597 /**
88598 * Tests if a given node always evaluates to a boolean value
88599 * @param {ASTNode} node An expression node
88600 * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
88601 */
88602
88603
88604 function isBooleanExpression(node) {
88605 return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) || node.type === "UnaryExpression" && node.operator === "!";
88606 }
88607 /**
88608 * Test if the node matches the pattern id ? id : expression
88609 * @param {ASTNode} node The ConditionalExpression to check.
88610 * @returns {boolean} True if the pattern is matched, and false otherwise
88611 * @private
88612 */
88613
88614
88615 function matchesDefaultAssignment(node) {
88616 return node.test.type === "Identifier" && node.consequent.type === "Identifier" && node.test.name === node.consequent.name;
88617 }
88618
88619 return {
88620 ConditionalExpression(node) {
88621 if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) {
88622 context.report({
88623 node,
88624 loc: node.consequent.loc.start,
88625 messageId: "unnecessaryConditionalExpression",
88626
88627 fix(fixer) {
88628 if (node.consequent.value === node.alternate.value) {
88629 // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
88630 return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null;
88631 }
88632
88633 if (node.alternate.value) {
88634 // Replace `foo() ? false : true` with `!(foo())`
88635 return fixer.replaceText(node, invertExpression(node.test));
88636 } // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
88637
88638
88639 return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : "!".concat(invertExpression(node.test)));
88640 }
88641
88642 });
88643 } else if (!defaultAssignment && matchesDefaultAssignment(node)) {
88644 context.report({
88645 node,
88646 loc: node.consequent.loc.start,
88647 messageId: "unnecessaryConditionalAssignment",
88648 fix: fixer => {
88649 const shouldParenthesizeAlternate = astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE && !astUtils.isParenthesised(sourceCode, node.alternate);
88650 const alternateText = shouldParenthesizeAlternate ? "(".concat(sourceCode.getText(node.alternate), ")") : astUtils.getParenthesisedText(sourceCode, node.alternate);
88651 const testText = astUtils.getParenthesisedText(sourceCode, node.test);
88652 return fixer.replaceText(node, "".concat(testText, " || ").concat(alternateText));
88653 }
88654 });
88655 }
88656 }
88657
88658 };
88659 }
88660
88661};
88662
88663/***/ }),
6a5a0f88 88664/* 642 */
eb39fafa
DC
88665/***/ (function(module, exports, __webpack_require__) {
88666
88667"use strict";
88668/**
88669 * @fileoverview Checks for unreachable code due to return, throws, break, and continue.
88670 * @author Joel Feenstra
88671 */
88672 //------------------------------------------------------------------------------
88673// Helpers
88674//------------------------------------------------------------------------------
88675
88676/**
88677 * Checks whether or not a given variable declarator has the initializer.
88678 * @param {ASTNode} node A VariableDeclarator node to check.
88679 * @returns {boolean} `true` if the node has the initializer.
88680 */
88681
88682function isInitialized(node) {
88683 return Boolean(node.init);
88684}
88685/**
88686 * Checks whether or not a given code path segment is unreachable.
88687 * @param {CodePathSegment} segment A CodePathSegment to check.
88688 * @returns {boolean} `true` if the segment is unreachable.
88689 */
88690
88691
88692function isUnreachable(segment) {
88693 return !segment.reachable;
88694}
88695/**
88696 * The class to distinguish consecutive unreachable statements.
88697 */
88698
88699
88700class ConsecutiveRange {
88701 constructor(sourceCode) {
88702 this.sourceCode = sourceCode;
88703 this.startNode = null;
88704 this.endNode = null;
88705 }
88706 /**
88707 * The location object of this range.
88708 * @type {Object}
88709 */
88710
88711
88712 get location() {
88713 return {
88714 start: this.startNode.loc.start,
88715 end: this.endNode.loc.end
88716 };
88717 }
88718 /**
88719 * `true` if this range is empty.
88720 * @type {boolean}
88721 */
88722
88723
88724 get isEmpty() {
88725 return !(this.startNode && this.endNode);
88726 }
88727 /**
88728 * Checks whether the given node is inside of this range.
88729 * @param {ASTNode|Token} node The node to check.
88730 * @returns {boolean} `true` if the node is inside of this range.
88731 */
88732
88733
88734 contains(node) {
88735 return node.range[0] >= this.startNode.range[0] && node.range[1] <= this.endNode.range[1];
88736 }
88737 /**
88738 * Checks whether the given node is consecutive to this range.
88739 * @param {ASTNode} node The node to check.
88740 * @returns {boolean} `true` if the node is consecutive to this range.
88741 */
88742
88743
88744 isConsecutive(node) {
88745 return this.contains(this.sourceCode.getTokenBefore(node));
88746 }
88747 /**
88748 * Merges the given node to this range.
88749 * @param {ASTNode} node The node to merge.
88750 * @returns {void}
88751 */
88752
88753
88754 merge(node) {
88755 this.endNode = node;
88756 }
88757 /**
88758 * Resets this range by the given node or null.
88759 * @param {ASTNode|null} node The node to reset, or null.
88760 * @returns {void}
88761 */
88762
88763
88764 reset(node) {
88765 this.startNode = this.endNode = node;
88766 }
88767
88768} //------------------------------------------------------------------------------
88769// Rule Definition
88770//------------------------------------------------------------------------------
88771
88772
88773module.exports = {
88774 meta: {
88775 type: "problem",
88776 docs: {
88777 description: "disallow unreachable code after `return`, `throw`, `continue`, and `break` statements",
88778 category: "Possible Errors",
88779 recommended: true,
88780 url: "https://eslint.org/docs/rules/no-unreachable"
88781 },
88782 schema: [],
88783 messages: {
88784 unreachableCode: "Unreachable code."
88785 }
88786 },
88787
88788 create(context) {
88789 let currentCodePath = null;
88790 const range = new ConsecutiveRange(context.getSourceCode());
88791 /**
88792 * Reports a given node if it's unreachable.
88793 * @param {ASTNode} node A statement node to report.
88794 * @returns {void}
88795 */
88796
88797 function reportIfUnreachable(node) {
88798 let nextNode = null;
88799
88800 if (node && currentCodePath.currentSegments.every(isUnreachable)) {
88801 // Store this statement to distinguish consecutive statements.
88802 if (range.isEmpty) {
88803 range.reset(node);
88804 return;
88805 } // Skip if this statement is inside of the current range.
88806
88807
88808 if (range.contains(node)) {
88809 return;
88810 } // Merge if this statement is consecutive to the current range.
88811
88812
88813 if (range.isConsecutive(node)) {
88814 range.merge(node);
88815 return;
88816 }
88817
88818 nextNode = node;
88819 }
88820 /*
88821 * Report the current range since this statement is reachable or is
88822 * not consecutive to the current range.
88823 */
88824
88825
88826 if (!range.isEmpty) {
88827 context.report({
88828 messageId: "unreachableCode",
88829 loc: range.location,
88830 node: range.startNode
88831 });
88832 } // Update the current range.
88833
88834
88835 range.reset(nextNode);
88836 }
88837
88838 return {
88839 // Manages the current code path.
88840 onCodePathStart(codePath) {
88841 currentCodePath = codePath;
88842 },
88843
88844 onCodePathEnd() {
88845 currentCodePath = currentCodePath.upper;
88846 },
88847
88848 // Registers for all statement nodes (excludes FunctionDeclaration).
88849 BlockStatement: reportIfUnreachable,
88850 BreakStatement: reportIfUnreachable,
88851 ClassDeclaration: reportIfUnreachable,
88852 ContinueStatement: reportIfUnreachable,
88853 DebuggerStatement: reportIfUnreachable,
88854 DoWhileStatement: reportIfUnreachable,
88855 ExpressionStatement: reportIfUnreachable,
88856 ForInStatement: reportIfUnreachable,
88857 ForOfStatement: reportIfUnreachable,
88858 ForStatement: reportIfUnreachable,
88859 IfStatement: reportIfUnreachable,
88860 ImportDeclaration: reportIfUnreachable,
88861 LabeledStatement: reportIfUnreachable,
88862 ReturnStatement: reportIfUnreachable,
88863 SwitchStatement: reportIfUnreachable,
88864 ThrowStatement: reportIfUnreachable,
88865 TryStatement: reportIfUnreachable,
88866
88867 VariableDeclaration(node) {
88868 if (node.kind !== "var" || node.declarations.some(isInitialized)) {
88869 reportIfUnreachable(node);
88870 }
88871 },
88872
88873 WhileStatement: reportIfUnreachable,
88874 WithStatement: reportIfUnreachable,
88875 ExportNamedDeclaration: reportIfUnreachable,
88876 ExportDefaultDeclaration: reportIfUnreachable,
88877 ExportAllDeclaration: reportIfUnreachable,
88878
88879 "Program:exit"() {
88880 reportIfUnreachable();
88881 }
88882
88883 };
88884 }
88885
88886};
88887
88888/***/ }),
6a5a0f88 88889/* 643 */
eb39fafa
DC
88890/***/ (function(module, exports, __webpack_require__) {
88891
88892"use strict";
88893/**
88894 * @fileoverview Rule to flag unsafe statements in finally block
88895 * @author Onur Temizkan
88896 */
88897 //------------------------------------------------------------------------------
88898// Helpers
88899//------------------------------------------------------------------------------
88900
88901const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
88902const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u;
88903const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u; //------------------------------------------------------------------------------
88904// Rule Definition
88905//------------------------------------------------------------------------------
88906
88907module.exports = {
88908 meta: {
88909 type: "problem",
88910 docs: {
88911 description: "disallow control flow statements in `finally` blocks",
88912 category: "Possible Errors",
88913 recommended: true,
88914 url: "https://eslint.org/docs/rules/no-unsafe-finally"
88915 },
88916 schema: [],
88917 messages: {
88918 unsafeUsage: "Unsafe usage of {{nodeType}}."
88919 }
88920 },
88921
88922 create(context) {
88923 /**
88924 * Checks if the node is the finalizer of a TryStatement
88925 * @param {ASTNode} node node to check.
88926 * @returns {boolean} - true if the node is the finalizer of a TryStatement
88927 */
88928 function isFinallyBlock(node) {
88929 return node.parent.type === "TryStatement" && node.parent.finalizer === node;
88930 }
88931 /**
88932 * Climbs up the tree if the node is not a sentinel node
88933 * @param {ASTNode} node node to check.
88934 * @param {string} label label of the break or continue statement
88935 * @returns {boolean} - return whether the node is a finally block or a sentinel node
88936 */
88937
88938
88939 function isInFinallyBlock(node, label) {
88940 let labelInside = false;
88941 let sentinelNodeType;
88942
88943 if (node.type === "BreakStatement" && !node.label) {
88944 sentinelNodeType = SENTINEL_NODE_TYPE_BREAK;
88945 } else if (node.type === "ContinueStatement") {
88946 sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE;
88947 } else {
88948 sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW;
88949 }
88950
88951 for (let currentNode = node; currentNode && !sentinelNodeType.test(currentNode.type); currentNode = currentNode.parent) {
88952 if (currentNode.parent.label && label && currentNode.parent.label.name === label.name) {
88953 labelInside = true;
88954 }
88955
88956 if (isFinallyBlock(currentNode)) {
88957 if (label && labelInside) {
88958 return false;
88959 }
88960
88961 return true;
88962 }
88963 }
88964
88965 return false;
88966 }
88967 /**
88968 * Checks whether the possibly-unsafe statement is inside a finally block.
88969 * @param {ASTNode} node node to check.
88970 * @returns {void}
88971 */
88972
88973
88974 function check(node) {
88975 if (isInFinallyBlock(node, node.label)) {
88976 context.report({
88977 messageId: "unsafeUsage",
88978 data: {
88979 nodeType: node.type
88980 },
88981 node,
88982 line: node.loc.line,
88983 column: node.loc.column
88984 });
88985 }
88986 }
88987
88988 return {
88989 ReturnStatement: check,
88990 ThrowStatement: check,
88991 BreakStatement: check,
88992 ContinueStatement: check
88993 };
88994 }
88995
88996};
88997
88998/***/ }),
6a5a0f88 88999/* 644 */
eb39fafa
DC
89000/***/ (function(module, exports, __webpack_require__) {
89001
89002"use strict";
89003/**
89004 * @fileoverview Rule to disallow negating the left operand of relational operators
89005 * @author Toru Nagashima
89006 */
89007 //------------------------------------------------------------------------------
89008// Requirements
89009//------------------------------------------------------------------------------
89010
89011const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
89012// Helpers
89013//------------------------------------------------------------------------------
89014
89015/**
89016 * Checks whether the given operator is `in` or `instanceof`
89017 * @param {string} op The operator type to check.
89018 * @returns {boolean} `true` if the operator is `in` or `instanceof`
89019 */
89020
89021
89022function isInOrInstanceOfOperator(op) {
89023 return op === "in" || op === "instanceof";
89024}
89025/**
89026 * Checks whether the given operator is an ordering relational operator or not.
89027 * @param {string} op The operator type to check.
89028 * @returns {boolean} `true` if the operator is an ordering relational operator.
89029 */
89030
89031
89032function isOrderingRelationalOperator(op) {
89033 return op === "<" || op === ">" || op === ">=" || op === "<=";
89034}
89035/**
89036 * Checks whether the given node is a logical negation expression or not.
89037 * @param {ASTNode} node The node to check.
89038 * @returns {boolean} `true` if the node is a logical negation expression.
89039 */
89040
89041
89042function isNegation(node) {
89043 return node.type === "UnaryExpression" && node.operator === "!";
89044} //------------------------------------------------------------------------------
89045// Rule Definition
89046//------------------------------------------------------------------------------
89047
89048
89049module.exports = {
89050 meta: {
89051 type: "problem",
89052 docs: {
89053 description: "disallow negating the left operand of relational operators",
89054 category: "Possible Errors",
89055 recommended: true,
89056 url: "https://eslint.org/docs/rules/no-unsafe-negation",
89057 suggestion: true
89058 },
89059 schema: [{
89060 type: "object",
89061 properties: {
89062 enforceForOrderingRelations: {
89063 type: "boolean",
89064 default: false
89065 }
89066 },
89067 additionalProperties: false
89068 }],
89069 fixable: null,
89070 messages: {
89071 unexpected: "Unexpected negating the left operand of '{{operator}}' operator.",
89072 suggestNegatedExpression: "Negate '{{operator}}' expression instead of its left operand. This changes the current behavior.",
89073 suggestParenthesisedNegation: "Wrap negation in '()' to make the intention explicit. This preserves the current behavior."
89074 }
89075 },
89076
89077 create(context) {
89078 const sourceCode = context.getSourceCode();
89079 const options = context.options[0] || {};
89080 const enforceForOrderingRelations = options.enforceForOrderingRelations === true;
89081 return {
89082 BinaryExpression(node) {
89083 const operator = node.operator;
89084 const orderingRelationRuleApplies = enforceForOrderingRelations && isOrderingRelationalOperator(operator);
89085
89086 if ((isInOrInstanceOfOperator(operator) || orderingRelationRuleApplies) && isNegation(node.left) && !astUtils.isParenthesised(sourceCode, node.left)) {
89087 context.report({
89088 node,
89089 loc: node.left.loc,
89090 messageId: "unexpected",
89091 data: {
89092 operator
89093 },
89094 suggest: [{
89095 messageId: "suggestNegatedExpression",
89096 data: {
89097 operator
89098 },
89099
89100 fix(fixer) {
89101 const negationToken = sourceCode.getFirstToken(node.left);
89102 const fixRange = [negationToken.range[1], node.range[1]];
89103 const text = sourceCode.text.slice(fixRange[0], fixRange[1]);
89104 return fixer.replaceTextRange(fixRange, "(".concat(text, ")"));
89105 }
89106
89107 }, {
89108 messageId: "suggestParenthesisedNegation",
89109
89110 fix(fixer) {
89111 return fixer.replaceText(node.left, "(".concat(sourceCode.getText(node.left), ")"));
89112 }
89113
89114 }]
89115 });
89116 }
89117 }
89118
89119 };
89120 }
89121
89122};
89123
89124/***/ }),
6a5a0f88 89125/* 645 */
eb39fafa
DC
89126/***/ (function(module, exports, __webpack_require__) {
89127
89128"use strict";
89129/**
89130 * @fileoverview Flag expressions in statement position that do not side effect
89131 * @author Michael Ficarra
89132 */
89133 //------------------------------------------------------------------------------
89134// Rule Definition
89135//------------------------------------------------------------------------------
89136
89137module.exports = {
89138 meta: {
89139 type: "suggestion",
89140 docs: {
89141 description: "disallow unused expressions",
89142 category: "Best Practices",
89143 recommended: false,
89144 url: "https://eslint.org/docs/rules/no-unused-expressions"
89145 },
89146 schema: [{
89147 type: "object",
89148 properties: {
89149 allowShortCircuit: {
89150 type: "boolean",
89151 default: false
89152 },
89153 allowTernary: {
89154 type: "boolean",
89155 default: false
89156 },
89157 allowTaggedTemplates: {
89158 type: "boolean",
89159 default: false
89160 }
89161 },
89162 additionalProperties: false
89163 }],
89164 messages: {
89165 unusedExpression: "Expected an assignment or function call and instead saw an expression."
89166 }
89167 },
89168
89169 create(context) {
89170 const config = context.options[0] || {},
89171 allowShortCircuit = config.allowShortCircuit || false,
89172 allowTernary = config.allowTernary || false,
89173 allowTaggedTemplates = config.allowTaggedTemplates || false; // eslint-disable-next-line jsdoc/require-description
89174
89175 /**
89176 * @param {ASTNode} node any node
89177 * @returns {boolean} whether the given node structurally represents a directive
89178 */
89179
89180 function looksLikeDirective(node) {
89181 return node.type === "ExpressionStatement" && node.expression.type === "Literal" && typeof node.expression.value === "string";
89182 } // eslint-disable-next-line jsdoc/require-description
89183
89184 /**
89185 * @param {Function} predicate ([a] -> Boolean) the function used to make the determination
89186 * @param {a[]} list the input list
89187 * @returns {a[]} the leading sequence of members in the given list that pass the given predicate
89188 */
89189
89190
89191 function takeWhile(predicate, list) {
89192 for (let i = 0; i < list.length; ++i) {
89193 if (!predicate(list[i])) {
89194 return list.slice(0, i);
89195 }
89196 }
89197
89198 return list.slice();
89199 } // eslint-disable-next-line jsdoc/require-description
89200
89201 /**
89202 * @param {ASTNode} node a Program or BlockStatement node
89203 * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body
89204 */
89205
89206
89207 function directives(node) {
89208 return takeWhile(looksLikeDirective, node.body);
89209 } // eslint-disable-next-line jsdoc/require-description
89210
89211 /**
89212 * @param {ASTNode} node any node
89213 * @param {ASTNode[]} ancestors the given node's ancestors
89214 * @returns {boolean} whether the given node is considered a directive in its current position
89215 */
89216
89217
89218 function isDirective(node, ancestors) {
89219 const parent = ancestors[ancestors.length - 1],
89220 grandparent = ancestors[ancestors.length - 2];
89221 return (parent.type === "Program" || parent.type === "BlockStatement" && /Function/u.test(grandparent.type)) && directives(parent).indexOf(node) >= 0;
89222 }
89223 /**
89224 * Determines whether or not a given node is a valid expression. Recurses on short circuit eval and ternary nodes if enabled by flags.
89225 * @param {ASTNode} node any node
89226 * @returns {boolean} whether the given node is a valid expression
89227 */
89228
89229
89230 function isValidExpression(node) {
89231 if (allowTernary) {
89232 // Recursive check for ternary and logical expressions
89233 if (node.type === "ConditionalExpression") {
89234 return isValidExpression(node.consequent) && isValidExpression(node.alternate);
89235 }
89236 }
89237
89238 if (allowShortCircuit) {
89239 if (node.type === "LogicalExpression") {
89240 return isValidExpression(node.right);
89241 }
89242 }
89243
89244 if (allowTaggedTemplates && node.type === "TaggedTemplateExpression") {
89245 return true;
89246 }
89247
89248 return /^(?:Assignment|Call|New|Update|Yield|Await)Expression$/u.test(node.type) || node.type === "UnaryExpression" && ["delete", "void"].indexOf(node.operator) >= 0;
89249 }
89250
89251 return {
89252 ExpressionStatement(node) {
89253 if (!isValidExpression(node.expression) && !isDirective(node, context.getAncestors())) {
89254 context.report({
89255 node,
89256 messageId: "unusedExpression"
89257 });
89258 }
89259 }
89260
89261 };
89262 }
89263
89264};
89265
89266/***/ }),
6a5a0f88 89267/* 646 */
eb39fafa
DC
89268/***/ (function(module, exports, __webpack_require__) {
89269
89270"use strict";
89271/**
89272 * @fileoverview Rule to disallow unused labels.
89273 * @author Toru Nagashima
89274 */
89275 //------------------------------------------------------------------------------
89276// Rule Definition
89277//------------------------------------------------------------------------------
89278
89279module.exports = {
89280 meta: {
89281 type: "suggestion",
89282 docs: {
89283 description: "disallow unused labels",
89284 category: "Best Practices",
89285 recommended: true,
89286 url: "https://eslint.org/docs/rules/no-unused-labels"
89287 },
89288 schema: [],
89289 fixable: "code",
89290 messages: {
89291 unused: "'{{name}}:' is defined but never used."
89292 }
89293 },
89294
89295 create(context) {
89296 const sourceCode = context.getSourceCode();
89297 let scopeInfo = null;
89298 /**
89299 * Adds a scope info to the stack.
89300 * @param {ASTNode} node A node to add. This is a LabeledStatement.
89301 * @returns {void}
89302 */
89303
89304 function enterLabeledScope(node) {
89305 scopeInfo = {
89306 label: node.label.name,
89307 used: false,
89308 upper: scopeInfo
89309 };
89310 }
89311 /**
89312 * Removes the top of the stack.
89313 * At the same time, this reports the label if it's never used.
89314 * @param {ASTNode} node A node to report. This is a LabeledStatement.
89315 * @returns {void}
89316 */
89317
89318
89319 function exitLabeledScope(node) {
89320 if (!scopeInfo.used) {
89321 context.report({
89322 node: node.label,
89323 messageId: "unused",
89324 data: node.label,
89325
89326 fix(fixer) {
89327 /*
89328 * Only perform a fix if there are no comments between the label and the body. This will be the case
89329 * when there is exactly one token/comment (the ":") between the label and the body.
89330 */
89331 if (sourceCode.getTokenAfter(node.label, {
89332 includeComments: true
89333 }) === sourceCode.getTokenBefore(node.body, {
89334 includeComments: true
89335 })) {
89336 return fixer.removeRange([node.range[0], node.body.range[0]]);
89337 }
89338
89339 return null;
89340 }
89341
89342 });
89343 }
89344
89345 scopeInfo = scopeInfo.upper;
89346 }
89347 /**
89348 * Marks the label of a given node as used.
89349 * @param {ASTNode} node A node to mark. This is a BreakStatement or
89350 * ContinueStatement.
89351 * @returns {void}
89352 */
89353
89354
89355 function markAsUsed(node) {
89356 if (!node.label) {
89357 return;
89358 }
89359
89360 const label = node.label.name;
89361 let info = scopeInfo;
89362
89363 while (info) {
89364 if (info.label === label) {
89365 info.used = true;
89366 break;
89367 }
89368
89369 info = info.upper;
89370 }
89371 }
89372
89373 return {
89374 LabeledStatement: enterLabeledScope,
89375 "LabeledStatement:exit": exitLabeledScope,
89376 BreakStatement: markAsUsed,
89377 ContinueStatement: markAsUsed
89378 };
89379 }
89380
89381};
89382
89383/***/ }),
6a5a0f88 89384/* 647 */
eb39fafa
DC
89385/***/ (function(module, exports, __webpack_require__) {
89386
89387"use strict";
89388/**
89389 * @fileoverview Rule to flag declared but unused variables
89390 * @author Ilya Volodin
89391 */
89392 //------------------------------------------------------------------------------
89393// Requirements
89394//------------------------------------------------------------------------------
89395
89396const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
89397// Typedefs
89398//------------------------------------------------------------------------------
89399
89400/**
89401 * Bag of data used for formatting the `unusedVar` lint message.
89402 * @typedef {Object} UnusedVarMessageData
89403 * @property {string} varName The name of the unused var.
89404 * @property {'defined'|'assigned a value'} action Description of the vars state.
89405 * @property {string} additional Any additional info to be appended at the end.
89406 */
89407//------------------------------------------------------------------------------
89408// Rule Definition
89409//------------------------------------------------------------------------------
89410
89411
89412module.exports = {
89413 meta: {
89414 type: "problem",
89415 docs: {
89416 description: "disallow unused variables",
89417 category: "Variables",
89418 recommended: true,
89419 url: "https://eslint.org/docs/rules/no-unused-vars"
89420 },
89421 schema: [{
89422 oneOf: [{
89423 enum: ["all", "local"]
89424 }, {
89425 type: "object",
89426 properties: {
89427 vars: {
89428 enum: ["all", "local"]
89429 },
89430 varsIgnorePattern: {
89431 type: "string"
89432 },
89433 args: {
89434 enum: ["all", "after-used", "none"]
89435 },
89436 ignoreRestSiblings: {
89437 type: "boolean"
89438 },
89439 argsIgnorePattern: {
89440 type: "string"
89441 },
89442 caughtErrors: {
89443 enum: ["all", "none"]
89444 },
89445 caughtErrorsIgnorePattern: {
89446 type: "string"
89447 }
89448 }
89449 }]
89450 }],
89451 messages: {
89452 unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}."
89453 }
89454 },
89455
89456 create(context) {
89457 const sourceCode = context.getSourceCode();
89458 const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
89459 const config = {
89460 vars: "all",
89461 args: "after-used",
89462 ignoreRestSiblings: false,
89463 caughtErrors: "none"
89464 };
89465 const firstOption = context.options[0];
89466
89467 if (firstOption) {
89468 if (typeof firstOption === "string") {
89469 config.vars = firstOption;
89470 } else {
89471 config.vars = firstOption.vars || config.vars;
89472 config.args = firstOption.args || config.args;
89473 config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings;
89474 config.caughtErrors = firstOption.caughtErrors || config.caughtErrors;
89475
89476 if (firstOption.varsIgnorePattern) {
89477 config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u");
89478 }
89479
89480 if (firstOption.argsIgnorePattern) {
89481 config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u");
89482 }
89483
89484 if (firstOption.caughtErrorsIgnorePattern) {
89485 config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u");
89486 }
89487 }
89488 }
89489 /**
89490 * Generates the message data about the variable being defined and unused,
89491 * including the ignore pattern if configured.
89492 * @param {Variable} unusedVar eslint-scope variable object.
89493 * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
89494 */
89495
89496
89497 function getDefinedMessageData(unusedVar) {
89498 const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type;
89499 let type;
89500 let pattern;
89501
89502 if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) {
89503 type = "args";
89504 pattern = config.caughtErrorsIgnorePattern.toString();
89505 } else if (defType === "Parameter" && config.argsIgnorePattern) {
89506 type = "args";
89507 pattern = config.argsIgnorePattern.toString();
89508 } else if (defType !== "Parameter" && config.varsIgnorePattern) {
89509 type = "vars";
89510 pattern = config.varsIgnorePattern.toString();
89511 }
89512
89513 const additional = type ? ". Allowed unused ".concat(type, " must match ").concat(pattern) : "";
89514 return {
89515 varName: unusedVar.name,
89516 action: "defined",
89517 additional
89518 };
89519 }
89520 /**
89521 * Generate the warning message about the variable being
89522 * assigned and unused, including the ignore pattern if configured.
89523 * @param {Variable} unusedVar eslint-scope variable object.
89524 * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
89525 */
89526
89527
89528 function getAssignedMessageData(unusedVar) {
89529 const additional = config.varsIgnorePattern ? ". Allowed unused vars must match ".concat(config.varsIgnorePattern.toString()) : "";
89530 return {
89531 varName: unusedVar.name,
89532 action: "assigned a value",
89533 additional
89534 };
89535 } //--------------------------------------------------------------------------
89536 // Helpers
89537 //--------------------------------------------------------------------------
89538
89539
89540 const STATEMENT_TYPE = /(?:Statement|Declaration)$/u;
89541 /**
89542 * Determines if a given variable is being exported from a module.
89543 * @param {Variable} variable eslint-scope variable object.
89544 * @returns {boolean} True if the variable is exported, false if not.
89545 * @private
89546 */
89547
89548 function isExported(variable) {
89549 const definition = variable.defs[0];
89550
89551 if (definition) {
89552 let node = definition.node;
89553
89554 if (node.type === "VariableDeclarator") {
89555 node = node.parent;
89556 } else if (definition.type === "Parameter") {
89557 return false;
89558 }
89559
89560 return node.parent.type.indexOf("Export") === 0;
89561 }
89562
89563 return false;
89564 }
89565 /**
89566 * Determines if a variable has a sibling rest property
89567 * @param {Variable} variable eslint-scope variable object.
89568 * @returns {boolean} True if the variable is exported, false if not.
89569 * @private
89570 */
89571
89572
89573 function hasRestSpreadSibling(variable) {
89574 if (config.ignoreRestSiblings) {
89575 return variable.defs.some(def => {
89576 const propertyNode = def.name.parent;
89577 const patternNode = propertyNode.parent;
89578 return propertyNode.type === "Property" && patternNode.type === "ObjectPattern" && REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type);
89579 });
89580 }
89581
89582 return false;
89583 }
89584 /**
89585 * Determines if a reference is a read operation.
89586 * @param {Reference} ref An eslint-scope Reference
89587 * @returns {boolean} whether the given reference represents a read operation
89588 * @private
89589 */
89590
89591
89592 function isReadRef(ref) {
89593 return ref.isRead();
89594 }
89595 /**
89596 * Determine if an identifier is referencing an enclosing function name.
89597 * @param {Reference} ref The reference to check.
89598 * @param {ASTNode[]} nodes The candidate function nodes.
89599 * @returns {boolean} True if it's a self-reference, false if not.
89600 * @private
89601 */
89602
89603
89604 function isSelfReference(ref, nodes) {
89605 let scope = ref.from;
89606
89607 while (scope) {
89608 if (nodes.indexOf(scope.block) >= 0) {
89609 return true;
89610 }
89611
89612 scope = scope.upper;
89613 }
89614
89615 return false;
89616 }
89617 /**
89618 * Gets a list of function definitions for a specified variable.
89619 * @param {Variable} variable eslint-scope variable object.
89620 * @returns {ASTNode[]} Function nodes.
89621 * @private
89622 */
89623
89624
89625 function getFunctionDefinitions(variable) {
89626 const functionDefinitions = [];
89627 variable.defs.forEach(def => {
89628 const {
89629 type,
89630 node
89631 } = def; // FunctionDeclarations
89632
89633 if (type === "FunctionName") {
89634 functionDefinitions.push(node);
89635 } // FunctionExpressions
89636
89637
89638 if (type === "Variable" && node.init && (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
89639 functionDefinitions.push(node.init);
89640 }
89641 });
89642 return functionDefinitions;
89643 }
89644 /**
89645 * Checks the position of given nodes.
89646 * @param {ASTNode} inner A node which is expected as inside.
89647 * @param {ASTNode} outer A node which is expected as outside.
89648 * @returns {boolean} `true` if the `inner` node exists in the `outer` node.
89649 * @private
89650 */
89651
89652
89653 function isInside(inner, outer) {
89654 return inner.range[0] >= outer.range[0] && inner.range[1] <= outer.range[1];
89655 }
89656 /**
89657 * If a given reference is left-hand side of an assignment, this gets
89658 * the right-hand side node of the assignment.
89659 *
89660 * In the following cases, this returns null.
89661 *
89662 * - The reference is not the LHS of an assignment expression.
89663 * - The reference is inside of a loop.
89664 * - The reference is inside of a function scope which is different from
89665 * the declaration.
89666 * @param {eslint-scope.Reference} ref A reference to check.
89667 * @param {ASTNode} prevRhsNode The previous RHS node.
89668 * @returns {ASTNode|null} The RHS node or null.
89669 * @private
89670 */
89671
89672
89673 function getRhsNode(ref, prevRhsNode) {
89674 const id = ref.identifier;
89675 const parent = id.parent;
89676 const grandparent = parent.parent;
89677 const refScope = ref.from.variableScope;
89678 const varScope = ref.resolved.scope.variableScope;
89679 const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
89680 /*
89681 * Inherits the previous node if this reference is in the node.
89682 * This is for `a = a + a`-like code.
89683 */
89684
89685 if (prevRhsNode && isInside(id, prevRhsNode)) {
89686 return prevRhsNode;
89687 }
89688
89689 if (parent.type === "AssignmentExpression" && grandparent.type === "ExpressionStatement" && id === parent.left && !canBeUsedLater) {
89690 return parent.right;
89691 }
89692
89693 return null;
89694 }
89695 /**
89696 * Checks whether a given function node is stored to somewhere or not.
89697 * If the function node is stored, the function can be used later.
89698 * @param {ASTNode} funcNode A function node to check.
89699 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
89700 * @returns {boolean} `true` if under the following conditions:
89701 * - the funcNode is assigned to a variable.
89702 * - the funcNode is bound as an argument of a function call.
89703 * - the function is bound to a property and the object satisfies above conditions.
89704 * @private
89705 */
89706
89707
89708 function isStorableFunction(funcNode, rhsNode) {
89709 let node = funcNode;
89710 let parent = funcNode.parent;
89711
89712 while (parent && isInside(parent, rhsNode)) {
89713 switch (parent.type) {
89714 case "SequenceExpression":
89715 if (parent.expressions[parent.expressions.length - 1] !== node) {
89716 return false;
89717 }
89718
89719 break;
89720
89721 case "CallExpression":
89722 case "NewExpression":
89723 return parent.callee !== node;
89724
89725 case "AssignmentExpression":
89726 case "TaggedTemplateExpression":
89727 case "YieldExpression":
89728 return true;
89729
89730 default:
89731 if (STATEMENT_TYPE.test(parent.type)) {
89732 /*
89733 * If it encountered statements, this is a complex pattern.
89734 * Since analyzing complex patterns is hard, this returns `true` to avoid false positive.
89735 */
89736 return true;
89737 }
89738
89739 }
89740
89741 node = parent;
89742 parent = parent.parent;
89743 }
89744
89745 return false;
89746 }
89747 /**
89748 * Checks whether a given Identifier node exists inside of a function node which can be used later.
89749 *
89750 * "can be used later" means:
89751 * - the function is assigned to a variable.
89752 * - the function is bound to a property and the object can be used later.
89753 * - the function is bound as an argument of a function call.
89754 *
89755 * If a reference exists in a function which can be used later, the reference is read when the function is called.
89756 * @param {ASTNode} id An Identifier node to check.
89757 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
89758 * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later.
89759 * @private
89760 */
89761
89762
89763 function isInsideOfStorableFunction(id, rhsNode) {
89764 const funcNode = astUtils.getUpperFunction(id);
89765 return funcNode && isInside(funcNode, rhsNode) && isStorableFunction(funcNode, rhsNode);
89766 }
89767 /**
89768 * Checks whether a given reference is a read to update itself or not.
89769 * @param {eslint-scope.Reference} ref A reference to check.
89770 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
89771 * @returns {boolean} The reference is a read to update itself.
89772 * @private
89773 */
89774
89775
89776 function isReadForItself(ref, rhsNode) {
89777 const id = ref.identifier;
89778 const parent = id.parent;
89779 const grandparent = parent.parent;
89780 return ref.isRead() && ( // self update. e.g. `a += 1`, `a++`
89781 // in RHS of an assignment for itself. e.g. `a = a + 1`
89782 parent.type === "AssignmentExpression" && grandparent.type === "ExpressionStatement" && parent.left === id || parent.type === "UpdateExpression" && grandparent.type === "ExpressionStatement" || rhsNode && isInside(id, rhsNode) && !isInsideOfStorableFunction(id, rhsNode));
89783 }
89784 /**
89785 * Determine if an identifier is used either in for-in loops.
89786 * @param {Reference} ref The reference to check.
89787 * @returns {boolean} whether reference is used in the for-in loops
89788 * @private
89789 */
89790
89791
89792 function isForInRef(ref) {
89793 let target = ref.identifier.parent; // "for (var ...) { return; }"
89794
89795 if (target.type === "VariableDeclarator") {
89796 target = target.parent.parent;
89797 }
89798
89799 if (target.type !== "ForInStatement") {
89800 return false;
89801 } // "for (...) { return; }"
89802
89803
89804 if (target.body.type === "BlockStatement") {
89805 target = target.body.body[0]; // "for (...) return;"
89806 } else {
89807 target = target.body;
89808 } // For empty loop body
89809
89810
89811 if (!target) {
89812 return false;
89813 }
89814
89815 return target.type === "ReturnStatement";
89816 }
89817 /**
89818 * Determines if the variable is used.
89819 * @param {Variable} variable The variable to check.
89820 * @returns {boolean} True if the variable is used
89821 * @private
89822 */
89823
89824
89825 function isUsedVariable(variable) {
89826 const functionNodes = getFunctionDefinitions(variable),
89827 isFunctionDefinition = functionNodes.length > 0;
89828 let rhsNode = null;
89829 return variable.references.some(ref => {
89830 if (isForInRef(ref)) {
89831 return true;
89832 }
89833
89834 const forItself = isReadForItself(ref, rhsNode);
89835 rhsNode = getRhsNode(ref, rhsNode);
89836 return isReadRef(ref) && !forItself && !(isFunctionDefinition && isSelfReference(ref, functionNodes));
89837 });
89838 }
89839 /**
89840 * Checks whether the given variable is after the last used parameter.
89841 * @param {eslint-scope.Variable} variable The variable to check.
89842 * @returns {boolean} `true` if the variable is defined after the last
89843 * used parameter.
89844 */
89845
89846
89847 function isAfterLastUsedArg(variable) {
89848 const def = variable.defs[0];
89849 const params = context.getDeclaredVariables(def.node);
89850 const posteriorParams = params.slice(params.indexOf(variable) + 1); // If any used parameters occur after this parameter, do not report.
89851
89852 return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
89853 }
89854 /**
89855 * Gets an array of variables without read references.
89856 * @param {Scope} scope an eslint-scope Scope object.
89857 * @param {Variable[]} unusedVars an array that saving result.
89858 * @returns {Variable[]} unused variables of the scope and descendant scopes.
89859 * @private
89860 */
89861
89862
89863 function collectUnusedVariables(scope, unusedVars) {
89864 const variables = scope.variables;
89865 const childScopes = scope.childScopes;
89866 let i, l;
89867
89868 if (scope.type !== "global" || config.vars === "all") {
89869 for (i = 0, l = variables.length; i < l; ++i) {
89870 const variable = variables[i]; // skip a variable of class itself name in the class scope
89871
89872 if (scope.type === "class" && scope.block.id === variable.identifiers[0]) {
89873 continue;
89874 } // skip function expression names and variables marked with markVariableAsUsed()
89875
89876
89877 if (scope.functionExpressionScope || variable.eslintUsed) {
89878 continue;
89879 } // skip implicit "arguments" variable
89880
89881
89882 if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) {
89883 continue;
89884 } // explicit global variables don't have definitions.
89885
89886
89887 const def = variable.defs[0];
89888
89889 if (def) {
89890 const type = def.type; // skip catch variables
89891
89892 if (type === "CatchClause") {
89893 if (config.caughtErrors === "none") {
89894 continue;
89895 } // skip ignored parameters
89896
89897
89898 if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) {
89899 continue;
89900 }
89901 }
89902
89903 if (type === "Parameter") {
89904 // skip any setter argument
89905 if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") {
89906 continue;
89907 } // if "args" option is "none", skip any parameter
89908
89909
89910 if (config.args === "none") {
89911 continue;
89912 } // skip ignored parameters
89913
89914
89915 if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) {
89916 continue;
89917 } // if "args" option is "after-used", skip used variables
89918
89919
89920 if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) {
89921 continue;
89922 }
89923 } else {
89924 // skip ignored variables
89925 if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) {
89926 continue;
89927 }
89928 }
89929 }
89930
89931 if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) {
89932 unusedVars.push(variable);
89933 }
89934 }
89935 }
89936
89937 for (i = 0, l = childScopes.length; i < l; ++i) {
89938 collectUnusedVariables(childScopes[i], unusedVars);
89939 }
89940
89941 return unusedVars;
89942 } //--------------------------------------------------------------------------
89943 // Public
89944 //--------------------------------------------------------------------------
89945
89946
89947 return {
89948 "Program:exit"(programNode) {
89949 const unusedVars = collectUnusedVariables(context.getScope(), []);
89950
89951 for (let i = 0, l = unusedVars.length; i < l; ++i) {
89952 const unusedVar = unusedVars[i]; // Report the first declaration.
89953
89954 if (unusedVar.defs.length > 0) {
89955 context.report({
89956 node: unusedVar.identifiers[0],
89957 messageId: "unusedVar",
89958 data: unusedVar.references.some(ref => ref.isWrite()) ? getAssignedMessageData(unusedVar) : getDefinedMessageData(unusedVar)
89959 }); // If there are no regular declaration, report the first `/*globals*/` comment directive.
89960 } else if (unusedVar.eslintExplicitGlobalComments) {
89961 const directiveComment = unusedVar.eslintExplicitGlobalComments[0];
89962 context.report({
89963 node: programNode,
89964 loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name),
89965 messageId: "unusedVar",
89966 data: getDefinedMessageData(unusedVar)
89967 });
89968 }
89969 }
89970 }
89971
89972 };
89973 }
89974
89975};
89976
89977/***/ }),
6a5a0f88 89978/* 648 */
eb39fafa
DC
89979/***/ (function(module, exports, __webpack_require__) {
89980
89981"use strict";
89982/**
89983 * @fileoverview Rule to flag use of variables before they are defined
89984 * @author Ilya Volodin
89985 */
89986 //------------------------------------------------------------------------------
89987// Helpers
89988//------------------------------------------------------------------------------
89989
89990const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u;
89991const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u;
89992/**
89993 * Parses a given value as options.
89994 * @param {any} options A value to parse.
89995 * @returns {Object} The parsed options.
89996 */
89997
89998function parseOptions(options) {
89999 let functions = true;
90000 let classes = true;
90001 let variables = true;
90002
90003 if (typeof options === "string") {
90004 functions = options !== "nofunc";
90005 } else if (typeof options === "object" && options !== null) {
90006 functions = options.functions !== false;
90007 classes = options.classes !== false;
90008 variables = options.variables !== false;
90009 }
90010
90011 return {
90012 functions,
90013 classes,
90014 variables
90015 };
90016}
90017/**
90018 * Checks whether or not a given variable is a function declaration.
90019 * @param {eslint-scope.Variable} variable A variable to check.
90020 * @returns {boolean} `true` if the variable is a function declaration.
90021 */
90022
90023
90024function isFunction(variable) {
90025 return variable.defs[0].type === "FunctionName";
90026}
90027/**
90028 * Checks whether or not a given variable is a class declaration in an upper function scope.
90029 * @param {eslint-scope.Variable} variable A variable to check.
90030 * @param {eslint-scope.Reference} reference A reference to check.
90031 * @returns {boolean} `true` if the variable is a class declaration.
90032 */
90033
90034
90035function isOuterClass(variable, reference) {
90036 return variable.defs[0].type === "ClassName" && variable.scope.variableScope !== reference.from.variableScope;
90037}
90038/**
90039 * Checks whether or not a given variable is a variable declaration in an upper function scope.
90040 * @param {eslint-scope.Variable} variable A variable to check.
90041 * @param {eslint-scope.Reference} reference A reference to check.
90042 * @returns {boolean} `true` if the variable is a variable declaration.
90043 */
90044
90045
90046function isOuterVariable(variable, reference) {
90047 return variable.defs[0].type === "Variable" && variable.scope.variableScope !== reference.from.variableScope;
90048}
90049/**
90050 * Checks whether or not a given location is inside of the range of a given node.
90051 * @param {ASTNode} node An node to check.
90052 * @param {number} location A location to check.
90053 * @returns {boolean} `true` if the location is inside of the range of the node.
90054 */
90055
90056
90057function isInRange(node, location) {
90058 return node && node.range[0] <= location && location <= node.range[1];
90059}
90060/**
90061 * Checks whether or not a given reference is inside of the initializers of a given variable.
90062 *
90063 * This returns `true` in the following cases:
90064 *
90065 * var a = a
90066 * var [a = a] = list
90067 * var {a = a} = obj
90068 * for (var a in a) {}
90069 * for (var a of a) {}
90070 * @param {Variable} variable A variable to check.
90071 * @param {Reference} reference A reference to check.
90072 * @returns {boolean} `true` if the reference is inside of the initializers.
90073 */
90074
90075
90076function isInInitializer(variable, reference) {
90077 if (variable.scope !== reference.from) {
90078 return false;
90079 }
90080
90081 let node = variable.identifiers[0].parent;
90082 const location = reference.identifier.range[1];
90083
90084 while (node) {
90085 if (node.type === "VariableDeclarator") {
90086 if (isInRange(node.init, location)) {
90087 return true;
90088 }
90089
90090 if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && isInRange(node.parent.parent.right, location)) {
90091 return true;
90092 }
90093
90094 break;
90095 } else if (node.type === "AssignmentPattern") {
90096 if (isInRange(node.right, location)) {
90097 return true;
90098 }
90099 } else if (SENTINEL_TYPE.test(node.type)) {
90100 break;
90101 }
90102
90103 node = node.parent;
90104 }
90105
90106 return false;
90107} //------------------------------------------------------------------------------
90108// Rule Definition
90109//------------------------------------------------------------------------------
90110
90111
90112module.exports = {
90113 meta: {
90114 type: "problem",
90115 docs: {
90116 description: "disallow the use of variables before they are defined",
90117 category: "Variables",
90118 recommended: false,
90119 url: "https://eslint.org/docs/rules/no-use-before-define"
90120 },
90121 schema: [{
90122 oneOf: [{
90123 enum: ["nofunc"]
90124 }, {
90125 type: "object",
90126 properties: {
90127 functions: {
90128 type: "boolean"
90129 },
90130 classes: {
90131 type: "boolean"
90132 },
90133 variables: {
90134 type: "boolean"
90135 }
90136 },
90137 additionalProperties: false
90138 }]
90139 }],
90140 messages: {
90141 usedBeforeDefined: "'{{name}}' was used before it was defined."
90142 }
90143 },
90144
90145 create(context) {
90146 const options = parseOptions(context.options[0]);
90147 /**
90148 * Determines whether a given use-before-define case should be reported according to the options.
90149 * @param {eslint-scope.Variable} variable The variable that gets used before being defined
90150 * @param {eslint-scope.Reference} reference The reference to the variable
90151 * @returns {boolean} `true` if the usage should be reported
90152 */
90153
90154 function isForbidden(variable, reference) {
90155 if (isFunction(variable)) {
90156 return options.functions;
90157 }
90158
90159 if (isOuterClass(variable, reference)) {
90160 return options.classes;
90161 }
90162
90163 if (isOuterVariable(variable, reference)) {
90164 return options.variables;
90165 }
90166
90167 return true;
90168 }
90169 /**
90170 * Finds and validates all variables in a given scope.
90171 * @param {Scope} scope The scope object.
90172 * @returns {void}
90173 * @private
90174 */
90175
90176
90177 function findVariablesInScope(scope) {
90178 scope.references.forEach(reference => {
90179 const variable = reference.resolved;
90180 /*
90181 * Skips when the reference is:
90182 * - initialization's.
90183 * - referring to an undefined variable.
90184 * - referring to a global environment variable (there're no identifiers).
90185 * - located preceded by the variable (except in initializers).
90186 * - allowed by options.
90187 */
90188
90189 if (reference.init || !variable || variable.identifiers.length === 0 || variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference) || !isForbidden(variable, reference)) {
90190 return;
90191 } // Reports.
90192
90193
90194 context.report({
90195 node: reference.identifier,
90196 messageId: "usedBeforeDefined",
90197 data: reference.identifier
90198 });
90199 });
90200 scope.childScopes.forEach(findVariablesInScope);
90201 }
90202
90203 return {
90204 Program() {
90205 findVariablesInScope(context.getScope());
90206 }
90207
90208 };
90209 }
90210
90211};
90212
90213/***/ }),
6a5a0f88 90214/* 649 */
eb39fafa
DC
90215/***/ (function(module, exports, __webpack_require__) {
90216
90217"use strict";
90218/**
90219 * @fileoverview Rule to disallow useless backreferences in regular expressions
90220 * @author Milos Djermanovic
90221 */
90222 //------------------------------------------------------------------------------
90223// Requirements
90224//------------------------------------------------------------------------------
90225
90226const {
90227 CALL,
90228 CONSTRUCT,
90229 ReferenceTracker,
90230 getStringIfConstant
90231} = __webpack_require__(549);
90232
90233const {
90234 RegExpParser,
90235 visitRegExpAST
90236} = __webpack_require__(527);
90237
90238const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
90239// Helpers
90240//------------------------------------------------------------------------------
90241
90242
90243const parser = new RegExpParser();
90244/**
90245 * Finds the path from the given `regexpp` AST node to the root node.
90246 * @param {regexpp.Node} node Node.
90247 * @returns {regexpp.Node[]} Array that starts with the given node and ends with the root node.
90248 */
90249
90250function getPathToRoot(node) {
90251 const path = [];
90252 let current = node;
90253
90254 do {
90255 path.push(current);
90256 current = current.parent;
90257 } while (current);
90258
90259 return path;
90260}
90261/**
90262 * Determines whether the given `regexpp` AST node is a lookaround node.
90263 * @param {regexpp.Node} node Node.
90264 * @returns {boolean} `true` if it is a lookaround node.
90265 */
90266
90267
90268function isLookaround(node) {
90269 return node.type === "Assertion" && (node.kind === "lookahead" || node.kind === "lookbehind");
90270}
90271/**
90272 * Determines whether the given `regexpp` AST node is a negative lookaround node.
90273 * @param {regexpp.Node} node Node.
90274 * @returns {boolean} `true` if it is a negative lookaround node.
90275 */
90276
90277
90278function isNegativeLookaround(node) {
90279 return isLookaround(node) && node.negate;
90280} //------------------------------------------------------------------------------
90281// Rule Definition
90282//------------------------------------------------------------------------------
90283
90284
90285module.exports = {
90286 meta: {
90287 type: "problem",
90288 docs: {
90289 description: "disallow useless backreferences in regular expressions",
90290 category: "Possible Errors",
90291 recommended: false,
90292 url: "https://eslint.org/docs/rules/no-useless-backreference"
90293 },
90294 schema: [],
90295 messages: {
90296 nested: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' from within that group.",
90297 forward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears later in the pattern.",
90298 backward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears before in the same lookbehind.",
90299 disjunctive: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in another alternative.",
90300 intoNegativeLookaround: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in a negative lookaround."
90301 }
90302 },
90303
90304 create(context) {
90305 /**
90306 * Checks and reports useless backreferences in the given regular expression.
90307 * @param {ASTNode} node Node that represents regular expression. A regex literal or RegExp constructor call.
90308 * @param {string} pattern Regular expression pattern.
90309 * @param {string} flags Regular expression flags.
90310 * @returns {void}
90311 */
90312 function checkRegex(node, pattern, flags) {
90313 let regExpAST;
90314
90315 try {
90316 regExpAST = parser.parsePattern(pattern, 0, pattern.length, flags.includes("u"));
90317 } catch (e) {
90318 // Ignore regular expressions with syntax errors
90319 return;
90320 }
90321
90322 visitRegExpAST(regExpAST, {
90323 onBackreferenceEnter(bref) {
90324 const group = bref.resolved,
90325 brefPath = getPathToRoot(bref),
90326 groupPath = getPathToRoot(group);
90327 let messageId = null;
90328
90329 if (brefPath.includes(group)) {
90330 // group is bref's ancestor => bref is nested ('nested reference') => group hasn't matched yet when bref starts to match.
90331 messageId = "nested";
90332 } else {
90333 // Start from the root to find the lowest common ancestor.
90334 let i = brefPath.length - 1,
90335 j = groupPath.length - 1;
90336
90337 do {
90338 i--;
90339 j--;
90340 } while (brefPath[i] === groupPath[j]);
90341
90342 const indexOfLowestCommonAncestor = j + 1,
90343 groupCut = groupPath.slice(0, indexOfLowestCommonAncestor),
90344 commonPath = groupPath.slice(indexOfLowestCommonAncestor),
90345 lowestCommonLookaround = commonPath.find(isLookaround),
90346 isMatchingBackward = lowestCommonLookaround && lowestCommonLookaround.kind === "lookbehind";
90347
90348 if (!isMatchingBackward && bref.end <= group.start) {
90349 // bref is left, group is right ('forward reference') => group hasn't matched yet when bref starts to match.
90350 messageId = "forward";
90351 } else if (isMatchingBackward && group.end <= bref.start) {
90352 // the opposite of the previous when the regex is matching backward in a lookbehind context.
90353 messageId = "backward";
90354 } else if (lodash.last(groupCut).type === "Alternative") {
90355 // group's and bref's ancestor nodes below the lowest common ancestor are sibling alternatives => they're disjunctive.
90356 messageId = "disjunctive";
90357 } else if (groupCut.some(isNegativeLookaround)) {
90358 // group is in a negative lookaround which isn't bref's ancestor => group has already failed when bref starts to match.
90359 messageId = "intoNegativeLookaround";
90360 }
90361 }
90362
90363 if (messageId) {
90364 context.report({
90365 node,
90366 messageId,
90367 data: {
90368 bref: bref.raw,
90369 group: group.raw
90370 }
90371 });
90372 }
90373 }
90374
90375 });
90376 }
90377
90378 return {
90379 "Literal[regex]"(node) {
90380 const {
90381 pattern,
90382 flags
90383 } = node.regex;
90384 checkRegex(node, pattern, flags);
90385 },
90386
90387 Program() {
90388 const scope = context.getScope(),
90389 tracker = new ReferenceTracker(scope),
90390 traceMap = {
90391 RegExp: {
90392 [CALL]: true,
90393 [CONSTRUCT]: true
90394 }
90395 };
90396
90397 for (const {
90398 node
90399 } of tracker.iterateGlobalReferences(traceMap)) {
90400 const [patternNode, flagsNode] = node.arguments,
90401 pattern = getStringIfConstant(patternNode, scope),
90402 flags = getStringIfConstant(flagsNode, scope);
90403
90404 if (typeof pattern === "string") {
90405 checkRegex(node, pattern, flags || "");
90406 }
90407 }
90408 }
90409
90410 };
90411 }
90412
90413};
90414
90415/***/ }),
6a5a0f88 90416/* 650 */
eb39fafa
DC
90417/***/ (function(module, exports, __webpack_require__) {
90418
90419"use strict";
90420/**
90421 * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`.
90422 * @author Toru Nagashima
90423 */
90424
90425
90426const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
90427// Helpers
90428//------------------------------------------------------------------------------
90429
90430/**
90431 * Checks whether or not a node is a `.call()`/`.apply()`.
90432 * @param {ASTNode} node A CallExpression node to check.
90433 * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`.
90434 */
90435
90436
90437function isCallOrNonVariadicApply(node) {
90438 return node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier" && node.callee.computed === false && (node.callee.property.name === "call" && node.arguments.length >= 1 || node.callee.property.name === "apply" && node.arguments.length === 2 && node.arguments[1].type === "ArrayExpression");
90439}
90440/**
90441 * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`.
90442 * @param {ASTNode|null} expectedThis The node that is the owner of the applied function.
90443 * @param {ASTNode} thisArg The node that is given to the first argument of the `.call()`/`.apply()`.
90444 * @param {SourceCode} sourceCode The ESLint source code object.
90445 * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`.
90446 */
90447
90448
90449function isValidThisArg(expectedThis, thisArg, sourceCode) {
90450 if (!expectedThis) {
90451 return astUtils.isNullOrUndefined(thisArg);
90452 }
90453
90454 return astUtils.equalTokens(expectedThis, thisArg, sourceCode);
90455} //------------------------------------------------------------------------------
90456// Rule Definition
90457//------------------------------------------------------------------------------
90458
90459
90460module.exports = {
90461 meta: {
90462 type: "suggestion",
90463 docs: {
90464 description: "disallow unnecessary calls to `.call()` and `.apply()`",
90465 category: "Best Practices",
90466 recommended: false,
90467 url: "https://eslint.org/docs/rules/no-useless-call"
90468 },
90469 schema: [],
90470 messages: {
90471 unnecessaryCall: "Unnecessary '.{{name}}()'."
90472 }
90473 },
90474
90475 create(context) {
90476 const sourceCode = context.getSourceCode();
90477 return {
90478 CallExpression(node) {
90479 if (!isCallOrNonVariadicApply(node)) {
90480 return;
90481 }
90482
90483 const applied = node.callee.object;
90484 const expectedThis = applied.type === "MemberExpression" ? applied.object : null;
90485 const thisArg = node.arguments[0];
90486
90487 if (isValidThisArg(expectedThis, thisArg, sourceCode)) {
90488 context.report({
90489 node,
90490 messageId: "unnecessaryCall",
90491 data: {
90492 name: node.callee.property.name
90493 }
90494 });
90495 }
90496 }
90497
90498 };
90499 }
90500
90501};
90502
90503/***/ }),
6a5a0f88 90504/* 651 */
eb39fafa
DC
90505/***/ (function(module, exports, __webpack_require__) {
90506
90507"use strict";
90508/**
90509 * @fileoverview Reports useless `catch` clauses that just rethrow their error.
90510 * @author Teddy Katz
90511 */
90512 //------------------------------------------------------------------------------
90513// Rule Definition
90514//------------------------------------------------------------------------------
90515
90516module.exports = {
90517 meta: {
90518 type: "suggestion",
90519 docs: {
90520 description: "disallow unnecessary `catch` clauses",
90521 category: "Best Practices",
90522 recommended: true,
90523 url: "https://eslint.org/docs/rules/no-useless-catch"
90524 },
90525 schema: [],
90526 messages: {
90527 unnecessaryCatchClause: "Unnecessary catch clause.",
90528 unnecessaryCatch: "Unnecessary try/catch wrapper."
90529 }
90530 },
90531
90532 create(context) {
90533 return {
90534 CatchClause(node) {
90535 if (node.param && node.param.type === "Identifier" && node.body.body.length && node.body.body[0].type === "ThrowStatement" && node.body.body[0].argument.type === "Identifier" && node.body.body[0].argument.name === node.param.name) {
90536 if (node.parent.finalizer) {
90537 context.report({
90538 node,
90539 messageId: "unnecessaryCatchClause"
90540 });
90541 } else {
90542 context.report({
90543 node: node.parent,
90544 messageId: "unnecessaryCatch"
90545 });
90546 }
90547 }
90548 }
90549
90550 };
90551 }
90552
90553};
90554
90555/***/ }),
6a5a0f88 90556/* 652 */
eb39fafa
DC
90557/***/ (function(module, exports, __webpack_require__) {
90558
90559"use strict";
90560/**
90561 * @fileoverview Rule to disallow unnecessary computed property keys in object literals
90562 * @author Burak Yigit Kaya
90563 */
90564 //------------------------------------------------------------------------------
90565// Requirements
90566//------------------------------------------------------------------------------
90567
90568const lodash = __webpack_require__(403);
90569
90570const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
90571// Rule Definition
90572//------------------------------------------------------------------------------
90573
90574
90575module.exports = {
90576 meta: {
90577 type: "suggestion",
90578 docs: {
90579 description: "disallow unnecessary computed property keys in objects and classes",
90580 category: "ECMAScript 6",
90581 recommended: false,
90582 url: "https://eslint.org/docs/rules/no-useless-computed-key"
90583 },
90584 schema: [{
90585 type: "object",
90586 properties: {
90587 enforceForClassMembers: {
90588 type: "boolean",
90589 default: false
90590 }
90591 },
90592 additionalProperties: false
90593 }],
90594 fixable: "code",
90595 messages: {
90596 unnecessarilyComputedProperty: "Unnecessarily computed property [{{property}}] found."
90597 }
90598 },
90599
90600 create(context) {
90601 const sourceCode = context.getSourceCode();
90602 const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers;
90603 /**
90604 * Reports a given node if it violated this rule.
90605 * @param {ASTNode} node The node to check.
90606 * @returns {void}
90607 */
90608
90609 function check(node) {
90610 if (!node.computed) {
90611 return;
90612 }
90613
90614 const key = node.key,
90615 nodeType = typeof key.value;
90616 let allowedKey;
90617
90618 if (node.type === "MethodDefinition") {
90619 allowedKey = node.static ? "prototype" : "constructor";
90620 } else {
90621 allowedKey = "__proto__";
90622 }
90623
90624 if (key.type === "Literal" && (nodeType === "string" || nodeType === "number") && key.value !== allowedKey) {
90625 context.report({
90626 node,
90627 messageId: "unnecessarilyComputedProperty",
90628 data: {
90629 property: sourceCode.getText(key)
90630 },
90631
90632 fix(fixer) {
90633 const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken);
90634 const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken); // If there are comments between the brackets and the property name, don't do a fix.
90635
90636 if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) {
90637 return null;
90638 }
90639
90640 const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket); // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
90641
90642 const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] && !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key));
90643 const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw;
90644 return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey);
90645 }
90646
90647 });
90648 }
90649 }
90650
90651 return {
90652 Property: check,
90653 MethodDefinition: enforceForClassMembers ? check : lodash.noop
90654 };
90655 }
90656
90657};
90658
90659/***/ }),
6a5a0f88 90660/* 653 */
eb39fafa
DC
90661/***/ (function(module, exports, __webpack_require__) {
90662
90663"use strict";
90664/**
90665 * @fileoverview disallow unnecessary concatenation of template strings
90666 * @author Henry Zhu
90667 */
90668 //------------------------------------------------------------------------------
90669// Requirements
90670//------------------------------------------------------------------------------
90671
90672const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
90673// Helpers
90674//------------------------------------------------------------------------------
90675
90676/**
90677 * Checks whether or not a given node is a concatenation.
90678 * @param {ASTNode} node A node to check.
90679 * @returns {boolean} `true` if the node is a concatenation.
90680 */
90681
90682
90683function isConcatenation(node) {
90684 return node.type === "BinaryExpression" && node.operator === "+";
90685}
90686/**
90687 * Checks if the given token is a `+` token or not.
90688 * @param {Token} token The token to check.
90689 * @returns {boolean} `true` if the token is a `+` token.
90690 */
90691
90692
90693function isConcatOperatorToken(token) {
90694 return token.value === "+" && token.type === "Punctuator";
90695}
90696/**
90697 * Get's the right most node on the left side of a BinaryExpression with + operator.
90698 * @param {ASTNode} node A BinaryExpression node to check.
90699 * @returns {ASTNode} node
90700 */
90701
90702
90703function getLeft(node) {
90704 let left = node.left;
90705
90706 while (isConcatenation(left)) {
90707 left = left.right;
90708 }
90709
90710 return left;
90711}
90712/**
90713 * Get's the left most node on the right side of a BinaryExpression with + operator.
90714 * @param {ASTNode} node A BinaryExpression node to check.
90715 * @returns {ASTNode} node
90716 */
90717
90718
90719function getRight(node) {
90720 let right = node.right;
90721
90722 while (isConcatenation(right)) {
90723 right = right.left;
90724 }
90725
90726 return right;
90727} //------------------------------------------------------------------------------
90728// Rule Definition
90729//------------------------------------------------------------------------------
90730
90731
90732module.exports = {
90733 meta: {
90734 type: "suggestion",
90735 docs: {
90736 description: "disallow unnecessary concatenation of literals or template literals",
90737 category: "Best Practices",
90738 recommended: false,
90739 url: "https://eslint.org/docs/rules/no-useless-concat"
90740 },
90741 schema: [],
90742 messages: {
90743 unexpectedConcat: "Unexpected string concatenation of literals."
90744 }
90745 },
90746
90747 create(context) {
90748 const sourceCode = context.getSourceCode();
90749 return {
90750 BinaryExpression(node) {
90751 // check if not concatenation
90752 if (node.operator !== "+") {
90753 return;
90754 } // account for the `foo + "a" + "b"` case
90755
90756
90757 const left = getLeft(node);
90758 const right = getRight(node);
90759
90760 if (astUtils.isStringLiteral(left) && astUtils.isStringLiteral(right) && astUtils.isTokenOnSameLine(left, right)) {
90761 const operatorToken = sourceCode.getFirstTokenBetween(left, right, isConcatOperatorToken);
90762 context.report({
90763 node,
56c4a2cb 90764 loc: operatorToken.loc,
eb39fafa
DC
90765 messageId: "unexpectedConcat"
90766 });
90767 }
90768 }
90769
90770 };
90771 }
90772
90773};
90774
90775/***/ }),
6a5a0f88 90776/* 654 */
eb39fafa
DC
90777/***/ (function(module, exports, __webpack_require__) {
90778
90779"use strict";
90780/**
90781 * @fileoverview Rule to flag the use of redundant constructors in classes.
90782 * @author Alberto Rodríguez
90783 */
90784 //------------------------------------------------------------------------------
90785// Helpers
90786//------------------------------------------------------------------------------
90787
90788/**
90789 * Checks whether a given array of statements is a single call of `super`.
90790 * @param {ASTNode[]} body An array of statements to check.
90791 * @returns {boolean} `true` if the body is a single call of `super`.
90792 */
90793
90794function isSingleSuperCall(body) {
90795 return body.length === 1 && body[0].type === "ExpressionStatement" && body[0].expression.type === "CallExpression" && body[0].expression.callee.type === "Super";
90796}
90797/**
90798 * Checks whether a given node is a pattern which doesn't have any side effects.
90799 * Default parameters and Destructuring parameters can have side effects.
90800 * @param {ASTNode} node A pattern node.
90801 * @returns {boolean} `true` if the node doesn't have any side effects.
90802 */
90803
90804
90805function isSimple(node) {
90806 return node.type === "Identifier" || node.type === "RestElement";
90807}
90808/**
90809 * Checks whether a given array of expressions is `...arguments` or not.
90810 * `super(...arguments)` passes all arguments through.
90811 * @param {ASTNode[]} superArgs An array of expressions to check.
90812 * @returns {boolean} `true` if the superArgs is `...arguments`.
90813 */
90814
90815
90816function isSpreadArguments(superArgs) {
90817 return superArgs.length === 1 && superArgs[0].type === "SpreadElement" && superArgs[0].argument.type === "Identifier" && superArgs[0].argument.name === "arguments";
90818}
90819/**
90820 * Checks whether given 2 nodes are identifiers which have the same name or not.
90821 * @param {ASTNode} ctorParam A node to check.
90822 * @param {ASTNode} superArg A node to check.
90823 * @returns {boolean} `true` if the nodes are identifiers which have the same
90824 * name.
90825 */
90826
90827
90828function isValidIdentifierPair(ctorParam, superArg) {
90829 return ctorParam.type === "Identifier" && superArg.type === "Identifier" && ctorParam.name === superArg.name;
90830}
90831/**
90832 * Checks whether given 2 nodes are a rest/spread pair which has the same values.
90833 * @param {ASTNode} ctorParam A node to check.
90834 * @param {ASTNode} superArg A node to check.
90835 * @returns {boolean} `true` if the nodes are a rest/spread pair which has the
90836 * same values.
90837 */
90838
90839
90840function isValidRestSpreadPair(ctorParam, superArg) {
90841 return ctorParam.type === "RestElement" && superArg.type === "SpreadElement" && isValidIdentifierPair(ctorParam.argument, superArg.argument);
90842}
90843/**
90844 * Checks whether given 2 nodes have the same value or not.
90845 * @param {ASTNode} ctorParam A node to check.
90846 * @param {ASTNode} superArg A node to check.
90847 * @returns {boolean} `true` if the nodes have the same value or not.
90848 */
90849
90850
90851function isValidPair(ctorParam, superArg) {
90852 return isValidIdentifierPair(ctorParam, superArg) || isValidRestSpreadPair(ctorParam, superArg);
90853}
90854/**
90855 * Checks whether the parameters of a constructor and the arguments of `super()`
90856 * have the same values or not.
90857 * @param {ASTNode} ctorParams The parameters of a constructor to check.
90858 * @param {ASTNode} superArgs The arguments of `super()` to check.
90859 * @returns {boolean} `true` if those have the same values.
90860 */
90861
90862
90863function isPassingThrough(ctorParams, superArgs) {
90864 if (ctorParams.length !== superArgs.length) {
90865 return false;
90866 }
90867
90868 for (let i = 0; i < ctorParams.length; ++i) {
90869 if (!isValidPair(ctorParams[i], superArgs[i])) {
90870 return false;
90871 }
90872 }
90873
90874 return true;
90875}
90876/**
90877 * Checks whether the constructor body is a redundant super call.
90878 * @param {Array} body constructor body content.
90879 * @param {Array} ctorParams The params to check against super call.
90880 * @returns {boolean} true if the constructor body is redundant
90881 */
90882
90883
90884function isRedundantSuperCall(body, ctorParams) {
90885 return isSingleSuperCall(body) && ctorParams.every(isSimple) && (isSpreadArguments(body[0].expression.arguments) || isPassingThrough(ctorParams, body[0].expression.arguments));
90886} //------------------------------------------------------------------------------
90887// Rule Definition
90888//------------------------------------------------------------------------------
90889
90890
90891module.exports = {
90892 meta: {
90893 type: "suggestion",
90894 docs: {
90895 description: "disallow unnecessary constructors",
90896 category: "ECMAScript 6",
90897 recommended: false,
90898 url: "https://eslint.org/docs/rules/no-useless-constructor"
90899 },
90900 schema: [],
90901 messages: {
90902 noUselessConstructor: "Useless constructor."
90903 }
90904 },
90905
90906 create(context) {
90907 /**
90908 * Checks whether a node is a redundant constructor
90909 * @param {ASTNode} node node to check
90910 * @returns {void}
90911 */
90912 function checkForConstructor(node) {
90913 if (node.kind !== "constructor") {
90914 return;
90915 }
90916
90917 const body = node.value.body.body;
90918 const ctorParams = node.value.params;
90919 const superClass = node.parent.parent.superClass;
90920
90921 if (superClass ? isRedundantSuperCall(body, ctorParams) : body.length === 0) {
90922 context.report({
90923 node,
90924 messageId: "noUselessConstructor"
90925 });
90926 }
90927 }
90928
90929 return {
90930 MethodDefinition: checkForConstructor
90931 };
90932 }
90933
90934};
90935
90936/***/ }),
6a5a0f88 90937/* 655 */
eb39fafa
DC
90938/***/ (function(module, exports, __webpack_require__) {
90939
90940"use strict";
90941/**
90942 * @fileoverview Look for useless escapes in strings and regexes
90943 * @author Onur Temizkan
90944 */
90945
90946
90947const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
90948// Rule Definition
90949//------------------------------------------------------------------------------
90950
90951/**
90952 * Returns the union of two sets.
90953 * @param {Set} setA The first set
90954 * @param {Set} setB The second set
90955 * @returns {Set} The union of the two sets
90956 */
90957
90958
90959function union(setA, setB) {
90960 return new Set(function* () {
90961 yield* setA;
90962 yield* setB;
90963 }());
90964}
90965
90966const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS);
90967const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]");
90968const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()Bk"));
90969/**
90970 * Parses a regular expression into a list of characters with character class info.
90971 * @param {string} regExpText The raw text used to create the regular expression
90972 * @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class.
90973 * @example
90974 *
90975 * parseRegExp('a\\b[cd-]')
90976 *
90977 * returns:
90978 * [
90979 * {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false},
90980 * {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false},
90981 * {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false},
90982 * {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false},
90983 * {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}
90984 * ]
90985 */
90986
90987function parseRegExp(regExpText) {
90988 const charList = [];
90989 regExpText.split("").reduce((state, char, index) => {
90990 if (!state.escapeNextChar) {
90991 if (char === "\\") {
90992 return Object.assign(state, {
90993 escapeNextChar: true
90994 });
90995 }
90996
90997 if (char === "[" && !state.inCharClass) {
90998 return Object.assign(state, {
90999 inCharClass: true,
91000 startingCharClass: true
91001 });
91002 }
91003
91004 if (char === "]" && state.inCharClass) {
91005 if (charList.length && charList[charList.length - 1].inCharClass) {
91006 charList[charList.length - 1].endsCharClass = true;
91007 }
91008
91009 return Object.assign(state, {
91010 inCharClass: false,
91011 startingCharClass: false
91012 });
91013 }
91014 }
91015
91016 charList.push({
91017 text: char,
91018 index,
91019 escaped: state.escapeNextChar,
91020 inCharClass: state.inCharClass,
91021 startsCharClass: state.startingCharClass,
91022 endsCharClass: false
91023 });
91024 return Object.assign(state, {
91025 escapeNextChar: false,
91026 startingCharClass: false
91027 });
91028 }, {
91029 escapeNextChar: false,
91030 inCharClass: false,
91031 startingCharClass: false
91032 });
91033 return charList;
91034}
91035
91036module.exports = {
91037 meta: {
91038 type: "suggestion",
91039 docs: {
91040 description: "disallow unnecessary escape characters",
91041 category: "Best Practices",
91042 recommended: true,
91043 url: "https://eslint.org/docs/rules/no-useless-escape",
91044 suggestion: true
91045 },
91046 messages: {
91047 unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
91048 removeEscape: "Remove the `\\`. This maintains the current functionality.",
91049 escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character."
91050 },
91051 schema: []
91052 },
91053
91054 create(context) {
91055 const sourceCode = context.getSourceCode();
91056 /**
91057 * Reports a node
91058 * @param {ASTNode} node The node to report
91059 * @param {number} startOffset The backslash's offset from the start of the node
91060 * @param {string} character The uselessly escaped character (not including the backslash)
91061 * @returns {void}
91062 */
91063
91064 function report(node, startOffset, character) {
91065 const start = sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset);
91066 const rangeStart = sourceCode.getIndexFromLoc(node.loc.start) + startOffset;
91067 const range = [rangeStart, rangeStart + 1];
91068 context.report({
91069 node,
91070 loc: {
91071 start,
91072 end: {
91073 line: start.line,
91074 column: start.column + 1
91075 }
91076 },
91077 messageId: "unnecessaryEscape",
91078 data: {
91079 character
91080 },
91081 suggest: [{
91082 messageId: "removeEscape",
91083
91084 fix(fixer) {
91085 return fixer.removeRange(range);
91086 }
91087
91088 }, {
91089 messageId: "escapeBackslash",
91090
91091 fix(fixer) {
91092 return fixer.insertTextBeforeRange(range, "\\");
91093 }
91094
91095 }]
91096 });
91097 }
91098 /**
91099 * Checks if the escape character in given string slice is unnecessary.
91100 * @private
91101 * @param {ASTNode} node node to validate.
91102 * @param {string} match string slice to validate.
91103 * @returns {void}
91104 */
91105
91106
91107 function validateString(node, match) {
91108 const isTemplateElement = node.type === "TemplateElement";
91109 const escapedChar = match[0][1];
91110 let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
91111 let isQuoteEscape;
91112
91113 if (isTemplateElement) {
91114 isQuoteEscape = escapedChar === "`";
91115
91116 if (escapedChar === "$") {
91117 // Warn if `\$` is not followed by `{`
91118 isUnnecessaryEscape = match.input[match.index + 2] !== "{";
91119 } else if (escapedChar === "{") {
91120 /*
91121 * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
91122 * is necessary and the rule should not warn. If preceded by `/$`, the rule
91123 * will warn for the `/$` instead, as it is the first unnecessarily escaped character.
91124 */
91125 isUnnecessaryEscape = match.input[match.index - 1] !== "$";
91126 }
91127 } else {
91128 isQuoteEscape = escapedChar === node.raw[0];
91129 }
91130
91131 if (isUnnecessaryEscape && !isQuoteEscape) {
91132 report(node, match.index + 1, match[0].slice(1));
91133 }
91134 }
91135 /**
91136 * Checks if a node has an escape.
91137 * @param {ASTNode} node node to check.
91138 * @returns {void}
91139 */
91140
91141
91142 function check(node) {
91143 const isTemplateElement = node.type === "TemplateElement";
91144
91145 if (isTemplateElement && node.parent && node.parent.parent && node.parent.parent.type === "TaggedTemplateExpression" && node.parent === node.parent.parent.quasi) {
91146 // Don't report tagged template literals, because the backslash character is accessible to the tag function.
91147 return;
91148 }
91149
91150 if (typeof node.value === "string" || isTemplateElement) {
91151 /*
91152 * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
91153 * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
91154 */
91155 if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
91156 return;
91157 }
91158
91159 const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1);
91160 const pattern = /\\[^\d]/gu;
91161 let match;
91162
91163 while (match = pattern.exec(value)) {
91164 validateString(node, match);
91165 }
91166 } else if (node.regex) {
91167 parseRegExp(node.regex.pattern)
91168 /*
91169 * The '-' character is a special case, because it's only valid to escape it if it's in a character
91170 * class, and is not at either edge of the character class. To account for this, don't consider '-'
91171 * characters to be valid in general, and filter out '-' characters that appear in the middle of a
91172 * character class.
91173 */
91174 .filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass))
91175 /*
91176 * The '^' character is also a special case; it must always be escaped outside of character classes, but
91177 * it only needs to be escaped in character classes if it's at the beginning of the character class. To
91178 * account for this, consider it to be a valid escape character outside of character classes, and filter
91179 * out '^' characters that appear at the start of a character class.
91180 */
91181 .filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass)) // Filter out characters that aren't escaped.
91182 .filter(charInfo => charInfo.escaped) // Filter out characters that are valid to escape, based on their position in the regular expression.
91183 .filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text)) // Report all the remaining characters.
91184 .forEach(charInfo => report(node, charInfo.index, charInfo.text));
91185 }
91186 }
91187
91188 return {
91189 Literal: check,
91190 TemplateElement: check
91191 };
91192 }
91193
91194};
91195
91196/***/ }),
6a5a0f88 91197/* 656 */
eb39fafa
DC
91198/***/ (function(module, exports, __webpack_require__) {
91199
91200"use strict";
91201/**
91202 * @fileoverview Disallow renaming import, export, and destructured assignments to the same name.
91203 * @author Kai Cataldo
91204 */
91205 //------------------------------------------------------------------------------
91206// Rule Definition
91207//------------------------------------------------------------------------------
91208
91209module.exports = {
91210 meta: {
91211 type: "suggestion",
91212 docs: {
91213 description: "disallow renaming import, export, and destructured assignments to the same name",
91214 category: "ECMAScript 6",
91215 recommended: false,
91216 url: "https://eslint.org/docs/rules/no-useless-rename"
91217 },
91218 fixable: "code",
91219 schema: [{
91220 type: "object",
91221 properties: {
91222 ignoreDestructuring: {
91223 type: "boolean",
91224 default: false
91225 },
91226 ignoreImport: {
91227 type: "boolean",
91228 default: false
91229 },
91230 ignoreExport: {
91231 type: "boolean",
91232 default: false
91233 }
91234 },
91235 additionalProperties: false
91236 }],
91237 messages: {
91238 unnecessarilyRenamed: "{{type}} {{name}} unnecessarily renamed."
91239 }
91240 },
91241
91242 create(context) {
91243 const sourceCode = context.getSourceCode(),
91244 options = context.options[0] || {},
91245 ignoreDestructuring = options.ignoreDestructuring === true,
91246 ignoreImport = options.ignoreImport === true,
91247 ignoreExport = options.ignoreExport === true; //--------------------------------------------------------------------------
91248 // Helpers
91249 //--------------------------------------------------------------------------
91250
91251 /**
91252 * Reports error for unnecessarily renamed assignments
91253 * @param {ASTNode} node node to report
91254 * @param {ASTNode} initial node with initial name value
91255 * @param {ASTNode} result node with new name value
91256 * @param {string} type the type of the offending node
91257 * @returns {void}
91258 */
91259
91260 function reportError(node, initial, result, type) {
91261 const name = initial.type === "Identifier" ? initial.name : initial.value;
91262 return context.report({
91263 node,
91264 messageId: "unnecessarilyRenamed",
91265 data: {
91266 name,
91267 type
91268 },
91269
91270 fix(fixer) {
91271 if (sourceCode.commentsExistBetween(initial, result)) {
91272 return null;
91273 }
91274
91275 const replacementText = result.type === "AssignmentPattern" ? sourceCode.getText(result) : name;
91276 return fixer.replaceTextRange([initial.range[0], result.range[1]], replacementText);
91277 }
91278
91279 });
91280 }
91281 /**
91282 * Checks whether a destructured assignment is unnecessarily renamed
91283 * @param {ASTNode} node node to check
91284 * @returns {void}
91285 */
91286
91287
91288 function checkDestructured(node) {
91289 if (ignoreDestructuring) {
91290 return;
91291 }
91292
91293 for (const property of node.properties) {
91294 /*
91295 * TODO: Remove after babel-eslint removes ExperimentalRestProperty
91296 * https://github.com/eslint/eslint/issues/12335
91297 */
91298 if (property.type === "ExperimentalRestProperty") {
91299 continue;
91300 }
91301 /**
91302 * Properties using shorthand syntax and rest elements can not be renamed.
91303 * If the property is computed, we have no idea if a rename is useless or not.
91304 */
91305
91306
91307 if (property.shorthand || property.type === "RestElement" || property.computed) {
91308 continue;
91309 }
91310
91311 const key = property.key.type === "Identifier" && property.key.name || property.key.type === "Literal" && property.key.value;
91312 const renamedKey = property.value.type === "AssignmentPattern" ? property.value.left.name : property.value.name;
91313
91314 if (key === renamedKey) {
91315 reportError(property, property.key, property.value, "Destructuring assignment");
91316 }
91317 }
91318 }
91319 /**
91320 * Checks whether an import is unnecessarily renamed
91321 * @param {ASTNode} node node to check
91322 * @returns {void}
91323 */
91324
91325
91326 function checkImport(node) {
91327 if (ignoreImport) {
91328 return;
91329 }
91330
91331 if (node.imported.name === node.local.name && node.imported.range[0] !== node.local.range[0]) {
91332 reportError(node, node.imported, node.local, "Import");
91333 }
91334 }
91335 /**
91336 * Checks whether an export is unnecessarily renamed
91337 * @param {ASTNode} node node to check
91338 * @returns {void}
91339 */
91340
91341
91342 function checkExport(node) {
91343 if (ignoreExport) {
91344 return;
91345 }
91346
91347 if (node.local.name === node.exported.name && node.local.range[0] !== node.exported.range[0]) {
91348 reportError(node, node.local, node.exported, "Export");
91349 }
91350 } //--------------------------------------------------------------------------
91351 // Public
91352 //--------------------------------------------------------------------------
91353
91354
91355 return {
91356 ObjectPattern: checkDestructured,
91357 ImportSpecifier: checkImport,
91358 ExportSpecifier: checkExport
91359 };
91360 }
91361
91362};
91363
91364/***/ }),
6a5a0f88 91365/* 657 */
eb39fafa
DC
91366/***/ (function(module, exports, __webpack_require__) {
91367
91368"use strict";
91369/**
91370 * @fileoverview Disallow redundant return statements
91371 * @author Teddy Katz
91372 */
91373 //------------------------------------------------------------------------------
91374// Requirements
91375//------------------------------------------------------------------------------
91376
91377const astUtils = __webpack_require__(426),
91378 FixTracker = __webpack_require__(538); //------------------------------------------------------------------------------
91379// Helpers
91380//------------------------------------------------------------------------------
91381
91382/**
91383 * Removes the given element from the array.
91384 * @param {Array} array The source array to remove.
91385 * @param {any} element The target item to remove.
91386 * @returns {void}
91387 */
91388
91389
91390function remove(array, element) {
91391 const index = array.indexOf(element);
91392
91393 if (index !== -1) {
91394 array.splice(index, 1);
91395 }
91396}
91397/**
91398 * Checks whether it can remove the given return statement or not.
91399 * @param {ASTNode} node The return statement node to check.
91400 * @returns {boolean} `true` if the node is removable.
91401 */
91402
91403
91404function isRemovable(node) {
91405 return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type);
91406}
91407/**
91408 * Checks whether the given return statement is in a `finally` block or not.
91409 * @param {ASTNode} node The return statement node to check.
91410 * @returns {boolean} `true` if the node is in a `finally` block.
91411 */
91412
91413
91414function isInFinally(node) {
91415 for (let currentNode = node; currentNode && currentNode.parent && !astUtils.isFunction(currentNode); currentNode = currentNode.parent) {
91416 if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) {
91417 return true;
91418 }
91419 }
91420
91421 return false;
91422} //------------------------------------------------------------------------------
91423// Rule Definition
91424//------------------------------------------------------------------------------
91425
91426
91427module.exports = {
91428 meta: {
91429 type: "suggestion",
91430 docs: {
91431 description: "disallow redundant return statements",
91432 category: "Best Practices",
91433 recommended: false,
91434 url: "https://eslint.org/docs/rules/no-useless-return"
91435 },
91436 fixable: "code",
91437 schema: [],
91438 messages: {
91439 unnecessaryReturn: "Unnecessary return statement."
91440 }
91441 },
91442
91443 create(context) {
91444 const segmentInfoMap = new WeakMap();
91445 const usedUnreachableSegments = new WeakSet();
91446 const sourceCode = context.getSourceCode();
91447 let scopeInfo = null;
91448 /**
91449 * Checks whether the given segment is terminated by a return statement or not.
91450 * @param {CodePathSegment} segment The segment to check.
91451 * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable.
91452 */
91453
91454 function isReturned(segment) {
91455 const info = segmentInfoMap.get(segment);
91456 return !info || info.returned;
91457 }
91458 /**
91459 * Collects useless return statements from the given previous segments.
91460 *
91461 * A previous segment may be an unreachable segment.
91462 * In that case, the information object of the unreachable segment is not
91463 * initialized because `onCodePathSegmentStart` event is not notified for
91464 * unreachable segments.
91465 * This goes to the previous segments of the unreachable segment recursively
91466 * if the unreachable segment was generated by a return statement. Otherwise,
91467 * this ignores the unreachable segment.
91468 *
91469 * This behavior would simulate code paths for the case that the return
91470 * statement does not exist.
91471 * @param {ASTNode[]} uselessReturns The collected return statements.
91472 * @param {CodePathSegment[]} prevSegments The previous segments to traverse.
91473 * @param {WeakSet<CodePathSegment>} [providedTraversedSegments] A set of segments that have already been traversed in this call
91474 * @returns {ASTNode[]} `uselessReturns`.
91475 */
91476
91477
91478 function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) {
91479 const traversedSegments = providedTraversedSegments || new WeakSet();
91480
91481 for (const segment of prevSegments) {
91482 if (!segment.reachable) {
91483 if (!traversedSegments.has(segment)) {
91484 traversedSegments.add(segment);
91485 getUselessReturns(uselessReturns, segment.allPrevSegments.filter(isReturned), traversedSegments);
91486 }
91487
91488 continue;
91489 }
91490
91491 uselessReturns.push(...segmentInfoMap.get(segment).uselessReturns);
91492 }
91493
91494 return uselessReturns;
91495 }
91496 /**
91497 * Removes the return statements on the given segment from the useless return
91498 * statement list.
91499 *
91500 * This segment may be an unreachable segment.
91501 * In that case, the information object of the unreachable segment is not
91502 * initialized because `onCodePathSegmentStart` event is not notified for
91503 * unreachable segments.
91504 * This goes to the previous segments of the unreachable segment recursively
91505 * if the unreachable segment was generated by a return statement. Otherwise,
91506 * this ignores the unreachable segment.
91507 *
91508 * This behavior would simulate code paths for the case that the return
91509 * statement does not exist.
91510 * @param {CodePathSegment} segment The segment to get return statements.
91511 * @returns {void}
91512 */
91513
91514
91515 function markReturnStatementsOnSegmentAsUsed(segment) {
91516 if (!segment.reachable) {
91517 usedUnreachableSegments.add(segment);
91518 segment.allPrevSegments.filter(isReturned).filter(prevSegment => !usedUnreachableSegments.has(prevSegment)).forEach(markReturnStatementsOnSegmentAsUsed);
91519 return;
91520 }
91521
91522 const info = segmentInfoMap.get(segment);
91523
91524 for (const node of info.uselessReturns) {
91525 remove(scopeInfo.uselessReturns, node);
91526 }
91527
91528 info.uselessReturns = [];
91529 }
91530 /**
91531 * Removes the return statements on the current segments from the useless
91532 * return statement list.
91533 *
91534 * This function will be called at every statement except FunctionDeclaration,
91535 * BlockStatement, and BreakStatement.
91536 *
91537 * - FunctionDeclarations are always executed whether it's returned or not.
91538 * - BlockStatements do nothing.
91539 * - BreakStatements go the next merely.
91540 * @returns {void}
91541 */
91542
91543
91544 function markReturnStatementsOnCurrentSegmentsAsUsed() {
91545 scopeInfo.codePath.currentSegments.forEach(markReturnStatementsOnSegmentAsUsed);
91546 } //----------------------------------------------------------------------
91547 // Public
91548 //----------------------------------------------------------------------
91549
91550
91551 return {
91552 // Makes and pushs a new scope information.
91553 onCodePathStart(codePath) {
91554 scopeInfo = {
91555 upper: scopeInfo,
91556 uselessReturns: [],
91557 codePath
91558 };
91559 },
91560
91561 // Reports useless return statements if exist.
91562 onCodePathEnd() {
91563 for (const node of scopeInfo.uselessReturns) {
91564 context.report({
91565 node,
91566 loc: node.loc,
91567 messageId: "unnecessaryReturn",
91568
91569 fix(fixer) {
91570 if (isRemovable(node) && !sourceCode.getCommentsInside(node).length) {
91571 /*
91572 * Extend the replacement range to include the
91573 * entire function to avoid conflicting with
91574 * no-else-return.
91575 * https://github.com/eslint/eslint/issues/8026
91576 */
91577 return new FixTracker(fixer, sourceCode).retainEnclosingFunction(node).remove(node);
91578 }
91579
91580 return null;
91581 }
91582
91583 });
91584 }
91585
91586 scopeInfo = scopeInfo.upper;
91587 },
91588
91589 /*
91590 * Initializes segments.
91591 * NOTE: This event is notified for only reachable segments.
91592 */
91593 onCodePathSegmentStart(segment) {
91594 const info = {
91595 uselessReturns: getUselessReturns([], segment.allPrevSegments),
91596 returned: false
91597 }; // Stores the info.
91598
91599 segmentInfoMap.set(segment, info);
91600 },
91601
91602 // Adds ReturnStatement node to check whether it's useless or not.
91603 ReturnStatement(node) {
91604 if (node.argument) {
91605 markReturnStatementsOnCurrentSegmentsAsUsed();
91606 }
91607
91608 if (node.argument || astUtils.isInLoop(node) || isInFinally(node) || // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647).
91609 !scopeInfo.codePath.currentSegments.some(s => s.reachable)) {
91610 return;
91611 }
91612
91613 for (const segment of scopeInfo.codePath.currentSegments) {
91614 const info = segmentInfoMap.get(segment);
91615
91616 if (info) {
91617 info.uselessReturns.push(node);
91618 info.returned = true;
91619 }
91620 }
91621
91622 scopeInfo.uselessReturns.push(node);
91623 },
91624
91625 /*
91626 * Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement.
91627 * Removes return statements of the current segments from the useless return statement list.
91628 */
91629 ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed,
91630 ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91631 DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91632 DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91633 EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91634 ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91635 ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91636 ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91637 ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91638 IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91639 ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed,
91640 LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91641 SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91642 ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91643 TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91644 VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed,
91645 WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91646 WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed,
91647 ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed,
91648 ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed,
91649 ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed
91650 };
91651 }
91652
91653};
91654
91655/***/ }),
6a5a0f88 91656/* 658 */
eb39fafa
DC
91657/***/ (function(module, exports, __webpack_require__) {
91658
91659"use strict";
91660/**
91661 * @fileoverview Rule to check for the usage of var.
91662 * @author Jamund Ferguson
91663 */
91664 //------------------------------------------------------------------------------
91665// Requirements
91666//------------------------------------------------------------------------------
91667
91668const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
91669// Helpers
91670//------------------------------------------------------------------------------
91671
91672/**
91673 * Check whether a given variable is a global variable or not.
91674 * @param {eslint-scope.Variable} variable The variable to check.
91675 * @returns {boolean} `true` if the variable is a global variable.
91676 */
91677
91678
91679function isGlobal(variable) {
91680 return Boolean(variable.scope) && variable.scope.type === "global";
91681}
91682/**
91683 * Finds the nearest function scope or global scope walking up the scope
91684 * hierarchy.
91685 * @param {eslint-scope.Scope} scope The scope to traverse.
91686 * @returns {eslint-scope.Scope} a function scope or global scope containing the given
91687 * scope.
91688 */
91689
91690
91691function getEnclosingFunctionScope(scope) {
91692 let currentScope = scope;
91693
91694 while (currentScope.type !== "function" && currentScope.type !== "global") {
91695 currentScope = currentScope.upper;
91696 }
91697
91698 return currentScope;
91699}
91700/**
91701 * Checks whether the given variable has any references from a more specific
91702 * function expression (i.e. a closure).
91703 * @param {eslint-scope.Variable} variable A variable to check.
91704 * @returns {boolean} `true` if the variable is used from a closure.
91705 */
91706
91707
91708function isReferencedInClosure(variable) {
91709 const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope);
91710 return variable.references.some(reference => getEnclosingFunctionScope(reference.from) !== enclosingFunctionScope);
91711}
91712/**
91713 * Checks whether the given node is the assignee of a loop.
91714 * @param {ASTNode} node A VariableDeclaration node to check.
91715 * @returns {boolean} `true` if the declaration is assigned as part of loop
91716 * iteration.
91717 */
91718
91719
91720function isLoopAssignee(node) {
91721 return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && node === node.parent.left;
91722}
91723/**
91724 * Checks whether the given variable declaration is immediately initialized.
91725 * @param {ASTNode} node A VariableDeclaration node to check.
91726 * @returns {boolean} `true` if the declaration has an initializer.
91727 */
91728
91729
91730function isDeclarationInitialized(node) {
91731 return node.declarations.every(declarator => declarator.init !== null);
91732}
91733
91734const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/u;
91735/**
91736 * Gets the scope node which directly contains a given node.
91737 * @param {ASTNode} node A node to get. This is a `VariableDeclaration` or
91738 * an `Identifier`.
91739 * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`,
91740 * `SwitchStatement`, `ForStatement`, `ForInStatement`, and
91741 * `ForOfStatement`.
91742 */
91743
91744function getScopeNode(node) {
91745 for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
91746 if (SCOPE_NODE_TYPE.test(currentNode.type)) {
91747 return currentNode;
91748 }
91749 }
91750 /* istanbul ignore next : unreachable */
91751
91752
91753 return null;
91754}
91755/**
91756 * Checks whether a given variable is redeclared or not.
91757 * @param {eslint-scope.Variable} variable A variable to check.
91758 * @returns {boolean} `true` if the variable is redeclared.
91759 */
91760
91761
91762function isRedeclared(variable) {
91763 return variable.defs.length >= 2;
91764}
91765/**
91766 * Checks whether a given variable is used from outside of the specified scope.
91767 * @param {ASTNode} scopeNode A scope node to check.
91768 * @returns {Function} The predicate function which checks whether a given
91769 * variable is used from outside of the specified scope.
91770 */
91771
91772
91773function isUsedFromOutsideOf(scopeNode) {
91774 /**
91775 * Checks whether a given reference is inside of the specified scope or not.
91776 * @param {eslint-scope.Reference} reference A reference to check.
91777 * @returns {boolean} `true` if the reference is inside of the specified
91778 * scope.
91779 */
91780 function isOutsideOfScope(reference) {
91781 const scope = scopeNode.range;
91782 const id = reference.identifier.range;
91783 return id[0] < scope[0] || id[1] > scope[1];
91784 }
91785
91786 return function (variable) {
91787 return variable.references.some(isOutsideOfScope);
91788 };
91789}
91790/**
91791 * Creates the predicate function which checks whether a variable has their references in TDZ.
91792 *
91793 * The predicate function would return `true`:
91794 *
91795 * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};)
91796 * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};)
91797 * - if a reference is in the expression of their initializer. E.g. (var a = a;)
91798 * @param {ASTNode} node The initializer node of VariableDeclarator.
91799 * @returns {Function} The predicate function.
91800 * @private
91801 */
91802
91803
91804function hasReferenceInTDZ(node) {
91805 const initStart = node.range[0];
91806 const initEnd = node.range[1];
91807 return variable => {
91808 const id = variable.defs[0].name;
91809 const idStart = id.range[0];
91810 const defaultValue = id.parent.type === "AssignmentPattern" ? id.parent.right : null;
91811 const defaultStart = defaultValue && defaultValue.range[0];
91812 const defaultEnd = defaultValue && defaultValue.range[1];
91813 return variable.references.some(reference => {
91814 const start = reference.identifier.range[0];
91815 const end = reference.identifier.range[1];
91816 return !reference.init && (start < idStart || defaultValue !== null && start >= defaultStart && end <= defaultEnd || start >= initStart && end <= initEnd);
91817 });
91818 };
91819}
91820/**
91821 * Checks whether a given variable has name that is allowed for 'var' declarations,
91822 * but disallowed for `let` declarations.
91823 * @param {eslint-scope.Variable} variable The variable to check.
91824 * @returns {boolean} `true` if the variable has a disallowed name.
91825 */
91826
91827
91828function hasNameDisallowedForLetDeclarations(variable) {
91829 return variable.name === "let";
91830} //------------------------------------------------------------------------------
91831// Rule Definition
91832//------------------------------------------------------------------------------
91833
91834
91835module.exports = {
91836 meta: {
91837 type: "suggestion",
91838 docs: {
91839 description: "require `let` or `const` instead of `var`",
91840 category: "ECMAScript 6",
91841 recommended: false,
91842 url: "https://eslint.org/docs/rules/no-var"
91843 },
91844 schema: [],
91845 fixable: "code",
91846 messages: {
91847 unexpectedVar: "Unexpected var, use let or const instead."
91848 }
91849 },
91850
91851 create(context) {
91852 const sourceCode = context.getSourceCode();
91853 /**
91854 * Checks whether the variables which are defined by the given declarator node have their references in TDZ.
91855 * @param {ASTNode} declarator The VariableDeclarator node to check.
91856 * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ.
91857 */
91858
91859 function hasSelfReferenceInTDZ(declarator) {
91860 if (!declarator.init) {
91861 return false;
91862 }
91863
91864 const variables = context.getDeclaredVariables(declarator);
91865 return variables.some(hasReferenceInTDZ(declarator.init));
91866 }
91867 /**
91868 * Checks whether it can fix a given variable declaration or not.
91869 * It cannot fix if the following cases:
91870 *
91871 * - A variable is a global variable.
91872 * - A variable is declared on a SwitchCase node.
91873 * - A variable is redeclared.
91874 * - A variable is used from outside the scope.
91875 * - A variable is used from a closure within a loop.
91876 * - A variable might be used before it is assigned within a loop.
91877 * - A variable might be used in TDZ.
91878 * - A variable is declared in statement position (e.g. a single-line `IfStatement`)
91879 * - A variable has name that is disallowed for `let` declarations.
91880 *
91881 * ## A variable is declared on a SwitchCase node.
91882 *
91883 * If this rule modifies 'var' declarations on a SwitchCase node, it
91884 * would generate the warnings of 'no-case-declarations' rule. And the
91885 * 'eslint:recommended' preset includes 'no-case-declarations' rule, so
91886 * this rule doesn't modify those declarations.
91887 *
91888 * ## A variable is redeclared.
91889 *
91890 * The language spec disallows redeclarations of `let` declarations.
91891 * Those variables would cause syntax errors.
91892 *
91893 * ## A variable is used from outside the scope.
91894 *
91895 * The language spec disallows accesses from outside of the scope for
91896 * `let` declarations. Those variables would cause reference errors.
91897 *
91898 * ## A variable is used from a closure within a loop.
91899 *
91900 * A `var` declaration within a loop shares the same variable instance
91901 * across all loop iterations, while a `let` declaration creates a new
91902 * instance for each iteration. This means if a variable in a loop is
91903 * referenced by any closure, changing it from `var` to `let` would
91904 * change the behavior in a way that is generally unsafe.
91905 *
91906 * ## A variable might be used before it is assigned within a loop.
91907 *
91908 * Within a loop, a `let` declaration without an initializer will be
91909 * initialized to null, while a `var` declaration will retain its value
91910 * from the previous iteration, so it is only safe to change `var` to
91911 * `let` if we can statically determine that the variable is always
91912 * assigned a value before its first access in the loop body. To keep
91913 * the implementation simple, we only convert `var` to `let` within
91914 * loops when the variable is a loop assignee or the declaration has an
91915 * initializer.
91916 * @param {ASTNode} node A variable declaration node to check.
91917 * @returns {boolean} `true` if it can fix the node.
91918 */
91919
91920
91921 function canFix(node) {
91922 const variables = context.getDeclaredVariables(node);
91923 const scopeNode = getScopeNode(node);
91924
91925 if (node.parent.type === "SwitchCase" || node.declarations.some(hasSelfReferenceInTDZ) || variables.some(isGlobal) || variables.some(isRedeclared) || variables.some(isUsedFromOutsideOf(scopeNode)) || variables.some(hasNameDisallowedForLetDeclarations)) {
91926 return false;
91927 }
91928
91929 if (astUtils.isInLoop(node)) {
91930 if (variables.some(isReferencedInClosure)) {
91931 return false;
91932 }
91933
91934 if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) {
91935 return false;
91936 }
91937 }
91938
91939 if (!isLoopAssignee(node) && !(node.parent.type === "ForStatement" && node.parent.init === node) && !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
91940 // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed.
91941 return false;
91942 }
91943
91944 return true;
91945 }
91946 /**
91947 * Reports a given variable declaration node.
91948 * @param {ASTNode} node A variable declaration node to report.
91949 * @returns {void}
91950 */
91951
91952
91953 function report(node) {
91954 context.report({
91955 node,
91956 messageId: "unexpectedVar",
91957
91958 fix(fixer) {
91959 const varToken = sourceCode.getFirstToken(node, {
91960 filter: t => t.value === "var"
91961 });
91962 return canFix(node) ? fixer.replaceText(varToken, "let") : null;
91963 }
91964
91965 });
91966 }
91967
91968 return {
91969 "VariableDeclaration:exit"(node) {
91970 if (node.kind === "var") {
91971 report(node);
91972 }
91973 }
91974
91975 };
91976 }
91977
91978};
91979
91980/***/ }),
6a5a0f88 91981/* 659 */
eb39fafa
DC
91982/***/ (function(module, exports, __webpack_require__) {
91983
91984"use strict";
91985/**
91986 * @fileoverview Rule to disallow use of void operator.
91987 * @author Mike Sidorov
91988 */
91989 //------------------------------------------------------------------------------
91990// Rule Definition
91991//------------------------------------------------------------------------------
91992
91993module.exports = {
91994 meta: {
91995 type: "suggestion",
91996 docs: {
91997 description: "disallow `void` operators",
91998 category: "Best Practices",
91999 recommended: false,
92000 url: "https://eslint.org/docs/rules/no-void"
92001 },
92002 messages: {
92003 noVoid: "Expected 'undefined' and instead saw 'void'."
92004 },
92005 schema: [{
92006 type: "object",
92007 properties: {
92008 allowAsStatement: {
92009 type: "boolean",
92010 default: false
92011 }
92012 },
92013 additionalProperties: false
92014 }]
92015 },
92016
92017 create(context) {
92018 const allowAsStatement = context.options[0] && context.options[0].allowAsStatement; //--------------------------------------------------------------------------
92019 // Public
92020 //--------------------------------------------------------------------------
92021
92022 return {
92023 'UnaryExpression[operator="void"]'(node) {
92024 if (allowAsStatement && node.parent && node.parent.type === "ExpressionStatement") {
92025 return;
92026 }
92027
92028 context.report({
92029 node,
92030 messageId: "noVoid"
92031 });
92032 }
92033
92034 };
92035 }
92036
92037};
92038
92039/***/ }),
6a5a0f88 92040/* 660 */
eb39fafa
DC
92041/***/ (function(module, exports, __webpack_require__) {
92042
92043"use strict";
92044/**
92045 * @fileoverview Rule that warns about used warning comments
92046 * @author Alexander Schmidt <https://github.com/lxanders>
92047 */
92048
92049
92050const {
92051 escapeRegExp
92052} = __webpack_require__(403);
92053
92054const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
92055// Rule Definition
92056//------------------------------------------------------------------------------
92057
92058
92059module.exports = {
92060 meta: {
92061 type: "suggestion",
92062 docs: {
92063 description: "disallow specified warning terms in comments",
92064 category: "Best Practices",
92065 recommended: false,
92066 url: "https://eslint.org/docs/rules/no-warning-comments"
92067 },
92068 schema: [{
92069 type: "object",
92070 properties: {
92071 terms: {
92072 type: "array",
92073 items: {
92074 type: "string"
92075 }
92076 },
92077 location: {
92078 enum: ["start", "anywhere"]
92079 }
92080 },
92081 additionalProperties: false
92082 }],
92083 messages: {
92084 unexpectedComment: "Unexpected '{{matchedTerm}}' comment."
92085 }
92086 },
92087
92088 create(context) {
92089 const sourceCode = context.getSourceCode(),
92090 configuration = context.options[0] || {},
92091 warningTerms = configuration.terms || ["todo", "fixme", "xxx"],
92092 location = configuration.location || "start",
92093 selfConfigRegEx = /\bno-warning-comments\b/u;
92094 /**
92095 * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified
92096 * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not
92097 * require word boundaries on that side.
92098 * @param {string} term A term to convert to a RegExp
92099 * @returns {RegExp} The term converted to a RegExp
92100 */
92101
92102 function convertToRegExp(term) {
92103 const escaped = escapeRegExp(term);
92104 const wordBoundary = "\\b";
92105 const eitherOrWordBoundary = "|".concat(wordBoundary);
92106 let prefix;
92107 /*
92108 * If the term ends in a word character (a-z0-9_), ensure a word
92109 * boundary at the end, so that substrings do not get falsely
92110 * matched. eg "todo" in a string such as "mastodon".
92111 * If the term ends in a non-word character, then \b won't match on
92112 * the boundary to the next non-word character, which would likely
92113 * be a space. For example `/\bFIX!\b/.test('FIX! blah') === false`.
92114 * In these cases, use no bounding match. Same applies for the
92115 * prefix, handled below.
92116 */
92117
92118 const suffix = /\w$/u.test(term) ? "\\b" : "";
92119
92120 if (location === "start") {
92121 /*
92122 * When matching at the start, ignore leading whitespace, and
92123 * there's no need to worry about word boundaries.
92124 */
92125 prefix = "^\\s*";
92126 } else if (/^\w/u.test(term)) {
92127 prefix = wordBoundary;
92128 } else {
92129 prefix = "";
92130 }
92131
92132 if (location === "start") {
92133 /*
92134 * For location "start" the regex should be
92135 * ^\s*TERM\b. This checks the word boundary
92136 * at the beginning of the comment.
92137 */
92138 return new RegExp(prefix + escaped + suffix, "iu");
92139 }
92140 /*
92141 * For location "anywhere" the regex should be
92142 * \bTERM\b|\bTERM\b, this checks the entire comment
92143 * for the term.
92144 */
92145
92146
92147 return new RegExp(prefix + escaped + suffix + eitherOrWordBoundary + term + wordBoundary, "iu");
92148 }
92149
92150 const warningRegExps = warningTerms.map(convertToRegExp);
92151 /**
92152 * Checks the specified comment for matches of the configured warning terms and returns the matches.
92153 * @param {string} comment The comment which is checked.
92154 * @returns {Array} All matched warning terms for this comment.
92155 */
92156
92157 function commentContainsWarningTerm(comment) {
92158 const matches = [];
92159 warningRegExps.forEach((regex, index) => {
92160 if (regex.test(comment)) {
92161 matches.push(warningTerms[index]);
92162 }
92163 });
92164 return matches;
92165 }
92166 /**
92167 * Checks the specified node for matching warning comments and reports them.
92168 * @param {ASTNode} node The AST node being checked.
92169 * @returns {void} undefined.
92170 */
92171
92172
92173 function checkComment(node) {
92174 if (astUtils.isDirectiveComment(node) && selfConfigRegEx.test(node.value)) {
92175 return;
92176 }
92177
92178 const matches = commentContainsWarningTerm(node.value);
92179 matches.forEach(matchedTerm => {
92180 context.report({
92181 node,
92182 messageId: "unexpectedComment",
92183 data: {
92184 matchedTerm
92185 }
92186 });
92187 });
92188 }
92189
92190 return {
92191 Program() {
92192 const comments = sourceCode.getAllComments();
92193 comments.filter(token => token.type !== "Shebang").forEach(checkComment);
92194 }
92195
92196 };
92197 }
92198
92199};
92200
92201/***/ }),
6a5a0f88 92202/* 661 */
eb39fafa
DC
92203/***/ (function(module, exports, __webpack_require__) {
92204
92205"use strict";
92206/**
92207 * @fileoverview Rule to disallow whitespace before properties
92208 * @author Kai Cataldo
92209 */
92210 //------------------------------------------------------------------------------
92211// Requirements
92212//------------------------------------------------------------------------------
92213
92214const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
92215// Rule Definition
92216//------------------------------------------------------------------------------
92217
92218
92219module.exports = {
92220 meta: {
92221 type: "layout",
92222 docs: {
92223 description: "disallow whitespace before properties",
92224 category: "Stylistic Issues",
92225 recommended: false,
92226 url: "https://eslint.org/docs/rules/no-whitespace-before-property"
92227 },
92228 fixable: "whitespace",
92229 schema: [],
92230 messages: {
92231 unexpectedWhitespace: "Unexpected whitespace before property {{propName}}."
92232 }
92233 },
92234
92235 create(context) {
92236 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
92237 // Helpers
92238 //--------------------------------------------------------------------------
92239
92240 /**
92241 * Reports whitespace before property token
92242 * @param {ASTNode} node the node to report in the event of an error
92243 * @param {Token} leftToken the left token
92244 * @param {Token} rightToken the right token
92245 * @returns {void}
92246 * @private
92247 */
92248
92249 function reportError(node, leftToken, rightToken) {
92250 const replacementText = node.computed ? "" : ".";
92251 context.report({
92252 node,
92253 messageId: "unexpectedWhitespace",
92254 data: {
92255 propName: sourceCode.getText(node.property)
92256 },
92257
92258 fix(fixer) {
92259 if (!node.computed && astUtils.isDecimalInteger(node.object)) {
92260 /*
92261 * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError.
92262 * Don't fix this case.
92263 */
92264 return null;
92265 }
92266
92267 return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], replacementText);
92268 }
92269
92270 });
92271 } //--------------------------------------------------------------------------
92272 // Public
92273 //--------------------------------------------------------------------------
92274
92275
92276 return {
92277 MemberExpression(node) {
92278 let rightToken;
92279 let leftToken;
92280
92281 if (!astUtils.isTokenOnSameLine(node.object, node.property)) {
92282 return;
92283 }
92284
92285 if (node.computed) {
92286 rightToken = sourceCode.getTokenBefore(node.property, astUtils.isOpeningBracketToken);
92287 leftToken = sourceCode.getTokenBefore(rightToken);
92288 } else {
92289 rightToken = sourceCode.getFirstToken(node.property);
92290 leftToken = sourceCode.getTokenBefore(rightToken, 1);
92291 }
92292
92293 if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) {
92294 reportError(node, leftToken, rightToken);
92295 }
92296 }
92297
92298 };
92299 }
92300
92301};
92302
92303/***/ }),
6a5a0f88 92304/* 662 */
eb39fafa
DC
92305/***/ (function(module, exports, __webpack_require__) {
92306
92307"use strict";
92308/**
92309 * @fileoverview Rule to flag use of with statement
92310 * @author Nicholas C. Zakas
92311 */
92312 //------------------------------------------------------------------------------
92313// Rule Definition
92314//------------------------------------------------------------------------------
92315
92316module.exports = {
92317 meta: {
92318 type: "suggestion",
92319 docs: {
92320 description: "disallow `with` statements",
92321 category: "Best Practices",
92322 recommended: true,
92323 url: "https://eslint.org/docs/rules/no-with"
92324 },
92325 schema: [],
92326 messages: {
92327 unexpectedWith: "Unexpected use of 'with' statement."
92328 }
92329 },
92330
92331 create(context) {
92332 return {
92333 WithStatement(node) {
92334 context.report({
92335 node,
92336 messageId: "unexpectedWith"
92337 });
92338 }
92339
92340 };
92341 }
92342
92343};
92344
92345/***/ }),
6a5a0f88 92346/* 663 */
eb39fafa
DC
92347/***/ (function(module, exports, __webpack_require__) {
92348
92349"use strict";
92350/**
92351 * @fileoverview enforce the location of single-line statements
92352 * @author Teddy Katz
92353 */
92354 //------------------------------------------------------------------------------
92355// Rule Definition
92356//------------------------------------------------------------------------------
92357
92358const POSITION_SCHEMA = {
92359 enum: ["beside", "below", "any"]
92360};
92361module.exports = {
92362 meta: {
92363 type: "layout",
92364 docs: {
92365 description: "enforce the location of single-line statements",
92366 category: "Stylistic Issues",
92367 recommended: false,
92368 url: "https://eslint.org/docs/rules/nonblock-statement-body-position"
92369 },
92370 fixable: "whitespace",
92371 schema: [POSITION_SCHEMA, {
92372 properties: {
92373 overrides: {
92374 properties: {
92375 if: POSITION_SCHEMA,
92376 else: POSITION_SCHEMA,
92377 while: POSITION_SCHEMA,
92378 do: POSITION_SCHEMA,
92379 for: POSITION_SCHEMA
92380 },
92381 additionalProperties: false
92382 }
92383 },
92384 additionalProperties: false
92385 }],
92386 messages: {
92387 expectNoLinebreak: "Expected no linebreak before this statement.",
92388 expectLinebreak: "Expected a linebreak before this statement."
92389 }
92390 },
92391
92392 create(context) {
92393 const sourceCode = context.getSourceCode(); //----------------------------------------------------------------------
92394 // Helpers
92395 //----------------------------------------------------------------------
92396
92397 /**
92398 * Gets the applicable preference for a particular keyword
92399 * @param {string} keywordName The name of a keyword, e.g. 'if'
92400 * @returns {string} The applicable option for the keyword, e.g. 'beside'
92401 */
92402
92403 function getOption(keywordName) {
92404 return context.options[1] && context.options[1].overrides && context.options[1].overrides[keywordName] || context.options[0] || "beside";
92405 }
92406 /**
92407 * Validates the location of a single-line statement
92408 * @param {ASTNode} node The single-line statement
92409 * @param {string} keywordName The applicable keyword name for the single-line statement
92410 * @returns {void}
92411 */
92412
92413
92414 function validateStatement(node, keywordName) {
92415 const option = getOption(keywordName);
92416
92417 if (node.type === "BlockStatement" || option === "any") {
92418 return;
92419 }
92420
92421 const tokenBefore = sourceCode.getTokenBefore(node);
92422
92423 if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") {
92424 context.report({
92425 node,
92426 messageId: "expectLinebreak",
92427 fix: fixer => fixer.insertTextBefore(node, "\n")
92428 });
92429 } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") {
92430 context.report({
92431 node,
92432 messageId: "expectNoLinebreak",
92433
92434 fix(fixer) {
92435 if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) {
92436 return null;
92437 }
92438
92439 return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " ");
92440 }
92441
92442 });
92443 }
92444 } //----------------------------------------------------------------------
92445 // Public
92446 //----------------------------------------------------------------------
92447
92448
92449 return {
92450 IfStatement(node) {
92451 validateStatement(node.consequent, "if"); // Check the `else` node, but don't check 'else if' statements.
92452
92453 if (node.alternate && node.alternate.type !== "IfStatement") {
92454 validateStatement(node.alternate, "else");
92455 }
92456 },
92457
92458 WhileStatement: node => validateStatement(node.body, "while"),
92459 DoWhileStatement: node => validateStatement(node.body, "do"),
92460 ForStatement: node => validateStatement(node.body, "for"),
92461 ForInStatement: node => validateStatement(node.body, "for"),
92462 ForOfStatement: node => validateStatement(node.body, "for")
92463 };
92464 }
92465
92466};
92467
92468/***/ }),
6a5a0f88 92469/* 664 */
eb39fafa
DC
92470/***/ (function(module, exports, __webpack_require__) {
92471
92472"use strict";
92473/**
92474 * @fileoverview Rule to require or disallow line breaks inside braces.
92475 * @author Toru Nagashima
92476 */
92477 //------------------------------------------------------------------------------
92478// Requirements
92479//------------------------------------------------------------------------------
92480
92481const astUtils = __webpack_require__(426);
92482
92483const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
92484// Helpers
92485//------------------------------------------------------------------------------
92486// Schema objects.
92487
92488
92489const OPTION_VALUE = {
92490 oneOf: [{
92491 enum: ["always", "never"]
92492 }, {
92493 type: "object",
92494 properties: {
92495 multiline: {
92496 type: "boolean"
92497 },
92498 minProperties: {
92499 type: "integer",
92500 minimum: 0
92501 },
92502 consistent: {
92503 type: "boolean"
92504 }
92505 },
92506 additionalProperties: false,
92507 minProperties: 1
92508 }]
92509};
92510/**
92511 * Normalizes a given option value.
92512 * @param {string|Object|undefined} value An option value to parse.
92513 * @returns {{multiline: boolean, minProperties: number, consistent: boolean}} Normalized option object.
92514 */
92515
92516function normalizeOptionValue(value) {
92517 let multiline = false;
92518 let minProperties = Number.POSITIVE_INFINITY;
92519 let consistent = false;
92520
92521 if (value) {
92522 if (value === "always") {
92523 minProperties = 0;
92524 } else if (value === "never") {
92525 minProperties = Number.POSITIVE_INFINITY;
92526 } else {
92527 multiline = Boolean(value.multiline);
92528 minProperties = value.minProperties || Number.POSITIVE_INFINITY;
92529 consistent = Boolean(value.consistent);
92530 }
92531 } else {
92532 consistent = true;
92533 }
92534
92535 return {
92536 multiline,
92537 minProperties,
92538 consistent
92539 };
92540}
92541/**
92542 * Normalizes a given option value.
92543 * @param {string|Object|undefined} options An option value to parse.
92544 * @returns {{
92545 * ObjectExpression: {multiline: boolean, minProperties: number, consistent: boolean},
92546 * ObjectPattern: {multiline: boolean, minProperties: number, consistent: boolean},
92547 * ImportDeclaration: {multiline: boolean, minProperties: number, consistent: boolean},
92548 * ExportNamedDeclaration : {multiline: boolean, minProperties: number, consistent: boolean}
92549 * }} Normalized option object.
92550 */
92551
92552
92553function normalizeOptions(options) {
92554 const isNodeSpecificOption = lodash.overSome([lodash.isPlainObject, lodash.isString]);
92555
92556 if (lodash.isPlainObject(options) && lodash.some(options, isNodeSpecificOption)) {
92557 return {
92558 ObjectExpression: normalizeOptionValue(options.ObjectExpression),
92559 ObjectPattern: normalizeOptionValue(options.ObjectPattern),
92560 ImportDeclaration: normalizeOptionValue(options.ImportDeclaration),
92561 ExportNamedDeclaration: normalizeOptionValue(options.ExportDeclaration)
92562 };
92563 }
92564
92565 const value = normalizeOptionValue(options);
92566 return {
92567 ObjectExpression: value,
92568 ObjectPattern: value,
92569 ImportDeclaration: value,
92570 ExportNamedDeclaration: value
92571 };
92572}
92573/**
92574 * Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration
92575 * node needs to be checked for missing line breaks
92576 * @param {ASTNode} node Node under inspection
92577 * @param {Object} options option specific to node type
92578 * @param {Token} first First object property
92579 * @param {Token} last Last object property
92580 * @returns {boolean} `true` if node needs to be checked for missing line breaks
92581 */
92582
92583
92584function areLineBreaksRequired(node, options, first, last) {
92585 let objectProperties;
92586
92587 if (node.type === "ObjectExpression" || node.type === "ObjectPattern") {
92588 objectProperties = node.properties;
92589 } else {
92590 // is ImportDeclaration or ExportNamedDeclaration
92591 objectProperties = node.specifiers.filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier");
92592 }
92593
92594 return objectProperties.length >= options.minProperties || options.multiline && objectProperties.length > 0 && first.loc.start.line !== last.loc.end.line;
92595} //------------------------------------------------------------------------------
92596// Rule Definition
92597//------------------------------------------------------------------------------
92598
92599
92600module.exports = {
92601 meta: {
92602 type: "layout",
92603 docs: {
92604 description: "enforce consistent line breaks inside braces",
92605 category: "Stylistic Issues",
92606 recommended: false,
92607 url: "https://eslint.org/docs/rules/object-curly-newline"
92608 },
92609 fixable: "whitespace",
92610 schema: [{
92611 oneOf: [OPTION_VALUE, {
92612 type: "object",
92613 properties: {
92614 ObjectExpression: OPTION_VALUE,
92615 ObjectPattern: OPTION_VALUE,
92616 ImportDeclaration: OPTION_VALUE,
92617 ExportDeclaration: OPTION_VALUE
92618 },
92619 additionalProperties: false,
92620 minProperties: 1
92621 }]
92622 }],
92623 messages: {
92624 unexpectedLinebreakBeforeClosingBrace: "Unexpected line break before this closing brace.",
92625 unexpectedLinebreakAfterOpeningBrace: "Unexpected line break after this opening brace.",
92626 expectedLinebreakBeforeClosingBrace: "Expected a line break before this closing brace.",
92627 expectedLinebreakAfterOpeningBrace: "Expected a line break after this opening brace."
92628 }
92629 },
92630
92631 create(context) {
92632 const sourceCode = context.getSourceCode();
92633 const normalizedOptions = normalizeOptions(context.options[0]);
92634 /**
92635 * Reports a given node if it violated this rule.
92636 * @param {ASTNode} node A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node.
92637 * @returns {void}
92638 */
92639
92640 function check(node) {
92641 const options = normalizedOptions[node.type];
92642
92643 if (node.type === "ImportDeclaration" && !node.specifiers.some(specifier => specifier.type === "ImportSpecifier") || node.type === "ExportNamedDeclaration" && !node.specifiers.some(specifier => specifier.type === "ExportSpecifier")) {
92644 return;
92645 }
92646
92647 const openBrace = sourceCode.getFirstToken(node, token => token.value === "{");
92648 let closeBrace;
92649
92650 if (node.typeAnnotation) {
92651 closeBrace = sourceCode.getTokenBefore(node.typeAnnotation);
92652 } else {
92653 closeBrace = sourceCode.getLastToken(node, token => token.value === "}");
92654 }
92655
92656 let first = sourceCode.getTokenAfter(openBrace, {
92657 includeComments: true
92658 });
92659 let last = sourceCode.getTokenBefore(closeBrace, {
92660 includeComments: true
92661 });
92662 const needsLineBreaks = areLineBreaksRequired(node, options, first, last);
92663 const hasCommentsFirstToken = astUtils.isCommentToken(first);
92664 const hasCommentsLastToken = astUtils.isCommentToken(last);
92665 /*
92666 * Use tokens or comments to check multiline or not.
92667 * But use only tokens to check whether line breaks are needed.
92668 * This allows:
92669 * var obj = { // eslint-disable-line foo
92670 * a: 1
92671 * }
92672 */
92673
92674 first = sourceCode.getTokenAfter(openBrace);
92675 last = sourceCode.getTokenBefore(closeBrace);
92676
92677 if (needsLineBreaks) {
92678 if (astUtils.isTokenOnSameLine(openBrace, first)) {
92679 context.report({
92680 messageId: "expectedLinebreakAfterOpeningBrace",
92681 node,
92682 loc: openBrace.loc.start,
92683
92684 fix(fixer) {
92685 if (hasCommentsFirstToken) {
92686 return null;
92687 }
92688
92689 return fixer.insertTextAfter(openBrace, "\n");
92690 }
92691
92692 });
92693 }
92694
92695 if (astUtils.isTokenOnSameLine(last, closeBrace)) {
92696 context.report({
92697 messageId: "expectedLinebreakBeforeClosingBrace",
92698 node,
92699 loc: closeBrace.loc.start,
92700
92701 fix(fixer) {
92702 if (hasCommentsLastToken) {
92703 return null;
92704 }
92705
92706 return fixer.insertTextBefore(closeBrace, "\n");
92707 }
92708
92709 });
92710 }
92711 } else {
92712 const consistent = options.consistent;
92713 const hasLineBreakBetweenOpenBraceAndFirst = !astUtils.isTokenOnSameLine(openBrace, first);
92714 const hasLineBreakBetweenCloseBraceAndLast = !astUtils.isTokenOnSameLine(last, closeBrace);
92715
92716 if (!consistent && hasLineBreakBetweenOpenBraceAndFirst || consistent && hasLineBreakBetweenOpenBraceAndFirst && !hasLineBreakBetweenCloseBraceAndLast) {
92717 context.report({
92718 messageId: "unexpectedLinebreakAfterOpeningBrace",
92719 node,
92720 loc: openBrace.loc.start,
92721
92722 fix(fixer) {
92723 if (hasCommentsFirstToken) {
92724 return null;
92725 }
92726
92727 return fixer.removeRange([openBrace.range[1], first.range[0]]);
92728 }
92729
92730 });
92731 }
92732
92733 if (!consistent && hasLineBreakBetweenCloseBraceAndLast || consistent && !hasLineBreakBetweenOpenBraceAndFirst && hasLineBreakBetweenCloseBraceAndLast) {
92734 context.report({
92735 messageId: "unexpectedLinebreakBeforeClosingBrace",
92736 node,
92737 loc: closeBrace.loc.start,
92738
92739 fix(fixer) {
92740 if (hasCommentsLastToken) {
92741 return null;
92742 }
92743
92744 return fixer.removeRange([last.range[1], closeBrace.range[0]]);
92745 }
92746
92747 });
92748 }
92749 }
92750 }
92751
92752 return {
92753 ObjectExpression: check,
92754 ObjectPattern: check,
92755 ImportDeclaration: check,
92756 ExportNamedDeclaration: check
92757 };
92758 }
92759
92760};
92761
92762/***/ }),
6a5a0f88 92763/* 665 */
eb39fafa
DC
92764/***/ (function(module, exports, __webpack_require__) {
92765
92766"use strict";
92767/**
92768 * @fileoverview Disallows or enforces spaces inside of object literals.
92769 * @author Jamund Ferguson
92770 */
92771
92772
92773const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
92774// Rule Definition
92775//------------------------------------------------------------------------------
92776
92777
92778module.exports = {
92779 meta: {
92780 type: "layout",
92781 docs: {
92782 description: "enforce consistent spacing inside braces",
92783 category: "Stylistic Issues",
92784 recommended: false,
92785 url: "https://eslint.org/docs/rules/object-curly-spacing"
92786 },
92787 fixable: "whitespace",
92788 schema: [{
92789 enum: ["always", "never"]
92790 }, {
92791 type: "object",
92792 properties: {
92793 arraysInObjects: {
92794 type: "boolean"
92795 },
92796 objectsInObjects: {
92797 type: "boolean"
92798 }
92799 },
92800 additionalProperties: false
92801 }],
92802 messages: {
92803 requireSpaceBefore: "A space is required before '{{token}}'.",
92804 requireSpaceAfter: "A space is required after '{{token}}'.",
92805 unexpectedSpaceBefore: "There should be no space before '{{token}}'.",
92806 unexpectedSpaceAfter: "There should be no space after '{{token}}'."
92807 }
92808 },
92809
92810 create(context) {
92811 const spaced = context.options[0] === "always",
92812 sourceCode = context.getSourceCode();
92813 /**
92814 * Determines whether an option is set, relative to the spacing option.
92815 * If spaced is "always", then check whether option is set to false.
92816 * If spaced is "never", then check whether option is set to true.
92817 * @param {Object} option The option to exclude.
92818 * @returns {boolean} Whether or not the property is excluded.
92819 */
92820
92821 function isOptionSet(option) {
92822 return context.options[1] ? context.options[1][option] === !spaced : false;
92823 }
92824
92825 const options = {
92826 spaced,
92827 arraysInObjectsException: isOptionSet("arraysInObjects"),
92828 objectsInObjectsException: isOptionSet("objectsInObjects")
92829 }; //--------------------------------------------------------------------------
92830 // Helpers
92831 //--------------------------------------------------------------------------
92832
92833 /**
92834 * Reports that there shouldn't be a space after the first token
92835 * @param {ASTNode} node The node to report in the event of an error.
92836 * @param {Token} token The token to use for the report.
92837 * @returns {void}
92838 */
92839
92840 function reportNoBeginningSpace(node, token) {
92841 const nextToken = context.getSourceCode().getTokenAfter(token, {
92842 includeComments: true
92843 });
92844 context.report({
92845 node,
92846 loc: {
92847 start: token.loc.end,
92848 end: nextToken.loc.start
92849 },
92850 messageId: "unexpectedSpaceAfter",
92851 data: {
92852 token: token.value
92853 },
92854
92855 fix(fixer) {
92856 return fixer.removeRange([token.range[1], nextToken.range[0]]);
92857 }
92858
92859 });
92860 }
92861 /**
92862 * Reports that there shouldn't be a space before the last token
92863 * @param {ASTNode} node The node to report in the event of an error.
92864 * @param {Token} token The token to use for the report.
92865 * @returns {void}
92866 */
92867
92868
92869 function reportNoEndingSpace(node, token) {
92870 const previousToken = context.getSourceCode().getTokenBefore(token, {
92871 includeComments: true
92872 });
92873 context.report({
92874 node,
92875 loc: {
92876 start: previousToken.loc.end,
92877 end: token.loc.start
92878 },
92879 messageId: "unexpectedSpaceBefore",
92880 data: {
92881 token: token.value
92882 },
92883
92884 fix(fixer) {
92885 return fixer.removeRange([previousToken.range[1], token.range[0]]);
92886 }
92887
92888 });
92889 }
92890 /**
92891 * Reports that there should be a space after the first token
92892 * @param {ASTNode} node The node to report in the event of an error.
92893 * @param {Token} token The token to use for the report.
92894 * @returns {void}
92895 */
92896
92897
92898 function reportRequiredBeginningSpace(node, token) {
92899 context.report({
92900 node,
92901 loc: token.loc,
92902 messageId: "requireSpaceAfter",
92903 data: {
92904 token: token.value
92905 },
92906
92907 fix(fixer) {
92908 return fixer.insertTextAfter(token, " ");
92909 }
92910
92911 });
92912 }
92913 /**
92914 * Reports that there should be a space before the last token
92915 * @param {ASTNode} node The node to report in the event of an error.
92916 * @param {Token} token The token to use for the report.
92917 * @returns {void}
92918 */
92919
92920
92921 function reportRequiredEndingSpace(node, token) {
92922 context.report({
92923 node,
92924 loc: token.loc,
92925 messageId: "requireSpaceBefore",
92926 data: {
92927 token: token.value
92928 },
92929
92930 fix(fixer) {
92931 return fixer.insertTextBefore(token, " ");
92932 }
92933
92934 });
92935 }
92936 /**
92937 * Determines if spacing in curly braces is valid.
92938 * @param {ASTNode} node The AST node to check.
92939 * @param {Token} first The first token to check (should be the opening brace)
92940 * @param {Token} second The second token to check (should be first after the opening brace)
92941 * @param {Token} penultimate The penultimate token to check (should be last before closing brace)
92942 * @param {Token} last The last token to check (should be closing brace)
92943 * @returns {void}
92944 */
92945
92946
92947 function validateBraceSpacing(node, first, second, penultimate, last) {
92948 if (astUtils.isTokenOnSameLine(first, second)) {
92949 const firstSpaced = sourceCode.isSpaceBetweenTokens(first, second);
92950
92951 if (options.spaced && !firstSpaced) {
92952 reportRequiredBeginningSpace(node, first);
92953 }
92954
92955 if (!options.spaced && firstSpaced && second.type !== "Line") {
92956 reportNoBeginningSpace(node, first);
92957 }
92958 }
92959
92960 if (astUtils.isTokenOnSameLine(penultimate, last)) {
92961 const shouldCheckPenultimate = options.arraysInObjectsException && astUtils.isClosingBracketToken(penultimate) || options.objectsInObjectsException && astUtils.isClosingBraceToken(penultimate);
92962 const penultimateType = shouldCheckPenultimate && sourceCode.getNodeByRangeIndex(penultimate.range[0]).type;
92963 const closingCurlyBraceMustBeSpaced = options.arraysInObjectsException && penultimateType === "ArrayExpression" || options.objectsInObjectsException && (penultimateType === "ObjectExpression" || penultimateType === "ObjectPattern") ? !options.spaced : options.spaced;
92964 const lastSpaced = sourceCode.isSpaceBetweenTokens(penultimate, last);
92965
92966 if (closingCurlyBraceMustBeSpaced && !lastSpaced) {
92967 reportRequiredEndingSpace(node, last);
92968 }
92969
92970 if (!closingCurlyBraceMustBeSpaced && lastSpaced) {
92971 reportNoEndingSpace(node, last);
92972 }
92973 }
92974 }
92975 /**
92976 * Gets '}' token of an object node.
92977 *
92978 * Because the last token of object patterns might be a type annotation,
92979 * this traverses tokens preceded by the last property, then returns the
92980 * first '}' token.
92981 * @param {ASTNode} node The node to get. This node is an
92982 * ObjectExpression or an ObjectPattern. And this node has one or
92983 * more properties.
92984 * @returns {Token} '}' token.
92985 */
92986
92987
92988 function getClosingBraceOfObject(node) {
92989 const lastProperty = node.properties[node.properties.length - 1];
92990 return sourceCode.getTokenAfter(lastProperty, astUtils.isClosingBraceToken);
92991 }
92992 /**
92993 * Reports a given object node if spacing in curly braces is invalid.
92994 * @param {ASTNode} node An ObjectExpression or ObjectPattern node to check.
92995 * @returns {void}
92996 */
92997
92998
92999 function checkForObject(node) {
93000 if (node.properties.length === 0) {
93001 return;
93002 }
93003
93004 const first = sourceCode.getFirstToken(node),
93005 last = getClosingBraceOfObject(node),
93006 second = sourceCode.getTokenAfter(first, {
93007 includeComments: true
93008 }),
93009 penultimate = sourceCode.getTokenBefore(last, {
93010 includeComments: true
93011 });
93012 validateBraceSpacing(node, first, second, penultimate, last);
93013 }
93014 /**
93015 * Reports a given import node if spacing in curly braces is invalid.
93016 * @param {ASTNode} node An ImportDeclaration node to check.
93017 * @returns {void}
93018 */
93019
93020
93021 function checkForImport(node) {
93022 if (node.specifiers.length === 0) {
93023 return;
93024 }
93025
93026 let firstSpecifier = node.specifiers[0];
93027 const lastSpecifier = node.specifiers[node.specifiers.length - 1];
93028
93029 if (lastSpecifier.type !== "ImportSpecifier") {
93030 return;
93031 }
93032
93033 if (firstSpecifier.type !== "ImportSpecifier") {
93034 firstSpecifier = node.specifiers[1];
93035 }
93036
93037 const first = sourceCode.getTokenBefore(firstSpecifier),
93038 last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken),
93039 second = sourceCode.getTokenAfter(first, {
93040 includeComments: true
93041 }),
93042 penultimate = sourceCode.getTokenBefore(last, {
93043 includeComments: true
93044 });
93045 validateBraceSpacing(node, first, second, penultimate, last);
93046 }
93047 /**
93048 * Reports a given export node if spacing in curly braces is invalid.
93049 * @param {ASTNode} node An ExportNamedDeclaration node to check.
93050 * @returns {void}
93051 */
93052
93053
93054 function checkForExport(node) {
93055 if (node.specifiers.length === 0) {
93056 return;
93057 }
93058
93059 const firstSpecifier = node.specifiers[0],
93060 lastSpecifier = node.specifiers[node.specifiers.length - 1],
93061 first = sourceCode.getTokenBefore(firstSpecifier),
93062 last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken),
93063 second = sourceCode.getTokenAfter(first, {
93064 includeComments: true
93065 }),
93066 penultimate = sourceCode.getTokenBefore(last, {
93067 includeComments: true
93068 });
93069 validateBraceSpacing(node, first, second, penultimate, last);
93070 } //--------------------------------------------------------------------------
93071 // Public
93072 //--------------------------------------------------------------------------
93073
93074
93075 return {
93076 // var {x} = y;
93077 ObjectPattern: checkForObject,
93078 // var y = {x: 'y'}
93079 ObjectExpression: checkForObject,
93080 // import {y} from 'x';
93081 ImportDeclaration: checkForImport,
93082 // export {name} from 'yo';
93083 ExportNamedDeclaration: checkForExport
93084 };
93085 }
93086
93087};
93088
93089/***/ }),
6a5a0f88 93090/* 666 */
eb39fafa
DC
93091/***/ (function(module, exports, __webpack_require__) {
93092
93093"use strict";
93094/**
93095 * @fileoverview Rule to enforce placing object properties on separate lines.
93096 * @author Vitor Balocco
93097 */
93098 //------------------------------------------------------------------------------
93099// Rule Definition
93100//------------------------------------------------------------------------------
93101
93102module.exports = {
93103 meta: {
93104 type: "layout",
93105 docs: {
93106 description: "enforce placing object properties on separate lines",
93107 category: "Stylistic Issues",
93108 recommended: false,
93109 url: "https://eslint.org/docs/rules/object-property-newline"
93110 },
93111 schema: [{
93112 type: "object",
93113 properties: {
93114 allowAllPropertiesOnSameLine: {
93115 type: "boolean",
93116 default: false
93117 },
93118 allowMultiplePropertiesPerLine: {
93119 // Deprecated
93120 type: "boolean",
93121 default: false
93122 }
93123 },
93124 additionalProperties: false
93125 }],
93126 fixable: "whitespace",
93127 messages: {
93128 propertiesOnNewlineAll: "Object properties must go on a new line if they aren't all on the same line.",
93129 propertiesOnNewline: "Object properties must go on a new line."
93130 }
93131 },
93132
93133 create(context) {
93134 const allowSameLine = context.options[0] && (context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine
93135 /* Deprecated */
93136 );
93137 const messageId = allowSameLine ? "propertiesOnNewlineAll" : "propertiesOnNewline";
93138 const sourceCode = context.getSourceCode();
93139 return {
93140 ObjectExpression(node) {
93141 if (allowSameLine) {
93142 if (node.properties.length > 1) {
93143 const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]);
93144 const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]);
93145
93146 if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) {
93147 // All keys and values are on the same line
93148 return;
93149 }
93150 }
93151 }
93152
93153 for (let i = 1; i < node.properties.length; i++) {
93154 const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]);
93155 const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]);
93156
93157 if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) {
93158 context.report({
93159 node,
93160 loc: firstTokenOfCurrentProperty.loc.start,
93161 messageId,
93162
93163 fix(fixer) {
93164 const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty);
93165 const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]]; // Don't perform a fix if there are any comments between the comma and the next property.
93166
93167 if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) {
93168 return null;
93169 }
93170
93171 return fixer.replaceTextRange(rangeAfterComma, "\n");
93172 }
93173
93174 });
93175 }
93176 }
93177 }
93178
93179 };
93180 }
93181
93182};
93183
93184/***/ }),
6a5a0f88 93185/* 667 */
eb39fafa
DC
93186/***/ (function(module, exports, __webpack_require__) {
93187
93188"use strict";
93189/**
93190 * @fileoverview Rule to enforce concise object methods and properties.
93191 * @author Jamund Ferguson
93192 */
93193
93194
93195const OPTIONS = {
93196 always: "always",
93197 never: "never",
93198 methods: "methods",
93199 properties: "properties",
93200 consistent: "consistent",
93201 consistentAsNeeded: "consistent-as-needed"
93202}; //------------------------------------------------------------------------------
93203// Requirements
93204//------------------------------------------------------------------------------
93205
93206const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
93207// Rule Definition
93208//------------------------------------------------------------------------------
93209
93210
93211module.exports = {
93212 meta: {
93213 type: "suggestion",
93214 docs: {
93215 description: "require or disallow method and property shorthand syntax for object literals",
93216 category: "ECMAScript 6",
93217 recommended: false,
93218 url: "https://eslint.org/docs/rules/object-shorthand"
93219 },
93220 fixable: "code",
93221 schema: {
93222 anyOf: [{
93223 type: "array",
93224 items: [{
93225 enum: ["always", "methods", "properties", "never", "consistent", "consistent-as-needed"]
93226 }],
93227 minItems: 0,
93228 maxItems: 1
93229 }, {
93230 type: "array",
93231 items: [{
93232 enum: ["always", "methods", "properties"]
93233 }, {
93234 type: "object",
93235 properties: {
93236 avoidQuotes: {
93237 type: "boolean"
93238 }
93239 },
93240 additionalProperties: false
93241 }],
93242 minItems: 0,
93243 maxItems: 2
93244 }, {
93245 type: "array",
93246 items: [{
93247 enum: ["always", "methods"]
93248 }, {
93249 type: "object",
93250 properties: {
93251 ignoreConstructors: {
93252 type: "boolean"
93253 },
93254 avoidQuotes: {
93255 type: "boolean"
93256 },
93257 avoidExplicitReturnArrows: {
93258 type: "boolean"
93259 }
93260 },
93261 additionalProperties: false
93262 }],
93263 minItems: 0,
93264 maxItems: 2
93265 }]
93266 },
93267 messages: {
93268 expectedAllPropertiesShorthanded: "Expected shorthand for all properties.",
93269 expectedLiteralMethodLongform: "Expected longform method syntax for string literal keys.",
93270 expectedPropertyShorthand: "Expected property shorthand.",
93271 expectedPropertyLongform: "Expected longform property syntax.",
93272 expectedMethodShorthand: "Expected method shorthand.",
93273 expectedMethodLongform: "Expected longform method syntax.",
93274 unexpectedMix: "Unexpected mix of shorthand and non-shorthand properties."
93275 }
93276 },
93277
93278 create(context) {
93279 const APPLY = context.options[0] || OPTIONS.always;
93280 const APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always;
93281 const APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always;
93282 const APPLY_NEVER = APPLY === OPTIONS.never;
93283 const APPLY_CONSISTENT = APPLY === OPTIONS.consistent;
93284 const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded;
93285 const PARAMS = context.options[1] || {};
93286 const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors;
93287 const AVOID_QUOTES = PARAMS.avoidQuotes;
93288 const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows;
93289 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
93290 // Helpers
93291 //--------------------------------------------------------------------------
93292
93293 const CTOR_PREFIX_REGEX = /[^_$0-9]/u;
93294 /**
93295 * Determines if the first character of the name is a capital letter.
93296 * @param {string} name The name of the node to evaluate.
93297 * @returns {boolean} True if the first character of the property name is a capital letter, false if not.
93298 * @private
93299 */
93300
93301 function isConstructor(name) {
93302 const match = CTOR_PREFIX_REGEX.exec(name); // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8'
93303
93304 if (!match) {
93305 return false;
93306 }
93307
93308 const firstChar = name.charAt(match.index);
93309 return firstChar === firstChar.toUpperCase();
93310 }
93311 /**
93312 * Determines if the property can have a shorthand form.
93313 * @param {ASTNode} property Property AST node
93314 * @returns {boolean} True if the property can have a shorthand form
93315 * @private
93316 *
93317 */
93318
93319
93320 function canHaveShorthand(property) {
93321 return property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadElement" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty";
93322 }
93323 /**
93324 * Checks whether a node is a string literal.
93325 * @param {ASTNode} node Any AST node.
93326 * @returns {boolean} `true` if it is a string literal.
93327 */
93328
93329
93330 function isStringLiteral(node) {
93331 return node.type === "Literal" && typeof node.value === "string";
93332 }
93333 /**
93334 * Determines if the property is a shorthand or not.
93335 * @param {ASTNode} property Property AST node
93336 * @returns {boolean} True if the property is considered shorthand, false if not.
93337 * @private
93338 *
93339 */
93340
93341
93342 function isShorthand(property) {
93343 // property.method is true when `{a(){}}`.
93344 return property.shorthand || property.method;
93345 }
93346 /**
93347 * Determines if the property's key and method or value are named equally.
93348 * @param {ASTNode} property Property AST node
93349 * @returns {boolean} True if the key and value are named equally, false if not.
93350 * @private
93351 *
93352 */
93353
93354
93355 function isRedundant(property) {
93356 const value = property.value;
93357
93358 if (value.type === "FunctionExpression") {
93359 return !value.id; // Only anonymous should be shorthand method.
93360 }
93361
93362 if (value.type === "Identifier") {
93363 return astUtils.getStaticPropertyName(property) === value.name;
93364 }
93365
93366 return false;
93367 }
93368 /**
93369 * Ensures that an object's properties are consistently shorthand, or not shorthand at all.
93370 * @param {ASTNode} node Property AST node
93371 * @param {boolean} checkRedundancy Whether to check longform redundancy
93372 * @returns {void}
93373 *
93374 */
93375
93376
93377 function checkConsistency(node, checkRedundancy) {
93378 // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand.
93379 const properties = node.properties.filter(canHaveShorthand); // Do we still have properties left after filtering the getters and setters?
93380
93381 if (properties.length > 0) {
93382 const shorthandProperties = properties.filter(isShorthand);
93383 /*
93384 * If we do not have an equal number of longform properties as
93385 * shorthand properties, we are using the annotations inconsistently
93386 */
93387
93388 if (shorthandProperties.length !== properties.length) {
93389 // We have at least 1 shorthand property
93390 if (shorthandProperties.length > 0) {
93391 context.report({
93392 node,
93393 messageId: "unexpectedMix"
93394 });
93395 } else if (checkRedundancy) {
93396 /*
93397 * If all properties of the object contain a method or value with a name matching it's key,
93398 * all the keys are redundant.
93399 */
93400 const canAlwaysUseShorthand = properties.every(isRedundant);
93401
93402 if (canAlwaysUseShorthand) {
93403 context.report({
93404 node,
93405 messageId: "expectedAllPropertiesShorthanded"
93406 });
93407 }
93408 }
93409 }
93410 }
93411 }
93412 /**
93413 * Fixes a FunctionExpression node by making it into a shorthand property.
93414 * @param {SourceCodeFixer} fixer The fixer object
93415 * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value
93416 * @returns {Object} A fix for this node
93417 */
93418
93419
93420 function makeFunctionShorthand(fixer, node) {
93421 const firstKeyToken = node.computed ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken) : sourceCode.getFirstToken(node.key);
93422 const lastKeyToken = node.computed ? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken) : sourceCode.getLastToken(node.key);
93423 const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
93424 let keyPrefix = ""; // key: /* */ () => {}
93425
93426 if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
93427 return null;
93428 }
93429
93430 if (node.value.async) {
93431 keyPrefix += "async ";
93432 }
93433
93434 if (node.value.generator) {
93435 keyPrefix += "*";
93436 }
93437
93438 const fixRange = [firstKeyToken.range[0], node.range[1]];
93439 const methodPrefix = keyPrefix + keyText;
93440
93441 if (node.value.type === "FunctionExpression") {
93442 const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
93443 const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;
93444 return fixer.replaceTextRange(fixRange, methodPrefix + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1]));
93445 }
93446
93447 const arrowToken = sourceCode.getTokenBefore(node.value.body, astUtils.isArrowToken);
93448 const fnBody = sourceCode.text.slice(arrowToken.range[1], node.value.range[1]);
93449 let shouldAddParensAroundParameters = false;
93450 let tokenBeforeParams;
93451
93452 if (node.value.params.length === 0) {
93453 tokenBeforeParams = sourceCode.getFirstToken(node.value, astUtils.isOpeningParenToken);
93454 } else {
93455 tokenBeforeParams = sourceCode.getTokenBefore(node.value.params[0]);
93456 }
93457
93458 if (node.value.params.length === 1) {
93459 const hasParen = astUtils.isOpeningParenToken(tokenBeforeParams);
93460 const isTokenOutsideNode = tokenBeforeParams.range[0] < node.range[0];
93461 shouldAddParensAroundParameters = !hasParen || isTokenOutsideNode;
93462 }
93463
93464 const sliceStart = shouldAddParensAroundParameters ? node.value.params[0].range[0] : tokenBeforeParams.range[0];
93465 const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1];
93466 const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd);
93467 const newParamText = shouldAddParensAroundParameters ? "(".concat(oldParamText, ")") : oldParamText;
93468 return fixer.replaceTextRange(fixRange, methodPrefix + newParamText + fnBody);
93469 }
93470 /**
93471 * Fixes a FunctionExpression node by making it into a longform property.
93472 * @param {SourceCodeFixer} fixer The fixer object
93473 * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value
93474 * @returns {Object} A fix for this node
93475 */
93476
93477
93478 function makeFunctionLongform(fixer, node) {
93479 const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key);
93480 const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key);
93481 const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
93482 let functionHeader = "function";
93483
93484 if (node.value.async) {
93485 functionHeader = "async ".concat(functionHeader);
93486 }
93487
93488 if (node.value.generator) {
93489 functionHeader = "".concat(functionHeader, "*");
93490 }
93491
93492 return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], "".concat(keyText, ": ").concat(functionHeader));
93493 }
93494 /*
93495 * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`),
93496 * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is
93497 * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical
93498 * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered,
93499 * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited.
93500 * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them
93501 * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule,
93502 * because converting it into a method would change the value of one of the lexical identifiers.
93503 */
93504
93505
93506 const lexicalScopeStack = [];
93507 const arrowsWithLexicalIdentifiers = new WeakSet();
93508 const argumentsIdentifiers = new WeakSet();
93509 /**
93510 * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack.
93511 * Also, this marks all `arguments` identifiers so that they can be detected later.
93512 * @returns {void}
93513 */
93514
93515 function enterFunction() {
93516 lexicalScopeStack.unshift(new Set());
93517 context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => {
93518 variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
93519 });
93520 }
93521 /**
93522 * Exits a function. This pops the current set of arrow functions off the lexical scope stack.
93523 * @returns {void}
93524 */
93525
93526
93527 function exitFunction() {
93528 lexicalScopeStack.shift();
93529 }
93530 /**
93531 * Marks the current function as having a lexical keyword. This implies that all arrow functions
93532 * in the current lexical scope contain a reference to this lexical keyword.
93533 * @returns {void}
93534 */
93535
93536
93537 function reportLexicalIdentifier() {
93538 lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction));
93539 } //--------------------------------------------------------------------------
93540 // Public
93541 //--------------------------------------------------------------------------
93542
93543
93544 return {
93545 Program: enterFunction,
93546 FunctionDeclaration: enterFunction,
93547 FunctionExpression: enterFunction,
93548 "Program:exit": exitFunction,
93549 "FunctionDeclaration:exit": exitFunction,
93550 "FunctionExpression:exit": exitFunction,
93551
93552 ArrowFunctionExpression(node) {
93553 lexicalScopeStack[0].add(node);
93554 },
93555
93556 "ArrowFunctionExpression:exit"(node) {
93557 lexicalScopeStack[0].delete(node);
93558 },
93559
93560 ThisExpression: reportLexicalIdentifier,
93561 Super: reportLexicalIdentifier,
93562
93563 MetaProperty(node) {
93564 if (node.meta.name === "new" && node.property.name === "target") {
93565 reportLexicalIdentifier();
93566 }
93567 },
93568
93569 Identifier(node) {
93570 if (argumentsIdentifiers.has(node)) {
93571 reportLexicalIdentifier();
93572 }
93573 },
93574
93575 ObjectExpression(node) {
93576 if (APPLY_CONSISTENT) {
93577 checkConsistency(node, false);
93578 } else if (APPLY_CONSISTENT_AS_NEEDED) {
93579 checkConsistency(node, true);
93580 }
93581 },
93582
93583 "Property:exit"(node) {
93584 const isConciseProperty = node.method || node.shorthand; // Ignore destructuring assignment
93585
93586 if (node.parent.type === "ObjectPattern") {
93587 return;
93588 } // getters and setters are ignored
93589
93590
93591 if (node.kind === "get" || node.kind === "set") {
93592 return;
93593 } // only computed methods can fail the following checks
93594
93595
93596 if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") {
93597 return;
93598 } //--------------------------------------------------------------
93599 // Checks for property/method shorthand.
93600
93601
93602 if (isConciseProperty) {
93603 if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) {
93604 const messageId = APPLY_NEVER ? "expectedMethodLongform" : "expectedLiteralMethodLongform"; // { x() {} } should be written as { x: function() {} }
93605
93606 context.report({
93607 node,
93608 messageId,
93609 fix: fixer => makeFunctionLongform(fixer, node)
93610 });
93611 } else if (APPLY_NEVER) {
93612 // { x } should be written as { x: x }
93613 context.report({
93614 node,
93615 messageId: "expectedPropertyLongform",
93616 fix: fixer => fixer.insertTextAfter(node.key, ": ".concat(node.key.name))
93617 });
93618 }
93619 } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) {
93620 if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) {
93621 return;
93622 }
93623
93624 if (AVOID_QUOTES && isStringLiteral(node.key)) {
93625 return;
93626 } // {[x]: function(){}} should be written as {[x]() {}}
93627
93628
93629 if (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression" && node.value.body.type === "BlockStatement" && AVOID_EXPLICIT_RETURN_ARROWS && !arrowsWithLexicalIdentifiers.has(node.value)) {
93630 context.report({
93631 node,
93632 messageId: "expectedMethodShorthand",
93633 fix: fixer => makeFunctionShorthand(fixer, node)
93634 });
93635 }
93636 } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) {
93637 // {x: x} should be written as {x}
93638 context.report({
93639 node,
93640 messageId: "expectedPropertyShorthand",
93641
93642 fix(fixer) {
93643 return fixer.replaceText(node, node.value.name);
93644 }
93645
93646 });
93647 } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) {
93648 if (AVOID_QUOTES) {
93649 return;
93650 } // {"x": x} should be written as {x}
93651
93652
93653 context.report({
93654 node,
93655 messageId: "expectedPropertyShorthand",
93656
93657 fix(fixer) {
93658 return fixer.replaceText(node, node.value.name);
93659 }
93660
93661 });
93662 }
93663 }
93664
93665 };
93666 }
93667
93668};
93669
93670/***/ }),
6a5a0f88 93671/* 668 */
eb39fafa
DC
93672/***/ (function(module, exports, __webpack_require__) {
93673
93674"use strict";
93675/**
93676 * @fileoverview A rule to control the use of single variable declarations.
93677 * @author Ian Christian Myers
93678 */
93679 //------------------------------------------------------------------------------
93680// Rule Definition
93681//------------------------------------------------------------------------------
93682
93683module.exports = {
93684 meta: {
93685 type: "suggestion",
93686 docs: {
93687 description: "enforce variables to be declared either together or separately in functions",
93688 category: "Stylistic Issues",
93689 recommended: false,
93690 url: "https://eslint.org/docs/rules/one-var"
93691 },
93692 fixable: "code",
93693 schema: [{
93694 oneOf: [{
93695 enum: ["always", "never", "consecutive"]
93696 }, {
93697 type: "object",
93698 properties: {
93699 separateRequires: {
93700 type: "boolean"
93701 },
93702 var: {
93703 enum: ["always", "never", "consecutive"]
93704 },
93705 let: {
93706 enum: ["always", "never", "consecutive"]
93707 },
93708 const: {
93709 enum: ["always", "never", "consecutive"]
93710 }
93711 },
93712 additionalProperties: false
93713 }, {
93714 type: "object",
93715 properties: {
93716 initialized: {
93717 enum: ["always", "never", "consecutive"]
93718 },
93719 uninitialized: {
93720 enum: ["always", "never", "consecutive"]
93721 }
93722 },
93723 additionalProperties: false
93724 }]
93725 }],
93726 messages: {
93727 combineUninitialized: "Combine this with the previous '{{type}}' statement with uninitialized variables.",
93728 combineInitialized: "Combine this with the previous '{{type}}' statement with initialized variables.",
93729 splitUninitialized: "Split uninitialized '{{type}}' declarations into multiple statements.",
93730 splitInitialized: "Split initialized '{{type}}' declarations into multiple statements.",
93731 splitRequires: "Split requires to be separated into a single block.",
93732 combine: "Combine this with the previous '{{type}}' statement.",
93733 split: "Split '{{type}}' declarations into multiple statements."
93734 }
93735 },
93736
93737 create(context) {
93738 const MODE_ALWAYS = "always";
93739 const MODE_NEVER = "never";
93740 const MODE_CONSECUTIVE = "consecutive";
93741 const mode = context.options[0] || MODE_ALWAYS;
93742 const options = {};
93743
93744 if (typeof mode === "string") {
93745 // simple options configuration with just a string
93746 options.var = {
93747 uninitialized: mode,
93748 initialized: mode
93749 };
93750 options.let = {
93751 uninitialized: mode,
93752 initialized: mode
93753 };
93754 options.const = {
93755 uninitialized: mode,
93756 initialized: mode
93757 };
93758 } else if (typeof mode === "object") {
93759 // options configuration is an object
93760 options.separateRequires = !!mode.separateRequires;
93761 options.var = {
93762 uninitialized: mode.var,
93763 initialized: mode.var
93764 };
93765 options.let = {
93766 uninitialized: mode.let,
93767 initialized: mode.let
93768 };
93769 options.const = {
93770 uninitialized: mode.const,
93771 initialized: mode.const
93772 };
93773
93774 if (Object.prototype.hasOwnProperty.call(mode, "uninitialized")) {
93775 options.var.uninitialized = mode.uninitialized;
93776 options.let.uninitialized = mode.uninitialized;
93777 options.const.uninitialized = mode.uninitialized;
93778 }
93779
93780 if (Object.prototype.hasOwnProperty.call(mode, "initialized")) {
93781 options.var.initialized = mode.initialized;
93782 options.let.initialized = mode.initialized;
93783 options.const.initialized = mode.initialized;
93784 }
93785 }
93786
93787 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
93788 // Helpers
93789 //--------------------------------------------------------------------------
93790
93791 const functionStack = [];
93792 const blockStack = [];
93793 /**
93794 * Increments the blockStack counter.
93795 * @returns {void}
93796 * @private
93797 */
93798
93799 function startBlock() {
93800 blockStack.push({
93801 let: {
93802 initialized: false,
93803 uninitialized: false
93804 },
93805 const: {
93806 initialized: false,
93807 uninitialized: false
93808 }
93809 });
93810 }
93811 /**
93812 * Increments the functionStack counter.
93813 * @returns {void}
93814 * @private
93815 */
93816
93817
93818 function startFunction() {
93819 functionStack.push({
93820 initialized: false,
93821 uninitialized: false
93822 });
93823 startBlock();
93824 }
93825 /**
93826 * Decrements the blockStack counter.
93827 * @returns {void}
93828 * @private
93829 */
93830
93831
93832 function endBlock() {
93833 blockStack.pop();
93834 }
93835 /**
93836 * Decrements the functionStack counter.
93837 * @returns {void}
93838 * @private
93839 */
93840
93841
93842 function endFunction() {
93843 functionStack.pop();
93844 endBlock();
93845 }
93846 /**
93847 * Check if a variable declaration is a require.
93848 * @param {ASTNode} decl variable declaration Node
93849 * @returns {bool} if decl is a require, return true; else return false.
93850 * @private
93851 */
93852
93853
93854 function isRequire(decl) {
93855 return decl.init && decl.init.type === "CallExpression" && decl.init.callee.name === "require";
93856 }
93857 /**
93858 * Records whether initialized/uninitialized/required variables are defined in current scope.
93859 * @param {string} statementType node.kind, one of: "var", "let", or "const"
93860 * @param {ASTNode[]} declarations List of declarations
93861 * @param {Object} currentScope The scope being investigated
93862 * @returns {void}
93863 * @private
93864 */
93865
93866
93867 function recordTypes(statementType, declarations, currentScope) {
93868 for (let i = 0; i < declarations.length; i++) {
93869 if (declarations[i].init === null) {
93870 if (options[statementType] && options[statementType].uninitialized === MODE_ALWAYS) {
93871 currentScope.uninitialized = true;
93872 }
93873 } else {
93874 if (options[statementType] && options[statementType].initialized === MODE_ALWAYS) {
93875 if (options.separateRequires && isRequire(declarations[i])) {
93876 currentScope.required = true;
93877 } else {
93878 currentScope.initialized = true;
93879 }
93880 }
93881 }
93882 }
93883 }
93884 /**
93885 * Determines the current scope (function or block)
93886 * @param {string} statementType node.kind, one of: "var", "let", or "const"
93887 * @returns {Object} The scope associated with statementType
93888 */
93889
93890
93891 function getCurrentScope(statementType) {
93892 let currentScope;
93893
93894 if (statementType === "var") {
93895 currentScope = functionStack[functionStack.length - 1];
93896 } else if (statementType === "let") {
93897 currentScope = blockStack[blockStack.length - 1].let;
93898 } else if (statementType === "const") {
93899 currentScope = blockStack[blockStack.length - 1].const;
93900 }
93901
93902 return currentScope;
93903 }
93904 /**
93905 * Counts the number of initialized and uninitialized declarations in a list of declarations
93906 * @param {ASTNode[]} declarations List of declarations
93907 * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations
93908 * @private
93909 */
93910
93911
93912 function countDeclarations(declarations) {
93913 const counts = {
93914 uninitialized: 0,
93915 initialized: 0
93916 };
93917
93918 for (let i = 0; i < declarations.length; i++) {
93919 if (declarations[i].init === null) {
93920 counts.uninitialized++;
93921 } else {
93922 counts.initialized++;
93923 }
93924 }
93925
93926 return counts;
93927 }
93928 /**
93929 * Determines if there is more than one var statement in the current scope.
93930 * @param {string} statementType node.kind, one of: "var", "let", or "const"
93931 * @param {ASTNode[]} declarations List of declarations
93932 * @returns {boolean} Returns true if it is the first var declaration, false if not.
93933 * @private
93934 */
93935
93936
93937 function hasOnlyOneStatement(statementType, declarations) {
93938 const declarationCounts = countDeclarations(declarations);
93939 const currentOptions = options[statementType] || {};
93940 const currentScope = getCurrentScope(statementType);
93941 const hasRequires = declarations.some(isRequire);
93942
93943 if (currentOptions.uninitialized === MODE_ALWAYS && currentOptions.initialized === MODE_ALWAYS) {
93944 if (currentScope.uninitialized || currentScope.initialized) {
93945 if (!hasRequires) {
93946 return false;
93947 }
93948 }
93949 }
93950
93951 if (declarationCounts.uninitialized > 0) {
93952 if (currentOptions.uninitialized === MODE_ALWAYS && currentScope.uninitialized) {
93953 return false;
93954 }
93955 }
93956
93957 if (declarationCounts.initialized > 0) {
93958 if (currentOptions.initialized === MODE_ALWAYS && currentScope.initialized) {
93959 if (!hasRequires) {
93960 return false;
93961 }
93962 }
93963 }
93964
93965 if (currentScope.required && hasRequires) {
93966 return false;
93967 }
93968
93969 recordTypes(statementType, declarations, currentScope);
93970 return true;
93971 }
93972 /**
93973 * Fixer to join VariableDeclaration's into a single declaration
93974 * @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join
93975 * @returns {Function} The fixer function
93976 */
93977
93978
93979 function joinDeclarations(declarations) {
93980 const declaration = declarations[0];
93981 const body = Array.isArray(declaration.parent.parent.body) ? declaration.parent.parent.body : [];
93982 const currentIndex = body.findIndex(node => node.range[0] === declaration.parent.range[0]);
93983 const previousNode = body[currentIndex - 1];
93984 return fixer => {
93985 const type = sourceCode.getTokenBefore(declaration);
93986 const prevSemi = sourceCode.getTokenBefore(type);
93987 const res = [];
93988
93989 if (previousNode && previousNode.kind === sourceCode.getText(type)) {
93990 if (prevSemi.value === ";") {
93991 res.push(fixer.replaceText(prevSemi, ","));
93992 } else {
93993 res.push(fixer.insertTextAfter(prevSemi, ","));
93994 }
93995
93996 res.push(fixer.replaceText(type, ""));
93997 }
93998
93999 return res;
94000 };
94001 }
94002 /**
94003 * Fixer to split a VariableDeclaration into individual declarations
94004 * @param {VariableDeclaration} declaration The `VariableDeclaration` to split
94005 * @returns {Function} The fixer function
94006 */
94007
94008
94009 function splitDeclarations(declaration) {
94010 return fixer => declaration.declarations.map(declarator => {
94011 const tokenAfterDeclarator = sourceCode.getTokenAfter(declarator);
94012
94013 if (tokenAfterDeclarator === null) {
94014 return null;
94015 }
94016
94017 const afterComma = sourceCode.getTokenAfter(tokenAfterDeclarator, {
94018 includeComments: true
94019 });
94020
94021 if (tokenAfterDeclarator.value !== ",") {
94022 return null;
94023 }
94024 /*
94025 * `var x,y`
94026 * tokenAfterDeclarator ^^ afterComma
94027 */
94028
94029
94030 if (afterComma.range[0] === tokenAfterDeclarator.range[1]) {
94031 return fixer.replaceText(tokenAfterDeclarator, "; ".concat(declaration.kind, " "));
94032 }
94033 /*
94034 * `var x,
94035 * tokenAfterDeclarator ^
94036 * y`
94037 * ^ afterComma
94038 */
94039
94040
94041 if (afterComma.loc.start.line > tokenAfterDeclarator.loc.end.line || afterComma.type === "Line" || afterComma.type === "Block") {
94042 let lastComment = afterComma;
94043
94044 while (lastComment.type === "Line" || lastComment.type === "Block") {
94045 lastComment = sourceCode.getTokenAfter(lastComment, {
94046 includeComments: true
94047 });
94048 }
94049
94050 return fixer.replaceTextRange([tokenAfterDeclarator.range[0], lastComment.range[0]], ";".concat(sourceCode.text.slice(tokenAfterDeclarator.range[1], lastComment.range[0])).concat(declaration.kind, " "));
94051 }
94052
94053 return fixer.replaceText(tokenAfterDeclarator, "; ".concat(declaration.kind));
94054 }).filter(x => x);
94055 }
94056 /**
94057 * Checks a given VariableDeclaration node for errors.
94058 * @param {ASTNode} node The VariableDeclaration node to check
94059 * @returns {void}
94060 * @private
94061 */
94062
94063
94064 function checkVariableDeclaration(node) {
94065 const parent = node.parent;
94066 const type = node.kind;
94067
94068 if (!options[type]) {
94069 return;
94070 }
94071
94072 const declarations = node.declarations;
94073 const declarationCounts = countDeclarations(declarations);
94074 const mixedRequires = declarations.some(isRequire) && !declarations.every(isRequire);
94075
94076 if (options[type].initialized === MODE_ALWAYS) {
94077 if (options.separateRequires && mixedRequires) {
94078 context.report({
94079 node,
94080 messageId: "splitRequires"
94081 });
94082 }
94083 } // consecutive
94084
94085
94086 const nodeIndex = parent.body && parent.body.length > 0 && parent.body.indexOf(node) || 0;
94087
94088 if (nodeIndex > 0) {
94089 const previousNode = parent.body[nodeIndex - 1];
94090 const isPreviousNodeDeclaration = previousNode.type === "VariableDeclaration";
94091 const declarationsWithPrevious = declarations.concat(previousNode.declarations || []);
94092
94093 if (isPreviousNodeDeclaration && previousNode.kind === type && !(declarationsWithPrevious.some(isRequire) && !declarationsWithPrevious.every(isRequire))) {
94094 const previousDeclCounts = countDeclarations(previousNode.declarations);
94095
94096 if (options[type].initialized === MODE_CONSECUTIVE && options[type].uninitialized === MODE_CONSECUTIVE) {
94097 context.report({
94098 node,
94099 messageId: "combine",
94100 data: {
94101 type
94102 },
94103 fix: joinDeclarations(declarations)
94104 });
94105 } else if (options[type].initialized === MODE_CONSECUTIVE && declarationCounts.initialized > 0 && previousDeclCounts.initialized > 0) {
94106 context.report({
94107 node,
94108 messageId: "combineInitialized",
94109 data: {
94110 type
94111 },
94112 fix: joinDeclarations(declarations)
94113 });
94114 } else if (options[type].uninitialized === MODE_CONSECUTIVE && declarationCounts.uninitialized > 0 && previousDeclCounts.uninitialized > 0) {
94115 context.report({
94116 node,
94117 messageId: "combineUninitialized",
94118 data: {
94119 type
94120 },
94121 fix: joinDeclarations(declarations)
94122 });
94123 }
94124 }
94125 } // always
94126
94127
94128 if (!hasOnlyOneStatement(type, declarations)) {
94129 if (options[type].initialized === MODE_ALWAYS && options[type].uninitialized === MODE_ALWAYS) {
94130 context.report({
94131 node,
94132 messageId: "combine",
94133 data: {
94134 type
94135 },
94136 fix: joinDeclarations(declarations)
94137 });
94138 } else {
94139 if (options[type].initialized === MODE_ALWAYS && declarationCounts.initialized > 0) {
94140 context.report({
94141 node,
94142 messageId: "combineInitialized",
94143 data: {
94144 type
94145 },
94146 fix: joinDeclarations(declarations)
94147 });
94148 }
94149
94150 if (options[type].uninitialized === MODE_ALWAYS && declarationCounts.uninitialized > 0) {
94151 if (node.parent.left === node && (node.parent.type === "ForInStatement" || node.parent.type === "ForOfStatement")) {
94152 return;
94153 }
94154
94155 context.report({
94156 node,
94157 messageId: "combineUninitialized",
94158 data: {
94159 type
94160 },
94161 fix: joinDeclarations(declarations)
94162 });
94163 }
94164 }
94165 } // never
94166
94167
94168 if (parent.type !== "ForStatement" || parent.init !== node) {
94169 const totalDeclarations = declarationCounts.uninitialized + declarationCounts.initialized;
94170
94171 if (totalDeclarations > 1) {
94172 if (options[type].initialized === MODE_NEVER && options[type].uninitialized === MODE_NEVER) {
94173 // both initialized and uninitialized
94174 context.report({
94175 node,
94176 messageId: "split",
94177 data: {
94178 type
94179 },
94180 fix: splitDeclarations(node)
94181 });
94182 } else if (options[type].initialized === MODE_NEVER && declarationCounts.initialized > 0) {
94183 // initialized
94184 context.report({
94185 node,
94186 messageId: "splitInitialized",
94187 data: {
94188 type
94189 },
94190 fix: splitDeclarations(node)
94191 });
94192 } else if (options[type].uninitialized === MODE_NEVER && declarationCounts.uninitialized > 0) {
94193 // uninitialized
94194 context.report({
94195 node,
94196 messageId: "splitUninitialized",
94197 data: {
94198 type
94199 },
94200 fix: splitDeclarations(node)
94201 });
94202 }
94203 }
94204 }
94205 } //--------------------------------------------------------------------------
94206 // Public API
94207 //--------------------------------------------------------------------------
94208
94209
94210 return {
94211 Program: startFunction,
94212 FunctionDeclaration: startFunction,
94213 FunctionExpression: startFunction,
94214 ArrowFunctionExpression: startFunction,
94215 BlockStatement: startBlock,
94216 ForStatement: startBlock,
94217 ForInStatement: startBlock,
94218 ForOfStatement: startBlock,
94219 SwitchStatement: startBlock,
94220 VariableDeclaration: checkVariableDeclaration,
94221 "ForStatement:exit": endBlock,
94222 "ForOfStatement:exit": endBlock,
94223 "ForInStatement:exit": endBlock,
94224 "SwitchStatement:exit": endBlock,
94225 "BlockStatement:exit": endBlock,
94226 "Program:exit": endFunction,
94227 "FunctionDeclaration:exit": endFunction,
94228 "FunctionExpression:exit": endFunction,
94229 "ArrowFunctionExpression:exit": endFunction
94230 };
94231 }
94232
94233};
94234
94235/***/ }),
6a5a0f88 94236/* 669 */
eb39fafa
DC
94237/***/ (function(module, exports, __webpack_require__) {
94238
94239"use strict";
94240/**
94241 * @fileoverview Rule to check multiple var declarations per line
94242 * @author Alberto Rodríguez
94243 */
94244 //------------------------------------------------------------------------------
94245// Rule Definition
94246//------------------------------------------------------------------------------
94247
94248module.exports = {
94249 meta: {
94250 type: "suggestion",
94251 docs: {
94252 description: "require or disallow newlines around variable declarations",
94253 category: "Stylistic Issues",
94254 recommended: false,
94255 url: "https://eslint.org/docs/rules/one-var-declaration-per-line"
94256 },
94257 schema: [{
94258 enum: ["always", "initializations"]
94259 }],
94260 fixable: "whitespace",
94261 messages: {
94262 expectVarOnNewline: "Expected variable declaration to be on a new line."
94263 }
94264 },
94265
94266 create(context) {
94267 const always = context.options[0] === "always"; //--------------------------------------------------------------------------
94268 // Helpers
94269 //--------------------------------------------------------------------------
94270
94271 /**
94272 * Determine if provided keyword is a variant of for specifiers
94273 * @private
94274 * @param {string} keyword keyword to test
94275 * @returns {boolean} True if `keyword` is a variant of for specifier
94276 */
94277
94278 function isForTypeSpecifier(keyword) {
94279 return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
94280 }
94281 /**
94282 * Checks newlines around variable declarations.
94283 * @private
94284 * @param {ASTNode} node `VariableDeclaration` node to test
94285 * @returns {void}
94286 */
94287
94288
94289 function checkForNewLine(node) {
94290 if (isForTypeSpecifier(node.parent.type)) {
94291 return;
94292 }
94293
94294 const declarations = node.declarations;
94295 let prev;
94296 declarations.forEach(current => {
94297 if (prev && prev.loc.end.line === current.loc.start.line) {
94298 if (always || prev.init || current.init) {
94299 context.report({
94300 node,
94301 messageId: "expectVarOnNewline",
6a5a0f88 94302 loc: current.loc,
eb39fafa
DC
94303 fix: fixer => fixer.insertTextBefore(current, "\n")
94304 });
94305 }
94306 }
94307
94308 prev = current;
94309 });
94310 } //--------------------------------------------------------------------------
94311 // Public
94312 //--------------------------------------------------------------------------
94313
94314
94315 return {
94316 VariableDeclaration: checkForNewLine
94317 };
94318 }
94319
94320};
94321
94322/***/ }),
6a5a0f88 94323/* 670 */
eb39fafa
DC
94324/***/ (function(module, exports, __webpack_require__) {
94325
94326"use strict";
94327/**
94328 * @fileoverview Rule to replace assignment expressions with operator assignment
94329 * @author Brandon Mills
94330 */
94331 //------------------------------------------------------------------------------
94332// Requirements
94333//------------------------------------------------------------------------------
94334
94335const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
94336// Helpers
94337//------------------------------------------------------------------------------
94338
94339/**
94340 * Checks whether an operator is commutative and has an operator assignment
94341 * shorthand form.
94342 * @param {string} operator Operator to check.
94343 * @returns {boolean} True if the operator is commutative and has a
94344 * shorthand form.
94345 */
94346
94347
94348function isCommutativeOperatorWithShorthand(operator) {
94349 return ["*", "&", "^", "|"].indexOf(operator) >= 0;
94350}
94351/**
94352 * Checks whether an operator is not commutative and has an operator assignment
94353 * shorthand form.
94354 * @param {string} operator Operator to check.
94355 * @returns {boolean} True if the operator is not commutative and has
94356 * a shorthand form.
94357 */
94358
94359
94360function isNonCommutativeOperatorWithShorthand(operator) {
94361 return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].indexOf(operator) >= 0;
94362} //------------------------------------------------------------------------------
94363// Rule Definition
94364//------------------------------------------------------------------------------
94365
94366/**
94367 * Checks whether two expressions reference the same value. For example:
94368 * a = a
94369 * a.b = a.b
94370 * a[0] = a[0]
94371 * a['b'] = a['b']
94372 * @param {ASTNode} a Left side of the comparison.
94373 * @param {ASTNode} b Right side of the comparison.
94374 * @returns {boolean} True if both sides match and reference the same value.
94375 */
94376
94377
94378function same(a, b) {
94379 if (a.type !== b.type) {
94380 return false;
94381 }
94382
94383 switch (a.type) {
94384 case "Identifier":
94385 return a.name === b.name;
94386
94387 case "Literal":
94388 return a.value === b.value;
94389
94390 case "MemberExpression":
94391 /*
94392 * x[0] = x[0]
94393 * x[y] = x[y]
94394 * x.y = x.y
94395 */
94396 return same(a.object, b.object) && same(a.property, b.property);
94397
94398 case "ThisExpression":
94399 return true;
94400
94401 default:
94402 return false;
94403 }
94404}
94405/**
94406 * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
94407 * toString calls regardless of whether assignment shorthand is used)
94408 * @param {ASTNode} node The node on the left side of the expression
94409 * @returns {boolean} `true` if the node can be fixed
94410 */
94411
94412
94413function canBeFixed(node) {
94414 return node.type === "Identifier" || node.type === "MemberExpression" && (node.object.type === "Identifier" || node.object.type === "ThisExpression") && (!node.computed || node.property.type === "Literal");
94415}
94416
94417module.exports = {
94418 meta: {
94419 type: "suggestion",
94420 docs: {
94421 description: "require or disallow assignment operator shorthand where possible",
94422 category: "Stylistic Issues",
94423 recommended: false,
94424 url: "https://eslint.org/docs/rules/operator-assignment"
94425 },
94426 schema: [{
94427 enum: ["always", "never"]
94428 }],
94429 fixable: "code",
94430 messages: {
94431 replaced: "Assignment can be replaced with operator assignment.",
94432 unexpected: "Unexpected operator assignment shorthand."
94433 }
94434 },
94435
94436 create(context) {
94437 const sourceCode = context.getSourceCode();
94438 /**
94439 * Returns the operator token of an AssignmentExpression or BinaryExpression
94440 * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
94441 * @returns {Token} The operator token in the node
94442 */
94443
94444 function getOperatorToken(node) {
94445 return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
94446 }
94447 /**
94448 * Ensures that an assignment uses the shorthand form where possible.
94449 * @param {ASTNode} node An AssignmentExpression node.
94450 * @returns {void}
94451 */
94452
94453
94454 function verify(node) {
94455 if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
94456 return;
94457 }
94458
94459 const left = node.left;
94460 const expr = node.right;
94461 const operator = expr.operator;
94462
94463 if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
94464 if (same(left, expr.left)) {
94465 context.report({
94466 node,
94467 messageId: "replaced",
94468
94469 fix(fixer) {
94470 if (canBeFixed(left)) {
94471 const equalsToken = getOperatorToken(node);
94472 const operatorToken = getOperatorToken(expr);
94473 const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
94474 const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]); // Check for comments that would be removed.
94475
94476 if (sourceCode.commentsExistBetween(equalsToken, operatorToken)) {
94477 return null;
94478 }
94479
94480 return fixer.replaceText(node, "".concat(leftText).concat(expr.operator, "=").concat(rightText));
94481 }
94482
94483 return null;
94484 }
94485
94486 });
94487 } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
94488 /*
94489 * This case can't be fixed safely.
94490 * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
94491 * change the execution order of the valueOf() functions.
94492 */
94493 context.report({
94494 node,
94495 messageId: "replaced"
94496 });
94497 }
94498 }
94499 }
94500 /**
94501 * Warns if an assignment expression uses operator assignment shorthand.
94502 * @param {ASTNode} node An AssignmentExpression node.
94503 * @returns {void}
94504 */
94505
94506
94507 function prohibit(node) {
94508 if (node.operator !== "=") {
94509 context.report({
94510 node,
94511 messageId: "unexpected",
94512
94513 fix(fixer) {
94514 if (canBeFixed(node.left)) {
94515 const firstToken = sourceCode.getFirstToken(node);
94516 const operatorToken = getOperatorToken(node);
94517 const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
94518 const newOperator = node.operator.slice(0, -1);
94519 let rightText; // Check for comments that would be duplicated.
94520
94521 if (sourceCode.commentsExistBetween(firstToken, operatorToken)) {
94522 return null;
94523 } // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
94524
94525
94526 if (astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({
94527 type: "BinaryExpression",
94528 operator: newOperator
94529 }) && !astUtils.isParenthesised(sourceCode, node.right)) {
94530 rightText = "".concat(sourceCode.text.slice(operatorToken.range[1], node.right.range[0]), "(").concat(sourceCode.getText(node.right), ")");
94531 } else {
94532 const tokenAfterOperator = sourceCode.getTokenAfter(operatorToken, {
94533 includeComments: true
94534 });
94535 let rightTextPrefix = "";
94536
94537 if (operatorToken.range[1] === tokenAfterOperator.range[0] && !astUtils.canTokensBeAdjacent({
94538 type: "Punctuator",
94539 value: newOperator
94540 }, tokenAfterOperator)) {
94541 rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
94542 }
94543
94544 rightText = "".concat(rightTextPrefix).concat(sourceCode.text.slice(operatorToken.range[1], node.range[1]));
94545 }
94546
94547 return fixer.replaceText(node, "".concat(leftText, "= ").concat(leftText).concat(newOperator).concat(rightText));
94548 }
94549
94550 return null;
94551 }
94552
94553 });
94554 }
94555 }
94556
94557 return {
94558 AssignmentExpression: context.options[0] !== "never" ? verify : prohibit
94559 };
94560 }
94561
94562};
94563
94564/***/ }),
6a5a0f88 94565/* 671 */
eb39fafa
DC
94566/***/ (function(module, exports, __webpack_require__) {
94567
94568"use strict";
94569/**
94570 * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before
94571 * @author Benoît Zugmeyer
94572 */
94573 //------------------------------------------------------------------------------
94574// Requirements
94575//------------------------------------------------------------------------------
94576
94577const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
94578// Rule Definition
94579//------------------------------------------------------------------------------
94580
94581
94582module.exports = {
94583 meta: {
94584 type: "layout",
94585 docs: {
94586 description: "enforce consistent linebreak style for operators",
94587 category: "Stylistic Issues",
94588 recommended: false,
94589 url: "https://eslint.org/docs/rules/operator-linebreak"
94590 },
94591 schema: [{
94592 enum: ["after", "before", "none", null]
94593 }, {
94594 type: "object",
94595 properties: {
94596 overrides: {
94597 type: "object",
94598 properties: {
94599 anyOf: {
94600 type: "string",
94601 enum: ["after", "before", "none", "ignore"]
94602 }
94603 }
94604 }
94605 },
94606 additionalProperties: false
94607 }],
94608 fixable: "code",
94609 messages: {
94610 operatorAtBeginning: "'{{operator}}' should be placed at the beginning of the line.",
94611 operatorAtEnd: "'{{operator}}' should be placed at the end of the line.",
94612 badLinebreak: "Bad line breaking before and after '{{operator}}'.",
94613 noLinebreak: "There should be no line break before or after '{{operator}}'."
94614 }
94615 },
94616
94617 create(context) {
94618 const usedDefaultGlobal = !context.options[0];
94619 const globalStyle = context.options[0] || "after";
94620 const options = context.options[1] || {};
94621 const styleOverrides = options.overrides ? Object.assign({}, options.overrides) : {};
94622
94623 if (usedDefaultGlobal && !styleOverrides["?"]) {
94624 styleOverrides["?"] = "before";
94625 }
94626
94627 if (usedDefaultGlobal && !styleOverrides[":"]) {
94628 styleOverrides[":"] = "before";
94629 }
94630
94631 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
94632 // Helpers
94633 //--------------------------------------------------------------------------
94634
94635 /**
94636 * Gets a fixer function to fix rule issues
94637 * @param {Token} operatorToken The operator token of an expression
94638 * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none'
94639 * @returns {Function} A fixer function
94640 */
94641
94642 function getFixer(operatorToken, desiredStyle) {
94643 return fixer => {
94644 const tokenBefore = sourceCode.getTokenBefore(operatorToken);
94645 const tokenAfter = sourceCode.getTokenAfter(operatorToken);
94646 const textBefore = sourceCode.text.slice(tokenBefore.range[1], operatorToken.range[0]);
94647 const textAfter = sourceCode.text.slice(operatorToken.range[1], tokenAfter.range[0]);
94648 const hasLinebreakBefore = !astUtils.isTokenOnSameLine(tokenBefore, operatorToken);
94649 const hasLinebreakAfter = !astUtils.isTokenOnSameLine(operatorToken, tokenAfter);
94650 let newTextBefore, newTextAfter;
94651
94652 if (hasLinebreakBefore !== hasLinebreakAfter && desiredStyle !== "none") {
94653 // If there is a comment before and after the operator, don't do a fix.
94654 if (sourceCode.getTokenBefore(operatorToken, {
94655 includeComments: true
94656 }) !== tokenBefore && sourceCode.getTokenAfter(operatorToken, {
94657 includeComments: true
94658 }) !== tokenAfter) {
94659 return null;
94660 }
94661 /*
94662 * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator.
94663 * foo &&
94664 * bar
94665 * would get fixed to
94666 * foo
94667 * && bar
94668 */
94669
94670
94671 newTextBefore = textAfter;
94672 newTextAfter = textBefore;
94673 } else {
94674 const LINEBREAK_REGEX = astUtils.createGlobalLinebreakMatcher(); // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings.
94675
94676 newTextBefore = desiredStyle === "before" || textBefore.trim() ? textBefore : textBefore.replace(LINEBREAK_REGEX, "");
94677 newTextAfter = desiredStyle === "after" || textAfter.trim() ? textAfter : textAfter.replace(LINEBREAK_REGEX, ""); // If there was no change (due to interfering comments), don't output a fix.
94678
94679 if (newTextBefore === textBefore && newTextAfter === textAfter) {
94680 return null;
94681 }
94682 }
94683
94684 if (newTextAfter === "" && tokenAfter.type === "Punctuator" && "+-".includes(operatorToken.value) && tokenAfter.value === operatorToken.value) {
94685 // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-.
94686 newTextAfter += " ";
94687 }
94688
94689 return fixer.replaceTextRange([tokenBefore.range[1], tokenAfter.range[0]], newTextBefore + operatorToken.value + newTextAfter);
94690 };
94691 }
94692 /**
94693 * Checks the operator placement
94694 * @param {ASTNode} node The node to check
94695 * @param {ASTNode} leftSide The node that comes before the operator in `node`
94696 * @private
94697 * @returns {void}
94698 */
94699
94700
94701 function validateNode(node, leftSide) {
94702 /*
94703 * When the left part of a binary expression is a single expression wrapped in
94704 * parentheses (ex: `(a) + b`), leftToken will be the last token of the expression
94705 * and operatorToken will be the closing parenthesis.
94706 * The leftToken should be the last closing parenthesis, and the operatorToken
94707 * should be the token right after that.
94708 */
94709 const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken);
94710 const leftToken = sourceCode.getTokenBefore(operatorToken);
94711 const rightToken = sourceCode.getTokenAfter(operatorToken);
94712 const operator = operatorToken.value;
94713 const operatorStyleOverride = styleOverrides[operator];
94714 const style = operatorStyleOverride || globalStyle;
94715 const fix = getFixer(operatorToken, style); // if single line
94716
94717 if (astUtils.isTokenOnSameLine(leftToken, operatorToken) && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {// do nothing.
94718 } else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) && !astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
94719 // lone operator
94720 context.report({
94721 node,
94722 loc: operatorToken.loc,
94723 messageId: "badLinebreak",
94724 data: {
94725 operator
94726 },
94727 fix
94728 });
94729 } else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) {
94730 context.report({
94731 node,
94732 loc: operatorToken.loc,
94733 messageId: "operatorAtBeginning",
94734 data: {
94735 operator
94736 },
94737 fix
94738 });
94739 } else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
94740 context.report({
94741 node,
94742 loc: operatorToken.loc,
94743 messageId: "operatorAtEnd",
94744 data: {
94745 operator
94746 },
94747 fix
94748 });
94749 } else if (style === "none") {
94750 context.report({
94751 node,
94752 loc: operatorToken.loc,
94753 messageId: "noLinebreak",
94754 data: {
94755 operator
94756 },
94757 fix
94758 });
94759 }
94760 }
94761 /**
94762 * Validates a binary expression using `validateNode`
94763 * @param {BinaryExpression|LogicalExpression|AssignmentExpression} node node to be validated
94764 * @returns {void}
94765 */
94766
94767
94768 function validateBinaryExpression(node) {
94769 validateNode(node, node.left);
94770 } //--------------------------------------------------------------------------
94771 // Public
94772 //--------------------------------------------------------------------------
94773
94774
94775 return {
94776 BinaryExpression: validateBinaryExpression,
94777 LogicalExpression: validateBinaryExpression,
94778 AssignmentExpression: validateBinaryExpression,
94779
94780 VariableDeclarator(node) {
94781 if (node.init) {
94782 validateNode(node, node.id);
94783 }
94784 },
94785
94786 ConditionalExpression(node) {
94787 validateNode(node, node.test);
94788 validateNode(node, node.consequent);
94789 }
94790
94791 };
94792 }
94793
94794};
94795
94796/***/ }),
6a5a0f88 94797/* 672 */
eb39fafa
DC
94798/***/ (function(module, exports, __webpack_require__) {
94799
94800"use strict";
94801/**
94802 * @fileoverview A rule to ensure blank lines within blocks.
94803 * @author Mathias Schreck <https://github.com/lo1tuma>
94804 */
94805 //------------------------------------------------------------------------------
94806// Requirements
94807//------------------------------------------------------------------------------
94808
94809const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
94810// Rule Definition
94811//------------------------------------------------------------------------------
94812
94813
94814module.exports = {
94815 meta: {
94816 type: "layout",
94817 docs: {
94818 description: "require or disallow padding within blocks",
94819 category: "Stylistic Issues",
94820 recommended: false,
94821 url: "https://eslint.org/docs/rules/padded-blocks"
94822 },
94823 fixable: "whitespace",
94824 schema: [{
94825 oneOf: [{
94826 enum: ["always", "never"]
94827 }, {
94828 type: "object",
94829 properties: {
94830 blocks: {
94831 enum: ["always", "never"]
94832 },
94833 switches: {
94834 enum: ["always", "never"]
94835 },
94836 classes: {
94837 enum: ["always", "never"]
94838 }
94839 },
94840 additionalProperties: false,
94841 minProperties: 1
94842 }]
94843 }, {
94844 type: "object",
94845 properties: {
94846 allowSingleLineBlocks: {
94847 type: "boolean"
94848 }
94849 }
94850 }],
94851 messages: {
94852 alwaysPadBlock: "Block must be padded by blank lines.",
94853 neverPadBlock: "Block must not be padded by blank lines."
94854 }
94855 },
94856
94857 create(context) {
94858 const options = {};
94859 const typeOptions = context.options[0] || "always";
94860 const exceptOptions = context.options[1] || {};
94861
94862 if (typeof typeOptions === "string") {
94863 const shouldHavePadding = typeOptions === "always";
94864 options.blocks = shouldHavePadding;
94865 options.switches = shouldHavePadding;
94866 options.classes = shouldHavePadding;
94867 } else {
94868 if (Object.prototype.hasOwnProperty.call(typeOptions, "blocks")) {
94869 options.blocks = typeOptions.blocks === "always";
94870 }
94871
94872 if (Object.prototype.hasOwnProperty.call(typeOptions, "switches")) {
94873 options.switches = typeOptions.switches === "always";
94874 }
94875
94876 if (Object.prototype.hasOwnProperty.call(typeOptions, "classes")) {
94877 options.classes = typeOptions.classes === "always";
94878 }
94879 }
94880
94881 if (Object.prototype.hasOwnProperty.call(exceptOptions, "allowSingleLineBlocks")) {
94882 options.allowSingleLineBlocks = exceptOptions.allowSingleLineBlocks === true;
94883 }
94884
94885 const sourceCode = context.getSourceCode();
94886 /**
94887 * Gets the open brace token from a given node.
94888 * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace.
94889 * @returns {Token} The token of the open brace.
94890 */
94891
94892 function getOpenBrace(node) {
94893 if (node.type === "SwitchStatement") {
94894 return sourceCode.getTokenBefore(node.cases[0]);
94895 }
94896
94897 return sourceCode.getFirstToken(node);
94898 }
94899 /**
94900 * Checks if the given parameter is a comment node
94901 * @param {ASTNode|Token} node An AST node or token
94902 * @returns {boolean} True if node is a comment
94903 */
94904
94905
94906 function isComment(node) {
94907 return node.type === "Line" || node.type === "Block";
94908 }
94909 /**
94910 * Checks if there is padding between two tokens
94911 * @param {Token} first The first token
94912 * @param {Token} second The second token
94913 * @returns {boolean} True if there is at least a line between the tokens
94914 */
94915
94916
94917 function isPaddingBetweenTokens(first, second) {
94918 return second.loc.start.line - first.loc.end.line >= 2;
94919 }
94920 /**
94921 * Checks if the given token has a blank line after it.
94922 * @param {Token} token The token to check.
94923 * @returns {boolean} Whether or not the token is followed by a blank line.
94924 */
94925
94926
94927 function getFirstBlockToken(token) {
94928 let prev,
94929 first = token;
94930
94931 do {
94932 prev = first;
94933 first = sourceCode.getTokenAfter(first, {
94934 includeComments: true
94935 });
94936 } while (isComment(first) && first.loc.start.line === prev.loc.end.line);
94937
94938 return first;
94939 }
94940 /**
94941 * Checks if the given token is preceded by a blank line.
94942 * @param {Token} token The token to check
94943 * @returns {boolean} Whether or not the token is preceded by a blank line
94944 */
94945
94946
94947 function getLastBlockToken(token) {
94948 let last = token,
94949 next;
94950
94951 do {
94952 next = last;
94953 last = sourceCode.getTokenBefore(last, {
94954 includeComments: true
94955 });
94956 } while (isComment(last) && last.loc.end.line === next.loc.start.line);
94957
94958 return last;
94959 }
94960 /**
94961 * Checks if a node should be padded, according to the rule config.
94962 * @param {ASTNode} node The AST node to check.
94963 * @returns {boolean} True if the node should be padded, false otherwise.
94964 */
94965
94966
94967 function requirePaddingFor(node) {
94968 switch (node.type) {
94969 case "BlockStatement":
94970 return options.blocks;
94971
94972 case "SwitchStatement":
94973 return options.switches;
94974
94975 case "ClassBody":
94976 return options.classes;
94977
94978 /* istanbul ignore next */
94979
94980 default:
94981 throw new Error("unreachable");
94982 }
94983 }
94984 /**
94985 * Checks the given BlockStatement node to be padded if the block is not empty.
94986 * @param {ASTNode} node The AST node of a BlockStatement.
94987 * @returns {void} undefined.
94988 */
94989
94990
94991 function checkPadding(node) {
94992 const openBrace = getOpenBrace(node),
94993 firstBlockToken = getFirstBlockToken(openBrace),
94994 tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, {
94995 includeComments: true
94996 }),
94997 closeBrace = sourceCode.getLastToken(node),
94998 lastBlockToken = getLastBlockToken(closeBrace),
94999 tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, {
95000 includeComments: true
95001 }),
95002 blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken),
95003 blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
95004
95005 if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) {
95006 return;
95007 }
95008
95009 if (requirePaddingFor(node)) {
95010 if (!blockHasTopPadding) {
95011 context.report({
95012 node,
95013 loc: {
6a5a0f88
TL
95014 start: tokenBeforeFirst.loc.start,
95015 end: firstBlockToken.loc.start
eb39fafa
DC
95016 },
95017
95018 fix(fixer) {
95019 return fixer.insertTextAfter(tokenBeforeFirst, "\n");
95020 },
95021
95022 messageId: "alwaysPadBlock"
95023 });
95024 }
95025
95026 if (!blockHasBottomPadding) {
95027 context.report({
95028 node,
95029 loc: {
6a5a0f88
TL
95030 end: tokenAfterLast.loc.start,
95031 start: lastBlockToken.loc.end
eb39fafa
DC
95032 },
95033
95034 fix(fixer) {
95035 return fixer.insertTextBefore(tokenAfterLast, "\n");
95036 },
95037
95038 messageId: "alwaysPadBlock"
95039 });
95040 }
95041 } else {
95042 if (blockHasTopPadding) {
95043 context.report({
95044 node,
95045 loc: {
6a5a0f88
TL
95046 start: tokenBeforeFirst.loc.start,
95047 end: firstBlockToken.loc.start
eb39fafa
DC
95048 },
95049
95050 fix(fixer) {
95051 return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n");
95052 },
95053
95054 messageId: "neverPadBlock"
95055 });
95056 }
95057
95058 if (blockHasBottomPadding) {
95059 context.report({
95060 node,
95061 loc: {
6a5a0f88
TL
95062 end: tokenAfterLast.loc.start,
95063 start: lastBlockToken.loc.end
eb39fafa
DC
95064 },
95065 messageId: "neverPadBlock",
95066
95067 fix(fixer) {
95068 return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n");
95069 }
95070
95071 });
95072 }
95073 }
95074 }
95075
95076 const rule = {};
95077
95078 if (Object.prototype.hasOwnProperty.call(options, "switches")) {
95079 rule.SwitchStatement = function (node) {
95080 if (node.cases.length === 0) {
95081 return;
95082 }
95083
95084 checkPadding(node);
95085 };
95086 }
95087
95088 if (Object.prototype.hasOwnProperty.call(options, "blocks")) {
95089 rule.BlockStatement = function (node) {
95090 if (node.body.length === 0) {
95091 return;
95092 }
95093
95094 checkPadding(node);
95095 };
95096 }
95097
95098 if (Object.prototype.hasOwnProperty.call(options, "classes")) {
95099 rule.ClassBody = function (node) {
95100 if (node.body.length === 0) {
95101 return;
95102 }
95103
95104 checkPadding(node);
95105 };
95106 }
95107
95108 return rule;
95109 }
95110
95111};
95112
95113/***/ }),
6a5a0f88 95114/* 673 */
eb39fafa
DC
95115/***/ (function(module, exports, __webpack_require__) {
95116
95117"use strict";
95118/**
95119 * @fileoverview Rule to require or disallow newlines between statements
95120 * @author Toru Nagashima
95121 */
95122 //------------------------------------------------------------------------------
95123// Requirements
95124//------------------------------------------------------------------------------
95125
95126function _templateObject() {
95127 const data = _taggedTemplateLiteral(["^(s*?", ")s*", "(s*;?)$"], ["^(\\s*?", ")\\s*", "(\\s*;?)$"]);
95128
95129 _templateObject = function _templateObject() {
95130 return data;
95131 };
95132
95133 return data;
95134}
95135
95136function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
95137
95138const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
95139// Helpers
95140//------------------------------------------------------------------------------
95141
95142
95143const LT = "[".concat(Array.from(astUtils.LINEBREAKS).join(""), "]");
95144const PADDING_LINE_SEQUENCE = new RegExp(String.raw(_templateObject(), LT, LT), "u");
95145const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u;
95146const CJS_IMPORT = /^require\(/u;
95147/**
95148 * Creates tester which check if a node starts with specific keyword.
95149 * @param {string} keyword The keyword to test.
95150 * @returns {Object} the created tester.
95151 * @private
95152 */
95153
95154function newKeywordTester(keyword) {
95155 return {
95156 test: (node, sourceCode) => sourceCode.getFirstToken(node).value === keyword
95157 };
95158}
95159/**
95160 * Creates tester which check if a node starts with specific keyword and spans a single line.
95161 * @param {string} keyword The keyword to test.
95162 * @returns {Object} the created tester.
95163 * @private
95164 */
95165
95166
95167function newSinglelineKeywordTester(keyword) {
95168 return {
95169 test: (node, sourceCode) => node.loc.start.line === node.loc.end.line && sourceCode.getFirstToken(node).value === keyword
95170 };
95171}
95172/**
95173 * Creates tester which check if a node starts with specific keyword and spans multiple lines.
95174 * @param {string} keyword The keyword to test.
95175 * @returns {Object} the created tester.
95176 * @private
95177 */
95178
95179
95180function newMultilineKeywordTester(keyword) {
95181 return {
95182 test: (node, sourceCode) => node.loc.start.line !== node.loc.end.line && sourceCode.getFirstToken(node).value === keyword
95183 };
95184}
95185/**
95186 * Creates tester which check if a node is specific type.
95187 * @param {string} type The node type to test.
95188 * @returns {Object} the created tester.
95189 * @private
95190 */
95191
95192
95193function newNodeTypeTester(type) {
95194 return {
95195 test: node => node.type === type
95196 };
95197}
95198/**
95199 * Checks the given node is an expression statement of IIFE.
95200 * @param {ASTNode} node The node to check.
95201 * @returns {boolean} `true` if the node is an expression statement of IIFE.
95202 * @private
95203 */
95204
95205
95206function isIIFEStatement(node) {
95207 if (node.type === "ExpressionStatement") {
95208 let call = node.expression;
95209
95210 if (call.type === "UnaryExpression") {
95211 call = call.argument;
95212 }
95213
95214 return call.type === "CallExpression" && astUtils.isFunction(call.callee);
95215 }
95216
95217 return false;
95218}
95219/**
95220 * Checks whether the given node is a block-like statement.
95221 * This checks the last token of the node is the closing brace of a block.
95222 * @param {SourceCode} sourceCode The source code to get tokens.
95223 * @param {ASTNode} node The node to check.
95224 * @returns {boolean} `true` if the node is a block-like statement.
95225 * @private
95226 */
95227
95228
95229function isBlockLikeStatement(sourceCode, node) {
95230 // do-while with a block is a block-like statement.
95231 if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") {
95232 return true;
95233 }
95234 /*
95235 * IIFE is a block-like statement specially from
95236 * JSCS#disallowPaddingNewLinesAfterBlocks.
95237 */
95238
95239
95240 if (isIIFEStatement(node)) {
95241 return true;
95242 } // Checks the last token is a closing brace of blocks.
95243
95244
95245 const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken);
95246 const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken) ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) : null;
95247 return Boolean(belongingNode) && (belongingNode.type === "BlockStatement" || belongingNode.type === "SwitchStatement");
95248}
95249/**
95250 * Check whether the given node is a directive or not.
95251 * @param {ASTNode} node The node to check.
95252 * @param {SourceCode} sourceCode The source code object to get tokens.
95253 * @returns {boolean} `true` if the node is a directive.
95254 */
95255
95256
95257function isDirective(node, sourceCode) {
95258 return node.type === "ExpressionStatement" && (node.parent.type === "Program" || node.parent.type === "BlockStatement" && astUtils.isFunction(node.parent.parent)) && node.expression.type === "Literal" && typeof node.expression.value === "string" && !astUtils.isParenthesised(sourceCode, node.expression);
95259}
95260/**
95261 * Check whether the given node is a part of directive prologue or not.
95262 * @param {ASTNode} node The node to check.
95263 * @param {SourceCode} sourceCode The source code object to get tokens.
95264 * @returns {boolean} `true` if the node is a part of directive prologue.
95265 */
95266
95267
95268function isDirectivePrologue(node, sourceCode) {
95269 if (isDirective(node, sourceCode)) {
95270 for (const sibling of node.parent.body) {
95271 if (sibling === node) {
95272 break;
95273 }
95274
95275 if (!isDirective(sibling, sourceCode)) {
95276 return false;
95277 }
95278 }
95279
95280 return true;
95281 }
95282
95283 return false;
95284}
95285/**
95286 * Gets the actual last token.
95287 *
95288 * If a semicolon is semicolon-less style's semicolon, this ignores it.
95289 * For example:
95290 *
95291 * foo()
95292 * ;[1, 2, 3].forEach(bar)
95293 * @param {SourceCode} sourceCode The source code to get tokens.
95294 * @param {ASTNode} node The node to get.
95295 * @returns {Token} The actual last token.
95296 * @private
95297 */
95298
95299
95300function getActualLastToken(sourceCode, node) {
95301 const semiToken = sourceCode.getLastToken(node);
95302 const prevToken = sourceCode.getTokenBefore(semiToken);
95303 const nextToken = sourceCode.getTokenAfter(semiToken);
95304 const isSemicolonLessStyle = Boolean(prevToken && nextToken && prevToken.range[0] >= node.range[0] && astUtils.isSemicolonToken(semiToken) && semiToken.loc.start.line !== prevToken.loc.end.line && semiToken.loc.end.line === nextToken.loc.start.line);
95305 return isSemicolonLessStyle ? prevToken : semiToken;
95306}
95307/**
95308 * This returns the concatenation of the first 2 captured strings.
95309 * @param {string} _ Unused. Whole matched string.
95310 * @param {string} trailingSpaces The trailing spaces of the first line.
95311 * @param {string} indentSpaces The indentation spaces of the last line.
95312 * @returns {string} The concatenation of trailingSpaces and indentSpaces.
95313 * @private
95314 */
95315
95316
95317function replacerToRemovePaddingLines(_, trailingSpaces, indentSpaces) {
95318 return trailingSpaces + indentSpaces;
95319}
95320/**
95321 * Check and report statements for `any` configuration.
95322 * It does nothing.
95323 * @returns {void}
95324 * @private
95325 */
95326
95327
95328function verifyForAny() {}
95329/**
95330 * Check and report statements for `never` configuration.
95331 * This autofix removes blank lines between the given 2 statements.
95332 * However, if comments exist between 2 blank lines, it does not remove those
95333 * blank lines automatically.
95334 * @param {RuleContext} context The rule context to report.
95335 * @param {ASTNode} _ Unused. The previous node to check.
95336 * @param {ASTNode} nextNode The next node to check.
95337 * @param {Array<Token[]>} paddingLines The array of token pairs that blank
95338 * lines exist between the pair.
95339 * @returns {void}
95340 * @private
95341 */
95342
95343
95344function verifyForNever(context, _, nextNode, paddingLines) {
95345 if (paddingLines.length === 0) {
95346 return;
95347 }
95348
95349 context.report({
95350 node: nextNode,
95351 messageId: "unexpectedBlankLine",
95352
95353 fix(fixer) {
95354 if (paddingLines.length >= 2) {
95355 return null;
95356 }
95357
95358 const prevToken = paddingLines[0][0];
95359 const nextToken = paddingLines[0][1];
95360 const start = prevToken.range[1];
95361 const end = nextToken.range[0];
95362 const text = context.getSourceCode().text.slice(start, end).replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines);
95363 return fixer.replaceTextRange([start, end], text);
95364 }
95365
95366 });
95367}
95368/**
95369 * Check and report statements for `always` configuration.
95370 * This autofix inserts a blank line between the given 2 statements.
95371 * If the `prevNode` has trailing comments, it inserts a blank line after the
95372 * trailing comments.
95373 * @param {RuleContext} context The rule context to report.
95374 * @param {ASTNode} prevNode The previous node to check.
95375 * @param {ASTNode} nextNode The next node to check.
95376 * @param {Array<Token[]>} paddingLines The array of token pairs that blank
95377 * lines exist between the pair.
95378 * @returns {void}
95379 * @private
95380 */
95381
95382
95383function verifyForAlways(context, prevNode, nextNode, paddingLines) {
95384 if (paddingLines.length > 0) {
95385 return;
95386 }
95387
95388 context.report({
95389 node: nextNode,
95390 messageId: "expectedBlankLine",
95391
95392 fix(fixer) {
95393 const sourceCode = context.getSourceCode();
95394 let prevToken = getActualLastToken(sourceCode, prevNode);
95395 const nextToken = sourceCode.getFirstTokenBetween(prevToken, nextNode, {
95396 includeComments: true,
95397
95398 /**
95399 * Skip the trailing comments of the previous node.
95400 * This inserts a blank line after the last trailing comment.
95401 *
95402 * For example:
95403 *
95404 * foo(); // trailing comment.
95405 * // comment.
95406 * bar();
95407 *
95408 * Get fixed to:
95409 *
95410 * foo(); // trailing comment.
95411 *
95412 * // comment.
95413 * bar();
95414 * @param {Token} token The token to check.
95415 * @returns {boolean} `true` if the token is not a trailing comment.
95416 * @private
95417 */
95418 filter(token) {
95419 if (astUtils.isTokenOnSameLine(prevToken, token)) {
95420 prevToken = token;
95421 return false;
95422 }
95423
95424 return true;
95425 }
95426
95427 }) || nextNode;
95428 const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) ? "\n\n" : "\n";
95429 return fixer.insertTextAfter(prevToken, insertText);
95430 }
95431
95432 });
95433}
95434/**
95435 * Types of blank lines.
95436 * `any`, `never`, and `always` are defined.
95437 * Those have `verify` method to check and report statements.
95438 * @private
95439 */
95440
95441
95442const PaddingTypes = {
95443 any: {
95444 verify: verifyForAny
95445 },
95446 never: {
95447 verify: verifyForNever
95448 },
95449 always: {
95450 verify: verifyForAlways
95451 }
95452};
95453/**
95454 * Types of statements.
95455 * Those have `test` method to check it matches to the given statement.
95456 * @private
95457 */
95458
95459const StatementTypes = {
95460 "*": {
95461 test: () => true
95462 },
95463 "block-like": {
95464 test: (node, sourceCode) => isBlockLikeStatement(sourceCode, node)
95465 },
95466 "cjs-export": {
95467 test: (node, sourceCode) => node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && CJS_EXPORT.test(sourceCode.getText(node.expression.left))
95468 },
95469 "cjs-import": {
95470 test: (node, sourceCode) => node.type === "VariableDeclaration" && node.declarations.length > 0 && Boolean(node.declarations[0].init) && CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init))
95471 },
95472 directive: {
95473 test: isDirectivePrologue
95474 },
95475 expression: {
95476 test: (node, sourceCode) => node.type === "ExpressionStatement" && !isDirectivePrologue(node, sourceCode)
95477 },
95478 iife: {
95479 test: isIIFEStatement
95480 },
95481 "multiline-block-like": {
95482 test: (node, sourceCode) => node.loc.start.line !== node.loc.end.line && isBlockLikeStatement(sourceCode, node)
95483 },
95484 "multiline-expression": {
95485 test: (node, sourceCode) => node.loc.start.line !== node.loc.end.line && node.type === "ExpressionStatement" && !isDirectivePrologue(node, sourceCode)
95486 },
95487 "multiline-const": newMultilineKeywordTester("const"),
95488 "multiline-let": newMultilineKeywordTester("let"),
95489 "multiline-var": newMultilineKeywordTester("var"),
95490 "singleline-const": newSinglelineKeywordTester("const"),
95491 "singleline-let": newSinglelineKeywordTester("let"),
95492 "singleline-var": newSinglelineKeywordTester("var"),
95493 block: newNodeTypeTester("BlockStatement"),
95494 empty: newNodeTypeTester("EmptyStatement"),
95495 function: newNodeTypeTester("FunctionDeclaration"),
95496 break: newKeywordTester("break"),
95497 case: newKeywordTester("case"),
95498 class: newKeywordTester("class"),
95499 const: newKeywordTester("const"),
95500 continue: newKeywordTester("continue"),
95501 debugger: newKeywordTester("debugger"),
95502 default: newKeywordTester("default"),
95503 do: newKeywordTester("do"),
95504 export: newKeywordTester("export"),
95505 for: newKeywordTester("for"),
95506 if: newKeywordTester("if"),
95507 import: newKeywordTester("import"),
95508 let: newKeywordTester("let"),
95509 return: newKeywordTester("return"),
95510 switch: newKeywordTester("switch"),
95511 throw: newKeywordTester("throw"),
95512 try: newKeywordTester("try"),
95513 var: newKeywordTester("var"),
95514 while: newKeywordTester("while"),
95515 with: newKeywordTester("with")
95516}; //------------------------------------------------------------------------------
95517// Rule Definition
95518//------------------------------------------------------------------------------
95519
95520module.exports = {
95521 meta: {
95522 type: "layout",
95523 docs: {
95524 description: "require or disallow padding lines between statements",
95525 category: "Stylistic Issues",
95526 recommended: false,
95527 url: "https://eslint.org/docs/rules/padding-line-between-statements"
95528 },
95529 fixable: "whitespace",
95530 schema: {
95531 definitions: {
95532 paddingType: {
95533 enum: Object.keys(PaddingTypes)
95534 },
95535 statementType: {
95536 anyOf: [{
95537 enum: Object.keys(StatementTypes)
95538 }, {
95539 type: "array",
95540 items: {
95541 enum: Object.keys(StatementTypes)
95542 },
95543 minItems: 1,
95544 uniqueItems: true,
95545 additionalItems: false
95546 }]
95547 }
95548 },
95549 type: "array",
95550 items: {
95551 type: "object",
95552 properties: {
95553 blankLine: {
95554 $ref: "#/definitions/paddingType"
95555 },
95556 prev: {
95557 $ref: "#/definitions/statementType"
95558 },
95559 next: {
95560 $ref: "#/definitions/statementType"
95561 }
95562 },
95563 additionalProperties: false,
95564 required: ["blankLine", "prev", "next"]
95565 },
95566 additionalItems: false
95567 },
95568 messages: {
95569 unexpectedBlankLine: "Unexpected blank line before this statement.",
95570 expectedBlankLine: "Expected blank line before this statement."
95571 }
95572 },
95573
95574 create(context) {
95575 const sourceCode = context.getSourceCode();
95576 const configureList = context.options || [];
95577 let scopeInfo = null;
95578 /**
95579 * Processes to enter to new scope.
95580 * This manages the current previous statement.
95581 * @returns {void}
95582 * @private
95583 */
95584
95585 function enterScope() {
95586 scopeInfo = {
95587 upper: scopeInfo,
95588 prevNode: null
95589 };
95590 }
95591 /**
95592 * Processes to exit from the current scope.
95593 * @returns {void}
95594 * @private
95595 */
95596
95597
95598 function exitScope() {
95599 scopeInfo = scopeInfo.upper;
95600 }
95601 /**
95602 * Checks whether the given node matches the given type.
95603 * @param {ASTNode} node The statement node to check.
95604 * @param {string|string[]} type The statement type to check.
95605 * @returns {boolean} `true` if the statement node matched the type.
95606 * @private
95607 */
95608
95609
95610 function match(node, type) {
95611 let innerStatementNode = node;
95612
95613 while (innerStatementNode.type === "LabeledStatement") {
95614 innerStatementNode = innerStatementNode.body;
95615 }
95616
95617 if (Array.isArray(type)) {
95618 return type.some(match.bind(null, innerStatementNode));
95619 }
95620
95621 return StatementTypes[type].test(innerStatementNode, sourceCode);
95622 }
95623 /**
95624 * Finds the last matched configure from configureList.
95625 * @param {ASTNode} prevNode The previous statement to match.
95626 * @param {ASTNode} nextNode The current statement to match.
95627 * @returns {Object} The tester of the last matched configure.
95628 * @private
95629 */
95630
95631
95632 function getPaddingType(prevNode, nextNode) {
95633 for (let i = configureList.length - 1; i >= 0; --i) {
95634 const configure = configureList[i];
95635 const matched = match(prevNode, configure.prev) && match(nextNode, configure.next);
95636
95637 if (matched) {
95638 return PaddingTypes[configure.blankLine];
95639 }
95640 }
95641
95642 return PaddingTypes.any;
95643 }
95644 /**
95645 * Gets padding line sequences between the given 2 statements.
95646 * Comments are separators of the padding line sequences.
95647 * @param {ASTNode} prevNode The previous statement to count.
95648 * @param {ASTNode} nextNode The current statement to count.
95649 * @returns {Array<Token[]>} The array of token pairs.
95650 * @private
95651 */
95652
95653
95654 function getPaddingLineSequences(prevNode, nextNode) {
95655 const pairs = [];
95656 let prevToken = getActualLastToken(sourceCode, prevNode);
95657
95658 if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) {
95659 do {
95660 const token = sourceCode.getTokenAfter(prevToken, {
95661 includeComments: true
95662 });
95663
95664 if (token.loc.start.line - prevToken.loc.end.line >= 2) {
95665 pairs.push([prevToken, token]);
95666 }
95667
95668 prevToken = token;
95669 } while (prevToken.range[0] < nextNode.range[0]);
95670 }
95671
95672 return pairs;
95673 }
95674 /**
95675 * Verify padding lines between the given node and the previous node.
95676 * @param {ASTNode} node The node to verify.
95677 * @returns {void}
95678 * @private
95679 */
95680
95681
95682 function verify(node) {
95683 const parentType = node.parent.type;
95684 const validParent = astUtils.STATEMENT_LIST_PARENTS.has(parentType) || parentType === "SwitchStatement";
95685
95686 if (!validParent) {
95687 return;
95688 } // Save this node as the current previous statement.
95689
95690
95691 const prevNode = scopeInfo.prevNode; // Verify.
95692
95693 if (prevNode) {
95694 const type = getPaddingType(prevNode, node);
95695 const paddingLines = getPaddingLineSequences(prevNode, node);
95696 type.verify(context, prevNode, node, paddingLines);
95697 }
95698
95699 scopeInfo.prevNode = node;
95700 }
95701 /**
95702 * Verify padding lines between the given node and the previous node.
95703 * Then process to enter to new scope.
95704 * @param {ASTNode} node The node to verify.
95705 * @returns {void}
95706 * @private
95707 */
95708
95709
95710 function verifyThenEnterScope(node) {
95711 verify(node);
95712 enterScope();
95713 }
95714
95715 return {
95716 Program: enterScope,
95717 BlockStatement: enterScope,
95718 SwitchStatement: enterScope,
95719 "Program:exit": exitScope,
95720 "BlockStatement:exit": exitScope,
95721 "SwitchStatement:exit": exitScope,
95722 ":statement": verify,
95723 SwitchCase: verifyThenEnterScope,
95724 "SwitchCase:exit": exitScope
95725 };
95726 }
95727
95728};
95729
95730/***/ }),
6a5a0f88 95731/* 674 */
eb39fafa
DC
95732/***/ (function(module, exports, __webpack_require__) {
95733
95734"use strict";
95735/**
95736 * @fileoverview A rule to suggest using arrow functions as callbacks.
95737 * @author Toru Nagashima
95738 */
95739 //------------------------------------------------------------------------------
95740// Helpers
95741//------------------------------------------------------------------------------
95742
95743/**
95744 * Checks whether or not a given variable is a function name.
95745 * @param {eslint-scope.Variable} variable A variable to check.
95746 * @returns {boolean} `true` if the variable is a function name.
95747 */
95748
95749function isFunctionName(variable) {
95750 return variable && variable.defs[0].type === "FunctionName";
95751}
95752/**
95753 * Checks whether or not a given MetaProperty node equals to a given value.
95754 * @param {ASTNode} node A MetaProperty node to check.
95755 * @param {string} metaName The name of `MetaProperty.meta`.
95756 * @param {string} propertyName The name of `MetaProperty.property`.
95757 * @returns {boolean} `true` if the node is the specific value.
95758 */
95759
95760
95761function checkMetaProperty(node, metaName, propertyName) {
95762 return node.meta.name === metaName && node.property.name === propertyName;
95763}
95764/**
95765 * Gets the variable object of `arguments` which is defined implicitly.
95766 * @param {eslint-scope.Scope} scope A scope to get.
95767 * @returns {eslint-scope.Variable} The found variable object.
95768 */
95769
95770
95771function getVariableOfArguments(scope) {
95772 const variables = scope.variables;
95773
95774 for (let i = 0; i < variables.length; ++i) {
95775 const variable = variables[i];
95776
95777 if (variable.name === "arguments") {
95778 /*
95779 * If there was a parameter which is named "arguments", the
95780 * implicit "arguments" is not defined.
95781 * So does fast return with null.
95782 */
95783 return variable.identifiers.length === 0 ? variable : null;
95784 }
95785 }
95786 /* istanbul ignore next */
95787
95788
95789 return null;
95790}
95791/**
95792 * Checks whether or not a given node is a callback.
95793 * @param {ASTNode} node A node to check.
95794 * @returns {Object}
95795 * {boolean} retv.isCallback - `true` if the node is a callback.
95796 * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`.
95797 */
95798
95799
95800function getCallbackInfo(node) {
95801 const retv = {
95802 isCallback: false,
95803 isLexicalThis: false
95804 };
95805 let currentNode = node;
95806 let parent = node.parent;
95807
95808 while (currentNode) {
95809 switch (parent.type) {
95810 // Checks parents recursively.
95811 case "LogicalExpression":
95812 case "ConditionalExpression":
95813 break;
95814 // Checks whether the parent node is `.bind(this)` call.
95815
95816 case "MemberExpression":
95817 if (parent.object === currentNode && !parent.property.computed && parent.property.type === "Identifier" && parent.property.name === "bind" && parent.parent.type === "CallExpression" && parent.parent.callee === parent) {
95818 retv.isLexicalThis = parent.parent.arguments.length === 1 && parent.parent.arguments[0].type === "ThisExpression";
95819 parent = parent.parent;
95820 } else {
95821 return retv;
95822 }
95823
95824 break;
95825 // Checks whether the node is a callback.
95826
95827 case "CallExpression":
95828 case "NewExpression":
95829 if (parent.callee !== currentNode) {
95830 retv.isCallback = true;
95831 }
95832
95833 return retv;
95834
95835 default:
95836 return retv;
95837 }
95838
95839 currentNode = parent;
95840 parent = parent.parent;
95841 }
95842 /* istanbul ignore next */
95843
95844
95845 throw new Error("unreachable");
95846}
95847/**
95848 * Checks whether a simple list of parameters contains any duplicates. This does not handle complex
95849 * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate
95850 * parameter names anyway. Instead, it always returns `false` for complex parameter lists.
95851 * @param {ASTNode[]} paramsList The list of parameters for a function
95852 * @returns {boolean} `true` if the list of parameters contains any duplicates
95853 */
95854
95855
95856function hasDuplicateParams(paramsList) {
95857 return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size;
95858} //------------------------------------------------------------------------------
95859// Rule Definition
95860//------------------------------------------------------------------------------
95861
95862
95863module.exports = {
95864 meta: {
95865 type: "suggestion",
95866 docs: {
95867 description: "require using arrow functions for callbacks",
95868 category: "ECMAScript 6",
95869 recommended: false,
95870 url: "https://eslint.org/docs/rules/prefer-arrow-callback"
95871 },
95872 schema: [{
95873 type: "object",
95874 properties: {
95875 allowNamedFunctions: {
95876 type: "boolean",
95877 default: false
95878 },
95879 allowUnboundThis: {
95880 type: "boolean",
95881 default: true
95882 }
95883 },
95884 additionalProperties: false
95885 }],
95886 fixable: "code",
95887 messages: {
95888 preferArrowCallback: "Unexpected function expression."
95889 }
95890 },
95891
95892 create(context) {
95893 const options = context.options[0] || {};
95894 const allowUnboundThis = options.allowUnboundThis !== false; // default to true
95895
95896 const allowNamedFunctions = options.allowNamedFunctions;
95897 const sourceCode = context.getSourceCode();
95898 /*
95899 * {Array<{this: boolean, super: boolean, meta: boolean}>}
95900 * - this - A flag which shows there are one or more ThisExpression.
95901 * - super - A flag which shows there are one or more Super.
95902 * - meta - A flag which shows there are one or more MethProperty.
95903 */
95904
95905 let stack = [];
95906 /**
95907 * Pushes new function scope with all `false` flags.
95908 * @returns {void}
95909 */
95910
95911 function enterScope() {
95912 stack.push({
95913 this: false,
95914 super: false,
95915 meta: false
95916 });
95917 }
95918 /**
95919 * Pops a function scope from the stack.
95920 * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope.
95921 */
95922
95923
95924 function exitScope() {
95925 return stack.pop();
95926 }
95927
95928 return {
95929 // Reset internal state.
95930 Program() {
95931 stack = [];
95932 },
95933
95934 // If there are below, it cannot replace with arrow functions merely.
95935 ThisExpression() {
95936 const info = stack[stack.length - 1];
95937
95938 if (info) {
95939 info.this = true;
95940 }
95941 },
95942
95943 Super() {
95944 const info = stack[stack.length - 1];
95945
95946 if (info) {
95947 info.super = true;
95948 }
95949 },
95950
95951 MetaProperty(node) {
95952 const info = stack[stack.length - 1];
95953
95954 if (info && checkMetaProperty(node, "new", "target")) {
95955 info.meta = true;
95956 }
95957 },
95958
95959 // To skip nested scopes.
95960 FunctionDeclaration: enterScope,
95961 "FunctionDeclaration:exit": exitScope,
95962 // Main.
95963 FunctionExpression: enterScope,
95964
95965 "FunctionExpression:exit"(node) {
95966 const scopeInfo = exitScope(); // Skip named function expressions
95967
95968 if (allowNamedFunctions && node.id && node.id.name) {
95969 return;
95970 } // Skip generators.
95971
95972
95973 if (node.generator) {
95974 return;
95975 } // Skip recursive functions.
95976
95977
95978 const nameVar = context.getDeclaredVariables(node)[0];
95979
95980 if (isFunctionName(nameVar) && nameVar.references.length > 0) {
95981 return;
95982 } // Skip if it's using arguments.
95983
95984
95985 const variable = getVariableOfArguments(context.getScope());
95986
95987 if (variable && variable.references.length > 0) {
95988 return;
95989 } // Reports if it's a callback which can replace with arrows.
95990
95991
95992 const callbackInfo = getCallbackInfo(node);
95993
95994 if (callbackInfo.isCallback && (!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) && !scopeInfo.super && !scopeInfo.meta) {
95995 context.report({
95996 node,
95997 messageId: "preferArrowCallback",
95998
95999 fix(fixer) {
96000 if (!callbackInfo.isLexicalThis && scopeInfo.this || hasDuplicateParams(node.params)) {
96001 /*
96002 * If the callback function does not have .bind(this) and contains a reference to `this`, there
96003 * is no way to determine what `this` should be, so don't perform any fixes.
96004 * If the callback function has duplicates in its list of parameters (possible in sloppy mode),
96005 * don't replace it with an arrow function, because this is a SyntaxError with arrow functions.
96006 */
96007 return null;
96008 }
96009
96010 const paramsLeftParen = node.params.length ? sourceCode.getTokenBefore(node.params[0]) : sourceCode.getTokenBefore(node.body, 1);
96011 const paramsRightParen = sourceCode.getTokenBefore(node.body);
96012 const asyncKeyword = node.async ? "async " : "";
96013 const paramsFullText = sourceCode.text.slice(paramsLeftParen.range[0], paramsRightParen.range[1]);
96014 const arrowFunctionText = "".concat(asyncKeyword).concat(paramsFullText, " => ").concat(sourceCode.getText(node.body));
96015 /*
96016 * If the callback function has `.bind(this)`, replace it with an arrow function and remove the binding.
96017 * Otherwise, just replace the arrow function itself.
96018 */
96019
96020 const replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;
96021 /*
96022 * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then
96023 * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even
96024 * though `foo || function() {}` is valid.
96025 */
96026
96027 const needsParens = replacedNode.parent.type !== "CallExpression" && replacedNode.parent.type !== "ConditionalExpression";
96028 const replacementText = needsParens ? "(".concat(arrowFunctionText, ")") : arrowFunctionText;
96029 return fixer.replaceText(replacedNode, replacementText);
96030 }
96031
96032 });
96033 }
96034 }
96035
96036 };
96037 }
96038
96039};
96040
96041/***/ }),
6a5a0f88 96042/* 675 */
eb39fafa
DC
96043/***/ (function(module, exports, __webpack_require__) {
96044
96045"use strict";
96046/**
96047 * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared.
96048 * @author Toru Nagashima
96049 */
96050
96051
96052const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
96053// Helpers
96054//------------------------------------------------------------------------------
96055
96056
96057const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u;
96058const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/u;
96059const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/u;
96060/**
96061 * Checks whether a given node is located at `ForStatement.init` or not.
96062 * @param {ASTNode} node A node to check.
96063 * @returns {boolean} `true` if the node is located at `ForStatement.init`.
96064 */
96065
96066function isInitOfForStatement(node) {
96067 return node.parent.type === "ForStatement" && node.parent.init === node;
96068}
96069/**
96070 * Checks whether a given Identifier node becomes a VariableDeclaration or not.
96071 * @param {ASTNode} identifier An Identifier node to check.
96072 * @returns {boolean} `true` if the node can become a VariableDeclaration.
96073 */
96074
96075
96076function canBecomeVariableDeclaration(identifier) {
96077 let node = identifier.parent;
96078
96079 while (PATTERN_TYPE.test(node.type)) {
96080 node = node.parent;
96081 }
96082
96083 return node.type === "VariableDeclarator" || node.type === "AssignmentExpression" && node.parent.type === "ExpressionStatement" && DECLARATION_HOST_TYPE.test(node.parent.parent.type);
96084}
96085/**
96086 * Checks if an property or element is from outer scope or function parameters
96087 * in destructing pattern.
96088 * @param {string} name A variable name to be checked.
96089 * @param {eslint-scope.Scope} initScope A scope to start find.
96090 * @returns {boolean} Indicates if the variable is from outer scope or function parameters.
96091 */
96092
96093
96094function isOuterVariableInDestructing(name, initScope) {
96095 if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) {
96096 return true;
96097 }
96098
96099 const variable = astUtils.getVariableByName(initScope, name);
96100
96101 if (variable !== null) {
96102 return variable.defs.some(def => def.type === "Parameter");
96103 }
96104
96105 return false;
96106}
96107/**
96108 * Gets the VariableDeclarator/AssignmentExpression node that a given reference
96109 * belongs to.
96110 * This is used to detect a mix of reassigned and never reassigned in a
96111 * destructuring.
96112 * @param {eslint-scope.Reference} reference A reference to get.
96113 * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or
96114 * null.
96115 */
96116
96117
96118function getDestructuringHost(reference) {
96119 if (!reference.isWrite()) {
96120 return null;
96121 }
96122
96123 let node = reference.identifier.parent;
96124
96125 while (PATTERN_TYPE.test(node.type)) {
96126 node = node.parent;
96127 }
96128
96129 if (!DESTRUCTURING_HOST_TYPE.test(node.type)) {
96130 return null;
96131 }
96132
96133 return node;
96134}
96135/**
96136 * Determines if a destructuring assignment node contains
96137 * any MemberExpression nodes. This is used to determine if a
96138 * variable that is only written once using destructuring can be
96139 * safely converted into a const declaration.
96140 * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check.
96141 * @returns {boolean} True if the destructuring pattern contains
96142 * a MemberExpression, false if not.
96143 */
96144
96145
96146function hasMemberExpressionAssignment(node) {
96147 switch (node.type) {
96148 case "ObjectPattern":
96149 return node.properties.some(prop => {
96150 if (prop) {
96151 /*
96152 * Spread elements have an argument property while
96153 * others have a value property. Because different
96154 * parsers use different node types for spread elements,
96155 * we just check if there is an argument property.
96156 */
96157 return hasMemberExpressionAssignment(prop.argument || prop.value);
96158 }
96159
96160 return false;
96161 });
96162
96163 case "ArrayPattern":
96164 return node.elements.some(element => {
96165 if (element) {
96166 return hasMemberExpressionAssignment(element);
96167 }
96168
96169 return false;
96170 });
96171
96172 case "AssignmentPattern":
96173 return hasMemberExpressionAssignment(node.left);
96174
96175 case "MemberExpression":
96176 return true;
96177 // no default
96178 }
96179
96180 return false;
96181}
96182/**
96183 * Gets an identifier node of a given variable.
96184 *
96185 * If the initialization exists or one or more reading references exist before
96186 * the first assignment, the identifier node is the node of the declaration.
96187 * Otherwise, the identifier node is the node of the first assignment.
96188 *
96189 * If the variable should not change to const, this function returns null.
96190 * - If the variable is reassigned.
96191 * - If the variable is never initialized nor assigned.
96192 * - If the variable is initialized in a different scope from the declaration.
96193 * - If the unique assignment of the variable cannot change to a declaration.
96194 * e.g. `if (a) b = 1` / `return (b = 1)`
96195 * - If the variable is declared in the global scope and `eslintUsed` is `true`.
96196 * `/*exported foo` directive comment makes such variables. This rule does not
96197 * warn such variables because this rule cannot distinguish whether the
96198 * exported variables are reassigned or not.
96199 * @param {eslint-scope.Variable} variable A variable to get.
96200 * @param {boolean} ignoreReadBeforeAssign
96201 * The value of `ignoreReadBeforeAssign` option.
96202 * @returns {ASTNode|null}
96203 * An Identifier node if the variable should change to const.
96204 * Otherwise, null.
96205 */
96206
96207
96208function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) {
96209 if (variable.eslintUsed && variable.scope.type === "global") {
96210 return null;
96211 } // Finds the unique WriteReference.
96212
96213
96214 let writer = null;
96215 let isReadBeforeInit = false;
96216 const references = variable.references;
96217
96218 for (let i = 0; i < references.length; ++i) {
96219 const reference = references[i];
96220
96221 if (reference.isWrite()) {
96222 const isReassigned = writer !== null && writer.identifier !== reference.identifier;
96223
96224 if (isReassigned) {
96225 return null;
96226 }
96227
96228 const destructuringHost = getDestructuringHost(reference);
96229
96230 if (destructuringHost !== null && destructuringHost.left !== void 0) {
96231 const leftNode = destructuringHost.left;
96232 let hasOuterVariables = false,
96233 hasNonIdentifiers = false;
96234
96235 if (leftNode.type === "ObjectPattern") {
96236 const properties = leftNode.properties;
96237 hasOuterVariables = properties.filter(prop => prop.value).map(prop => prop.value.name).some(name => isOuterVariableInDestructing(name, variable.scope));
96238 hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
96239 } else if (leftNode.type === "ArrayPattern") {
96240 const elements = leftNode.elements;
96241 hasOuterVariables = elements.map(element => element && element.name).some(name => isOuterVariableInDestructing(name, variable.scope));
96242 hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
96243 }
96244
96245 if (hasOuterVariables || hasNonIdentifiers) {
96246 return null;
96247 }
96248 }
96249
96250 writer = reference;
96251 } else if (reference.isRead() && writer === null) {
96252 if (ignoreReadBeforeAssign) {
96253 return null;
96254 }
96255
96256 isReadBeforeInit = true;
96257 }
96258 }
96259 /*
96260 * If the assignment is from a different scope, ignore it.
96261 * If the assignment cannot change to a declaration, ignore it.
96262 */
96263
96264
96265 const shouldBeConst = writer !== null && writer.from === variable.scope && canBecomeVariableDeclaration(writer.identifier);
96266
96267 if (!shouldBeConst) {
96268 return null;
96269 }
96270
96271 if (isReadBeforeInit) {
96272 return variable.defs[0].name;
96273 }
96274
96275 return writer.identifier;
96276}
96277/**
96278 * Groups by the VariableDeclarator/AssignmentExpression node that each
96279 * reference of given variables belongs to.
96280 * This is used to detect a mix of reassigned and never reassigned in a
96281 * destructuring.
96282 * @param {eslint-scope.Variable[]} variables Variables to group by destructuring.
96283 * @param {boolean} ignoreReadBeforeAssign
96284 * The value of `ignoreReadBeforeAssign` option.
96285 * @returns {Map<ASTNode, ASTNode[]>} Grouped identifier nodes.
96286 */
96287
96288
96289function groupByDestructuring(variables, ignoreReadBeforeAssign) {
96290 const identifierMap = new Map();
96291
96292 for (let i = 0; i < variables.length; ++i) {
96293 const variable = variables[i];
96294 const references = variable.references;
96295 const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign);
96296 let prevId = null;
96297
96298 for (let j = 0; j < references.length; ++j) {
96299 const reference = references[j];
96300 const id = reference.identifier;
96301 /*
96302 * Avoid counting a reference twice or more for default values of
96303 * destructuring.
96304 */
96305
96306 if (id === prevId) {
96307 continue;
96308 }
96309
96310 prevId = id; // Add the identifier node into the destructuring group.
96311
96312 const group = getDestructuringHost(reference);
96313
96314 if (group) {
96315 if (identifierMap.has(group)) {
96316 identifierMap.get(group).push(identifier);
96317 } else {
96318 identifierMap.set(group, [identifier]);
96319 }
96320 }
96321 }
96322 }
96323
96324 return identifierMap;
96325}
96326/**
96327 * Finds the nearest parent of node with a given type.
96328 * @param {ASTNode} node The node to search from.
96329 * @param {string} type The type field of the parent node.
96330 * @param {Function} shouldStop A predicate that returns true if the traversal should stop, and false otherwise.
96331 * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists.
96332 */
96333
96334
96335function findUp(node, type, shouldStop) {
96336 if (!node || shouldStop(node)) {
96337 return null;
96338 }
96339
96340 if (node.type === type) {
96341 return node;
96342 }
96343
96344 return findUp(node.parent, type, shouldStop);
96345} //------------------------------------------------------------------------------
96346// Rule Definition
96347//------------------------------------------------------------------------------
96348
96349
96350module.exports = {
96351 meta: {
96352 type: "suggestion",
96353 docs: {
96354 description: "require `const` declarations for variables that are never reassigned after declared",
96355 category: "ECMAScript 6",
96356 recommended: false,
96357 url: "https://eslint.org/docs/rules/prefer-const"
96358 },
96359 fixable: "code",
96360 schema: [{
96361 type: "object",
96362 properties: {
96363 destructuring: {
96364 enum: ["any", "all"],
96365 default: "any"
96366 },
96367 ignoreReadBeforeAssign: {
96368 type: "boolean",
96369 default: false
96370 }
96371 },
96372 additionalProperties: false
96373 }],
96374 messages: {
96375 useConst: "'{{name}}' is never reassigned. Use 'const' instead."
96376 }
96377 },
96378
96379 create(context) {
96380 const options = context.options[0] || {};
96381 const sourceCode = context.getSourceCode();
96382 const shouldMatchAnyDestructuredVariable = options.destructuring !== "all";
96383 const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true;
96384 const variables = [];
96385 let reportCount = 0;
96386 let checkedId = null;
96387 let checkedName = "";
96388 /**
96389 * Reports given identifier nodes if all of the nodes should be declared
96390 * as const.
96391 *
96392 * The argument 'nodes' is an array of Identifier nodes.
96393 * This node is the result of 'getIdentifierIfShouldBeConst()', so it's
96394 * nullable. In simple declaration or assignment cases, the length of
96395 * the array is 1. In destructuring cases, the length of the array can
96396 * be 2 or more.
96397 * @param {(eslint-scope.Reference|null)[]} nodes
96398 * References which are grouped by destructuring to report.
96399 * @returns {void}
96400 */
96401
96402 function checkGroup(nodes) {
96403 const nodesToReport = nodes.filter(Boolean);
96404
96405 if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) {
96406 const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement"));
96407 const isVarDecParentNull = varDeclParent === null;
96408
96409 if (!isVarDecParentNull && varDeclParent.declarations.length > 0) {
96410 const firstDeclaration = varDeclParent.declarations[0];
96411
96412 if (firstDeclaration.init) {
96413 const firstDecParent = firstDeclaration.init.parent;
96414 /*
96415 * First we check the declaration type and then depending on
96416 * if the type is a "VariableDeclarator" or its an "ObjectPattern"
96417 * we compare the name and id from the first identifier, if the names are different
96418 * we assign the new name, id and reset the count of reportCount and nodeCount in
96419 * order to check each block for the number of reported errors and base our fix
96420 * based on comparing nodes.length and nodesToReport.length.
96421 */
96422
96423 if (firstDecParent.type === "VariableDeclarator") {
96424 if (firstDecParent.id.name !== checkedName) {
96425 checkedName = firstDecParent.id.name;
96426 reportCount = 0;
96427 }
96428
96429 if (firstDecParent.id.type === "ObjectPattern") {
96430 if (firstDecParent.init.name !== checkedName) {
96431 checkedName = firstDecParent.init.name;
96432 reportCount = 0;
96433 }
96434 }
96435
96436 if (firstDecParent.id !== checkedId) {
96437 checkedId = firstDecParent.id;
96438 reportCount = 0;
96439 }
96440 }
96441 }
96442 }
96443
96444 let shouldFix = varDeclParent && ( // Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop)
96445 varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations.every(declaration => declaration.init)) &&
96446 /*
96447 * If options.destructuring is "all", then this warning will not occur unless
96448 * every assignment in the destructuring should be const. In that case, it's safe
96449 * to apply the fix.
96450 */
96451 nodesToReport.length === nodes.length;
96452
96453 if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) {
96454 if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) {
96455 /*
96456 * Add nodesToReport.length to a count, then comparing the count to the length
96457 * of the declarations in the current block.
96458 */
96459 reportCount += nodesToReport.length;
96460 shouldFix = shouldFix && reportCount === varDeclParent.declarations.length;
96461 }
96462 }
96463
96464 nodesToReport.forEach(node => {
96465 context.report({
96466 node,
96467 messageId: "useConst",
96468 data: node,
96469 fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind), "const") : null
96470 });
96471 });
96472 }
96473 }
96474
96475 return {
96476 "Program:exit"() {
96477 groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup);
96478 },
96479
96480 VariableDeclaration(node) {
96481 if (node.kind === "let" && !isInitOfForStatement(node)) {
96482 variables.push(...context.getDeclaredVariables(node));
96483 }
96484 }
96485
96486 };
96487 }
96488
96489};
96490
96491/***/ }),
6a5a0f88 96492/* 676 */
eb39fafa
DC
96493/***/ (function(module, exports, __webpack_require__) {
96494
96495"use strict";
96496/**
96497 * @fileoverview Prefer destructuring from arrays and objects
96498 * @author Alex LaFroscia
96499 */
96500 //------------------------------------------------------------------------------
96501// Rule Definition
96502//------------------------------------------------------------------------------
96503
96504module.exports = {
96505 meta: {
96506 type: "suggestion",
96507 docs: {
96508 description: "require destructuring from arrays and/or objects",
96509 category: "ECMAScript 6",
96510 recommended: false,
96511 url: "https://eslint.org/docs/rules/prefer-destructuring"
96512 },
96513 fixable: "code",
96514 schema: [{
96515 /*
96516 * old support {array: Boolean, object: Boolean}
96517 * new support {VariableDeclarator: {}, AssignmentExpression: {}}
96518 */
96519 oneOf: [{
96520 type: "object",
96521 properties: {
96522 VariableDeclarator: {
96523 type: "object",
96524 properties: {
96525 array: {
96526 type: "boolean"
96527 },
96528 object: {
96529 type: "boolean"
96530 }
96531 },
96532 additionalProperties: false
96533 },
96534 AssignmentExpression: {
96535 type: "object",
96536 properties: {
96537 array: {
96538 type: "boolean"
96539 },
96540 object: {
96541 type: "boolean"
96542 }
96543 },
96544 additionalProperties: false
96545 }
96546 },
96547 additionalProperties: false
96548 }, {
96549 type: "object",
96550 properties: {
96551 array: {
96552 type: "boolean"
96553 },
96554 object: {
96555 type: "boolean"
96556 }
96557 },
96558 additionalProperties: false
96559 }]
96560 }, {
96561 type: "object",
96562 properties: {
96563 enforceForRenamedProperties: {
96564 type: "boolean"
96565 }
96566 },
96567 additionalProperties: false
96568 }],
96569 messages: {
96570 preferDestructuring: "Use {{type}} destructuring."
96571 }
96572 },
96573
96574 create(context) {
96575 const enabledTypes = context.options[0];
96576 const enforceForRenamedProperties = context.options[1] && context.options[1].enforceForRenamedProperties;
96577 let normalizedOptions = {
96578 VariableDeclarator: {
96579 array: true,
96580 object: true
96581 },
96582 AssignmentExpression: {
96583 array: true,
96584 object: true
96585 }
96586 };
96587
96588 if (enabledTypes) {
96589 normalizedOptions = typeof enabledTypes.array !== "undefined" || typeof enabledTypes.object !== "undefined" ? {
96590 VariableDeclarator: enabledTypes,
96591 AssignmentExpression: enabledTypes
96592 } : enabledTypes;
96593 } //--------------------------------------------------------------------------
96594 // Helpers
96595 //--------------------------------------------------------------------------
96596 // eslint-disable-next-line jsdoc/require-description
96597
96598 /**
96599 * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
96600 * @param {string} destructuringType "array" or "object"
96601 * @returns {boolean} `true` if the destructuring type should be checked for the given node
96602 */
96603
96604
96605 function shouldCheck(nodeType, destructuringType) {
96606 return normalizedOptions && normalizedOptions[nodeType] && normalizedOptions[nodeType][destructuringType];
96607 }
96608 /**
96609 * Determines if the given node is accessing an array index
96610 *
96611 * This is used to differentiate array index access from object property
96612 * access.
96613 * @param {ASTNode} node the node to evaluate
96614 * @returns {boolean} whether or not the node is an integer
96615 */
96616
96617
96618 function isArrayIndexAccess(node) {
96619 return Number.isInteger(node.property.value);
96620 }
96621 /**
96622 * Report that the given node should use destructuring
96623 * @param {ASTNode} reportNode the node to report
96624 * @param {string} type the type of destructuring that should have been done
96625 * @param {Function|null} fix the fix function or null to pass to context.report
96626 * @returns {void}
96627 */
96628
96629
96630 function report(reportNode, type, fix) {
96631 context.report({
96632 node: reportNode,
96633 messageId: "preferDestructuring",
96634 data: {
96635 type
96636 },
96637 fix
96638 });
96639 }
96640 /**
96641 * Determines if a node should be fixed into object destructuring
96642 *
96643 * The fixer only fixes the simplest case of object destructuring,
96644 * like: `let x = a.x`;
96645 *
96646 * Assignment expression is not fixed.
96647 * Array destructuring is not fixed.
96648 * Renamed property is not fixed.
96649 * @param {ASTNode} node the the node to evaluate
96650 * @returns {boolean} whether or not the node should be fixed
96651 */
96652
96653
96654 function shouldFix(node) {
96655 return node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init.type === "MemberExpression" && node.id.name === node.init.property.name;
96656 }
96657 /**
96658 * Fix a node into object destructuring.
96659 * This function only handles the simplest case of object destructuring,
96660 * see {@link shouldFix}.
96661 * @param {SourceCodeFixer} fixer the fixer object
96662 * @param {ASTNode} node the node to be fixed.
96663 * @returns {Object} a fix for the node
96664 */
96665
96666
96667 function fixIntoObjectDestructuring(fixer, node) {
96668 const rightNode = node.init;
96669 const sourceCode = context.getSourceCode();
96670 return fixer.replaceText(node, "{".concat(rightNode.property.name, "} = ").concat(sourceCode.getText(rightNode.object)));
96671 }
96672 /**
96673 * Check that the `prefer-destructuring` rules are followed based on the
96674 * given left- and right-hand side of the assignment.
96675 *
96676 * Pulled out into a separate method so that VariableDeclarators and
96677 * AssignmentExpressions can share the same verification logic.
96678 * @param {ASTNode} leftNode the left-hand side of the assignment
96679 * @param {ASTNode} rightNode the right-hand side of the assignment
96680 * @param {ASTNode} reportNode the node to report the error on
96681 * @returns {void}
96682 */
96683
96684
96685 function performCheck(leftNode, rightNode, reportNode) {
96686 if (rightNode.type !== "MemberExpression" || rightNode.object.type === "Super") {
96687 return;
96688 }
96689
96690 if (isArrayIndexAccess(rightNode)) {
96691 if (shouldCheck(reportNode.type, "array")) {
96692 report(reportNode, "array", null);
96693 }
96694
96695 return;
96696 }
96697
96698 const fix = shouldFix(reportNode) ? fixer => fixIntoObjectDestructuring(fixer, reportNode) : null;
96699
96700 if (shouldCheck(reportNode.type, "object") && enforceForRenamedProperties) {
96701 report(reportNode, "object", fix);
96702 return;
96703 }
96704
96705 if (shouldCheck(reportNode.type, "object")) {
96706 const property = rightNode.property;
96707
96708 if (property.type === "Literal" && leftNode.name === property.value || property.type === "Identifier" && leftNode.name === property.name && !rightNode.computed) {
96709 report(reportNode, "object", fix);
96710 }
96711 }
96712 }
96713 /**
96714 * Check if a given variable declarator is coming from an property access
96715 * that should be using destructuring instead
96716 * @param {ASTNode} node the variable declarator to check
96717 * @returns {void}
96718 */
96719
96720
96721 function checkVariableDeclarator(node) {
96722 // Skip if variable is declared without assignment
96723 if (!node.init) {
96724 return;
96725 } // We only care about member expressions past this point
96726
96727
96728 if (node.init.type !== "MemberExpression") {
96729 return;
96730 }
96731
96732 performCheck(node.id, node.init, node);
96733 }
96734 /**
96735 * Run the `prefer-destructuring` check on an AssignmentExpression
96736 * @param {ASTNode} node the AssignmentExpression node
96737 * @returns {void}
96738 */
96739
96740
96741 function checkAssigmentExpression(node) {
96742 if (node.operator === "=") {
96743 performCheck(node.left, node.right, node);
96744 }
96745 } //--------------------------------------------------------------------------
96746 // Public
96747 //--------------------------------------------------------------------------
96748
96749
96750 return {
96751 VariableDeclarator: checkVariableDeclarator,
96752 AssignmentExpression: checkAssigmentExpression
96753 };
96754 }
96755
96756};
96757
96758/***/ }),
6a5a0f88 96759/* 677 */
eb39fafa
DC
96760/***/ (function(module, exports, __webpack_require__) {
96761
96762"use strict";
96763/**
96764 * @fileoverview Rule to disallow Math.pow in favor of the ** operator
96765 * @author Milos Djermanovic
96766 */
96767 //------------------------------------------------------------------------------
96768// Requirements
96769//------------------------------------------------------------------------------
96770
96771const astUtils = __webpack_require__(426);
96772
96773const {
96774 CALL,
96775 ReferenceTracker
96776} = __webpack_require__(549); //------------------------------------------------------------------------------
96777// Helpers
96778//------------------------------------------------------------------------------
96779
96780
96781const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({
96782 type: "BinaryExpression",
96783 operator: "**"
96784});
96785/**
96786 * Determines whether the given node needs parens if used as the base in an exponentiation binary expression.
96787 * @param {ASTNode} base The node to check.
96788 * @returns {boolean} `true` if the node needs to be parenthesised.
96789 */
96790
96791function doesBaseNeedParens(base) {
96792 return (// '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c
96793 astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR || // An unary operator cannot be used immediately before an exponentiation expression
96794 base.type === "UnaryExpression"
96795 );
96796}
96797/**
96798 * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression.
96799 * @param {ASTNode} exponent The node to check.
96800 * @returns {boolean} `true` if the node needs to be parenthesised.
96801 */
96802
96803
96804function doesExponentNeedParens(exponent) {
96805 // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c
96806 return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR;
96807}
96808/**
96809 * Determines whether an exponentiation binary expression at the place of the given node would need parens.
96810 * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression.
96811 * @param {SourceCode} sourceCode A SourceCode object.
96812 * @returns {boolean} `true` if the expression needs to be parenthesised.
96813 */
96814
96815
96816function doesExponentiationExpressionNeedParens(node, sourceCode) {
96817 const parent = node.parent;
96818 const needsParens = parent.type === "ClassDeclaration" || parent.type.endsWith("Expression") && astUtils.getPrecedence(parent) >= PRECEDENCE_OF_EXPONENTIATION_EXPR && !(parent.type === "BinaryExpression" && parent.operator === "**" && parent.right === node) && !((parent.type === "CallExpression" || parent.type === "NewExpression") && parent.arguments.includes(node)) && !(parent.type === "MemberExpression" && parent.computed && parent.property === node) && !(parent.type === "ArrayExpression");
96819 return needsParens && !astUtils.isParenthesised(sourceCode, node);
96820}
96821/**
96822 * Optionally parenthesizes given text.
96823 * @param {string} text The text to parenthesize.
96824 * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised.
96825 * @returns {string} parenthesised or unchanged text.
96826 */
96827
96828
96829function parenthesizeIfShould(text, shouldParenthesize) {
96830 return shouldParenthesize ? "(".concat(text, ")") : text;
96831} //------------------------------------------------------------------------------
96832// Rule Definition
96833//------------------------------------------------------------------------------
96834
96835
96836module.exports = {
96837 meta: {
96838 type: "suggestion",
96839 docs: {
96840 description: "disallow the use of `Math.pow` in favor of the `**` operator",
96841 category: "Stylistic Issues",
96842 recommended: false,
96843 url: "https://eslint.org/docs/rules/prefer-exponentiation-operator"
96844 },
96845 schema: [],
96846 fixable: "code",
96847 messages: {
96848 useExponentiation: "Use the '**' operator instead of 'Math.pow'."
96849 }
96850 },
96851
96852 create(context) {
96853 const sourceCode = context.getSourceCode();
96854 /**
96855 * Reports the given node.
96856 * @param {ASTNode} node 'Math.pow()' node to report.
96857 * @returns {void}
96858 */
96859
96860 function report(node) {
96861 context.report({
96862 node,
96863 messageId: "useExponentiation",
96864
96865 fix(fixer) {
96866 if (node.arguments.length !== 2 || node.arguments.some(arg => arg.type === "SpreadElement") || sourceCode.getCommentsInside(node).length > 0) {
96867 return null;
96868 }
96869
96870 const base = node.arguments[0],
96871 exponent = node.arguments[1],
96872 baseText = sourceCode.getText(base),
96873 exponentText = sourceCode.getText(exponent),
96874 shouldParenthesizeBase = doesBaseNeedParens(base),
96875 shouldParenthesizeExponent = doesExponentNeedParens(exponent),
96876 shouldParenthesizeAll = doesExponentiationExpressionNeedParens(node, sourceCode);
96877 let prefix = "",
96878 suffix = "";
96879
96880 if (!shouldParenthesizeAll) {
96881 if (!shouldParenthesizeBase) {
96882 const firstReplacementToken = sourceCode.getFirstToken(base),
96883 tokenBefore = sourceCode.getTokenBefore(node);
96884
96885 if (tokenBefore && tokenBefore.range[1] === node.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)) {
96886 prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c
96887 }
96888 }
96889
96890 if (!shouldParenthesizeExponent) {
96891 const lastReplacementToken = sourceCode.getLastToken(exponent),
96892 tokenAfter = sourceCode.getTokenAfter(node);
96893
96894 if (tokenAfter && node.range[1] === tokenAfter.range[0] && !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter)) {
96895 suffix = " "; // Math.pow(a, b)in c -> a**b in c
96896 }
96897 }
96898 }
96899
96900 const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase),
96901 exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent),
96902 replacement = parenthesizeIfShould("".concat(baseReplacement, "**").concat(exponentReplacement), shouldParenthesizeAll);
96903 return fixer.replaceText(node, "".concat(prefix).concat(replacement).concat(suffix));
96904 }
96905
96906 });
96907 }
96908
96909 return {
96910 Program() {
96911 const scope = context.getScope();
96912 const tracker = new ReferenceTracker(scope);
96913 const trackMap = {
96914 Math: {
96915 pow: {
96916 [CALL]: true
96917 }
96918 }
96919 };
96920
96921 for (const {
96922 node
96923 } of tracker.iterateGlobalReferences(trackMap)) {
96924 report(node);
96925 }
96926 }
96927
96928 };
96929 }
96930
96931};
96932
96933/***/ }),
6a5a0f88 96934/* 678 */
eb39fafa
DC
96935/***/ (function(module, exports, __webpack_require__) {
96936
96937"use strict";
96938/**
96939 * @fileoverview Rule to enforce requiring named capture groups in regular expression.
96940 * @author Pig Fang <https://github.com/g-plane>
96941 */
96942 //------------------------------------------------------------------------------
96943// Requirements
96944//------------------------------------------------------------------------------
96945
96946const {
96947 CALL,
96948 CONSTRUCT,
96949 ReferenceTracker,
96950 getStringIfConstant
96951} = __webpack_require__(549);
96952
96953const regexpp = __webpack_require__(527); //------------------------------------------------------------------------------
96954// Helpers
96955//------------------------------------------------------------------------------
96956
96957
96958const parser = new regexpp.RegExpParser(); //------------------------------------------------------------------------------
96959// Rule Definition
96960//------------------------------------------------------------------------------
96961
96962module.exports = {
96963 meta: {
96964 type: "suggestion",
96965 docs: {
96966 description: "enforce using named capture group in regular expression",
96967 category: "Best Practices",
96968 recommended: false,
96969 url: "https://eslint.org/docs/rules/prefer-named-capture-group"
96970 },
96971 schema: [],
96972 messages: {
96973 required: "Capture group '{{group}}' should be converted to a named or non-capturing group."
96974 }
96975 },
96976
96977 create(context) {
96978 /**
96979 * Function to check regular expression.
96980 * @param {string} pattern The regular expression pattern to be check.
96981 * @param {ASTNode} node AST node which contains regular expression.
96982 * @param {boolean} uFlag Flag indicates whether unicode mode is enabled or not.
96983 * @returns {void}
96984 */
96985 function checkRegex(pattern, node, uFlag) {
96986 let ast;
96987
96988 try {
96989 ast = parser.parsePattern(pattern, 0, pattern.length, uFlag);
96990 } catch (_) {
96991 // ignore regex syntax errors
96992 return;
96993 }
96994
96995 regexpp.visitRegExpAST(ast, {
96996 onCapturingGroupEnter(group) {
96997 if (!group.name) {
96998 context.report({
96999 node,
97000 messageId: "required",
97001 data: {
97002 group: group.raw
97003 }
97004 });
97005 }
97006 }
97007
97008 });
97009 }
97010
97011 return {
97012 Literal(node) {
97013 if (node.regex) {
97014 checkRegex(node.regex.pattern, node, node.regex.flags.includes("u"));
97015 }
97016 },
97017
97018 Program() {
97019 const scope = context.getScope();
97020 const tracker = new ReferenceTracker(scope);
97021 const traceMap = {
97022 RegExp: {
97023 [CALL]: true,
97024 [CONSTRUCT]: true
97025 }
97026 };
97027
97028 for (const {
97029 node
97030 } of tracker.iterateGlobalReferences(traceMap)) {
97031 const regex = getStringIfConstant(node.arguments[0]);
97032 const flags = getStringIfConstant(node.arguments[1]);
97033
97034 if (regex) {
97035 checkRegex(regex, node, flags && flags.includes("u"));
97036 }
97037 }
97038 }
97039
97040 };
97041 }
97042
97043};
97044
97045/***/ }),
6a5a0f88 97046/* 679 */
eb39fafa
DC
97047/***/ (function(module, exports, __webpack_require__) {
97048
97049"use strict";
97050/**
97051 * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals
97052 * @author Annie Zhang, Henry Zhu
97053 */
97054 //------------------------------------------------------------------------------
97055// Requirements
97056//------------------------------------------------------------------------------
97057
97058const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
97059// Helpers
97060//------------------------------------------------------------------------------
97061
97062
97063const radixMap = new Map([[2, {
97064 system: "binary",
97065 literalPrefix: "0b"
97066}], [8, {
97067 system: "octal",
97068 literalPrefix: "0o"
97069}], [16, {
97070 system: "hexadecimal",
97071 literalPrefix: "0x"
97072}]]);
97073/**
97074 * Checks to see if a CallExpression's callee node is `parseInt` or
97075 * `Number.parseInt`.
97076 * @param {ASTNode} calleeNode The callee node to evaluate.
97077 * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`,
97078 * false otherwise.
97079 */
97080
97081function isParseInt(calleeNode) {
97082 switch (calleeNode.type) {
97083 case "Identifier":
97084 return calleeNode.name === "parseInt";
97085
97086 case "MemberExpression":
97087 return calleeNode.object.type === "Identifier" && calleeNode.object.name === "Number" && calleeNode.property.type === "Identifier" && calleeNode.property.name === "parseInt";
97088 // no default
97089 }
97090
97091 return false;
97092} //------------------------------------------------------------------------------
97093// Rule Definition
97094//------------------------------------------------------------------------------
97095
97096
97097module.exports = {
97098 meta: {
97099 type: "suggestion",
97100 docs: {
97101 description: "disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals",
97102 category: "ECMAScript 6",
97103 recommended: false,
97104 url: "https://eslint.org/docs/rules/prefer-numeric-literals"
97105 },
97106 schema: [],
97107 messages: {
97108 useLiteral: "Use {{system}} literals instead of {{functionName}}()."
97109 },
97110 fixable: "code"
97111 },
97112
97113 create(context) {
97114 const sourceCode = context.getSourceCode(); //----------------------------------------------------------------------
97115 // Public
97116 //----------------------------------------------------------------------
97117
97118 return {
97119 "CallExpression[arguments.length=2]"(node) {
97120 const [strNode, radixNode] = node.arguments,
97121 str = astUtils.getStaticStringValue(strNode),
97122 radix = radixNode.value;
97123
97124 if (str !== null && astUtils.isStringLiteral(strNode) && radixNode.type === "Literal" && typeof radix === "number" && radixMap.has(radix) && isParseInt(node.callee)) {
97125 const {
97126 system,
97127 literalPrefix
97128 } = radixMap.get(radix);
97129 context.report({
97130 node,
97131 messageId: "useLiteral",
97132 data: {
97133 system,
97134 functionName: sourceCode.getText(node.callee)
97135 },
97136
97137 fix(fixer) {
97138 if (sourceCode.getCommentsInside(node).length) {
97139 return null;
97140 }
97141
97142 const replacement = "".concat(literalPrefix).concat(str);
97143
97144 if (+replacement !== parseInt(str, radix)) {
97145 /*
97146 * If the newly-produced literal would be invalid, (e.g. 0b1234),
97147 * or it would yield an incorrect parseInt result for some other reason, don't make a fix.
97148 */
97149 return null;
97150 }
97151
97152 const tokenBefore = sourceCode.getTokenBefore(node),
97153 tokenAfter = sourceCode.getTokenAfter(node);
97154 let prefix = "",
97155 suffix = "";
97156
97157 if (tokenBefore && tokenBefore.range[1] === node.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, replacement)) {
97158 prefix = " ";
97159 }
97160
97161 if (tokenAfter && node.range[1] === tokenAfter.range[0] && !astUtils.canTokensBeAdjacent(replacement, tokenAfter)) {
97162 suffix = " ";
97163 }
97164
97165 return fixer.replaceText(node, "".concat(prefix).concat(replacement).concat(suffix));
97166 }
97167
97168 });
97169 }
97170 }
97171
97172 };
97173 }
97174
97175};
97176
97177/***/ }),
6a5a0f88 97178/* 680 */
eb39fafa
DC
97179/***/ (function(module, exports, __webpack_require__) {
97180
97181"use strict";
97182/**
97183 * @fileoverview Prefers object spread property over Object.assign
97184 * @author Sharmila Jesupaul
97185 * See LICENSE file in root directory for full license.
97186 */
97187
97188
97189const {
97190 CALL,
97191 ReferenceTracker
97192} = __webpack_require__(549);
97193
97194const {
97195 isCommaToken,
97196 isOpeningParenToken,
97197 isClosingParenToken,
97198 isParenthesised
97199} = __webpack_require__(426);
97200
97201const ANY_SPACE = /\s/u;
97202/**
97203 * Helper that checks if the Object.assign call has array spread
97204 * @param {ASTNode} node The node that the rule warns on
97205 * @returns {boolean} - Returns true if the Object.assign call has array spread
97206 */
97207
97208function hasArraySpread(node) {
97209 return node.arguments.some(arg => arg.type === "SpreadElement");
97210}
97211/**
97212 * Determines whether the given node is an accessor property (getter/setter).
97213 * @param {ASTNode} node Node to check.
97214 * @returns {boolean} `true` if the node is a getter or a setter.
97215 */
97216
97217
97218function isAccessorProperty(node) {
97219 return node.type === "Property" && (node.kind === "get" || node.kind === "set");
97220}
97221/**
97222 * Determines whether the given object expression node has accessor properties (getters/setters).
97223 * @param {ASTNode} node `ObjectExpression` node to check.
97224 * @returns {boolean} `true` if the node has at least one getter/setter.
97225 */
97226
97227
97228function hasAccessors(node) {
97229 return node.properties.some(isAccessorProperty);
97230}
97231/**
97232 * Determines whether the given call expression node has object expression arguments with accessor properties (getters/setters).
97233 * @param {ASTNode} node `CallExpression` node to check.
97234 * @returns {boolean} `true` if the node has at least one argument that is an object expression with at least one getter/setter.
97235 */
97236
97237
97238function hasArgumentsWithAccessors(node) {
97239 return node.arguments.filter(arg => arg.type === "ObjectExpression").some(hasAccessors);
97240}
97241/**
97242 * Helper that checks if the node needs parentheses to be valid JS.
97243 * The default is to wrap the node in parentheses to avoid parsing errors.
97244 * @param {ASTNode} node The node that the rule warns on
97245 * @param {Object} sourceCode in context sourcecode object
97246 * @returns {boolean} - Returns true if the node needs parentheses
97247 */
97248
97249
97250function needsParens(node, sourceCode) {
97251 const parent = node.parent;
97252
97253 switch (parent.type) {
97254 case "VariableDeclarator":
97255 case "ArrayExpression":
97256 case "ReturnStatement":
97257 case "CallExpression":
97258 case "Property":
97259 return false;
97260
97261 case "AssignmentExpression":
97262 return parent.left === node && !isParenthesised(sourceCode, node);
97263
97264 default:
97265 return !isParenthesised(sourceCode, node);
97266 }
97267}
97268/**
97269 * Determines if an argument needs parentheses. The default is to not add parens.
97270 * @param {ASTNode} node The node to be checked.
97271 * @param {Object} sourceCode in context sourcecode object
97272 * @returns {boolean} True if the node needs parentheses
97273 */
97274
97275
97276function argNeedsParens(node, sourceCode) {
97277 switch (node.type) {
97278 case "AssignmentExpression":
97279 case "ArrowFunctionExpression":
97280 case "ConditionalExpression":
97281 return !isParenthesised(sourceCode, node);
97282
97283 default:
97284 return false;
97285 }
97286}
97287/**
97288 * Get the parenthesis tokens of a given ObjectExpression node.
97289 * This includes the braces of the object literal and enclosing parentheses.
97290 * @param {ASTNode} node The node to get.
97291 * @param {Token} leftArgumentListParen The opening paren token of the argument list.
97292 * @param {SourceCode} sourceCode The source code object to get tokens.
97293 * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location.
97294 */
97295
97296
97297function getParenTokens(node, leftArgumentListParen, sourceCode) {
97298 const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)];
97299 let leftNext = sourceCode.getTokenBefore(node);
97300 let rightNext = sourceCode.getTokenAfter(node); // Note: don't include the parens of the argument list.
97301
97302 while (leftNext && rightNext && leftNext.range[0] > leftArgumentListParen.range[0] && isOpeningParenToken(leftNext) && isClosingParenToken(rightNext)) {
97303 parens.push(leftNext, rightNext);
97304 leftNext = sourceCode.getTokenBefore(leftNext);
97305 rightNext = sourceCode.getTokenAfter(rightNext);
97306 }
97307
97308 return parens.sort((a, b) => a.range[0] - b.range[0]);
97309}
97310/**
97311 * Get the range of a given token and around whitespaces.
97312 * @param {Token} token The token to get range.
97313 * @param {SourceCode} sourceCode The source code object to get tokens.
97314 * @returns {number} The end of the range of the token and around whitespaces.
97315 */
97316
97317
97318function getStartWithSpaces(token, sourceCode) {
97319 const text = sourceCode.text;
97320 let start = token.range[0]; // If the previous token is a line comment then skip this step to avoid commenting this token out.
97321
97322 {
97323 const prevToken = sourceCode.getTokenBefore(token, {
97324 includeComments: true
97325 });
97326
97327 if (prevToken && prevToken.type === "Line") {
97328 return start;
97329 }
97330 } // Detect spaces before the token.
97331
97332 while (ANY_SPACE.test(text[start - 1] || "")) {
97333 start -= 1;
97334 }
97335
97336 return start;
97337}
97338/**
97339 * Get the range of a given token and around whitespaces.
97340 * @param {Token} token The token to get range.
97341 * @param {SourceCode} sourceCode The source code object to get tokens.
97342 * @returns {number} The start of the range of the token and around whitespaces.
97343 */
97344
97345
97346function getEndWithSpaces(token, sourceCode) {
97347 const text = sourceCode.text;
97348 let end = token.range[1]; // Detect spaces after the token.
97349
97350 while (ANY_SPACE.test(text[end] || "")) {
97351 end += 1;
97352 }
97353
97354 return end;
97355}
97356/**
97357 * Autofixes the Object.assign call to use an object spread instead.
97358 * @param {ASTNode|null} node The node that the rule warns on, i.e. the Object.assign call
97359 * @param {string} sourceCode sourceCode of the Object.assign call
97360 * @returns {Function} autofixer - replaces the Object.assign with a spread object.
97361 */
97362
97363
97364function defineFixer(node, sourceCode) {
97365 return function* (fixer) {
97366 const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken);
97367 const rightParen = sourceCode.getLastToken(node); // Remove everything before the opening paren: callee `Object.assign`, type arguments, and whitespace between the callee and the paren.
97368
97369 yield fixer.removeRange([node.range[0], leftParen.range[0]]); // Replace the parens of argument list to braces.
97370
97371 if (needsParens(node, sourceCode)) {
97372 yield fixer.replaceText(leftParen, "({");
97373 yield fixer.replaceText(rightParen, "})");
97374 } else {
97375 yield fixer.replaceText(leftParen, "{");
97376 yield fixer.replaceText(rightParen, "}");
97377 } // Process arguments.
97378
97379
97380 for (const argNode of node.arguments) {
97381 const innerParens = getParenTokens(argNode, leftParen, sourceCode);
97382 const left = innerParens.shift();
97383 const right = innerParens.pop();
97384
97385 if (argNode.type === "ObjectExpression") {
97386 const maybeTrailingComma = sourceCode.getLastToken(argNode, 1);
97387 const maybeArgumentComma = sourceCode.getTokenAfter(right);
97388 /*
97389 * Make bare this object literal.
97390 * And remove spaces inside of the braces for better formatting.
97391 */
97392
97393 for (const innerParen of innerParens) {
97394 yield fixer.remove(innerParen);
97395 }
97396
97397 const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)];
97398 const rightRange = [Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap
97399 right.range[1]];
97400 yield fixer.removeRange(leftRange);
97401 yield fixer.removeRange(rightRange); // Remove the comma of this argument if it's duplication.
97402
97403 if ((argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) && isCommaToken(maybeArgumentComma)) {
97404 yield fixer.remove(maybeArgumentComma);
97405 }
97406 } else {
97407 // Make spread.
97408 if (argNeedsParens(argNode, sourceCode)) {
97409 yield fixer.insertTextBefore(left, "...(");
97410 yield fixer.insertTextAfter(right, ")");
97411 } else {
97412 yield fixer.insertTextBefore(left, "...");
97413 }
97414 }
97415 }
97416 };
97417}
97418
97419module.exports = {
97420 meta: {
97421 type: "suggestion",
97422 docs: {
97423 description: "disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead.",
97424 category: "Stylistic Issues",
97425 recommended: false,
97426 url: "https://eslint.org/docs/rules/prefer-object-spread"
97427 },
97428 schema: [],
97429 fixable: "code",
97430 messages: {
97431 useSpreadMessage: "Use an object spread instead of `Object.assign` eg: `{ ...foo }`.",
97432 useLiteralMessage: "Use an object literal instead of `Object.assign`. eg: `{ foo: bar }`."
97433 }
97434 },
97435
97436 create(context) {
97437 const sourceCode = context.getSourceCode();
97438 return {
97439 Program() {
97440 const scope = context.getScope();
97441 const tracker = new ReferenceTracker(scope);
97442 const trackMap = {
97443 Object: {
97444 assign: {
97445 [CALL]: true
97446 }
97447 }
97448 }; // Iterate all calls of `Object.assign` (only of the global variable `Object`).
97449
97450 for (const {
97451 node
97452 } of tracker.iterateGlobalReferences(trackMap)) {
97453 if (node.arguments.length >= 1 && node.arguments[0].type === "ObjectExpression" && !hasArraySpread(node) && !(node.arguments.length > 1 && hasArgumentsWithAccessors(node))) {
97454 const messageId = node.arguments.length === 1 ? "useLiteralMessage" : "useSpreadMessage";
97455 const fix = defineFixer(node, sourceCode);
97456 context.report({
97457 node,
97458 messageId,
97459 fix
97460 });
97461 }
97462 }
97463 }
97464
97465 };
97466 }
97467
97468};
97469
97470/***/ }),
6a5a0f88 97471/* 681 */
eb39fafa
DC
97472/***/ (function(module, exports, __webpack_require__) {
97473
97474"use strict";
97475/**
97476 * @fileoverview restrict values that can be used as Promise rejection reasons
97477 * @author Teddy Katz
97478 */
97479
97480
97481const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
97482// Rule Definition
97483//------------------------------------------------------------------------------
97484
97485
97486module.exports = {
97487 meta: {
97488 type: "suggestion",
97489 docs: {
97490 description: "require using Error objects as Promise rejection reasons",
97491 category: "Best Practices",
97492 recommended: false,
97493 url: "https://eslint.org/docs/rules/prefer-promise-reject-errors"
97494 },
97495 fixable: null,
97496 schema: [{
97497 type: "object",
97498 properties: {
97499 allowEmptyReject: {
97500 type: "boolean",
97501 default: false
97502 }
97503 },
97504 additionalProperties: false
97505 }],
97506 messages: {
97507 rejectAnError: "Expected the Promise rejection reason to be an Error."
97508 }
97509 },
97510
97511 create(context) {
97512 const ALLOW_EMPTY_REJECT = context.options.length && context.options[0].allowEmptyReject; //----------------------------------------------------------------------
97513 // Helpers
97514 //----------------------------------------------------------------------
97515
97516 /**
97517 * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error
97518 * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise
97519 * @returns {void}
97520 */
97521
97522 function checkRejectCall(callExpression) {
97523 if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) {
97524 return;
97525 }
97526
97527 if (!callExpression.arguments.length || !astUtils.couldBeError(callExpression.arguments[0]) || callExpression.arguments[0].type === "Identifier" && callExpression.arguments[0].name === "undefined") {
97528 context.report({
97529 node: callExpression,
97530 messageId: "rejectAnError"
97531 });
97532 }
97533 }
97534 /**
97535 * Determines whether a function call is a Promise.reject() call
97536 * @param {ASTNode} node A CallExpression node
97537 * @returns {boolean} `true` if the call is a Promise.reject() call
97538 */
97539
97540
97541 function isPromiseRejectCall(node) {
97542 return node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "Promise" && node.callee.property.type === "Identifier" && node.callee.property.name === "reject";
97543 } //----------------------------------------------------------------------
97544 // Public
97545 //----------------------------------------------------------------------
97546
97547
97548 return {
97549 // Check `Promise.reject(value)` calls.
97550 CallExpression(node) {
97551 if (isPromiseRejectCall(node)) {
97552 checkRejectCall(node);
97553 }
97554 },
97555
97556 /*
97557 * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls.
97558 * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that
97559 * the nodes in the expression already have the `parent` property.
97560 */
97561 "NewExpression:exit"(node) {
97562 if (node.callee.type === "Identifier" && node.callee.name === "Promise" && node.arguments.length && astUtils.isFunction(node.arguments[0]) && node.arguments[0].params.length > 1 && node.arguments[0].params[1].type === "Identifier") {
97563 context.getDeclaredVariables(node.arguments[0])
97564 /*
97565 * Find the first variable that matches the second parameter's name.
97566 * If the first parameter has the same name as the second parameter, then the variable will actually
97567 * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten
97568 * by the second parameter. It's not possible for an expression with the variable to be evaluated before
97569 * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or
97570 * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for
97571 * this case.
97572 */
97573 .find(variable => variable.name === node.arguments[0].params[1].name) // Get the references to that variable.
97574 .references // Only check the references that read the parameter's value.
97575 .filter(ref => ref.isRead()) // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`.
97576 .filter(ref => ref.identifier.parent.type === "CallExpression" && ref.identifier === ref.identifier.parent.callee) // Check the argument of the function call to determine whether it's an Error.
97577 .forEach(ref => checkRejectCall(ref.identifier.parent));
97578 }
97579 }
97580
97581 };
97582 }
97583
97584};
97585
97586/***/ }),
6a5a0f88 97587/* 682 */
eb39fafa
DC
97588/***/ (function(module, exports, __webpack_require__) {
97589
97590"use strict";
97591/**
97592 * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods
97593 * @author Keith Cirkel <http://keithcirkel.co.uk>
97594 * @deprecated in ESLint v3.9.0
97595 */
97596 //------------------------------------------------------------------------------
97597// Rule Definition
97598//------------------------------------------------------------------------------
97599
97600module.exports = {
97601 meta: {
97602 type: "suggestion",
97603 docs: {
97604 description: "require `Reflect` methods where applicable",
97605 category: "ECMAScript 6",
97606 recommended: false,
97607 url: "https://eslint.org/docs/rules/prefer-reflect"
97608 },
97609 deprecated: true,
97610 replacedBy: [],
97611 schema: [{
97612 type: "object",
97613 properties: {
97614 exceptions: {
97615 type: "array",
97616 items: {
97617 enum: ["apply", "call", "delete", "defineProperty", "getOwnPropertyDescriptor", "getPrototypeOf", "setPrototypeOf", "isExtensible", "getOwnPropertyNames", "preventExtensions"]
97618 },
97619 uniqueItems: true
97620 }
97621 },
97622 additionalProperties: false
97623 }],
97624 messages: {
97625 preferReflect: "Avoid using {{existing}}, instead use {{substitute}}."
97626 }
97627 },
97628
97629 create(context) {
97630 const existingNames = {
97631 apply: "Function.prototype.apply",
97632 call: "Function.prototype.call",
97633 defineProperty: "Object.defineProperty",
97634 getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor",
97635 getPrototypeOf: "Object.getPrototypeOf",
97636 setPrototypeOf: "Object.setPrototypeOf",
97637 isExtensible: "Object.isExtensible",
97638 getOwnPropertyNames: "Object.getOwnPropertyNames",
97639 preventExtensions: "Object.preventExtensions"
97640 };
97641 const reflectSubstitutes = {
97642 apply: "Reflect.apply",
97643 call: "Reflect.apply",
97644 defineProperty: "Reflect.defineProperty",
97645 getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor",
97646 getPrototypeOf: "Reflect.getPrototypeOf",
97647 setPrototypeOf: "Reflect.setPrototypeOf",
97648 isExtensible: "Reflect.isExtensible",
97649 getOwnPropertyNames: "Reflect.getOwnPropertyNames",
97650 preventExtensions: "Reflect.preventExtensions"
97651 };
97652 const exceptions = (context.options[0] || {}).exceptions || [];
97653 /**
97654 * Reports the Reflect violation based on the `existing` and `substitute`
97655 * @param {Object} node The node that violates the rule.
97656 * @param {string} existing The existing method name that has been used.
97657 * @param {string} substitute The Reflect substitute that should be used.
97658 * @returns {void}
97659 */
97660
97661 function report(node, existing, substitute) {
97662 context.report({
97663 node,
97664 messageId: "preferReflect",
97665 data: {
97666 existing,
97667 substitute
97668 }
97669 });
97670 }
97671
97672 return {
97673 CallExpression(node) {
97674 const methodName = (node.callee.property || {}).name;
97675 const isReflectCall = (node.callee.object || {}).name === "Reflect";
97676 const hasReflectSubsitute = Object.prototype.hasOwnProperty.call(reflectSubstitutes, methodName);
97677 const userConfiguredException = exceptions.indexOf(methodName) !== -1;
97678
97679 if (hasReflectSubsitute && !isReflectCall && !userConfiguredException) {
97680 report(node, existingNames[methodName], reflectSubstitutes[methodName]);
97681 }
97682 },
97683
97684 UnaryExpression(node) {
97685 const isDeleteOperator = node.operator === "delete";
97686 const targetsIdentifier = node.argument.type === "Identifier";
97687 const userConfiguredException = exceptions.indexOf("delete") !== -1;
97688
97689 if (isDeleteOperator && !targetsIdentifier && !userConfiguredException) {
97690 report(node, "the delete keyword", "Reflect.deleteProperty");
97691 }
97692 }
97693
97694 };
97695 }
97696
97697};
97698
97699/***/ }),
6a5a0f88 97700/* 683 */
eb39fafa
DC
97701/***/ (function(module, exports, __webpack_require__) {
97702
97703"use strict";
97704/**
97705 * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals
97706 * @author Milos Djermanovic
97707 */
97708 //------------------------------------------------------------------------------
97709// Requirements
97710//------------------------------------------------------------------------------
97711
97712const astUtils = __webpack_require__(426);
97713
97714const {
97715 CALL,
97716 CONSTRUCT,
97717 ReferenceTracker,
97718 findVariable
97719} = __webpack_require__(549); //------------------------------------------------------------------------------
97720// Helpers
97721//------------------------------------------------------------------------------
97722
97723/**
97724 * Determines whether the given node is a string literal.
97725 * @param {ASTNode} node Node to check.
97726 * @returns {boolean} True if the node is a string literal.
97727 */
97728
97729
97730function isStringLiteral(node) {
97731 return node.type === "Literal" && typeof node.value === "string";
97732}
97733/**
97734 * Determines whether the given node is a template literal without expressions.
97735 * @param {ASTNode} node Node to check.
97736 * @returns {boolean} True if the node is a template literal without expressions.
97737 */
97738
97739
97740function isStaticTemplateLiteral(node) {
97741 return node.type === "TemplateLiteral" && node.expressions.length === 0;
97742} //------------------------------------------------------------------------------
97743// Rule Definition
97744//------------------------------------------------------------------------------
97745
97746
97747module.exports = {
97748 meta: {
97749 type: "suggestion",
97750 docs: {
97751 description: "disallow use of the `RegExp` constructor in favor of regular expression literals",
97752 category: "Best Practices",
97753 recommended: false,
97754 url: "https://eslint.org/docs/rules/prefer-regex-literals"
97755 },
97756 schema: [],
97757 messages: {
97758 unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor."
97759 }
97760 },
97761
97762 create(context) {
97763 /**
97764 * Determines whether the given identifier node is a reference to a global variable.
97765 * @param {ASTNode} node `Identifier` node to check.
97766 * @returns {boolean} True if the identifier is a reference to a global variable.
97767 */
97768 function isGlobalReference(node) {
97769 const scope = context.getScope();
97770 const variable = findVariable(scope, node);
97771 return variable !== null && variable.scope.type === "global" && variable.defs.length === 0;
97772 }
97773 /**
97774 * Determines whether the given node is a String.raw`` tagged template expression
97775 * with a static template literal.
97776 * @param {ASTNode} node Node to check.
97777 * @returns {boolean} True if the node is String.raw`` with a static template.
97778 */
97779
97780
97781 function isStringRawTaggedStaticTemplateLiteral(node) {
97782 return node.type === "TaggedTemplateExpression" && node.tag.type === "MemberExpression" && node.tag.object.type === "Identifier" && node.tag.object.name === "String" && isGlobalReference(node.tag.object) && astUtils.getStaticPropertyName(node.tag) === "raw" && isStaticTemplateLiteral(node.quasi);
97783 }
97784 /**
97785 * Determines whether the given node is considered to be a static string by the logic of this rule.
97786 * @param {ASTNode} node Node to check.
97787 * @returns {boolean} True if the node is a static string.
97788 */
97789
97790
97791 function isStaticString(node) {
97792 return isStringLiteral(node) || isStaticTemplateLiteral(node) || isStringRawTaggedStaticTemplateLiteral(node);
97793 }
97794
97795 return {
97796 Program() {
97797 const scope = context.getScope();
97798 const tracker = new ReferenceTracker(scope);
97799 const traceMap = {
97800 RegExp: {
97801 [CALL]: true,
97802 [CONSTRUCT]: true
97803 }
97804 };
97805
97806 for (const {
97807 node
97808 } of tracker.iterateGlobalReferences(traceMap)) {
97809 const args = node.arguments;
97810
97811 if ((args.length === 1 || args.length === 2) && args.every(isStaticString)) {
97812 context.report({
97813 node,
97814 messageId: "unexpectedRegExp"
97815 });
97816 }
97817 }
97818 }
97819
97820 };
97821 }
97822
97823};
97824
97825/***/ }),
6a5a0f88 97826/* 684 */
eb39fafa
DC
97827/***/ (function(module, exports, __webpack_require__) {
97828
97829"use strict";
97830/**
97831 * @fileoverview Rule to
97832 * @author Toru Nagashima
97833 */
97834 //------------------------------------------------------------------------------
97835// Helpers
97836//------------------------------------------------------------------------------
97837
97838/**
97839 * Gets the variable object of `arguments` which is defined implicitly.
97840 * @param {eslint-scope.Scope} scope A scope to get.
97841 * @returns {eslint-scope.Variable} The found variable object.
97842 */
97843
97844function getVariableOfArguments(scope) {
97845 const variables = scope.variables;
97846
97847 for (let i = 0; i < variables.length; ++i) {
97848 const variable = variables[i];
97849
97850 if (variable.name === "arguments") {
97851 /*
97852 * If there was a parameter which is named "arguments", the implicit "arguments" is not defined.
97853 * So does fast return with null.
97854 */
97855 return variable.identifiers.length === 0 ? variable : null;
97856 }
97857 }
97858 /* istanbul ignore next : unreachable */
97859
97860
97861 return null;
97862}
97863/**
97864 * Checks if the given reference is not normal member access.
97865 *
97866 * - arguments .... true // not member access
97867 * - arguments[i] .... true // computed member access
97868 * - arguments[0] .... true // computed member access
97869 * - arguments.length .... false // normal member access
97870 * @param {eslint-scope.Reference} reference The reference to check.
97871 * @returns {boolean} `true` if the reference is not normal member access.
97872 */
97873
97874
97875function isNotNormalMemberAccess(reference) {
97876 const id = reference.identifier;
97877 const parent = id.parent;
97878 return !(parent.type === "MemberExpression" && parent.object === id && !parent.computed);
97879} //------------------------------------------------------------------------------
97880// Rule Definition
97881//------------------------------------------------------------------------------
97882
97883
97884module.exports = {
97885 meta: {
97886 type: "suggestion",
97887 docs: {
97888 description: "require rest parameters instead of `arguments`",
97889 category: "ECMAScript 6",
97890 recommended: false,
97891 url: "https://eslint.org/docs/rules/prefer-rest-params"
97892 },
97893 schema: [],
97894 messages: {
97895 preferRestParams: "Use the rest parameters instead of 'arguments'."
97896 }
97897 },
97898
97899 create(context) {
97900 /**
97901 * Reports a given reference.
97902 * @param {eslint-scope.Reference} reference A reference to report.
97903 * @returns {void}
97904 */
97905 function report(reference) {
97906 context.report({
97907 node: reference.identifier,
97908 loc: reference.identifier.loc,
97909 messageId: "preferRestParams"
97910 });
97911 }
97912 /**
97913 * Reports references of the implicit `arguments` variable if exist.
97914 * @returns {void}
97915 */
97916
97917
97918 function checkForArguments() {
97919 const argumentsVar = getVariableOfArguments(context.getScope());
97920
97921 if (argumentsVar) {
97922 argumentsVar.references.filter(isNotNormalMemberAccess).forEach(report);
97923 }
97924 }
97925
97926 return {
97927 "FunctionDeclaration:exit": checkForArguments,
97928 "FunctionExpression:exit": checkForArguments
97929 };
97930 }
97931
97932};
97933
97934/***/ }),
6a5a0f88 97935/* 685 */
eb39fafa
DC
97936/***/ (function(module, exports, __webpack_require__) {
97937
97938"use strict";
97939/**
97940 * @fileoverview A rule to suggest using of the spread operator instead of `.apply()`.
97941 * @author Toru Nagashima
97942 */
97943
97944
97945const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
97946// Helpers
97947//------------------------------------------------------------------------------
97948
97949/**
97950 * Checks whether or not a node is a `.apply()` for variadic.
97951 * @param {ASTNode} node A CallExpression node to check.
97952 * @returns {boolean} Whether or not the node is a `.apply()` for variadic.
97953 */
97954
97955
97956function isVariadicApplyCalling(node) {
97957 return node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier" && node.callee.property.name === "apply" && node.callee.computed === false && node.arguments.length === 2 && node.arguments[1].type !== "ArrayExpression" && node.arguments[1].type !== "SpreadElement";
97958}
97959/**
97960 * Checks whether or not `thisArg` is not changed by `.apply()`.
97961 * @param {ASTNode|null} expectedThis The node that is the owner of the applied function.
97962 * @param {ASTNode} thisArg The node that is given to the first argument of the `.apply()`.
97963 * @param {RuleContext} context The ESLint rule context object.
97964 * @returns {boolean} Whether or not `thisArg` is not changed by `.apply()`.
97965 */
97966
97967
97968function isValidThisArg(expectedThis, thisArg, context) {
97969 if (!expectedThis) {
97970 return astUtils.isNullOrUndefined(thisArg);
97971 }
97972
97973 return astUtils.equalTokens(expectedThis, thisArg, context);
97974} //------------------------------------------------------------------------------
97975// Rule Definition
97976//------------------------------------------------------------------------------
97977
97978
97979module.exports = {
97980 meta: {
97981 type: "suggestion",
97982 docs: {
97983 description: "require spread operators instead of `.apply()`",
97984 category: "ECMAScript 6",
97985 recommended: false,
97986 url: "https://eslint.org/docs/rules/prefer-spread"
97987 },
97988 schema: [],
97989 fixable: null,
97990 messages: {
97991 preferSpread: "Use the spread operator instead of '.apply()'."
97992 }
97993 },
97994
97995 create(context) {
97996 const sourceCode = context.getSourceCode();
97997 return {
97998 CallExpression(node) {
97999 if (!isVariadicApplyCalling(node)) {
98000 return;
98001 }
98002
98003 const applied = node.callee.object;
98004 const expectedThis = applied.type === "MemberExpression" ? applied.object : null;
98005 const thisArg = node.arguments[0];
98006
98007 if (isValidThisArg(expectedThis, thisArg, sourceCode)) {
98008 context.report({
98009 node,
98010 messageId: "preferSpread"
98011 });
98012 }
98013 }
98014
98015 };
98016 }
98017
98018};
98019
98020/***/ }),
6a5a0f88 98021/* 686 */
eb39fafa
DC
98022/***/ (function(module, exports, __webpack_require__) {
98023
98024"use strict";
98025/**
98026 * @fileoverview A rule to suggest using template literals instead of string concatenation.
98027 * @author Toru Nagashima
98028 */
98029 //------------------------------------------------------------------------------
98030// Requirements
98031//------------------------------------------------------------------------------
98032
98033const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
98034// Helpers
98035//------------------------------------------------------------------------------
98036
98037/**
98038 * Checks whether or not a given node is a concatenation.
98039 * @param {ASTNode} node A node to check.
98040 * @returns {boolean} `true` if the node is a concatenation.
98041 */
98042
98043
98044function isConcatenation(node) {
98045 return node.type === "BinaryExpression" && node.operator === "+";
98046}
98047/**
98048 * Gets the top binary expression node for concatenation in parents of a given node.
98049 * @param {ASTNode} node A node to get.
98050 * @returns {ASTNode} the top binary expression node in parents of a given node.
98051 */
98052
98053
98054function getTopConcatBinaryExpression(node) {
98055 let currentNode = node;
98056
98057 while (isConcatenation(currentNode.parent)) {
98058 currentNode = currentNode.parent;
98059 }
98060
98061 return currentNode;
98062}
98063/**
98064 * Determines whether a given node is a octal escape sequence
98065 * @param {ASTNode} node A node to check
98066 * @returns {boolean} `true` if the node is an octal escape sequence
98067 */
98068
98069
98070function isOctalEscapeSequence(node) {
98071 // No need to check TemplateLiterals – would throw error with octal escape
98072 const isStringLiteral = node.type === "Literal" && typeof node.value === "string";
98073
98074 if (!isStringLiteral) {
98075 return false;
98076 }
98077
98078 return astUtils.hasOctalEscapeSequence(node.raw);
98079}
98080/**
98081 * Checks whether or not a node contains a octal escape sequence
98082 * @param {ASTNode} node A node to check
98083 * @returns {boolean} `true` if the node contains an octal escape sequence
98084 */
98085
98086
98087function hasOctalEscapeSequence(node) {
98088 if (isConcatenation(node)) {
98089 return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right);
98090 }
98091
98092 return isOctalEscapeSequence(node);
98093}
98094/**
98095 * Checks whether or not a given binary expression has string literals.
98096 * @param {ASTNode} node A node to check.
98097 * @returns {boolean} `true` if the node has string literals.
98098 */
98099
98100
98101function hasStringLiteral(node) {
98102 if (isConcatenation(node)) {
98103 // `left` is deeper than `right` normally.
98104 return hasStringLiteral(node.right) || hasStringLiteral(node.left);
98105 }
98106
98107 return astUtils.isStringLiteral(node);
98108}
98109/**
98110 * Checks whether or not a given binary expression has non string literals.
98111 * @param {ASTNode} node A node to check.
98112 * @returns {boolean} `true` if the node has non string literals.
98113 */
98114
98115
98116function hasNonStringLiteral(node) {
98117 if (isConcatenation(node)) {
98118 // `left` is deeper than `right` normally.
98119 return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left);
98120 }
98121
98122 return !astUtils.isStringLiteral(node);
98123}
98124/**
98125 * Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal.
98126 * @param {ASTNode} node The node that will be fixed to a template literal
98127 * @returns {boolean} `true` if the node will start with a template curly.
98128 */
98129
98130
98131function startsWithTemplateCurly(node) {
98132 if (node.type === "BinaryExpression") {
98133 return startsWithTemplateCurly(node.left);
98134 }
98135
98136 if (node.type === "TemplateLiteral") {
98137 return node.expressions.length && node.quasis.length && node.quasis[0].range[0] === node.quasis[0].range[1];
98138 }
98139
98140 return node.type !== "Literal" || typeof node.value !== "string";
98141}
98142/**
98143 * Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal.
98144 * @param {ASTNode} node The node that will be fixed to a template literal
98145 * @returns {boolean} `true` if the node will end with a template curly.
98146 */
98147
98148
98149function endsWithTemplateCurly(node) {
98150 if (node.type === "BinaryExpression") {
98151 return startsWithTemplateCurly(node.right);
98152 }
98153
98154 if (node.type === "TemplateLiteral") {
98155 return node.expressions.length && node.quasis.length && node.quasis[node.quasis.length - 1].range[0] === node.quasis[node.quasis.length - 1].range[1];
98156 }
98157
98158 return node.type !== "Literal" || typeof node.value !== "string";
98159} //------------------------------------------------------------------------------
98160// Rule Definition
98161//------------------------------------------------------------------------------
98162
98163
98164module.exports = {
98165 meta: {
98166 type: "suggestion",
98167 docs: {
98168 description: "require template literals instead of string concatenation",
98169 category: "ECMAScript 6",
98170 recommended: false,
98171 url: "https://eslint.org/docs/rules/prefer-template"
98172 },
98173 schema: [],
98174 fixable: "code",
98175 messages: {
98176 unexpectedStringConcatenation: "Unexpected string concatenation."
98177 }
98178 },
98179
98180 create(context) {
98181 const sourceCode = context.getSourceCode();
98182 let done = Object.create(null);
98183 /**
98184 * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens.
98185 * @param {ASTNode} node1 The first node
98186 * @param {ASTNode} node2 The second node
98187 * @returns {string} The text between the nodes, excluding other tokens
98188 */
98189
98190 function getTextBetween(node1, node2) {
98191 const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
98192 const sourceText = sourceCode.getText();
98193 return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
98194 }
98195 /**
98196 * Returns a template literal form of the given node.
98197 * @param {ASTNode} currentNode A node that should be converted to a template literal
98198 * @param {string} textBeforeNode Text that should appear before the node
98199 * @param {string} textAfterNode Text that should appear after the node
98200 * @returns {string} A string form of this node, represented as a template literal
98201 */
98202
98203
98204 function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
98205 if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
98206 /*
98207 * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
98208 * as a template placeholder. However, if the code already contains a backslash before the ${ or `
98209 * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
98210 * an actual backslash character to appear before the dollar sign).
98211 */
98212 return "`".concat(currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => {
98213 if (matched.lastIndexOf("\\") % 2) {
98214 return "\\".concat(matched);
98215 }
98216
98217 return matched; // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
98218 }).replace(new RegExp("\\\\".concat(currentNode.raw[0]), "gu"), currentNode.raw[0]), "`");
98219 }
98220
98221 if (currentNode.type === "TemplateLiteral") {
98222 return sourceCode.getText(currentNode);
98223 }
98224
98225 if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
98226 const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
98227 const textBeforePlus = getTextBetween(currentNode.left, plusSign);
98228 const textAfterPlus = getTextBetween(plusSign, currentNode.right);
98229 const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left);
98230 const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right);
98231
98232 if (leftEndsWithCurly) {
98233 // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
98234 // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
98235 return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) + getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1);
98236 }
98237
98238 if (rightStartsWithCurly) {
98239 // Otherwise, if the right side of the expression starts with a template curly, add the text there.
98240 // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
98241 return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) + getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1);
98242 }
98243 /*
98244 * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
98245 * the text between them.
98246 */
98247
98248
98249 return "".concat(getTemplateLiteral(currentNode.left, textBeforeNode, null)).concat(textBeforePlus, "+").concat(textAfterPlus).concat(getTemplateLiteral(currentNode.right, textAfterNode, null));
98250 }
98251
98252 return "`${".concat(textBeforeNode || "").concat(sourceCode.getText(currentNode)).concat(textAfterNode || "", "}`");
98253 }
98254 /**
98255 * Returns a fixer object that converts a non-string binary expression to a template literal
98256 * @param {SourceCodeFixer} fixer The fixer object
98257 * @param {ASTNode} node A node that should be converted to a template literal
98258 * @returns {Object} A fix for this binary expression
98259 */
98260
98261
98262 function fixNonStringBinaryExpression(fixer, node) {
98263 const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
98264
98265 if (hasOctalEscapeSequence(topBinaryExpr)) {
98266 return null;
98267 }
98268
98269 return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
98270 }
98271 /**
98272 * Reports if a given node is string concatenation with non string literals.
98273 * @param {ASTNode} node A node to check.
98274 * @returns {void}
98275 */
98276
98277
98278 function checkForStringConcat(node) {
98279 if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
98280 return;
98281 }
98282
98283 const topBinaryExpr = getTopConcatBinaryExpression(node.parent); // Checks whether or not this node had been checked already.
98284
98285 if (done[topBinaryExpr.range[0]]) {
98286 return;
98287 }
98288
98289 done[topBinaryExpr.range[0]] = true;
98290
98291 if (hasNonStringLiteral(topBinaryExpr)) {
98292 context.report({
98293 node: topBinaryExpr,
98294 messageId: "unexpectedStringConcatenation",
98295 fix: fixer => fixNonStringBinaryExpression(fixer, node)
98296 });
98297 }
98298 }
98299
98300 return {
98301 Program() {
98302 done = Object.create(null);
98303 },
98304
98305 Literal: checkForStringConcat,
98306 TemplateLiteral: checkForStringConcat
98307 };
98308 }
98309
98310};
98311
98312/***/ }),
6a5a0f88 98313/* 687 */
eb39fafa
DC
98314/***/ (function(module, exports, __webpack_require__) {
98315
98316"use strict";
98317/**
98318 * @fileoverview Rule to flag non-quoted property names in object literals.
98319 * @author Mathias Bynens <http://mathiasbynens.be/>
98320 */
98321 //------------------------------------------------------------------------------
98322// Requirements
98323//------------------------------------------------------------------------------
98324
98325const espree = __webpack_require__(394);
98326
98327const astUtils = __webpack_require__(426);
98328
98329const keywords = __webpack_require__(460); //------------------------------------------------------------------------------
98330// Rule Definition
98331//------------------------------------------------------------------------------
98332
98333
98334module.exports = {
98335 meta: {
98336 type: "suggestion",
98337 docs: {
98338 description: "require quotes around object literal property names",
98339 category: "Stylistic Issues",
98340 recommended: false,
98341 url: "https://eslint.org/docs/rules/quote-props"
98342 },
98343 schema: {
98344 anyOf: [{
98345 type: "array",
98346 items: [{
98347 enum: ["always", "as-needed", "consistent", "consistent-as-needed"]
98348 }],
98349 minItems: 0,
98350 maxItems: 1
98351 }, {
98352 type: "array",
98353 items: [{
98354 enum: ["always", "as-needed", "consistent", "consistent-as-needed"]
98355 }, {
98356 type: "object",
98357 properties: {
98358 keywords: {
98359 type: "boolean"
98360 },
98361 unnecessary: {
98362 type: "boolean"
98363 },
98364 numbers: {
98365 type: "boolean"
98366 }
98367 },
98368 additionalProperties: false
98369 }],
98370 minItems: 0,
98371 maxItems: 2
98372 }]
98373 },
98374 fixable: "code",
98375 messages: {
98376 requireQuotesDueToReservedWord: "Properties should be quoted as '{{property}}' is a reserved word.",
98377 inconsistentlyQuotedProperty: "Inconsistently quoted property '{{key}}' found.",
98378 unnecessarilyQuotedProperty: "Unnecessarily quoted property '{{property}}' found.",
98379 unquotedReservedProperty: "Unquoted reserved word '{{property}}' used as key.",
98380 unquotedNumericProperty: "Unquoted number literal '{{property}}' used as key.",
98381 unquotedPropertyFound: "Unquoted property '{{property}}' found.",
98382 redundantQuoting: "Properties shouldn't be quoted as all quotes are redundant."
98383 }
98384 },
98385
98386 create(context) {
98387 const MODE = context.options[0],
98388 KEYWORDS = context.options[1] && context.options[1].keywords,
98389 CHECK_UNNECESSARY = !context.options[1] || context.options[1].unnecessary !== false,
98390 NUMBERS = context.options[1] && context.options[1].numbers,
98391 sourceCode = context.getSourceCode();
98392 /**
98393 * Checks whether a certain string constitutes an ES3 token
98394 * @param {string} tokenStr The string to be checked.
98395 * @returns {boolean} `true` if it is an ES3 token.
98396 */
98397
98398 function isKeyword(tokenStr) {
98399 return keywords.indexOf(tokenStr) >= 0;
98400 }
98401 /**
98402 * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary)
98403 * @param {string} rawKey The raw key value from the source
98404 * @param {espreeTokens} tokens The espree-tokenized node key
98405 * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked
98406 * @returns {boolean} Whether or not a key has redundant quotes.
98407 * @private
98408 */
98409
98410
98411 function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) {
98412 return tokens.length === 1 && tokens[0].start === 0 && tokens[0].end === rawKey.length && (["Identifier", "Keyword", "Null", "Boolean"].indexOf(tokens[0].type) >= 0 || tokens[0].type === "Numeric" && !skipNumberLiterals && String(+tokens[0].value) === tokens[0].value);
98413 }
98414 /**
98415 * Returns a string representation of a property node with quotes removed
98416 * @param {ASTNode} key Key AST Node, which may or may not be quoted
98417 * @returns {string} A replacement string for this property
98418 */
98419
98420
98421 function getUnquotedKey(key) {
98422 return key.type === "Identifier" ? key.name : key.value;
98423 }
98424 /**
98425 * Returns a string representation of a property node with quotes added
98426 * @param {ASTNode} key Key AST Node, which may or may not be quoted
98427 * @returns {string} A replacement string for this property
98428 */
98429
98430
98431 function getQuotedKey(key) {
98432 if (key.type === "Literal" && typeof key.value === "string") {
98433 // If the key is already a string literal, don't replace the quotes with double quotes.
98434 return sourceCode.getText(key);
98435 } // Otherwise, the key is either an identifier or a number literal.
98436
98437
98438 return "\"".concat(key.type === "Identifier" ? key.name : key.value, "\"");
98439 }
98440 /**
98441 * Ensures that a property's key is quoted only when necessary
98442 * @param {ASTNode} node Property AST node
98443 * @returns {void}
98444 */
98445
98446
98447 function checkUnnecessaryQuotes(node) {
98448 const key = node.key;
98449
98450 if (node.method || node.computed || node.shorthand) {
98451 return;
98452 }
98453
98454 if (key.type === "Literal" && typeof key.value === "string") {
98455 let tokens;
98456
98457 try {
98458 tokens = espree.tokenize(key.value);
98459 } catch (e) {
98460 return;
98461 }
98462
98463 if (tokens.length !== 1) {
98464 return;
98465 }
98466
98467 const isKeywordToken = isKeyword(tokens[0].value);
98468
98469 if (isKeywordToken && KEYWORDS) {
98470 return;
98471 }
98472
98473 if (CHECK_UNNECESSARY && areQuotesRedundant(key.value, tokens, NUMBERS)) {
98474 context.report({
98475 node,
98476 messageId: "unnecessarilyQuotedProperty",
98477 data: {
98478 property: key.value
98479 },
98480 fix: fixer => fixer.replaceText(key, getUnquotedKey(key))
98481 });
98482 }
98483 } else if (KEYWORDS && key.type === "Identifier" && isKeyword(key.name)) {
98484 context.report({
98485 node,
98486 messageId: "unquotedReservedProperty",
98487 data: {
98488 property: key.name
98489 },
98490 fix: fixer => fixer.replaceText(key, getQuotedKey(key))
98491 });
98492 } else if (NUMBERS && key.type === "Literal" && astUtils.isNumericLiteral(key)) {
98493 context.report({
98494 node,
98495 messageId: "unquotedNumericProperty",
98496 data: {
98497 property: key.value
98498 },
98499 fix: fixer => fixer.replaceText(key, getQuotedKey(key))
98500 });
98501 }
98502 }
98503 /**
98504 * Ensures that a property's key is quoted
98505 * @param {ASTNode} node Property AST node
98506 * @returns {void}
98507 */
98508
98509
98510 function checkOmittedQuotes(node) {
98511 const key = node.key;
98512
98513 if (!node.method && !node.computed && !node.shorthand && !(key.type === "Literal" && typeof key.value === "string")) {
98514 context.report({
98515 node,
98516 messageId: "unquotedPropertyFound",
98517 data: {
98518 property: key.name || key.value
98519 },
98520 fix: fixer => fixer.replaceText(key, getQuotedKey(key))
98521 });
98522 }
98523 }
98524 /**
98525 * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes
98526 * @param {ASTNode} node Property AST node
98527 * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy
98528 * @returns {void}
98529 */
98530
98531
98532 function checkConsistency(node, checkQuotesRedundancy) {
98533 const quotedProps = [],
98534 unquotedProps = [];
98535 let keywordKeyName = null,
98536 necessaryQuotes = false;
98537 node.properties.forEach(property => {
98538 const key = property.key;
98539
98540 if (!key || property.method || property.computed || property.shorthand) {
98541 return;
98542 }
98543
98544 if (key.type === "Literal" && typeof key.value === "string") {
98545 quotedProps.push(property);
98546
98547 if (checkQuotesRedundancy) {
98548 let tokens;
98549
98550 try {
98551 tokens = espree.tokenize(key.value);
98552 } catch (e) {
98553 necessaryQuotes = true;
98554 return;
98555 }
98556
98557 necessaryQuotes = necessaryQuotes || !areQuotesRedundant(key.value, tokens) || KEYWORDS && isKeyword(tokens[0].value);
98558 }
98559 } else if (KEYWORDS && checkQuotesRedundancy && key.type === "Identifier" && isKeyword(key.name)) {
98560 unquotedProps.push(property);
98561 necessaryQuotes = true;
98562 keywordKeyName = key.name;
98563 } else {
98564 unquotedProps.push(property);
98565 }
98566 });
98567
98568 if (checkQuotesRedundancy && quotedProps.length && !necessaryQuotes) {
98569 quotedProps.forEach(property => {
98570 context.report({
98571 node: property,
98572 messageId: "redundantQuoting",
98573 fix: fixer => fixer.replaceText(property.key, getUnquotedKey(property.key))
98574 });
98575 });
98576 } else if (unquotedProps.length && keywordKeyName) {
98577 unquotedProps.forEach(property => {
98578 context.report({
98579 node: property,
98580 messageId: "requireQuotesDueToReservedWord",
98581 data: {
98582 property: keywordKeyName
98583 },
98584 fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key))
98585 });
98586 });
98587 } else if (quotedProps.length && unquotedProps.length) {
98588 unquotedProps.forEach(property => {
98589 context.report({
98590 node: property,
98591 messageId: "inconsistentlyQuotedProperty",
98592 data: {
98593 key: property.key.name || property.key.value
98594 },
98595 fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key))
98596 });
98597 });
98598 }
98599 }
98600
98601 return {
98602 Property(node) {
98603 if (MODE === "always" || !MODE) {
98604 checkOmittedQuotes(node);
98605 }
98606
98607 if (MODE === "as-needed") {
98608 checkUnnecessaryQuotes(node);
98609 }
98610 },
98611
98612 ObjectExpression(node) {
98613 if (MODE === "consistent") {
98614 checkConsistency(node, false);
98615 }
98616
98617 if (MODE === "consistent-as-needed") {
98618 checkConsistency(node, true);
98619 }
98620 }
98621
98622 };
98623 }
98624
98625};
98626
98627/***/ }),
6a5a0f88 98628/* 688 */
eb39fafa
DC
98629/***/ (function(module, exports, __webpack_require__) {
98630
98631"use strict";
98632/**
98633 * @fileoverview A rule to choose between single and double quote marks
98634 * @author Matt DuVall <http://www.mattduvall.com/>, Brandon Payton
98635 */
98636 //------------------------------------------------------------------------------
98637// Requirements
98638//------------------------------------------------------------------------------
98639
98640function _templateObject() {
98641 const data = _taggedTemplateLiteral(["(^|[^\\])(\\\\)*[", "]"], ["(^|[^\\\\])(\\\\\\\\)*[", "]"]);
98642
98643 _templateObject = function _templateObject() {
98644 return data;
98645 };
98646
98647 return data;
98648}
98649
98650function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
98651
98652const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
98653// Constants
98654//------------------------------------------------------------------------------
98655
98656
98657const QUOTE_SETTINGS = {
98658 double: {
98659 quote: "\"",
98660 alternateQuote: "'",
98661 description: "doublequote"
98662 },
98663 single: {
98664 quote: "'",
98665 alternateQuote: "\"",
98666 description: "singlequote"
98667 },
98668 backtick: {
98669 quote: "`",
98670 alternateQuote: "\"",
98671 description: "backtick"
98672 }
98673}; // An unescaped newline is a newline preceded by an even number of backslashes.
98674
98675const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw(_templateObject(), Array.from(astUtils.LINEBREAKS).join("")), "u");
98676/**
98677 * Switches quoting of javascript string between ' " and `
98678 * escaping and unescaping as necessary.
98679 * Only escaping of the minimal set of characters is changed.
98680 * Note: escaping of newlines when switching from backtick to other quotes is not handled.
98681 * @param {string} str A string to convert.
98682 * @returns {string} The string with changed quotes.
98683 * @private
98684 */
98685
98686QUOTE_SETTINGS.double.convert = QUOTE_SETTINGS.single.convert = QUOTE_SETTINGS.backtick.convert = function (str) {
98687 const newQuote = this.quote;
98688 const oldQuote = str[0];
98689
98690 if (newQuote === oldQuote) {
98691 return str;
98692 }
98693
98694 return newQuote + str.slice(1, -1).replace(/\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, (match, escaped, newline) => {
98695 if (escaped === oldQuote || oldQuote === "`" && escaped === "${") {
98696 return escaped; // unescape
98697 }
98698
98699 if (match === newQuote || newQuote === "`" && match === "${") {
98700 return "\\".concat(match); // escape
98701 }
98702
98703 if (newline && oldQuote === "`") {
98704 return "\\n"; // escape newlines
98705 }
98706
98707 return match;
98708 }) + newQuote;
98709};
98710
98711const AVOID_ESCAPE = "avoid-escape"; //------------------------------------------------------------------------------
98712// Rule Definition
98713//------------------------------------------------------------------------------
98714
98715module.exports = {
98716 meta: {
98717 type: "layout",
98718 docs: {
98719 description: "enforce the consistent use of either backticks, double, or single quotes",
98720 category: "Stylistic Issues",
98721 recommended: false,
98722 url: "https://eslint.org/docs/rules/quotes"
98723 },
98724 fixable: "code",
98725 schema: [{
98726 enum: ["single", "double", "backtick"]
98727 }, {
98728 anyOf: [{
98729 enum: ["avoid-escape"]
98730 }, {
98731 type: "object",
98732 properties: {
98733 avoidEscape: {
98734 type: "boolean"
98735 },
98736 allowTemplateLiterals: {
98737 type: "boolean"
98738 }
98739 },
98740 additionalProperties: false
98741 }]
98742 }],
98743 messages: {
98744 wrongQuotes: "Strings must use {{description}}."
98745 }
98746 },
98747
98748 create(context) {
98749 const quoteOption = context.options[0],
98750 settings = QUOTE_SETTINGS[quoteOption || "double"],
98751 options = context.options[1],
98752 allowTemplateLiterals = options && options.allowTemplateLiterals === true,
98753 sourceCode = context.getSourceCode();
98754 let avoidEscape = options && options.avoidEscape === true; // deprecated
98755
98756 if (options === AVOID_ESCAPE) {
98757 avoidEscape = true;
98758 }
98759 /**
98760 * Determines if a given node is part of JSX syntax.
98761 *
98762 * This function returns `true` in the following cases:
98763 *
98764 * - `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
98765 * - `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
98766 * - `<>foo</>` ... If the literal is a text content, the parent of the literal is `JSXFragment`.
98767 *
98768 * In particular, this function returns `false` in the following cases:
98769 *
98770 * - `<div className={"foo"}></div>`
98771 * - `<div>{"foo"}</div>`
98772 *
98773 * In both cases, inside of the braces is handled as normal JavaScript.
98774 * The braces are `JSXExpressionContainer` nodes.
98775 * @param {ASTNode} node The Literal node to check.
98776 * @returns {boolean} True if the node is a part of JSX, false if not.
98777 * @private
98778 */
98779
98780
98781 function isJSXLiteral(node) {
98782 return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
98783 }
98784 /**
98785 * Checks whether or not a given node is a directive.
98786 * The directive is a `ExpressionStatement` which has only a string literal.
98787 * @param {ASTNode} node A node to check.
98788 * @returns {boolean} Whether or not the node is a directive.
98789 * @private
98790 */
98791
98792
98793 function isDirective(node) {
98794 return node.type === "ExpressionStatement" && node.expression.type === "Literal" && typeof node.expression.value === "string";
98795 }
98796 /**
98797 * Checks whether or not a given node is a part of directive prologues.
98798 * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
98799 * @param {ASTNode} node A node to check.
98800 * @returns {boolean} Whether or not the node is a part of directive prologues.
98801 * @private
98802 */
98803
98804
98805 function isPartOfDirectivePrologue(node) {
98806 const block = node.parent.parent;
98807
98808 if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
98809 return false;
98810 } // Check the node is at a prologue.
98811
98812
98813 for (let i = 0; i < block.body.length; ++i) {
98814 const statement = block.body[i];
98815
98816 if (statement === node.parent) {
98817 return true;
98818 }
98819
98820 if (!isDirective(statement)) {
98821 break;
98822 }
98823 }
98824
98825 return false;
98826 }
98827 /**
98828 * Checks whether or not a given node is allowed as non backtick.
98829 * @param {ASTNode} node A node to check.
98830 * @returns {boolean} Whether or not the node is allowed as non backtick.
98831 * @private
98832 */
98833
98834
98835 function isAllowedAsNonBacktick(node) {
98836 const parent = node.parent;
98837
98838 switch (parent.type) {
98839 // Directive Prologues.
98840 case "ExpressionStatement":
98841 return isPartOfDirectivePrologue(node);
98842 // LiteralPropertyName.
98843
98844 case "Property":
98845 case "MethodDefinition":
98846 return parent.key === node && !parent.computed;
98847 // ModuleSpecifier.
98848
98849 case "ImportDeclaration":
98850 case "ExportNamedDeclaration":
98851 case "ExportAllDeclaration":
98852 return parent.source === node;
98853 // Others don't allow.
98854
98855 default:
98856 return false;
98857 }
98858 }
98859 /**
98860 * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
98861 * @param {ASTNode} node A TemplateLiteral node to check.
98862 * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
98863 * @private
98864 */
98865
98866
98867 function isUsingFeatureOfTemplateLiteral(node) {
98868 const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
98869
98870 if (hasTag) {
98871 return true;
98872 }
98873
98874 const hasStringInterpolation = node.expressions.length > 0;
98875
98876 if (hasStringInterpolation) {
98877 return true;
98878 }
98879
98880 const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
98881
98882 if (isMultilineString) {
98883 return true;
98884 }
98885
98886 return false;
98887 }
98888
98889 return {
98890 Literal(node) {
98891 const val = node.value,
98892 rawVal = node.raw;
98893
98894 if (settings && typeof val === "string") {
98895 let isValid = quoteOption === "backtick" && isAllowedAsNonBacktick(node) || isJSXLiteral(node) || astUtils.isSurroundedBy(rawVal, settings.quote);
98896
98897 if (!isValid && avoidEscape) {
98898 isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
98899 }
98900
98901 if (!isValid) {
98902 context.report({
98903 node,
98904 messageId: "wrongQuotes",
98905 data: {
98906 description: settings.description
98907 },
98908
98909 fix(fixer) {
98910 if (quoteOption === "backtick" && astUtils.hasOctalEscapeSequence(rawVal)) {
98911 // An octal escape sequence in a template literal would produce syntax error, even in non-strict mode.
98912 return null;
98913 }
98914
98915 return fixer.replaceText(node, settings.convert(node.raw));
98916 }
98917
98918 });
98919 }
98920 }
98921 },
98922
98923 TemplateLiteral(node) {
98924 // Don't throw an error if backticks are expected or a template literal feature is in use.
98925 if (allowTemplateLiterals || quoteOption === "backtick" || isUsingFeatureOfTemplateLiteral(node)) {
98926 return;
98927 }
98928
98929 context.report({
98930 node,
98931 messageId: "wrongQuotes",
98932 data: {
98933 description: settings.description
98934 },
98935
98936 fix(fixer) {
98937 if (isPartOfDirectivePrologue(node)) {
98938 /*
98939 * TemplateLiterals in a directive prologue aren't actually directives, but if they're
98940 * in the directive prologue, then fixing them might turn them into directives and change
98941 * the behavior of the code.
98942 */
98943 return null;
98944 }
98945
98946 return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
98947 }
98948
98949 });
98950 }
98951
98952 };
98953 }
98954
98955};
98956
98957/***/ }),
6a5a0f88 98958/* 689 */
eb39fafa
DC
98959/***/ (function(module, exports, __webpack_require__) {
98960
98961"use strict";
98962/**
98963 * @fileoverview Rule to flag use of parseInt without a radix argument
98964 * @author James Allardice
98965 */
98966 //------------------------------------------------------------------------------
98967// Requirements
98968//------------------------------------------------------------------------------
98969
98970const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
98971// Helpers
98972//------------------------------------------------------------------------------
98973
98974
98975const MODE_ALWAYS = "always",
98976 MODE_AS_NEEDED = "as-needed";
98977const validRadixValues = new Set(Array.from({
98978 length: 37 - 2
98979}, (_, index) => index + 2));
98980/**
98981 * Checks whether a given variable is shadowed or not.
98982 * @param {eslint-scope.Variable} variable A variable to check.
98983 * @returns {boolean} `true` if the variable is shadowed.
98984 */
98985
98986function isShadowed(variable) {
98987 return variable.defs.length >= 1;
98988}
98989/**
98990 * Checks whether a given node is a MemberExpression of `parseInt` method or not.
98991 * @param {ASTNode} node A node to check.
98992 * @returns {boolean} `true` if the node is a MemberExpression of `parseInt`
98993 * method.
98994 */
98995
98996
98997function isParseIntMethod(node) {
98998 return node.type === "MemberExpression" && !node.computed && node.property.type === "Identifier" && node.property.name === "parseInt";
98999}
99000/**
99001 * Checks whether a given node is a valid value of radix or not.
99002 *
99003 * The following values are invalid.
99004 *
99005 * - A literal except integers between 2 and 36.
99006 * - undefined.
99007 * @param {ASTNode} radix A node of radix to check.
99008 * @returns {boolean} `true` if the node is valid.
99009 */
99010
99011
99012function isValidRadix(radix) {
99013 return !(radix.type === "Literal" && !validRadixValues.has(radix.value) || radix.type === "Identifier" && radix.name === "undefined");
99014}
99015/**
99016 * Checks whether a given node is a default value of radix or not.
99017 * @param {ASTNode} radix A node of radix to check.
99018 * @returns {boolean} `true` if the node is the literal node of `10`.
99019 */
99020
99021
99022function isDefaultRadix(radix) {
99023 return radix.type === "Literal" && radix.value === 10;
99024} //------------------------------------------------------------------------------
99025// Rule Definition
99026//------------------------------------------------------------------------------
99027
99028
99029module.exports = {
99030 meta: {
99031 type: "suggestion",
99032 docs: {
99033 description: "enforce the consistent use of the radix argument when using `parseInt()`",
99034 category: "Best Practices",
99035 recommended: false,
99036 url: "https://eslint.org/docs/rules/radix"
99037 },
99038 schema: [{
99039 enum: ["always", "as-needed"]
99040 }],
99041 messages: {
99042 missingParameters: "Missing parameters.",
99043 redundantRadix: "Redundant radix parameter.",
99044 missingRadix: "Missing radix parameter.",
99045 invalidRadix: "Invalid radix parameter, must be an integer between 2 and 36."
99046 }
99047 },
99048
99049 create(context) {
99050 const mode = context.options[0] || MODE_ALWAYS;
99051 /**
99052 * Checks the arguments of a given CallExpression node and reports it if it
99053 * offends this rule.
99054 * @param {ASTNode} node A CallExpression node to check.
99055 * @returns {void}
99056 */
99057
99058 function checkArguments(node) {
99059 const args = node.arguments;
99060
99061 switch (args.length) {
99062 case 0:
99063 context.report({
99064 node,
99065 messageId: "missingParameters"
99066 });
99067 break;
99068
99069 case 1:
99070 if (mode === MODE_ALWAYS) {
99071 context.report({
99072 node,
99073 messageId: "missingRadix"
99074 });
99075 }
99076
99077 break;
99078
99079 default:
99080 if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) {
99081 context.report({
99082 node,
99083 messageId: "redundantRadix"
99084 });
99085 } else if (!isValidRadix(args[1])) {
99086 context.report({
99087 node,
99088 messageId: "invalidRadix"
99089 });
99090 }
99091
99092 break;
99093 }
99094 }
99095
99096 return {
99097 "Program:exit"() {
99098 const scope = context.getScope();
99099 let variable; // Check `parseInt()`
99100
99101 variable = astUtils.getVariableByName(scope, "parseInt");
99102
99103 if (variable && !isShadowed(variable)) {
99104 variable.references.forEach(reference => {
99105 const node = reference.identifier;
99106
99107 if (astUtils.isCallee(node)) {
99108 checkArguments(node.parent);
99109 }
99110 });
99111 } // Check `Number.parseInt()`
99112
99113
99114 variable = astUtils.getVariableByName(scope, "Number");
99115
99116 if (variable && !isShadowed(variable)) {
99117 variable.references.forEach(reference => {
99118 const node = reference.identifier.parent;
99119
99120 if (isParseIntMethod(node) && astUtils.isCallee(node)) {
99121 checkArguments(node.parent);
99122 }
99123 });
99124 }
99125 }
99126
99127 };
99128 }
99129
99130};
99131
99132/***/ }),
6a5a0f88 99133/* 690 */
eb39fafa
DC
99134/***/ (function(module, exports, __webpack_require__) {
99135
99136"use strict";
99137/**
99138 * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield`
99139 * @author Teddy Katz
99140 * @author Toru Nagashima
99141 */
99142
99143/**
99144 * Make the map from identifiers to each reference.
99145 * @param {escope.Scope} scope The scope to get references.
99146 * @param {Map<Identifier, escope.Reference>} [outReferenceMap] The map from identifier nodes to each reference object.
99147 * @returns {Map<Identifier, escope.Reference>} `referenceMap`.
99148 */
99149
99150function createReferenceMap(scope, outReferenceMap = new Map()) {
99151 for (const reference of scope.references) {
99152 outReferenceMap.set(reference.identifier, reference);
99153 }
99154
99155 for (const childScope of scope.childScopes) {
99156 if (childScope.type !== "function") {
99157 createReferenceMap(childScope, outReferenceMap);
99158 }
99159 }
99160
99161 return outReferenceMap;
99162}
99163/**
99164 * Get `reference.writeExpr` of a given reference.
99165 * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a`
99166 * @param {escope.Reference} reference The reference to get.
99167 * @returns {Expression|null} The `reference.writeExpr`.
99168 */
99169
99170
99171function getWriteExpr(reference) {
99172 if (reference.writeExpr) {
99173 return reference.writeExpr;
99174 }
99175
99176 let node = reference.identifier;
99177
99178 while (node) {
99179 const t = node.parent.type;
99180
99181 if (t === "AssignmentExpression" && node.parent.left === node) {
99182 return node.parent.right;
99183 }
99184
99185 if (t === "MemberExpression" && node.parent.object === node) {
99186 node = node.parent;
99187 continue;
99188 }
99189
99190 break;
99191 }
99192
99193 return null;
99194}
99195/**
99196 * Checks if an expression is a variable that can only be observed within the given function.
99197 * @param {Variable|null} variable The variable to check
99198 * @param {boolean} isMemberAccess If `true` then this is a member access.
99199 * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure.
99200 */
99201
99202
99203function isLocalVariableWithoutEscape(variable, isMemberAccess) {
99204 if (!variable) {
99205 return false; // A global variable which was not defined.
99206 } // If the reference is a property access and the variable is a parameter, it handles the variable is not local.
99207
99208
99209 if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) {
99210 return false;
99211 }
99212
99213 const functionScope = variable.scope.variableScope;
99214 return variable.references.every(reference => reference.from.variableScope === functionScope);
99215}
99216
99217class SegmentInfo {
99218 constructor() {
99219 this.info = new WeakMap();
99220 }
99221 /**
99222 * Initialize the segment information.
99223 * @param {PathSegment} segment The segment to initialize.
99224 * @returns {void}
99225 */
99226
99227
99228 initialize(segment) {
99229 const outdatedReadVariableNames = new Set();
99230 const freshReadVariableNames = new Set();
99231
99232 for (const prevSegment of segment.prevSegments) {
99233 const info = this.info.get(prevSegment);
99234
99235 if (info) {
99236 info.outdatedReadVariableNames.forEach(Set.prototype.add, outdatedReadVariableNames);
99237 info.freshReadVariableNames.forEach(Set.prototype.add, freshReadVariableNames);
99238 }
99239 }
99240
99241 this.info.set(segment, {
99242 outdatedReadVariableNames,
99243 freshReadVariableNames
99244 });
99245 }
99246 /**
99247 * Mark a given variable as read on given segments.
99248 * @param {PathSegment[]} segments The segments that it read the variable on.
99249 * @param {string} variableName The variable name to be read.
99250 * @returns {void}
99251 */
99252
99253
99254 markAsRead(segments, variableName) {
99255 for (const segment of segments) {
99256 const info = this.info.get(segment);
99257
99258 if (info) {
99259 info.freshReadVariableNames.add(variableName);
99260 }
99261 }
99262 }
99263 /**
99264 * Move `freshReadVariableNames` to `outdatedReadVariableNames`.
99265 * @param {PathSegment[]} segments The segments to process.
99266 * @returns {void}
99267 */
99268
99269
99270 makeOutdated(segments) {
99271 for (const segment of segments) {
99272 const info = this.info.get(segment);
99273
99274 if (info) {
99275 info.freshReadVariableNames.forEach(Set.prototype.add, info.outdatedReadVariableNames);
99276 info.freshReadVariableNames.clear();
99277 }
99278 }
99279 }
99280 /**
99281 * Check if a given variable is outdated on the current segments.
99282 * @param {PathSegment[]} segments The current segments.
99283 * @param {string} variableName The variable name to check.
99284 * @returns {boolean} `true` if the variable is outdated on the segments.
99285 */
99286
99287
99288 isOutdated(segments, variableName) {
99289 for (const segment of segments) {
99290 const info = this.info.get(segment);
99291
99292 if (info && info.outdatedReadVariableNames.has(variableName)) {
99293 return true;
99294 }
99295 }
99296
99297 return false;
99298 }
99299
99300} //------------------------------------------------------------------------------
99301// Rule Definition
99302//------------------------------------------------------------------------------
99303
99304
99305module.exports = {
99306 meta: {
99307 type: "problem",
99308 docs: {
99309 description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
99310 category: "Possible Errors",
99311 recommended: false,
99312 url: "https://eslint.org/docs/rules/require-atomic-updates"
99313 },
99314 fixable: null,
99315 schema: [],
99316 messages: {
99317 nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`."
99318 }
99319 },
99320
99321 create(context) {
99322 const sourceCode = context.getSourceCode();
99323 const assignmentReferences = new Map();
99324 const segmentInfo = new SegmentInfo();
99325 let stack = null;
99326 return {
99327 onCodePathStart(codePath) {
99328 const scope = context.getScope();
99329 const shouldVerify = scope.type === "function" && (scope.block.async || scope.block.generator);
99330 stack = {
99331 upper: stack,
99332 codePath,
99333 referenceMap: shouldVerify ? createReferenceMap(scope) : null
99334 };
99335 },
99336
99337 onCodePathEnd() {
99338 stack = stack.upper;
99339 },
99340
99341 // Initialize the segment information.
99342 onCodePathSegmentStart(segment) {
99343 segmentInfo.initialize(segment);
99344 },
99345
99346 // Handle references to prepare verification.
99347 Identifier(node) {
99348 const {
99349 codePath,
99350 referenceMap
99351 } = stack;
99352 const reference = referenceMap && referenceMap.get(node); // Ignore if this is not a valid variable reference.
99353
99354 if (!reference) {
99355 return;
99356 }
99357
99358 const name = reference.identifier.name;
99359 const variable = reference.resolved;
99360 const writeExpr = getWriteExpr(reference);
99361 const isMemberAccess = reference.identifier.parent.type === "MemberExpression"; // Add a fresh read variable.
99362
99363 if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) {
99364 segmentInfo.markAsRead(codePath.currentSegments, name);
99365 }
99366 /*
99367 * Register the variable to verify after ESLint traversed the `writeExpr` node
99368 * if this reference is an assignment to a variable which is referred from other closure.
99369 */
99370
99371
99372 if (writeExpr && writeExpr.parent.right === writeExpr && // ← exclude variable declarations.
99373 !isLocalVariableWithoutEscape(variable, isMemberAccess)) {
99374 let refs = assignmentReferences.get(writeExpr);
99375
99376 if (!refs) {
99377 refs = [];
99378 assignmentReferences.set(writeExpr, refs);
99379 }
99380
99381 refs.push(reference);
99382 }
99383 },
99384
99385 /*
99386 * Verify assignments.
99387 * If the reference exists in `outdatedReadVariableNames` list, report it.
99388 */
99389 ":expression:exit"(node) {
99390 const {
99391 codePath,
99392 referenceMap
99393 } = stack; // referenceMap exists if this is in a resumable function scope.
99394
99395 if (!referenceMap) {
99396 return;
99397 } // Mark the read variables on this code path as outdated.
99398
99399
99400 if (node.type === "AwaitExpression" || node.type === "YieldExpression") {
99401 segmentInfo.makeOutdated(codePath.currentSegments);
99402 } // Verify.
99403
99404
99405 const references = assignmentReferences.get(node);
99406
99407 if (references) {
99408 assignmentReferences.delete(node);
99409
99410 for (const reference of references) {
99411 const name = reference.identifier.name;
99412
99413 if (segmentInfo.isOutdated(codePath.currentSegments, name)) {
99414 context.report({
99415 node: node.parent,
99416 messageId: "nonAtomicUpdate",
99417 data: {
99418 value: sourceCode.getText(node.parent.left)
99419 }
99420 });
99421 }
99422 }
99423 }
99424 }
99425
99426 };
99427 }
99428
99429};
99430
99431/***/ }),
6a5a0f88 99432/* 691 */
eb39fafa
DC
99433/***/ (function(module, exports, __webpack_require__) {
99434
99435"use strict";
99436/**
99437 * @fileoverview Rule to disallow async functions which have no `await` expression.
99438 * @author Toru Nagashima
99439 */
99440 //------------------------------------------------------------------------------
99441// Requirements
99442//------------------------------------------------------------------------------
99443
99444const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
99445// Helpers
99446//------------------------------------------------------------------------------
99447
99448/**
99449 * Capitalize the 1st letter of the given text.
99450 * @param {string} text The text to capitalize.
99451 * @returns {string} The text that the 1st letter was capitalized.
99452 */
99453
99454
99455function capitalizeFirstLetter(text) {
99456 return text[0].toUpperCase() + text.slice(1);
99457} //------------------------------------------------------------------------------
99458// Rule Definition
99459//------------------------------------------------------------------------------
99460
99461
99462module.exports = {
99463 meta: {
99464 type: "suggestion",
99465 docs: {
99466 description: "disallow async functions which have no `await` expression",
99467 category: "Best Practices",
99468 recommended: false,
99469 url: "https://eslint.org/docs/rules/require-await"
99470 },
99471 schema: [],
99472 messages: {
99473 missingAwait: "{{name}} has no 'await' expression."
99474 }
99475 },
99476
99477 create(context) {
99478 const sourceCode = context.getSourceCode();
99479 let scopeInfo = null;
99480 /**
99481 * Push the scope info object to the stack.
99482 * @returns {void}
99483 */
99484
99485 function enterFunction() {
99486 scopeInfo = {
99487 upper: scopeInfo,
99488 hasAwait: false
99489 };
99490 }
99491 /**
99492 * Pop the top scope info object from the stack.
99493 * Also, it reports the function if needed.
99494 * @param {ASTNode} node The node to report.
99495 * @returns {void}
99496 */
99497
99498
99499 function exitFunction(node) {
99500 if (!node.generator && node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) {
99501 context.report({
99502 node,
99503 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
99504 messageId: "missingAwait",
99505 data: {
99506 name: capitalizeFirstLetter(astUtils.getFunctionNameWithKind(node))
99507 }
99508 });
99509 }
99510
99511 scopeInfo = scopeInfo.upper;
99512 }
99513
99514 return {
99515 FunctionDeclaration: enterFunction,
99516 FunctionExpression: enterFunction,
99517 ArrowFunctionExpression: enterFunction,
99518 "FunctionDeclaration:exit": exitFunction,
99519 "FunctionExpression:exit": exitFunction,
99520 "ArrowFunctionExpression:exit": exitFunction,
99521
99522 AwaitExpression() {
99523 if (!scopeInfo) {
99524 return;
99525 }
99526
99527 scopeInfo.hasAwait = true;
99528 },
99529
99530 ForOfStatement(node) {
99531 if (!scopeInfo) {
99532 return;
99533 }
99534
99535 if (node.await) {
99536 scopeInfo.hasAwait = true;
99537 }
99538 }
99539
99540 };
99541 }
99542
99543};
99544
99545/***/ }),
6a5a0f88 99546/* 692 */
eb39fafa
DC
99547/***/ (function(module, exports, __webpack_require__) {
99548
99549"use strict";
99550/**
99551 * @fileoverview Rule to check for jsdoc presence.
99552 * @author Gyandeep Singh
99553 */
99554
99555
99556module.exports = {
99557 meta: {
99558 type: "suggestion",
99559 docs: {
99560 description: "require JSDoc comments",
99561 category: "Stylistic Issues",
99562 recommended: false,
99563 url: "https://eslint.org/docs/rules/require-jsdoc"
99564 },
99565 schema: [{
99566 type: "object",
99567 properties: {
99568 require: {
99569 type: "object",
99570 properties: {
99571 ClassDeclaration: {
99572 type: "boolean",
99573 default: false
99574 },
99575 MethodDefinition: {
99576 type: "boolean",
99577 default: false
99578 },
99579 FunctionDeclaration: {
99580 type: "boolean",
99581 default: true
99582 },
99583 ArrowFunctionExpression: {
99584 type: "boolean",
99585 default: false
99586 },
99587 FunctionExpression: {
99588 type: "boolean",
99589 default: false
99590 }
99591 },
99592 additionalProperties: false,
99593 default: {}
99594 }
99595 },
99596 additionalProperties: false
99597 }],
99598 deprecated: true,
99599 replacedBy: [],
99600 messages: {
99601 missingJSDocComment: "Missing JSDoc comment."
99602 }
99603 },
99604
99605 create(context) {
99606 const source = context.getSourceCode();
99607 const DEFAULT_OPTIONS = {
99608 FunctionDeclaration: true,
99609 MethodDefinition: false,
99610 ClassDeclaration: false,
99611 ArrowFunctionExpression: false,
99612 FunctionExpression: false
99613 };
99614 const options = Object.assign(DEFAULT_OPTIONS, context.options[0] && context.options[0].require);
99615 /**
99616 * Report the error message
99617 * @param {ASTNode} node node to report
99618 * @returns {void}
99619 */
99620
99621 function report(node) {
99622 context.report({
99623 node,
99624 messageId: "missingJSDocComment"
99625 });
99626 }
99627 /**
99628 * Check if the jsdoc comment is present or not.
99629 * @param {ASTNode} node node to examine
99630 * @returns {void}
99631 */
99632
99633
99634 function checkJsDoc(node) {
99635 const jsdocComment = source.getJSDocComment(node);
99636
99637 if (!jsdocComment) {
99638 report(node);
99639 }
99640 }
99641
99642 return {
99643 FunctionDeclaration(node) {
99644 if (options.FunctionDeclaration) {
99645 checkJsDoc(node);
99646 }
99647 },
99648
99649 FunctionExpression(node) {
99650 if (options.MethodDefinition && node.parent.type === "MethodDefinition" || options.FunctionExpression && (node.parent.type === "VariableDeclarator" || node.parent.type === "Property" && node === node.parent.value)) {
99651 checkJsDoc(node);
99652 }
99653 },
99654
99655 ClassDeclaration(node) {
99656 if (options.ClassDeclaration) {
99657 checkJsDoc(node);
99658 }
99659 },
99660
99661 ArrowFunctionExpression(node) {
99662 if (options.ArrowFunctionExpression && node.parent.type === "VariableDeclarator") {
99663 checkJsDoc(node);
99664 }
99665 }
99666
99667 };
99668 }
99669
99670};
99671
99672/***/ }),
6a5a0f88 99673/* 693 */
eb39fafa
DC
99674/***/ (function(module, exports, __webpack_require__) {
99675
99676"use strict";
99677/**
99678 * @fileoverview Rule to enforce the use of `u` flag on RegExp.
99679 * @author Toru Nagashima
99680 */
99681 //------------------------------------------------------------------------------
99682// Requirements
99683//------------------------------------------------------------------------------
99684
99685const {
99686 CALL,
99687 CONSTRUCT,
99688 ReferenceTracker,
99689 getStringIfConstant
99690} = __webpack_require__(549); //------------------------------------------------------------------------------
99691// Rule Definition
99692//------------------------------------------------------------------------------
99693
99694
99695module.exports = {
99696 meta: {
99697 type: "suggestion",
99698 docs: {
99699 description: "enforce the use of `u` flag on RegExp",
99700 category: "Best Practices",
99701 recommended: false,
99702 url: "https://eslint.org/docs/rules/require-unicode-regexp"
99703 },
99704 messages: {
99705 requireUFlag: "Use the 'u' flag."
99706 },
99707 schema: []
99708 },
99709
99710 create(context) {
99711 return {
99712 "Literal[regex]"(node) {
99713 const flags = node.regex.flags || "";
99714
99715 if (!flags.includes("u")) {
99716 context.report({
99717 node,
99718 messageId: "requireUFlag"
99719 });
99720 }
99721 },
99722
99723 Program() {
99724 const scope = context.getScope();
99725 const tracker = new ReferenceTracker(scope);
99726 const trackMap = {
99727 RegExp: {
99728 [CALL]: true,
99729 [CONSTRUCT]: true
99730 }
99731 };
99732
99733 for (const {
99734 node
99735 } of tracker.iterateGlobalReferences(trackMap)) {
99736 const flagsNode = node.arguments[1];
99737 const flags = getStringIfConstant(flagsNode, scope);
99738
99739 if (!flagsNode || typeof flags === "string" && !flags.includes("u")) {
99740 context.report({
99741 node,
99742 messageId: "requireUFlag"
99743 });
99744 }
99745 }
99746 }
99747
99748 };
99749 }
99750
99751};
99752
99753/***/ }),
6a5a0f88 99754/* 694 */
eb39fafa
DC
99755/***/ (function(module, exports, __webpack_require__) {
99756
99757"use strict";
99758/**
99759 * @fileoverview Rule to flag the generator functions that does not have yield.
99760 * @author Toru Nagashima
99761 */
99762 //------------------------------------------------------------------------------
99763// Rule Definition
99764//------------------------------------------------------------------------------
99765
99766module.exports = {
99767 meta: {
99768 type: "suggestion",
99769 docs: {
99770 description: "require generator functions to contain `yield`",
99771 category: "ECMAScript 6",
99772 recommended: true,
99773 url: "https://eslint.org/docs/rules/require-yield"
99774 },
99775 schema: [],
99776 messages: {
99777 missingYield: "This generator function does not have 'yield'."
99778 }
99779 },
99780
99781 create(context) {
99782 const stack = [];
99783 /**
99784 * If the node is a generator function, start counting `yield` keywords.
99785 * @param {Node} node A function node to check.
99786 * @returns {void}
99787 */
99788
99789 function beginChecking(node) {
99790 if (node.generator) {
99791 stack.push(0);
99792 }
99793 }
99794 /**
99795 * If the node is a generator function, end counting `yield` keywords, then
99796 * reports result.
99797 * @param {Node} node A function node to check.
99798 * @returns {void}
99799 */
99800
99801
99802 function endChecking(node) {
99803 if (!node.generator) {
99804 return;
99805 }
99806
99807 const countYield = stack.pop();
99808
99809 if (countYield === 0 && node.body.body.length > 0) {
99810 context.report({
99811 node,
99812 messageId: "missingYield"
99813 });
99814 }
99815 }
99816
99817 return {
99818 FunctionDeclaration: beginChecking,
99819 "FunctionDeclaration:exit": endChecking,
99820 FunctionExpression: beginChecking,
99821 "FunctionExpression:exit": endChecking,
99822
99823 // Increases the count of `yield` keyword.
99824 YieldExpression() {
99825 /* istanbul ignore else */
99826 if (stack.length > 0) {
99827 stack[stack.length - 1] += 1;
99828 }
99829 }
99830
99831 };
99832 }
99833
99834};
99835
99836/***/ }),
6a5a0f88 99837/* 695 */
eb39fafa
DC
99838/***/ (function(module, exports, __webpack_require__) {
99839
99840"use strict";
99841/**
99842 * @fileoverview Enforce spacing between rest and spread operators and their expressions.
99843 * @author Kai Cataldo
99844 */
99845 //------------------------------------------------------------------------------
99846// Rule Definition
99847//------------------------------------------------------------------------------
99848
99849module.exports = {
99850 meta: {
99851 type: "layout",
99852 docs: {
99853 description: "enforce spacing between rest and spread operators and their expressions",
99854 category: "ECMAScript 6",
99855 recommended: false,
99856 url: "https://eslint.org/docs/rules/rest-spread-spacing"
99857 },
99858 fixable: "whitespace",
99859 schema: [{
99860 enum: ["always", "never"]
99861 }],
99862 messages: {
99863 unexpectedWhitespace: "Unexpected whitespace after {{type}} operator.",
99864 expectedWhitespace: "Expected whitespace after {{type}} operator."
99865 }
99866 },
99867
99868 create(context) {
99869 const sourceCode = context.getSourceCode(),
99870 alwaysSpace = context.options[0] === "always"; //--------------------------------------------------------------------------
99871 // Helpers
99872 //--------------------------------------------------------------------------
99873
99874 /**
99875 * Checks whitespace between rest/spread operators and their expressions
99876 * @param {ASTNode} node The node to check
99877 * @returns {void}
99878 */
99879
99880 function checkWhiteSpace(node) {
99881 const operator = sourceCode.getFirstToken(node),
99882 nextToken = sourceCode.getTokenAfter(operator),
99883 hasWhitespace = sourceCode.isSpaceBetweenTokens(operator, nextToken);
99884 let type;
99885
99886 switch (node.type) {
99887 case "SpreadElement":
99888 type = "spread";
99889
99890 if (node.parent.type === "ObjectExpression") {
99891 type += " property";
99892 }
99893
99894 break;
99895
99896 case "RestElement":
99897 type = "rest";
99898
99899 if (node.parent.type === "ObjectPattern") {
99900 type += " property";
99901 }
99902
99903 break;
99904
99905 case "ExperimentalSpreadProperty":
99906 type = "spread property";
99907 break;
99908
99909 case "ExperimentalRestProperty":
99910 type = "rest property";
99911 break;
99912
99913 default:
99914 return;
99915 }
99916
99917 if (alwaysSpace && !hasWhitespace) {
99918 context.report({
99919 node,
6a5a0f88 99920 loc: operator.loc,
eb39fafa
DC
99921 messageId: "expectedWhitespace",
99922 data: {
99923 type
99924 },
99925
99926 fix(fixer) {
99927 return fixer.replaceTextRange([operator.range[1], nextToken.range[0]], " ");
99928 }
99929
99930 });
99931 } else if (!alwaysSpace && hasWhitespace) {
99932 context.report({
99933 node,
99934 loc: {
6a5a0f88
TL
99935 start: operator.loc.end,
99936 end: nextToken.loc.start
eb39fafa
DC
99937 },
99938 messageId: "unexpectedWhitespace",
99939 data: {
99940 type
99941 },
99942
99943 fix(fixer) {
99944 return fixer.removeRange([operator.range[1], nextToken.range[0]]);
99945 }
99946
99947 });
99948 }
99949 } //--------------------------------------------------------------------------
99950 // Public
99951 //--------------------------------------------------------------------------
99952
99953
99954 return {
99955 SpreadElement: checkWhiteSpace,
99956 RestElement: checkWhiteSpace,
99957 ExperimentalSpreadProperty: checkWhiteSpace,
99958 ExperimentalRestProperty: checkWhiteSpace
99959 };
99960 }
99961
99962};
99963
99964/***/ }),
6a5a0f88 99965/* 696 */
eb39fafa
DC
99966/***/ (function(module, exports, __webpack_require__) {
99967
99968"use strict";
99969/**
99970 * @fileoverview Rule to flag missing semicolons.
99971 * @author Nicholas C. Zakas
99972 */
99973 //------------------------------------------------------------------------------
99974// Requirements
99975//------------------------------------------------------------------------------
99976
99977const FixTracker = __webpack_require__(538);
99978
99979const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
99980// Rule Definition
99981//------------------------------------------------------------------------------
99982
99983
99984module.exports = {
99985 meta: {
99986 type: "layout",
99987 docs: {
99988 description: "require or disallow semicolons instead of ASI",
99989 category: "Stylistic Issues",
99990 recommended: false,
99991 url: "https://eslint.org/docs/rules/semi"
99992 },
99993 fixable: "code",
99994 schema: {
99995 anyOf: [{
99996 type: "array",
99997 items: [{
99998 enum: ["never"]
99999 }, {
100000 type: "object",
100001 properties: {
100002 beforeStatementContinuationChars: {
100003 enum: ["always", "any", "never"]
100004 }
100005 },
100006 additionalProperties: false
100007 }],
100008 minItems: 0,
100009 maxItems: 2
100010 }, {
100011 type: "array",
100012 items: [{
100013 enum: ["always"]
100014 }, {
100015 type: "object",
100016 properties: {
100017 omitLastInOneLineBlock: {
100018 type: "boolean"
100019 }
100020 },
100021 additionalProperties: false
100022 }],
100023 minItems: 0,
100024 maxItems: 2
100025 }]
100026 },
100027 messages: {
100028 missingSemi: "Missing semicolon.",
100029 extraSemi: "Extra semicolon."
100030 }
100031 },
100032
100033 create(context) {
100034 const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-`
100035
100036 const options = context.options[1];
100037 const never = context.options[0] === "never";
100038 const exceptOneLine = Boolean(options && options.omitLastInOneLineBlock);
100039 const beforeStatementContinuationChars = options && options.beforeStatementContinuationChars || "any";
100040 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
100041 // Helpers
100042 //--------------------------------------------------------------------------
100043
100044 /**
100045 * Reports a semicolon error with appropriate location and message.
100046 * @param {ASTNode} node The node with an extra or missing semicolon.
100047 * @param {boolean} missing True if the semicolon is missing.
100048 * @returns {void}
100049 */
100050
100051 function report(node, missing) {
100052 const lastToken = sourceCode.getLastToken(node);
100053 let messageId, fix, loc;
100054
100055 if (!missing) {
100056 messageId = "missingSemi";
100057 loc = {
100058 start: lastToken.loc.end,
100059 end: astUtils.getNextLocation(sourceCode, lastToken.loc.end)
100060 };
100061
100062 fix = function fix(fixer) {
100063 return fixer.insertTextAfter(lastToken, ";");
100064 };
100065 } else {
100066 messageId = "extraSemi";
100067 loc = lastToken.loc;
100068
100069 fix = function fix(fixer) {
100070 /*
100071 * Expand the replacement range to include the surrounding
100072 * tokens to avoid conflicting with no-extra-semi.
100073 * https://github.com/eslint/eslint/issues/7928
100074 */
100075 return new FixTracker(fixer, sourceCode).retainSurroundingTokens(lastToken).remove(lastToken);
100076 };
100077 }
100078
100079 context.report({
100080 node,
100081 loc,
100082 messageId,
100083 fix
100084 });
100085 }
100086 /**
100087 * Check whether a given semicolon token is redundant.
100088 * @param {Token} semiToken A semicolon token to check.
100089 * @returns {boolean} `true` if the next token is `;` or `}`.
100090 */
100091
100092
100093 function isRedundantSemi(semiToken) {
100094 const nextToken = sourceCode.getTokenAfter(semiToken);
100095 return !nextToken || astUtils.isClosingBraceToken(nextToken) || astUtils.isSemicolonToken(nextToken);
100096 }
100097 /**
100098 * Check whether a given token is the closing brace of an arrow function.
100099 * @param {Token} lastToken A token to check.
100100 * @returns {boolean} `true` if the token is the closing brace of an arrow function.
100101 */
100102
100103
100104 function isEndOfArrowBlock(lastToken) {
100105 if (!astUtils.isClosingBraceToken(lastToken)) {
100106 return false;
100107 }
100108
100109 const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
100110 return node.type === "BlockStatement" && node.parent.type === "ArrowFunctionExpression";
100111 }
100112 /**
100113 * Check whether a given node is on the same line with the next token.
100114 * @param {Node} node A statement node to check.
100115 * @returns {boolean} `true` if the node is on the same line with the next token.
100116 */
100117
100118
100119 function isOnSameLineWithNextToken(node) {
100120 const prevToken = sourceCode.getLastToken(node, 1);
100121 const nextToken = sourceCode.getTokenAfter(node);
100122 return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
100123 }
100124 /**
100125 * Check whether a given node can connect the next line if the next line is unreliable.
100126 * @param {Node} node A statement node to check.
100127 * @returns {boolean} `true` if the node can connect the next line.
100128 */
100129
100130
100131 function maybeAsiHazardAfter(node) {
100132 const t = node.type;
100133
100134 if (t === "DoWhileStatement" || t === "BreakStatement" || t === "ContinueStatement" || t === "DebuggerStatement" || t === "ImportDeclaration" || t === "ExportAllDeclaration") {
100135 return false;
100136 }
100137
100138 if (t === "ReturnStatement") {
100139 return Boolean(node.argument);
100140 }
100141
100142 if (t === "ExportNamedDeclaration") {
100143 return Boolean(node.declaration);
100144 }
100145
100146 if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
100147 return false;
100148 }
100149
100150 return true;
100151 }
100152 /**
100153 * Check whether a given token can connect the previous statement.
100154 * @param {Token} token A token to check.
100155 * @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`.
100156 */
100157
100158
100159 function maybeAsiHazardBefore(token) {
100160 return Boolean(token) && OPT_OUT_PATTERN.test(token.value) && token.value !== "++" && token.value !== "--";
100161 }
100162 /**
100163 * Check if the semicolon of a given node is unnecessary, only true if:
100164 * - next token is a valid statement divider (`;` or `}`).
100165 * - next token is on a new line and the node is not connectable to the new line.
100166 * @param {Node} node A statement node to check.
100167 * @returns {boolean} whether the semicolon is unnecessary.
100168 */
100169
100170
100171 function canRemoveSemicolon(node) {
100172 if (isRedundantSemi(sourceCode.getLastToken(node))) {
100173 return true; // `;;` or `;}`
100174 }
100175
100176 if (isOnSameLineWithNextToken(node)) {
100177 return false; // One liner.
100178 }
100179
100180 if (beforeStatementContinuationChars === "never" && !maybeAsiHazardAfter(node)) {
100181 return true; // ASI works. This statement doesn't connect to the next.
100182 }
100183
100184 if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) {
100185 return true; // ASI works. The next token doesn't connect to this statement.
100186 }
100187
100188 return false;
100189 }
100190 /**
100191 * Checks a node to see if it's in a one-liner block statement.
100192 * @param {ASTNode} node The node to check.
100193 * @returns {boolean} whether the node is in a one-liner block statement.
100194 */
100195
100196
100197 function isOneLinerBlock(node) {
100198 const parent = node.parent;
100199 const nextToken = sourceCode.getTokenAfter(node);
100200
100201 if (!nextToken || nextToken.value !== "}") {
100202 return false;
100203 }
100204
100205 return !!parent && parent.type === "BlockStatement" && parent.loc.start.line === parent.loc.end.line;
100206 }
100207 /**
100208 * Checks a node to see if it's followed by a semicolon.
100209 * @param {ASTNode} node The node to check.
100210 * @returns {void}
100211 */
100212
100213
100214 function checkForSemicolon(node) {
100215 const isSemi = astUtils.isSemicolonToken(sourceCode.getLastToken(node));
100216
100217 if (never) {
100218 if (isSemi && canRemoveSemicolon(node)) {
100219 report(node, true);
100220 } else if (!isSemi && beforeStatementContinuationChars === "always" && maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) {
100221 report(node);
100222 }
100223 } else {
100224 const oneLinerBlock = exceptOneLine && isOneLinerBlock(node);
100225
100226 if (isSemi && oneLinerBlock) {
100227 report(node, true);
100228 } else if (!isSemi && !oneLinerBlock) {
100229 report(node);
100230 }
100231 }
100232 }
100233 /**
100234 * Checks to see if there's a semicolon after a variable declaration.
100235 * @param {ASTNode} node The node to check.
100236 * @returns {void}
100237 */
100238
100239
100240 function checkForSemicolonForVariableDeclaration(node) {
100241 const parent = node.parent;
100242
100243 if ((parent.type !== "ForStatement" || parent.init !== node) && (!/^For(?:In|Of)Statement/u.test(parent.type) || parent.left !== node)) {
100244 checkForSemicolon(node);
100245 }
100246 } //--------------------------------------------------------------------------
100247 // Public API
100248 //--------------------------------------------------------------------------
100249
100250
100251 return {
100252 VariableDeclaration: checkForSemicolonForVariableDeclaration,
100253 ExpressionStatement: checkForSemicolon,
100254 ReturnStatement: checkForSemicolon,
100255 ThrowStatement: checkForSemicolon,
100256 DoWhileStatement: checkForSemicolon,
100257 DebuggerStatement: checkForSemicolon,
100258 BreakStatement: checkForSemicolon,
100259 ContinueStatement: checkForSemicolon,
100260 ImportDeclaration: checkForSemicolon,
100261 ExportAllDeclaration: checkForSemicolon,
100262
100263 ExportNamedDeclaration(node) {
100264 if (!node.declaration) {
100265 checkForSemicolon(node);
100266 }
100267 },
100268
100269 ExportDefaultDeclaration(node) {
100270 if (!/(?:Class|Function)Declaration/u.test(node.declaration.type)) {
100271 checkForSemicolon(node);
100272 }
100273 }
100274
100275 };
100276 }
100277
100278};
100279
100280/***/ }),
6a5a0f88 100281/* 697 */
eb39fafa
DC
100282/***/ (function(module, exports, __webpack_require__) {
100283
100284"use strict";
100285/**
100286 * @fileoverview Validates spacing before and after semicolon
100287 * @author Mathias Schreck
100288 */
100289
100290
100291const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
100292// Rule Definition
100293//------------------------------------------------------------------------------
100294
100295
100296module.exports = {
100297 meta: {
100298 type: "layout",
100299 docs: {
100300 description: "enforce consistent spacing before and after semicolons",
100301 category: "Stylistic Issues",
100302 recommended: false,
100303 url: "https://eslint.org/docs/rules/semi-spacing"
100304 },
100305 fixable: "whitespace",
100306 schema: [{
100307 type: "object",
100308 properties: {
100309 before: {
100310 type: "boolean",
100311 default: false
100312 },
100313 after: {
100314 type: "boolean",
100315 default: true
100316 }
100317 },
100318 additionalProperties: false
100319 }],
100320 messages: {
100321 unexpectedWhitespaceBefore: "Unexpected whitespace before semicolon.",
100322 unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.",
100323 missingWhitespaceBefore: "Missing whitespace before semicolon.",
100324 missingWhitespaceAfter: "Missing whitespace after semicolon."
100325 }
100326 },
100327
100328 create(context) {
100329 const config = context.options[0],
100330 sourceCode = context.getSourceCode();
100331 let requireSpaceBefore = false,
100332 requireSpaceAfter = true;
100333
100334 if (typeof config === "object") {
100335 requireSpaceBefore = config.before;
100336 requireSpaceAfter = config.after;
100337 }
100338 /**
100339 * Checks if a given token has leading whitespace.
100340 * @param {Object} token The token to check.
100341 * @returns {boolean} True if the given token has leading space, false if not.
100342 */
100343
100344
100345 function hasLeadingSpace(token) {
100346 const tokenBefore = sourceCode.getTokenBefore(token);
100347 return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token);
100348 }
100349 /**
100350 * Checks if a given token has trailing whitespace.
100351 * @param {Object} token The token to check.
100352 * @returns {boolean} True if the given token has trailing space, false if not.
100353 */
100354
100355
100356 function hasTrailingSpace(token) {
100357 const tokenAfter = sourceCode.getTokenAfter(token);
100358 return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter);
100359 }
100360 /**
100361 * Checks if the given token is the last token in its line.
100362 * @param {Token} token The token to check.
100363 * @returns {boolean} Whether or not the token is the last in its line.
100364 */
100365
100366
100367 function isLastTokenInCurrentLine(token) {
100368 const tokenAfter = sourceCode.getTokenAfter(token);
100369 return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter));
100370 }
100371 /**
100372 * Checks if the given token is the first token in its line
100373 * @param {Token} token The token to check.
100374 * @returns {boolean} Whether or not the token is the first in its line.
100375 */
100376
100377
100378 function isFirstTokenInCurrentLine(token) {
100379 const tokenBefore = sourceCode.getTokenBefore(token);
100380 return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore));
100381 }
100382 /**
100383 * Checks if the next token of a given token is a closing parenthesis.
100384 * @param {Token} token The token to check.
100385 * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis.
100386 */
100387
100388
100389 function isBeforeClosingParen(token) {
100390 const nextToken = sourceCode.getTokenAfter(token);
100391 return nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken);
100392 }
100393 /**
6a5a0f88
TL
100394 * Report location example :
100395 *
100396 * for unexpected space `before`
100397 *
100398 * var a = 'b' ;
100399 * ^^^
100400 *
100401 * for unexpected space `after`
100402 *
100403 * var a = 'b'; c = 10;
100404 * ^^
100405 *
eb39fafa
DC
100406 * Reports if the given token has invalid spacing.
100407 * @param {Token} token The semicolon token to check.
100408 * @param {ASTNode} node The corresponding node of the token.
100409 * @returns {void}
100410 */
100411
100412
100413 function checkSemicolonSpacing(token, node) {
100414 if (astUtils.isSemicolonToken(token)) {
eb39fafa
DC
100415 if (hasLeadingSpace(token)) {
100416 if (!requireSpaceBefore) {
6a5a0f88
TL
100417 const tokenBefore = sourceCode.getTokenBefore(token);
100418 const loc = {
100419 start: tokenBefore.loc.end,
100420 end: token.loc.start
100421 };
eb39fafa
DC
100422 context.report({
100423 node,
6a5a0f88 100424 loc,
eb39fafa
DC
100425 messageId: "unexpectedWhitespaceBefore",
100426
100427 fix(fixer) {
eb39fafa
DC
100428 return fixer.removeRange([tokenBefore.range[1], token.range[0]]);
100429 }
100430
100431 });
100432 }
100433 } else {
100434 if (requireSpaceBefore) {
6a5a0f88 100435 const loc = token.loc;
eb39fafa
DC
100436 context.report({
100437 node,
6a5a0f88 100438 loc,
eb39fafa
DC
100439 messageId: "missingWhitespaceBefore",
100440
100441 fix(fixer) {
100442 return fixer.insertTextBefore(token, " ");
100443 }
100444
100445 });
100446 }
100447 }
100448
100449 if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) {
100450 if (hasTrailingSpace(token)) {
100451 if (!requireSpaceAfter) {
6a5a0f88
TL
100452 const tokenAfter = sourceCode.getTokenAfter(token);
100453 const loc = {
100454 start: token.loc.end,
100455 end: tokenAfter.loc.start
100456 };
eb39fafa
DC
100457 context.report({
100458 node,
6a5a0f88 100459 loc,
eb39fafa
DC
100460 messageId: "unexpectedWhitespaceAfter",
100461
100462 fix(fixer) {
eb39fafa
DC
100463 return fixer.removeRange([token.range[1], tokenAfter.range[0]]);
100464 }
100465
100466 });
100467 }
100468 } else {
100469 if (requireSpaceAfter) {
6a5a0f88 100470 const loc = token.loc;
eb39fafa
DC
100471 context.report({
100472 node,
6a5a0f88 100473 loc,
eb39fafa
DC
100474 messageId: "missingWhitespaceAfter",
100475
100476 fix(fixer) {
100477 return fixer.insertTextAfter(token, " ");
100478 }
100479
100480 });
100481 }
100482 }
100483 }
100484 }
100485 }
100486 /**
100487 * Checks the spacing of the semicolon with the assumption that the last token is the semicolon.
100488 * @param {ASTNode} node The node to check.
100489 * @returns {void}
100490 */
100491
100492
100493 function checkNode(node) {
100494 const token = sourceCode.getLastToken(node);
100495 checkSemicolonSpacing(token, node);
100496 }
100497
100498 return {
100499 VariableDeclaration: checkNode,
100500 ExpressionStatement: checkNode,
100501 BreakStatement: checkNode,
100502 ContinueStatement: checkNode,
100503 DebuggerStatement: checkNode,
100504 ReturnStatement: checkNode,
100505 ThrowStatement: checkNode,
100506 ImportDeclaration: checkNode,
100507 ExportNamedDeclaration: checkNode,
100508 ExportAllDeclaration: checkNode,
100509 ExportDefaultDeclaration: checkNode,
100510
100511 ForStatement(node) {
100512 if (node.init) {
100513 checkSemicolonSpacing(sourceCode.getTokenAfter(node.init), node);
100514 }
100515
100516 if (node.test) {
100517 checkSemicolonSpacing(sourceCode.getTokenAfter(node.test), node);
100518 }
100519 }
100520
100521 };
100522 }
100523
100524};
100525
100526/***/ }),
6a5a0f88 100527/* 698 */
eb39fafa
DC
100528/***/ (function(module, exports, __webpack_require__) {
100529
100530"use strict";
100531/**
100532 * @fileoverview Rule to enforce location of semicolons.
100533 * @author Toru Nagashima
100534 */
100535 //------------------------------------------------------------------------------
100536// Requirements
100537//------------------------------------------------------------------------------
100538
100539const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
100540// Rule Definition
100541//------------------------------------------------------------------------------
100542
100543
100544const SELECTOR = ":matches(".concat(["BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "ExportAllDeclaration", "ExportDefaultDeclaration", "ExportNamedDeclaration", "ExpressionStatement", "ImportDeclaration", "ReturnStatement", "ThrowStatement", "VariableDeclaration"].join(","), ")");
100545/**
100546 * Get the child node list of a given node.
100547 * This returns `Program#body`, `BlockStatement#body`, or `SwitchCase#consequent`.
100548 * This is used to check whether a node is the first/last child.
100549 * @param {Node} node A node to get child node list.
100550 * @returns {Node[]|null} The child node list.
100551 */
100552
100553function getChildren(node) {
100554 const t = node.type;
100555
100556 if (t === "BlockStatement" || t === "Program") {
100557 return node.body;
100558 }
100559
100560 if (t === "SwitchCase") {
100561 return node.consequent;
100562 }
100563
100564 return null;
100565}
100566/**
100567 * Check whether a given node is the last statement in the parent block.
100568 * @param {Node} node A node to check.
100569 * @returns {boolean} `true` if the node is the last statement in the parent block.
100570 */
100571
100572
100573function isLastChild(node) {
100574 const t = node.parent.type;
100575
100576 if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) {
100577 // before `else` keyword.
100578 return true;
100579 }
100580
100581 if (t === "DoWhileStatement") {
100582 // before `while` keyword.
100583 return true;
100584 }
100585
100586 const nodeList = getChildren(node.parent);
100587 return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc.
100588}
100589
100590module.exports = {
100591 meta: {
100592 type: "layout",
100593 docs: {
100594 description: "enforce location of semicolons",
100595 category: "Stylistic Issues",
100596 recommended: false,
100597 url: "https://eslint.org/docs/rules/semi-style"
100598 },
100599 schema: [{
100600 enum: ["last", "first"]
100601 }],
100602 fixable: "whitespace",
100603 messages: {
100604 expectedSemiColon: "Expected this semicolon to be at {{pos}}."
100605 }
100606 },
100607
100608 create(context) {
100609 const sourceCode = context.getSourceCode();
100610 const option = context.options[0] || "last";
100611 /**
100612 * Check the given semicolon token.
100613 * @param {Token} semiToken The semicolon token to check.
100614 * @param {"first"|"last"} expected The expected location to check.
100615 * @returns {void}
100616 */
100617
100618 function check(semiToken, expected) {
100619 const prevToken = sourceCode.getTokenBefore(semiToken);
100620 const nextToken = sourceCode.getTokenAfter(semiToken);
100621 const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken);
100622 const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken);
100623
100624 if (expected === "last" && !prevIsSameLine || expected === "first" && !nextIsSameLine) {
100625 context.report({
100626 loc: semiToken.loc,
100627 messageId: "expectedSemiColon",
100628 data: {
100629 pos: expected === "last" ? "the end of the previous line" : "the beginning of the next line"
100630 },
100631
100632 fix(fixer) {
100633 if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) {
100634 return null;
100635 }
100636
100637 const start = prevToken ? prevToken.range[1] : semiToken.range[0];
100638 const end = nextToken ? nextToken.range[0] : semiToken.range[1];
100639 const text = expected === "last" ? ";\n" : "\n;";
100640 return fixer.replaceTextRange([start, end], text);
100641 }
100642
100643 });
100644 }
100645 }
100646
100647 return {
100648 [SELECTOR](node) {
100649 if (option === "first" && isLastChild(node)) {
100650 return;
100651 }
100652
100653 const lastToken = sourceCode.getLastToken(node);
100654
100655 if (astUtils.isSemicolonToken(lastToken)) {
100656 check(lastToken, option);
100657 }
100658 },
100659
100660 ForStatement(node) {
100661 const firstSemi = node.init && sourceCode.getTokenAfter(node.init, astUtils.isSemicolonToken);
100662 const secondSemi = node.test && sourceCode.getTokenAfter(node.test, astUtils.isSemicolonToken);
100663
100664 if (firstSemi) {
100665 check(firstSemi, "last");
100666 }
100667
100668 if (secondSemi) {
100669 check(secondSemi, "last");
100670 }
100671 }
100672
100673 };
100674 }
100675
100676};
100677
100678/***/ }),
6a5a0f88 100679/* 699 */
eb39fafa
DC
100680/***/ (function(module, exports, __webpack_require__) {
100681
100682"use strict";
100683/**
100684 * @fileoverview Rule to require sorting of import declarations
100685 * @author Christian Schuller
100686 */
100687 //------------------------------------------------------------------------------
100688// Rule Definition
100689//------------------------------------------------------------------------------
100690
100691module.exports = {
100692 meta: {
100693 type: "suggestion",
100694 docs: {
100695 description: "enforce sorted import declarations within modules",
100696 category: "ECMAScript 6",
100697 recommended: false,
100698 url: "https://eslint.org/docs/rules/sort-imports"
100699 },
100700 schema: [{
100701 type: "object",
100702 properties: {
100703 ignoreCase: {
100704 type: "boolean",
100705 default: false
100706 },
100707 memberSyntaxSortOrder: {
100708 type: "array",
100709 items: {
100710 enum: ["none", "all", "multiple", "single"]
100711 },
100712 uniqueItems: true,
100713 minItems: 4,
100714 maxItems: 4
100715 },
100716 ignoreDeclarationSort: {
100717 type: "boolean",
100718 default: false
100719 },
100720 ignoreMemberSort: {
100721 type: "boolean",
100722 default: false
100723 }
100724 },
100725 additionalProperties: false
100726 }],
100727 fixable: "code",
100728 messages: {
100729 sortImportsAlphabetically: "Imports should be sorted alphabetically.",
100730 sortMembersAlphabetically: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.",
100731 unexpectedSyntaxOrder: "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax."
100732 }
100733 },
100734
100735 create(context) {
100736 const configuration = context.options[0] || {},
100737 ignoreCase = configuration.ignoreCase || false,
100738 ignoreDeclarationSort = configuration.ignoreDeclarationSort || false,
100739 ignoreMemberSort = configuration.ignoreMemberSort || false,
100740 memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"],
100741 sourceCode = context.getSourceCode();
100742 let previousDeclaration = null;
100743 /**
100744 * Gets the used member syntax style.
100745 *
100746 * import "my-module.js" --> none
100747 * import * as myModule from "my-module.js" --> all
100748 * import {myMember} from "my-module.js" --> single
100749 * import {foo, bar} from "my-module.js" --> multiple
100750 * @param {ASTNode} node the ImportDeclaration node.
100751 * @returns {string} used member parameter style, ["all", "multiple", "single"]
100752 */
100753
100754 function usedMemberSyntax(node) {
100755 if (node.specifiers.length === 0) {
100756 return "none";
100757 }
100758
100759 if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
100760 return "all";
100761 }
100762
100763 if (node.specifiers.length === 1) {
100764 return "single";
100765 }
100766
100767 return "multiple";
100768 }
100769 /**
100770 * Gets the group by member parameter index for given declaration.
100771 * @param {ASTNode} node the ImportDeclaration node.
100772 * @returns {number} the declaration group by member index.
100773 */
100774
100775
100776 function getMemberParameterGroupIndex(node) {
100777 return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node));
100778 }
100779 /**
100780 * Gets the local name of the first imported module.
100781 * @param {ASTNode} node the ImportDeclaration node.
100782 * @returns {?string} the local name of the first imported module.
100783 */
100784
100785
100786 function getFirstLocalMemberName(node) {
100787 if (node.specifiers[0]) {
100788 return node.specifiers[0].local.name;
100789 }
100790
100791 return null;
100792 }
100793
100794 return {
100795 ImportDeclaration(node) {
100796 if (!ignoreDeclarationSort) {
100797 if (previousDeclaration) {
100798 const currentMemberSyntaxGroupIndex = getMemberParameterGroupIndex(node),
100799 previousMemberSyntaxGroupIndex = getMemberParameterGroupIndex(previousDeclaration);
100800 let currentLocalMemberName = getFirstLocalMemberName(node),
100801 previousLocalMemberName = getFirstLocalMemberName(previousDeclaration);
100802
100803 if (ignoreCase) {
100804 previousLocalMemberName = previousLocalMemberName && previousLocalMemberName.toLowerCase();
100805 currentLocalMemberName = currentLocalMemberName && currentLocalMemberName.toLowerCase();
100806 }
100807 /*
100808 * When the current declaration uses a different member syntax,
100809 * then check if the ordering is correct.
100810 * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name.
100811 */
100812
100813
100814 if (currentMemberSyntaxGroupIndex !== previousMemberSyntaxGroupIndex) {
100815 if (currentMemberSyntaxGroupIndex < previousMemberSyntaxGroupIndex) {
100816 context.report({
100817 node,
100818 messageId: "unexpectedSyntaxOrder",
100819 data: {
100820 syntaxA: memberSyntaxSortOrder[currentMemberSyntaxGroupIndex],
100821 syntaxB: memberSyntaxSortOrder[previousMemberSyntaxGroupIndex]
100822 }
100823 });
100824 }
100825 } else {
100826 if (previousLocalMemberName && currentLocalMemberName && currentLocalMemberName < previousLocalMemberName) {
100827 context.report({
100828 node,
100829 messageId: "sortImportsAlphabetically"
100830 });
100831 }
100832 }
100833 }
100834
100835 previousDeclaration = node;
100836 }
100837
100838 if (!ignoreMemberSort) {
100839 const importSpecifiers = node.specifiers.filter(specifier => specifier.type === "ImportSpecifier");
100840 const getSortableName = ignoreCase ? specifier => specifier.local.name.toLowerCase() : specifier => specifier.local.name;
100841 const firstUnsortedIndex = importSpecifiers.map(getSortableName).findIndex((name, index, array) => array[index - 1] > name);
100842
100843 if (firstUnsortedIndex !== -1) {
100844 context.report({
100845 node: importSpecifiers[firstUnsortedIndex],
100846 messageId: "sortMembersAlphabetically",
100847 data: {
100848 memberName: importSpecifiers[firstUnsortedIndex].local.name
100849 },
100850
100851 fix(fixer) {
100852 if (importSpecifiers.some(specifier => sourceCode.getCommentsBefore(specifier).length || sourceCode.getCommentsAfter(specifier).length)) {
100853 // If there are comments in the ImportSpecifier list, don't rearrange the specifiers.
100854 return null;
100855 }
100856
100857 return fixer.replaceTextRange([importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]], importSpecifiers // Clone the importSpecifiers array to avoid mutating it
100858 .slice() // Sort the array into the desired order
100859 .sort((specifierA, specifierB) => {
100860 const aName = getSortableName(specifierA);
100861 const bName = getSortableName(specifierB);
100862 return aName > bName ? 1 : -1;
100863 }) // Build a string out of the sorted list of import specifiers and the text between the originals
100864 .reduce((sourceText, specifier, index) => {
100865 const textAfterSpecifier = index === importSpecifiers.length - 1 ? "" : sourceCode.getText().slice(importSpecifiers[index].range[1], importSpecifiers[index + 1].range[0]);
100866 return sourceText + sourceCode.getText(specifier) + textAfterSpecifier;
100867 }, ""));
100868 }
100869
100870 });
100871 }
100872 }
100873 }
100874
100875 };
100876 }
100877
100878};
100879
100880/***/ }),
6a5a0f88 100881/* 700 */
eb39fafa
DC
100882/***/ (function(module, exports, __webpack_require__) {
100883
100884"use strict";
100885/**
100886 * @fileoverview Rule to require object keys to be sorted
100887 * @author Toru Nagashima
100888 */
100889 //------------------------------------------------------------------------------
100890// Requirements
100891//------------------------------------------------------------------------------
100892
100893const astUtils = __webpack_require__(426),
6a5a0f88 100894 naturalCompare = __webpack_require__(701); //------------------------------------------------------------------------------
eb39fafa
DC
100895// Helpers
100896//------------------------------------------------------------------------------
100897
100898/**
100899 * Gets the property name of the given `Property` node.
100900 *
100901 * - If the property's key is an `Identifier` node, this returns the key's name
100902 * whether it's a computed property or not.
100903 * - If the property has a static name, this returns the static name.
100904 * - Otherwise, this returns null.
100905 * @param {ASTNode} node The `Property` node to get.
100906 * @returns {string|null} The property name or null.
100907 * @private
100908 */
100909
100910
100911function getPropertyName(node) {
100912 const staticName = astUtils.getStaticPropertyName(node);
100913
100914 if (staticName !== null) {
100915 return staticName;
100916 }
100917
100918 return node.key.name || null;
100919}
100920/**
100921 * Functions which check that the given 2 names are in specific order.
100922 *
100923 * Postfix `I` is meant insensitive.
100924 * Postfix `N` is meant natural.
100925 * @private
100926 */
100927
100928
100929const isValidOrders = {
100930 asc(a, b) {
100931 return a <= b;
100932 },
100933
100934 ascI(a, b) {
100935 return a.toLowerCase() <= b.toLowerCase();
100936 },
100937
100938 ascN(a, b) {
100939 return naturalCompare(a, b) <= 0;
100940 },
100941
100942 ascIN(a, b) {
100943 return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0;
100944 },
100945
100946 desc(a, b) {
100947 return isValidOrders.asc(b, a);
100948 },
100949
100950 descI(a, b) {
100951 return isValidOrders.ascI(b, a);
100952 },
100953
100954 descN(a, b) {
100955 return isValidOrders.ascN(b, a);
100956 },
100957
100958 descIN(a, b) {
100959 return isValidOrders.ascIN(b, a);
100960 }
100961
100962}; //------------------------------------------------------------------------------
100963// Rule Definition
100964//------------------------------------------------------------------------------
100965
100966module.exports = {
100967 meta: {
100968 type: "suggestion",
100969 docs: {
100970 description: "require object keys to be sorted",
100971 category: "Stylistic Issues",
100972 recommended: false,
100973 url: "https://eslint.org/docs/rules/sort-keys"
100974 },
100975 schema: [{
100976 enum: ["asc", "desc"]
100977 }, {
100978 type: "object",
100979 properties: {
100980 caseSensitive: {
100981 type: "boolean",
100982 default: true
100983 },
100984 natural: {
100985 type: "boolean",
100986 default: false
100987 },
100988 minKeys: {
100989 type: "integer",
100990 minimum: 2,
100991 default: 2
100992 }
100993 },
100994 additionalProperties: false
100995 }],
100996 messages: {
100997 sortKeys: "Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'."
100998 }
100999 },
101000
101001 create(context) {
101002 // Parse options.
101003 const order = context.options[0] || "asc";
101004 const options = context.options[1];
101005 const insensitive = options && options.caseSensitive === false;
101006 const natural = options && options.natural;
101007 const minKeys = options && options.minKeys;
101008 const isValidOrder = isValidOrders[order + (insensitive ? "I" : "") + (natural ? "N" : "")]; // The stack to save the previous property's name for each object literals.
101009
101010 let stack = null;
101011 return {
101012 ObjectExpression(node) {
101013 stack = {
101014 upper: stack,
101015 prevName: null,
101016 numKeys: node.properties.length
101017 };
101018 },
101019
101020 "ObjectExpression:exit"() {
101021 stack = stack.upper;
101022 },
101023
101024 SpreadElement(node) {
101025 if (node.parent.type === "ObjectExpression") {
101026 stack.prevName = null;
101027 }
101028 },
101029
101030 Property(node) {
101031 if (node.parent.type === "ObjectPattern") {
101032 return;
101033 }
101034
101035 const prevName = stack.prevName;
101036 const numKeys = stack.numKeys;
101037 const thisName = getPropertyName(node);
101038
101039 if (thisName !== null) {
101040 stack.prevName = thisName;
101041 }
101042
101043 if (prevName === null || thisName === null || numKeys < minKeys) {
101044 return;
101045 }
101046
101047 if (!isValidOrder(prevName, thisName)) {
101048 context.report({
101049 node,
101050 loc: node.key.loc,
101051 messageId: "sortKeys",
101052 data: {
101053 thisName,
101054 prevName,
101055 order,
101056 insensitive: insensitive ? "insensitive " : "",
101057 natural: natural ? "natural " : ""
101058 }
101059 });
101060 }
101061 }
101062
101063 };
101064 }
101065
101066};
101067
101068/***/ }),
6a5a0f88 101069/* 701 */
eb39fafa
DC
101070/***/ (function(module, exports) {
101071
101072/*
101073 * @version 1.4.0
101074 * @date 2015-10-26
101075 * @stability 3 - Stable
101076 * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
101077 * @license MIT License
101078 */
101079var naturalCompare = function naturalCompare(a, b) {
101080 var i,
101081 codeA,
101082 codeB = 1,
101083 posA = 0,
101084 posB = 0,
101085 alphabet = String.alphabet;
101086
101087 function getCode(str, pos, code) {
101088 if (code) {
101089 for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
101090
101091 return +str.slice(pos - 1, i);
101092 }
101093
101094 code = alphabet && alphabet.indexOf(str.charAt(pos));
101095 return code > -1 ? code + 76 : (code = str.charCodeAt(pos) || 0, code < 45 || code > 127) ? code : code < 46 ? 65 // -
101096 : code < 48 ? code - 1 : code < 58 ? code + 18 // 0-9
101097 : code < 65 ? code - 11 : code < 91 ? code + 11 // A-Z
101098 : code < 97 ? code - 37 : code < 123 ? code + 5 // a-z
101099 : code - 63;
101100 }
101101
101102 if ((a += "") != (b += "")) for (; codeB;) {
101103 codeA = getCode(a, posA++);
101104 codeB = getCode(b, posB++);
101105
101106 if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
101107 codeA = getCode(a, posA, posA);
101108 codeB = getCode(b, posB, posA = i);
101109 posB = i;
101110 }
101111
101112 if (codeA != codeB) return codeA < codeB ? -1 : 1;
101113 }
101114 return 0;
101115};
101116
101117try {
101118 module.exports = naturalCompare;
101119} catch (e) {
101120 String.naturalCompare = naturalCompare;
101121}
101122
101123/***/ }),
6a5a0f88 101124/* 702 */
eb39fafa
DC
101125/***/ (function(module, exports, __webpack_require__) {
101126
101127"use strict";
101128/**
101129 * @fileoverview Rule to require sorting of variables within a single Variable Declaration block
101130 * @author Ilya Volodin
101131 */
101132 //------------------------------------------------------------------------------
101133// Rule Definition
101134//------------------------------------------------------------------------------
101135
101136module.exports = {
101137 meta: {
101138 type: "suggestion",
101139 docs: {
101140 description: "require variables within the same declaration block to be sorted",
101141 category: "Stylistic Issues",
101142 recommended: false,
101143 url: "https://eslint.org/docs/rules/sort-vars"
101144 },
101145 schema: [{
101146 type: "object",
101147 properties: {
101148 ignoreCase: {
101149 type: "boolean",
101150 default: false
101151 }
101152 },
101153 additionalProperties: false
101154 }],
101155 fixable: "code",
101156 messages: {
101157 sortVars: "Variables within the same declaration block should be sorted alphabetically."
101158 }
101159 },
101160
101161 create(context) {
101162 const configuration = context.options[0] || {},
101163 ignoreCase = configuration.ignoreCase || false,
101164 sourceCode = context.getSourceCode();
101165 return {
101166 VariableDeclaration(node) {
101167 const idDeclarations = node.declarations.filter(decl => decl.id.type === "Identifier");
101168 const getSortableName = ignoreCase ? decl => decl.id.name.toLowerCase() : decl => decl.id.name;
101169 const unfixable = idDeclarations.some(decl => decl.init !== null && decl.init.type !== "Literal");
101170 let fixed = false;
101171 idDeclarations.slice(1).reduce((memo, decl) => {
101172 const lastVariableName = getSortableName(memo),
101173 currentVariableName = getSortableName(decl);
101174
101175 if (currentVariableName < lastVariableName) {
101176 context.report({
101177 node: decl,
101178 messageId: "sortVars",
101179
101180 fix(fixer) {
101181 if (unfixable || fixed) {
101182 return null;
101183 }
101184
101185 return fixer.replaceTextRange([idDeclarations[0].range[0], idDeclarations[idDeclarations.length - 1].range[1]], idDeclarations // Clone the idDeclarations array to avoid mutating it
101186 .slice() // Sort the array into the desired order
101187 .sort((declA, declB) => {
101188 const aName = getSortableName(declA);
101189 const bName = getSortableName(declB);
101190 return aName > bName ? 1 : -1;
101191 }) // Build a string out of the sorted list of identifier declarations and the text between the originals
101192 .reduce((sourceText, identifier, index) => {
101193 const textAfterIdentifier = index === idDeclarations.length - 1 ? "" : sourceCode.getText().slice(idDeclarations[index].range[1], idDeclarations[index + 1].range[0]);
101194 return sourceText + sourceCode.getText(identifier) + textAfterIdentifier;
101195 }, ""));
101196 }
101197
101198 });
101199 fixed = true;
101200 return memo;
101201 }
101202
101203 return decl;
101204 }, idDeclarations[0]);
101205 }
101206
101207 };
101208 }
101209
101210};
101211
101212/***/ }),
6a5a0f88 101213/* 703 */
eb39fafa
DC
101214/***/ (function(module, exports, __webpack_require__) {
101215
101216"use strict";
101217/**
101218 * @fileoverview A rule to ensure whitespace before blocks.
101219 * @author Mathias Schreck <https://github.com/lo1tuma>
101220 */
101221
101222
101223const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
101224// Rule Definition
101225//------------------------------------------------------------------------------
101226
101227
101228module.exports = {
101229 meta: {
101230 type: "layout",
101231 docs: {
101232 description: "enforce consistent spacing before blocks",
101233 category: "Stylistic Issues",
101234 recommended: false,
101235 url: "https://eslint.org/docs/rules/space-before-blocks"
101236 },
101237 fixable: "whitespace",
101238 schema: [{
101239 oneOf: [{
101240 enum: ["always", "never"]
101241 }, {
101242 type: "object",
101243 properties: {
101244 keywords: {
101245 enum: ["always", "never", "off"]
101246 },
101247 functions: {
101248 enum: ["always", "never", "off"]
101249 },
101250 classes: {
101251 enum: ["always", "never", "off"]
101252 }
101253 },
101254 additionalProperties: false
101255 }]
101256 }],
101257 messages: {
101258 unexpectedSpace: "Unexpected space before opening brace.",
101259 missingSpace: "Missing space before opening brace."
101260 }
101261 },
101262
101263 create(context) {
101264 const config = context.options[0],
101265 sourceCode = context.getSourceCode();
101266 let alwaysFunctions = true,
101267 alwaysKeywords = true,
101268 alwaysClasses = true,
101269 neverFunctions = false,
101270 neverKeywords = false,
101271 neverClasses = false;
101272
101273 if (typeof config === "object") {
101274 alwaysFunctions = config.functions === "always";
101275 alwaysKeywords = config.keywords === "always";
101276 alwaysClasses = config.classes === "always";
101277 neverFunctions = config.functions === "never";
101278 neverKeywords = config.keywords === "never";
101279 neverClasses = config.classes === "never";
101280 } else if (config === "never") {
101281 alwaysFunctions = false;
101282 alwaysKeywords = false;
101283 alwaysClasses = false;
101284 neverFunctions = true;
101285 neverKeywords = true;
101286 neverClasses = true;
101287 }
101288 /**
101289 * Checks whether or not a given token is an arrow operator (=>) or a keyword
101290 * in order to avoid to conflict with `arrow-spacing` and `keyword-spacing`.
101291 * @param {Token} token A token to check.
101292 * @returns {boolean} `true` if the token is an arrow operator.
101293 */
101294
101295
101296 function isConflicted(token) {
101297 return token.type === "Punctuator" && token.value === "=>" || token.type === "Keyword";
101298 }
101299 /**
101300 * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line.
101301 * @param {ASTNode|Token} node The AST node of a BlockStatement.
101302 * @returns {void} undefined.
101303 */
101304
101305
101306 function checkPrecedingSpace(node) {
101307 const precedingToken = sourceCode.getTokenBefore(node);
101308
101309 if (precedingToken && !isConflicted(precedingToken) && astUtils.isTokenOnSameLine(precedingToken, node)) {
101310 const hasSpace = sourceCode.isSpaceBetweenTokens(precedingToken, node);
101311 const parent = context.getAncestors().pop();
101312 let requireSpace;
101313 let requireNoSpace;
101314
101315 if (parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration") {
101316 requireSpace = alwaysFunctions;
101317 requireNoSpace = neverFunctions;
101318 } else if (node.type === "ClassBody") {
101319 requireSpace = alwaysClasses;
101320 requireNoSpace = neverClasses;
101321 } else {
101322 requireSpace = alwaysKeywords;
101323 requireNoSpace = neverKeywords;
101324 }
101325
101326 if (requireSpace && !hasSpace) {
101327 context.report({
101328 node,
101329 messageId: "missingSpace",
101330
101331 fix(fixer) {
101332 return fixer.insertTextBefore(node, " ");
101333 }
101334
101335 });
101336 } else if (requireNoSpace && hasSpace) {
101337 context.report({
101338 node,
101339 messageId: "unexpectedSpace",
101340
101341 fix(fixer) {
101342 return fixer.removeRange([precedingToken.range[1], node.range[0]]);
101343 }
101344
101345 });
101346 }
101347 }
101348 }
101349 /**
101350 * Checks if the CaseBlock of an given SwitchStatement node has a preceding space.
101351 * @param {ASTNode} node The node of a SwitchStatement.
101352 * @returns {void} undefined.
101353 */
101354
101355
101356 function checkSpaceBeforeCaseBlock(node) {
101357 const cases = node.cases;
101358 let openingBrace;
101359
101360 if (cases.length > 0) {
101361 openingBrace = sourceCode.getTokenBefore(cases[0]);
101362 } else {
101363 openingBrace = sourceCode.getLastToken(node, 1);
101364 }
101365
101366 checkPrecedingSpace(openingBrace);
101367 }
101368
101369 return {
101370 BlockStatement: checkPrecedingSpace,
101371 ClassBody: checkPrecedingSpace,
101372 SwitchStatement: checkSpaceBeforeCaseBlock
101373 };
101374 }
101375
101376};
101377
101378/***/ }),
6a5a0f88 101379/* 704 */
eb39fafa
DC
101380/***/ (function(module, exports, __webpack_require__) {
101381
101382"use strict";
101383/**
101384 * @fileoverview Rule to validate spacing before function paren.
101385 * @author Mathias Schreck <https://github.com/lo1tuma>
101386 */
101387 //------------------------------------------------------------------------------
101388// Requirements
101389//------------------------------------------------------------------------------
101390
101391const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
101392// Rule Definition
101393//------------------------------------------------------------------------------
101394
101395
101396module.exports = {
101397 meta: {
101398 type: "layout",
101399 docs: {
101400 description: "enforce consistent spacing before `function` definition opening parenthesis",
101401 category: "Stylistic Issues",
101402 recommended: false,
101403 url: "https://eslint.org/docs/rules/space-before-function-paren"
101404 },
101405 fixable: "whitespace",
101406 schema: [{
101407 oneOf: [{
101408 enum: ["always", "never"]
101409 }, {
101410 type: "object",
101411 properties: {
101412 anonymous: {
101413 enum: ["always", "never", "ignore"]
101414 },
101415 named: {
101416 enum: ["always", "never", "ignore"]
101417 },
101418 asyncArrow: {
101419 enum: ["always", "never", "ignore"]
101420 }
101421 },
101422 additionalProperties: false
101423 }]
101424 }],
101425 messages: {
101426 unexpectedSpace: "Unexpected space before function parentheses.",
101427 missingSpace: "Missing space before function parentheses."
101428 }
101429 },
101430
101431 create(context) {
101432 const sourceCode = context.getSourceCode();
101433 const baseConfig = typeof context.options[0] === "string" ? context.options[0] : "always";
101434 const overrideConfig = typeof context.options[0] === "object" ? context.options[0] : {};
101435 /**
101436 * Determines whether a function has a name.
101437 * @param {ASTNode} node The function node.
101438 * @returns {boolean} Whether the function has a name.
101439 */
101440
101441 function isNamedFunction(node) {
101442 if (node.id) {
101443 return true;
101444 }
101445
101446 const parent = node.parent;
101447 return parent.type === "MethodDefinition" || parent.type === "Property" && (parent.kind === "get" || parent.kind === "set" || parent.method);
101448 }
101449 /**
101450 * Gets the config for a given function
101451 * @param {ASTNode} node The function node
101452 * @returns {string} "always", "never", or "ignore"
101453 */
101454
101455
101456 function getConfigForFunction(node) {
101457 if (node.type === "ArrowFunctionExpression") {
101458 // Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar
101459 if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, {
101460 skip: 1
101461 }))) {
101462 return overrideConfig.asyncArrow || baseConfig;
101463 }
101464 } else if (isNamedFunction(node)) {
101465 return overrideConfig.named || baseConfig; // `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`
101466 } else if (!node.generator) {
101467 return overrideConfig.anonymous || baseConfig;
101468 }
101469
101470 return "ignore";
101471 }
101472 /**
101473 * Checks the parens of a function node
101474 * @param {ASTNode} node A function node
101475 * @returns {void}
101476 */
101477
101478
101479 function checkFunction(node) {
101480 const functionConfig = getConfigForFunction(node);
101481
101482 if (functionConfig === "ignore") {
101483 return;
101484 }
101485
101486 const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
101487 const leftToken = sourceCode.getTokenBefore(rightToken);
101488 const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken);
101489
101490 if (hasSpacing && functionConfig === "never") {
101491 context.report({
101492 node,
56c4a2cb
DC
101493 loc: {
101494 start: leftToken.loc.end,
101495 end: rightToken.loc.start
101496 },
eb39fafa
DC
101497 messageId: "unexpectedSpace",
101498
101499 fix(fixer) {
101500 const comments = sourceCode.getCommentsBefore(rightToken); // Don't fix anything if there's a single line comment between the left and the right token
101501
101502 if (comments.some(comment => comment.type === "Line")) {
101503 return null;
101504 }
101505
101506 return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], comments.reduce((text, comment) => text + sourceCode.getText(comment), ""));
101507 }
101508
101509 });
101510 } else if (!hasSpacing && functionConfig === "always") {
101511 context.report({
101512 node,
56c4a2cb 101513 loc: rightToken.loc,
eb39fafa
DC
101514 messageId: "missingSpace",
101515 fix: fixer => fixer.insertTextAfter(leftToken, " ")
101516 });
101517 }
101518 }
101519
101520 return {
101521 ArrowFunctionExpression: checkFunction,
101522 FunctionDeclaration: checkFunction,
101523 FunctionExpression: checkFunction
101524 };
101525 }
101526
101527};
101528
101529/***/ }),
6a5a0f88 101530/* 705 */
eb39fafa
DC
101531/***/ (function(module, exports, __webpack_require__) {
101532
101533"use strict";
101534/**
101535 * @fileoverview Disallows or enforces spaces inside of parentheses.
101536 * @author Jonathan Rajavuori
101537 */
101538
101539
101540const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
101541// Rule Definition
101542//------------------------------------------------------------------------------
101543
101544
101545module.exports = {
101546 meta: {
101547 type: "layout",
101548 docs: {
101549 description: "enforce consistent spacing inside parentheses",
101550 category: "Stylistic Issues",
101551 recommended: false,
101552 url: "https://eslint.org/docs/rules/space-in-parens"
101553 },
101554 fixable: "whitespace",
101555 schema: [{
101556 enum: ["always", "never"]
101557 }, {
101558 type: "object",
101559 properties: {
101560 exceptions: {
101561 type: "array",
101562 items: {
101563 enum: ["{}", "[]", "()", "empty"]
101564 },
101565 uniqueItems: true
101566 }
101567 },
101568 additionalProperties: false
101569 }],
101570 messages: {
101571 missingOpeningSpace: "There must be a space after this paren.",
101572 missingClosingSpace: "There must be a space before this paren.",
101573 rejectedOpeningSpace: "There should be no space after this paren.",
101574 rejectedClosingSpace: "There should be no space before this paren."
101575 }
101576 },
101577
101578 create(context) {
101579 const ALWAYS = context.options[0] === "always",
101580 exceptionsArrayOptions = context.options[1] && context.options[1].exceptions || [],
101581 options = {};
101582 let exceptions;
101583
101584 if (exceptionsArrayOptions.length) {
101585 options.braceException = exceptionsArrayOptions.includes("{}");
101586 options.bracketException = exceptionsArrayOptions.includes("[]");
101587 options.parenException = exceptionsArrayOptions.includes("()");
101588 options.empty = exceptionsArrayOptions.includes("empty");
101589 }
101590 /**
101591 * Produces an object with the opener and closer exception values
101592 * @returns {Object} `openers` and `closers` exception values
101593 * @private
101594 */
101595
101596
101597 function getExceptions() {
101598 const openers = [],
101599 closers = [];
101600
101601 if (options.braceException) {
101602 openers.push("{");
101603 closers.push("}");
101604 }
101605
101606 if (options.bracketException) {
101607 openers.push("[");
101608 closers.push("]");
101609 }
101610
101611 if (options.parenException) {
101612 openers.push("(");
101613 closers.push(")");
101614 }
101615
101616 if (options.empty) {
101617 openers.push(")");
101618 closers.push("(");
101619 }
101620
101621 return {
101622 openers,
101623 closers
101624 };
101625 } //--------------------------------------------------------------------------
101626 // Helpers
101627 //--------------------------------------------------------------------------
101628
101629
101630 const sourceCode = context.getSourceCode();
101631 /**
101632 * Determines if a token is one of the exceptions for the opener paren
101633 * @param {Object} token The token to check
101634 * @returns {boolean} True if the token is one of the exceptions for the opener paren
101635 */
101636
101637 function isOpenerException(token) {
101638 return exceptions.openers.includes(token.value);
101639 }
101640 /**
101641 * Determines if a token is one of the exceptions for the closer paren
101642 * @param {Object} token The token to check
101643 * @returns {boolean} True if the token is one of the exceptions for the closer paren
101644 */
101645
101646
101647 function isCloserException(token) {
101648 return exceptions.closers.includes(token.value);
101649 }
101650 /**
101651 * Determines if an opening paren is immediately followed by a required space
101652 * @param {Object} openingParenToken The paren token
101653 * @param {Object} tokenAfterOpeningParen The token after it
101654 * @returns {boolean} True if the opening paren is missing a required space
101655 */
101656
101657
101658 function openerMissingSpace(openingParenToken, tokenAfterOpeningParen) {
101659 if (sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) {
101660 return false;
101661 }
101662
101663 if (!options.empty && astUtils.isClosingParenToken(tokenAfterOpeningParen)) {
101664 return false;
101665 }
101666
101667 if (ALWAYS) {
101668 return !isOpenerException(tokenAfterOpeningParen);
101669 }
101670
101671 return isOpenerException(tokenAfterOpeningParen);
101672 }
101673 /**
101674 * Determines if an opening paren is immediately followed by a disallowed space
101675 * @param {Object} openingParenToken The paren token
101676 * @param {Object} tokenAfterOpeningParen The token after it
101677 * @returns {boolean} True if the opening paren has a disallowed space
101678 */
101679
101680
101681 function openerRejectsSpace(openingParenToken, tokenAfterOpeningParen) {
101682 if (!astUtils.isTokenOnSameLine(openingParenToken, tokenAfterOpeningParen)) {
101683 return false;
101684 }
101685
101686 if (tokenAfterOpeningParen.type === "Line") {
101687 return false;
101688 }
101689
101690 if (!sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) {
101691 return false;
101692 }
101693
101694 if (ALWAYS) {
101695 return isOpenerException(tokenAfterOpeningParen);
101696 }
101697
101698 return !isOpenerException(tokenAfterOpeningParen);
101699 }
101700 /**
101701 * Determines if a closing paren is immediately preceded by a required space
101702 * @param {Object} tokenBeforeClosingParen The token before the paren
101703 * @param {Object} closingParenToken The paren token
101704 * @returns {boolean} True if the closing paren is missing a required space
101705 */
101706
101707
101708 function closerMissingSpace(tokenBeforeClosingParen, closingParenToken) {
101709 if (sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) {
101710 return false;
101711 }
101712
101713 if (!options.empty && astUtils.isOpeningParenToken(tokenBeforeClosingParen)) {
101714 return false;
101715 }
101716
101717 if (ALWAYS) {
101718 return !isCloserException(tokenBeforeClosingParen);
101719 }
101720
101721 return isCloserException(tokenBeforeClosingParen);
101722 }
101723 /**
101724 * Determines if a closer paren is immediately preceded by a disallowed space
101725 * @param {Object} tokenBeforeClosingParen The token before the paren
101726 * @param {Object} closingParenToken The paren token
101727 * @returns {boolean} True if the closing paren has a disallowed space
101728 */
101729
101730
101731 function closerRejectsSpace(tokenBeforeClosingParen, closingParenToken) {
101732 if (!astUtils.isTokenOnSameLine(tokenBeforeClosingParen, closingParenToken)) {
101733 return false;
101734 }
101735
101736 if (!sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) {
101737 return false;
101738 }
101739
101740 if (ALWAYS) {
101741 return isCloserException(tokenBeforeClosingParen);
101742 }
101743
101744 return !isCloserException(tokenBeforeClosingParen);
101745 } //--------------------------------------------------------------------------
101746 // Public
101747 //--------------------------------------------------------------------------
101748
101749
101750 return {
101751 Program: function checkParenSpaces(node) {
101752 exceptions = getExceptions();
101753 const tokens = sourceCode.tokensAndComments;
101754 tokens.forEach((token, i) => {
101755 const prevToken = tokens[i - 1];
101756 const nextToken = tokens[i + 1]; // if token is not an opening or closing paren token, do nothing
101757
101758 if (!astUtils.isOpeningParenToken(token) && !astUtils.isClosingParenToken(token)) {
101759 return;
101760 } // if token is an opening paren and is not followed by a required space
101761
101762
101763 if (token.value === "(" && openerMissingSpace(token, nextToken)) {
101764 context.report({
101765 node,
101766 loc: token.loc,
101767 messageId: "missingOpeningSpace",
101768
101769 fix(fixer) {
101770 return fixer.insertTextAfter(token, " ");
101771 }
101772
101773 });
101774 } // if token is an opening paren and is followed by a disallowed space
101775
101776
101777 if (token.value === "(" && openerRejectsSpace(token, nextToken)) {
101778 context.report({
101779 node,
101780 loc: {
101781 start: token.loc.end,
101782 end: nextToken.loc.start
101783 },
101784 messageId: "rejectedOpeningSpace",
101785
101786 fix(fixer) {
101787 return fixer.removeRange([token.range[1], nextToken.range[0]]);
101788 }
101789
101790 });
101791 } // if token is a closing paren and is not preceded by a required space
101792
101793
101794 if (token.value === ")" && closerMissingSpace(prevToken, token)) {
101795 context.report({
101796 node,
101797 loc: token.loc,
101798 messageId: "missingClosingSpace",
101799
101800 fix(fixer) {
101801 return fixer.insertTextBefore(token, " ");
101802 }
101803
101804 });
101805 } // if token is a closing paren and is preceded by a disallowed space
101806
101807
101808 if (token.value === ")" && closerRejectsSpace(prevToken, token)) {
101809 context.report({
101810 node,
101811 loc: {
101812 start: prevToken.loc.end,
101813 end: token.loc.start
101814 },
101815 messageId: "rejectedClosingSpace",
101816
101817 fix(fixer) {
101818 return fixer.removeRange([prevToken.range[1], token.range[0]]);
101819 }
101820
101821 });
101822 }
101823 });
101824 }
101825 };
101826 }
101827
101828};
101829
101830/***/ }),
6a5a0f88 101831/* 706 */
eb39fafa
DC
101832/***/ (function(module, exports, __webpack_require__) {
101833
101834"use strict";
101835/**
101836 * @fileoverview Require spaces around infix operators
101837 * @author Michael Ficarra
101838 */
101839 //------------------------------------------------------------------------------
101840// Rule Definition
101841//------------------------------------------------------------------------------
101842
101843module.exports = {
101844 meta: {
101845 type: "layout",
101846 docs: {
101847 description: "require spacing around infix operators",
101848 category: "Stylistic Issues",
101849 recommended: false,
101850 url: "https://eslint.org/docs/rules/space-infix-ops"
101851 },
101852 fixable: "whitespace",
101853 schema: [{
101854 type: "object",
101855 properties: {
101856 int32Hint: {
101857 type: "boolean",
101858 default: false
101859 }
101860 },
101861 additionalProperties: false
101862 }],
101863 messages: {
101864 missingSpace: "Operator '{{operator}}' must be spaced."
101865 }
101866 },
101867
101868 create(context) {
101869 const int32Hint = context.options[0] ? context.options[0].int32Hint === true : false;
101870 const sourceCode = context.getSourceCode();
101871 /**
101872 * Returns the first token which violates the rule
101873 * @param {ASTNode} left The left node of the main node
101874 * @param {ASTNode} right The right node of the main node
101875 * @param {string} op The operator of the main node
101876 * @returns {Object} The violator token or null
101877 * @private
101878 */
101879
101880 function getFirstNonSpacedToken(left, right, op) {
101881 const operator = sourceCode.getFirstTokenBetween(left, right, token => token.value === op);
101882 const prev = sourceCode.getTokenBefore(operator);
101883 const next = sourceCode.getTokenAfter(operator);
101884
101885 if (!sourceCode.isSpaceBetweenTokens(prev, operator) || !sourceCode.isSpaceBetweenTokens(operator, next)) {
101886 return operator;
101887 }
101888
101889 return null;
101890 }
101891 /**
101892 * Reports an AST node as a rule violation
101893 * @param {ASTNode} mainNode The node to report
101894 * @param {Object} culpritToken The token which has a problem
101895 * @returns {void}
101896 * @private
101897 */
101898
101899
101900 function report(mainNode, culpritToken) {
101901 context.report({
101902 node: mainNode,
101903 loc: culpritToken.loc,
101904 messageId: "missingSpace",
101905 data: {
101906 operator: culpritToken.value
101907 },
101908
101909 fix(fixer) {
101910 const previousToken = sourceCode.getTokenBefore(culpritToken);
101911 const afterToken = sourceCode.getTokenAfter(culpritToken);
101912 let fixString = "";
101913
101914 if (culpritToken.range[0] - previousToken.range[1] === 0) {
101915 fixString = " ";
101916 }
101917
101918 fixString += culpritToken.value;
101919
101920 if (afterToken.range[0] - culpritToken.range[1] === 0) {
101921 fixString += " ";
101922 }
101923
101924 return fixer.replaceText(culpritToken, fixString);
101925 }
101926
101927 });
101928 }
101929 /**
101930 * Check if the node is binary then report
101931 * @param {ASTNode} node node to evaluate
101932 * @returns {void}
101933 * @private
101934 */
101935
101936
101937 function checkBinary(node) {
101938 const leftNode = node.left.typeAnnotation ? node.left.typeAnnotation : node.left;
101939 const rightNode = node.right; // search for = in AssignmentPattern nodes
101940
101941 const operator = node.operator || "=";
101942 const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, operator);
101943
101944 if (nonSpacedNode) {
101945 if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) {
101946 report(node, nonSpacedNode);
101947 }
101948 }
101949 }
101950 /**
101951 * Check if the node is conditional
101952 * @param {ASTNode} node node to evaluate
101953 * @returns {void}
101954 * @private
101955 */
101956
101957
101958 function checkConditional(node) {
101959 const nonSpacedConsequentNode = getFirstNonSpacedToken(node.test, node.consequent, "?");
101960 const nonSpacedAlternateNode = getFirstNonSpacedToken(node.consequent, node.alternate, ":");
101961
101962 if (nonSpacedConsequentNode) {
101963 report(node, nonSpacedConsequentNode);
101964 } else if (nonSpacedAlternateNode) {
101965 report(node, nonSpacedAlternateNode);
101966 }
101967 }
101968 /**
101969 * Check if the node is a variable
101970 * @param {ASTNode} node node to evaluate
101971 * @returns {void}
101972 * @private
101973 */
101974
101975
101976 function checkVar(node) {
101977 const leftNode = node.id.typeAnnotation ? node.id.typeAnnotation : node.id;
101978 const rightNode = node.init;
101979
101980 if (rightNode) {
101981 const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, "=");
101982
101983 if (nonSpacedNode) {
101984 report(node, nonSpacedNode);
101985 }
101986 }
101987 }
101988
101989 return {
101990 AssignmentExpression: checkBinary,
101991 AssignmentPattern: checkBinary,
101992 BinaryExpression: checkBinary,
101993 LogicalExpression: checkBinary,
101994 ConditionalExpression: checkConditional,
101995 VariableDeclarator: checkVar
101996 };
101997 }
101998
101999};
102000
102001/***/ }),
6a5a0f88 102002/* 707 */
eb39fafa
DC
102003/***/ (function(module, exports, __webpack_require__) {
102004
102005"use strict";
102006/**
102007 * @fileoverview This rule shoud require or disallow spaces before or after unary operations.
102008 * @author Marcin Kumorek
102009 */
102010 //------------------------------------------------------------------------------
102011// Requirements
102012//------------------------------------------------------------------------------
102013
102014const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
102015// Rule Definition
102016//------------------------------------------------------------------------------
102017
102018
102019module.exports = {
102020 meta: {
102021 type: "layout",
102022 docs: {
102023 description: "enforce consistent spacing before or after unary operators",
102024 category: "Stylistic Issues",
102025 recommended: false,
102026 url: "https://eslint.org/docs/rules/space-unary-ops"
102027 },
102028 fixable: "whitespace",
102029 schema: [{
102030 type: "object",
102031 properties: {
102032 words: {
102033 type: "boolean",
102034 default: true
102035 },
102036 nonwords: {
102037 type: "boolean",
102038 default: false
102039 },
102040 overrides: {
102041 type: "object",
102042 additionalProperties: {
102043 type: "boolean"
102044 }
102045 }
102046 },
102047 additionalProperties: false
102048 }],
102049 messages: {
102050 unexpectedBefore: "Unexpected space before unary operator '{{operator}}'.",
102051 unexpectedAfter: "Unexpected space after unary operator '{{operator}}'.",
102052 unexpectedAfterWord: "Unexpected space after unary word operator '{{word}}'.",
102053 wordOperator: "Unary word operator '{{word}}' must be followed by whitespace.",
102054 operator: "Unary operator '{{operator}}' must be followed by whitespace.",
102055 beforeUnaryExpressions: "Space is required before unary expressions '{{token}}'."
102056 }
102057 },
102058
102059 create(context) {
102060 const options = context.options[0] || {
102061 words: true,
102062 nonwords: false
102063 };
102064 const sourceCode = context.getSourceCode(); //--------------------------------------------------------------------------
102065 // Helpers
102066 //--------------------------------------------------------------------------
102067
102068 /**
102069 * Check if the node is the first "!" in a "!!" convert to Boolean expression
102070 * @param {ASTnode} node AST node
102071 * @returns {boolean} Whether or not the node is first "!" in "!!"
102072 */
102073
102074 function isFirstBangInBangBangExpression(node) {
102075 return node && node.type === "UnaryExpression" && node.argument.operator === "!" && node.argument && node.argument.type === "UnaryExpression" && node.argument.operator === "!";
102076 }
102077 /**
102078 * Checks if an override exists for a given operator.
102079 * @param {string} operator Operator
102080 * @returns {boolean} Whether or not an override has been provided for the operator
102081 */
102082
102083
102084 function overrideExistsForOperator(operator) {
102085 return options.overrides && Object.prototype.hasOwnProperty.call(options.overrides, operator);
102086 }
102087 /**
102088 * Gets the value that the override was set to for this operator
102089 * @param {string} operator Operator
102090 * @returns {boolean} Whether or not an override enforces a space with this operator
102091 */
102092
102093
102094 function overrideEnforcesSpaces(operator) {
102095 return options.overrides[operator];
102096 }
102097 /**
102098 * Verify Unary Word Operator has spaces after the word operator
102099 * @param {ASTnode} node AST node
102100 * @param {Object} firstToken first token from the AST node
102101 * @param {Object} secondToken second token from the AST node
102102 * @param {string} word The word to be used for reporting
102103 * @returns {void}
102104 */
102105
102106
102107 function verifyWordHasSpaces(node, firstToken, secondToken, word) {
102108 if (secondToken.range[0] === firstToken.range[1]) {
102109 context.report({
102110 node,
102111 messageId: "wordOperator",
102112 data: {
102113 word
102114 },
102115
102116 fix(fixer) {
102117 return fixer.insertTextAfter(firstToken, " ");
102118 }
102119
102120 });
102121 }
102122 }
102123 /**
102124 * Verify Unary Word Operator doesn't have spaces after the word operator
102125 * @param {ASTnode} node AST node
102126 * @param {Object} firstToken first token from the AST node
102127 * @param {Object} secondToken second token from the AST node
102128 * @param {string} word The word to be used for reporting
102129 * @returns {void}
102130 */
102131
102132
102133 function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) {
102134 if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) {
102135 if (secondToken.range[0] > firstToken.range[1]) {
102136 context.report({
102137 node,
102138 messageId: "unexpectedAfterWord",
102139 data: {
102140 word
102141 },
102142
102143 fix(fixer) {
102144 return fixer.removeRange([firstToken.range[1], secondToken.range[0]]);
102145 }
102146
102147 });
102148 }
102149 }
102150 }
102151 /**
102152 * Check Unary Word Operators for spaces after the word operator
102153 * @param {ASTnode} node AST node
102154 * @param {Object} firstToken first token from the AST node
102155 * @param {Object} secondToken second token from the AST node
102156 * @param {string} word The word to be used for reporting
102157 * @returns {void}
102158 */
102159
102160
102161 function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) {
102162 if (overrideExistsForOperator(word)) {
102163 if (overrideEnforcesSpaces(word)) {
102164 verifyWordHasSpaces(node, firstToken, secondToken, word);
102165 } else {
102166 verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word);
102167 }
102168 } else if (options.words) {
102169 verifyWordHasSpaces(node, firstToken, secondToken, word);
102170 } else {
102171 verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word);
102172 }
102173 }
102174 /**
102175 * Verifies YieldExpressions satisfy spacing requirements
102176 * @param {ASTnode} node AST node
102177 * @returns {void}
102178 */
102179
102180
102181 function checkForSpacesAfterYield(node) {
102182 const tokens = sourceCode.getFirstTokens(node, 3),
102183 word = "yield";
102184
102185 if (!node.argument || node.delegate) {
102186 return;
102187 }
102188
102189 checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word);
102190 }
102191 /**
102192 * Verifies AwaitExpressions satisfy spacing requirements
102193 * @param {ASTNode} node AwaitExpression AST node
102194 * @returns {void}
102195 */
102196
102197
102198 function checkForSpacesAfterAwait(node) {
102199 const tokens = sourceCode.getFirstTokens(node, 3);
102200 checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], "await");
102201 }
102202 /**
102203 * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator
102204 * @param {ASTnode} node AST node
102205 * @param {Object} firstToken First token in the expression
102206 * @param {Object} secondToken Second token in the expression
102207 * @returns {void}
102208 */
102209
102210
102211 function verifyNonWordsHaveSpaces(node, firstToken, secondToken) {
102212 if (node.prefix) {
102213 if (isFirstBangInBangBangExpression(node)) {
102214 return;
102215 }
102216
102217 if (firstToken.range[1] === secondToken.range[0]) {
102218 context.report({
102219 node,
102220 messageId: "operator",
102221 data: {
102222 operator: firstToken.value
102223 },
102224
102225 fix(fixer) {
102226 return fixer.insertTextAfter(firstToken, " ");
102227 }
102228
102229 });
102230 }
102231 } else {
102232 if (firstToken.range[1] === secondToken.range[0]) {
102233 context.report({
102234 node,
102235 messageId: "beforeUnaryExpressions",
102236 data: {
102237 token: secondToken.value
102238 },
102239
102240 fix(fixer) {
102241 return fixer.insertTextBefore(secondToken, " ");
102242 }
102243
102244 });
102245 }
102246 }
102247 }
102248 /**
102249 * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator
102250 * @param {ASTnode} node AST node
102251 * @param {Object} firstToken First token in the expression
102252 * @param {Object} secondToken Second token in the expression
102253 * @returns {void}
102254 */
102255
102256
102257 function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) {
102258 if (node.prefix) {
102259 if (secondToken.range[0] > firstToken.range[1]) {
102260 context.report({
102261 node,
102262 messageId: "unexpectedAfter",
102263 data: {
102264 operator: firstToken.value
102265 },
102266
102267 fix(fixer) {
102268 if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) {
102269 return fixer.removeRange([firstToken.range[1], secondToken.range[0]]);
102270 }
102271
102272 return null;
102273 }
102274
102275 });
102276 }
102277 } else {
102278 if (secondToken.range[0] > firstToken.range[1]) {
102279 context.report({
102280 node,
102281 messageId: "unexpectedBefore",
102282 data: {
102283 operator: secondToken.value
102284 },
102285
102286 fix(fixer) {
102287 return fixer.removeRange([firstToken.range[1], secondToken.range[0]]);
102288 }
102289
102290 });
102291 }
102292 }
102293 }
102294 /**
102295 * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements
102296 * @param {ASTnode} node AST node
102297 * @returns {void}
102298 */
102299
102300
102301 function checkForSpaces(node) {
102302 const tokens = node.type === "UpdateExpression" && !node.prefix ? sourceCode.getLastTokens(node, 2) : sourceCode.getFirstTokens(node, 2);
102303 const firstToken = tokens[0];
102304 const secondToken = tokens[1];
102305
102306 if ((node.type === "NewExpression" || node.prefix) && firstToken.type === "Keyword") {
102307 checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, firstToken.value);
102308 return;
102309 }
102310
102311 const operator = node.prefix ? tokens[0].value : tokens[1].value;
102312
102313 if (overrideExistsForOperator(operator)) {
102314 if (overrideEnforcesSpaces(operator)) {
102315 verifyNonWordsHaveSpaces(node, firstToken, secondToken);
102316 } else {
102317 verifyNonWordsDontHaveSpaces(node, firstToken, secondToken);
102318 }
102319 } else if (options.nonwords) {
102320 verifyNonWordsHaveSpaces(node, firstToken, secondToken);
102321 } else {
102322 verifyNonWordsDontHaveSpaces(node, firstToken, secondToken);
102323 }
102324 } //--------------------------------------------------------------------------
102325 // Public
102326 //--------------------------------------------------------------------------
102327
102328
102329 return {
102330 UnaryExpression: checkForSpaces,
102331 UpdateExpression: checkForSpaces,
102332 NewExpression: checkForSpaces,
102333 YieldExpression: checkForSpacesAfterYield,
102334 AwaitExpression: checkForSpacesAfterAwait
102335 };
102336 }
102337
102338};
102339
102340/***/ }),
6a5a0f88 102341/* 708 */
eb39fafa
DC
102342/***/ (function(module, exports, __webpack_require__) {
102343
102344"use strict";
102345/**
102346 * @fileoverview Source code for spaced-comments rule
102347 * @author Gyandeep Singh
102348 */
102349
102350
102351const lodash = __webpack_require__(403);
102352
102353const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
102354// Helpers
102355//------------------------------------------------------------------------------
102356
102357/**
102358 * Escapes the control characters of a given string.
102359 * @param {string} s A string to escape.
102360 * @returns {string} An escaped string.
102361 */
102362
102363
102364function escape(s) {
102365 return "(?:".concat(lodash.escapeRegExp(s), ")");
102366}
102367/**
102368 * Escapes the control characters of a given string.
102369 * And adds a repeat flag.
102370 * @param {string} s A string to escape.
102371 * @returns {string} An escaped string.
102372 */
102373
102374
102375function escapeAndRepeat(s) {
102376 return "".concat(escape(s), "+");
102377}
102378/**
102379 * Parses `markers` option.
102380 * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
102381 * @param {string[]} [markers] A marker list.
102382 * @returns {string[]} A marker list.
102383 */
102384
102385
102386function parseMarkersOption(markers) {
102387 // `*` is a marker for JSDoc comments.
102388 if (markers.indexOf("*") === -1) {
102389 return markers.concat("*");
102390 }
102391
102392 return markers;
102393}
102394/**
102395 * Creates string pattern for exceptions.
102396 * Generated pattern:
102397 *
102398 * 1. A space or an exception pattern sequence.
102399 * @param {string[]} exceptions An exception pattern list.
102400 * @returns {string} A regular expression string for exceptions.
102401 */
102402
102403
102404function createExceptionsPattern(exceptions) {
102405 let pattern = "";
102406 /*
102407 * A space or an exception pattern sequence.
102408 * [] ==> "\s"
102409 * ["-"] ==> "(?:\s|\-+$)"
102410 * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
102411 * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
102412 */
102413
102414 if (exceptions.length === 0) {
102415 // a space.
102416 pattern += "\\s";
102417 } else {
102418 // a space or...
102419 pattern += "(?:\\s|";
102420
102421 if (exceptions.length === 1) {
102422 // a sequence of the exception pattern.
102423 pattern += escapeAndRepeat(exceptions[0]);
102424 } else {
102425 // a sequence of one of the exception patterns.
102426 pattern += "(?:";
102427 pattern += exceptions.map(escapeAndRepeat).join("|");
102428 pattern += ")";
102429 }
102430
102431 pattern += "(?:$|[".concat(Array.from(astUtils.LINEBREAKS).join(""), "]))");
102432 }
102433
102434 return pattern;
102435}
102436/**
102437 * Creates RegExp object for `always` mode.
102438 * Generated pattern for beginning of comment:
102439 *
102440 * 1. First, a marker or nothing.
102441 * 2. Next, a space or an exception pattern sequence.
102442 * @param {string[]} markers A marker list.
102443 * @param {string[]} exceptions An exception pattern list.
102444 * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
102445 */
102446
102447
102448function createAlwaysStylePattern(markers, exceptions) {
102449 let pattern = "^";
102450 /*
102451 * A marker or nothing.
102452 * ["*"] ==> "\*?"
102453 * ["*", "!"] ==> "(?:\*|!)?"
102454 * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
102455 */
102456
102457 if (markers.length === 1) {
102458 // the marker.
102459 pattern += escape(markers[0]);
102460 } else {
102461 // one of markers.
102462 pattern += "(?:";
102463 pattern += markers.map(escape).join("|");
102464 pattern += ")";
102465 }
102466
102467 pattern += "?"; // or nothing.
102468
102469 pattern += createExceptionsPattern(exceptions);
102470 return new RegExp(pattern, "u");
102471}
102472/**
102473 * Creates RegExp object for `never` mode.
102474 * Generated pattern for beginning of comment:
102475 *
102476 * 1. First, a marker or nothing (captured).
102477 * 2. Next, a space or a tab.
102478 * @param {string[]} markers A marker list.
102479 * @returns {RegExp} A RegExp object for `never` mode.
102480 */
102481
102482
102483function createNeverStylePattern(markers) {
102484 const pattern = "^(".concat(markers.map(escape).join("|"), ")?[ \t]+");
102485 return new RegExp(pattern, "u");
102486} //------------------------------------------------------------------------------
102487// Rule Definition
102488//------------------------------------------------------------------------------
102489
102490
102491module.exports = {
102492 meta: {
102493 type: "suggestion",
102494 docs: {
102495 description: "enforce consistent spacing after the `//` or `/*` in a comment",
102496 category: "Stylistic Issues",
102497 recommended: false,
102498 url: "https://eslint.org/docs/rules/spaced-comment"
102499 },
102500 fixable: "whitespace",
102501 schema: [{
102502 enum: ["always", "never"]
102503 }, {
102504 type: "object",
102505 properties: {
102506 exceptions: {
102507 type: "array",
102508 items: {
102509 type: "string"
102510 }
102511 },
102512 markers: {
102513 type: "array",
102514 items: {
102515 type: "string"
102516 }
102517 },
102518 line: {
102519 type: "object",
102520 properties: {
102521 exceptions: {
102522 type: "array",
102523 items: {
102524 type: "string"
102525 }
102526 },
102527 markers: {
102528 type: "array",
102529 items: {
102530 type: "string"
102531 }
102532 }
102533 },
102534 additionalProperties: false
102535 },
102536 block: {
102537 type: "object",
102538 properties: {
102539 exceptions: {
102540 type: "array",
102541 items: {
102542 type: "string"
102543 }
102544 },
102545 markers: {
102546 type: "array",
102547 items: {
102548 type: "string"
102549 }
102550 },
102551 balanced: {
102552 type: "boolean",
102553 default: false
102554 }
102555 },
102556 additionalProperties: false
102557 }
102558 },
102559 additionalProperties: false
102560 }],
102561 messages: {
102562 unexpectedSpaceAfterMarker: "Unexpected space or tab after marker ({{refChar}}) in comment.",
102563 expectedExceptionAfter: "Expected exception block, space or tab after '{{refChar}}' in comment.",
102564 unexpectedSpaceBefore: "Unexpected space or tab before '*/' in comment.",
102565 unexpectedSpaceAfter: "Unexpected space or tab after '{{refChar}}' in comment.",
102566 expectedSpaceBefore: "Expected space or tab before '*/' in comment.",
102567 expectedSpaceAfter: "Expected space or tab after '{{refChar}}' in comment."
102568 }
102569 },
102570
102571 create(context) {
102572 const sourceCode = context.getSourceCode(); // Unless the first option is never, require a space
102573
102574 const requireSpace = context.options[0] !== "never";
102575 /*
102576 * Parse the second options.
102577 * If markers don't include `"*"`, it's added automatically for JSDoc
102578 * comments.
102579 */
102580
102581 const config = context.options[1] || {};
102582 const balanced = config.block && config.block.balanced;
102583 const styleRules = ["block", "line"].reduce((rule, type) => {
102584 const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []);
102585 const exceptions = config[type] && config[type].exceptions || config.exceptions || [];
102586 const endNeverPattern = "[ \t]+$"; // Create RegExp object for valid patterns.
102587
102588 rule[type] = {
102589 beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
102590 endRegex: balanced && requireSpace ? new RegExp("".concat(createExceptionsPattern(exceptions), "$"), "u") : new RegExp(endNeverPattern, "u"),
102591 hasExceptions: exceptions.length > 0,
102592 captureMarker: new RegExp("^(".concat(markers.map(escape).join("|"), ")"), "u"),
102593 markers: new Set(markers)
102594 };
102595 return rule;
102596 }, {});
102597 /**
102598 * Reports a beginning spacing error with an appropriate message.
102599 * @param {ASTNode} node A comment node to check.
102600 * @param {string} messageId An error message to report.
102601 * @param {Array} match An array of match results for markers.
102602 * @param {string} refChar Character used for reference in the error message.
102603 * @returns {void}
102604 */
102605
102606 function reportBegin(node, messageId, match, refChar) {
102607 const type = node.type.toLowerCase(),
102608 commentIdentifier = type === "block" ? "/*" : "//";
102609 context.report({
102610 node,
102611
102612 fix(fixer) {
102613 const start = node.range[0];
102614 let end = start + 2;
102615
102616 if (requireSpace) {
102617 if (match) {
102618 end += match[0].length;
102619 }
102620
102621 return fixer.insertTextAfterRange([start, end], " ");
102622 }
102623
102624 end += match[0].length;
102625 return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : ""));
102626 },
102627
102628 messageId,
102629 data: {
102630 refChar
102631 }
102632 });
102633 }
102634 /**
102635 * Reports an ending spacing error with an appropriate message.
102636 * @param {ASTNode} node A comment node to check.
102637 * @param {string} messageId An error message to report.
102638 * @param {string} match An array of the matched whitespace characters.
102639 * @returns {void}
102640 */
102641
102642
102643 function reportEnd(node, messageId, match) {
102644 context.report({
102645 node,
102646
102647 fix(fixer) {
102648 if (requireSpace) {
102649 return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " ");
102650 }
102651
102652 const end = node.range[1] - 2,
102653 start = end - match[0].length;
102654 return fixer.replaceTextRange([start, end], "");
102655 },
102656
102657 messageId
102658 });
102659 }
102660 /**
102661 * Reports a given comment if it's invalid.
102662 * @param {ASTNode} node a comment node to check.
102663 * @returns {void}
102664 */
102665
102666
102667 function checkCommentForSpace(node) {
102668 const type = node.type.toLowerCase(),
102669 rule = styleRules[type],
102670 commentIdentifier = type === "block" ? "/*" : "//"; // Ignores empty comments and comments that consist only of a marker.
102671
102672 if (node.value.length === 0 || rule.markers.has(node.value)) {
102673 return;
102674 }
102675
102676 const beginMatch = rule.beginRegex.exec(node.value);
102677 const endMatch = rule.endRegex.exec(node.value); // Checks.
102678
102679 if (requireSpace) {
102680 if (!beginMatch) {
102681 const hasMarker = rule.captureMarker.exec(node.value);
102682 const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
102683
102684 if (rule.hasExceptions) {
102685 reportBegin(node, "expectedExceptionAfter", hasMarker, marker);
102686 } else {
102687 reportBegin(node, "expectedSpaceAfter", hasMarker, marker);
102688 }
102689 }
102690
102691 if (balanced && type === "block" && !endMatch) {
102692 reportEnd(node, "expectedSpaceBefore");
102693 }
102694 } else {
102695 if (beginMatch) {
102696 if (!beginMatch[1]) {
102697 reportBegin(node, "unexpectedSpaceAfter", beginMatch, commentIdentifier);
102698 } else {
102699 reportBegin(node, "unexpectedSpaceAfterMarker", beginMatch, beginMatch[1]);
102700 }
102701 }
102702
102703 if (balanced && type === "block" && endMatch) {
102704 reportEnd(node, "unexpectedSpaceBefore", endMatch);
102705 }
102706 }
102707 }
102708
102709 return {
102710 Program() {
102711 const comments = sourceCode.getAllComments();
102712 comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace);
102713 }
102714
102715 };
102716 }
102717
102718};
102719
102720/***/ }),
6a5a0f88 102721/* 709 */
eb39fafa
DC
102722/***/ (function(module, exports, __webpack_require__) {
102723
102724"use strict";
102725/**
102726 * @fileoverview Rule to control usage of strict mode directives.
102727 * @author Brandon Mills
102728 */
102729 //------------------------------------------------------------------------------
102730// Requirements
102731//------------------------------------------------------------------------------
102732
102733const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
102734// Helpers
102735//------------------------------------------------------------------------------
102736
102737/**
102738 * Gets all of the Use Strict Directives in the Directive Prologue of a group of
102739 * statements.
102740 * @param {ASTNode[]} statements Statements in the program or function body.
102741 * @returns {ASTNode[]} All of the Use Strict Directives.
102742 */
102743
102744
102745function getUseStrictDirectives(statements) {
102746 const directives = [];
102747
102748 for (let i = 0; i < statements.length; i++) {
102749 const statement = statements[i];
102750
102751 if (statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && statement.expression.value === "use strict") {
102752 directives[i] = statement;
102753 } else {
102754 break;
102755 }
102756 }
102757
102758 return directives;
102759}
102760/**
102761 * Checks whether a given parameter is a simple parameter.
102762 * @param {ASTNode} node A pattern node to check.
102763 * @returns {boolean} `true` if the node is an Identifier node.
102764 */
102765
102766
102767function isSimpleParameter(node) {
102768 return node.type === "Identifier";
102769}
102770/**
102771 * Checks whether a given parameter list is a simple parameter list.
102772 * @param {ASTNode[]} params A parameter list to check.
102773 * @returns {boolean} `true` if the every parameter is an Identifier node.
102774 */
102775
102776
102777function isSimpleParameterList(params) {
102778 return params.every(isSimpleParameter);
102779} //------------------------------------------------------------------------------
102780// Rule Definition
102781//------------------------------------------------------------------------------
102782
102783
102784module.exports = {
102785 meta: {
102786 type: "suggestion",
102787 docs: {
102788 description: "require or disallow strict mode directives",
102789 category: "Strict Mode",
102790 recommended: false,
102791 url: "https://eslint.org/docs/rules/strict"
102792 },
102793 schema: [{
102794 enum: ["never", "global", "function", "safe"]
102795 }],
102796 fixable: "code",
102797 messages: {
102798 function: "Use the function form of 'use strict'.",
102799 global: "Use the global form of 'use strict'.",
102800 multiple: "Multiple 'use strict' directives.",
102801 never: "Strict mode is not permitted.",
102802 unnecessary: "Unnecessary 'use strict' directive.",
102803 module: "'use strict' is unnecessary inside of modules.",
102804 implied: "'use strict' is unnecessary when implied strict mode is enabled.",
102805 unnecessaryInClasses: "'use strict' is unnecessary inside of classes.",
102806 nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.",
102807 wrap: "Wrap {{name}} in a function with 'use strict' directive."
102808 }
102809 },
102810
102811 create(context) {
102812 const ecmaFeatures = context.parserOptions.ecmaFeatures || {},
102813 scopes = [],
102814 classScopes = [];
102815 let mode = context.options[0] || "safe";
102816
102817 if (ecmaFeatures.impliedStrict) {
102818 mode = "implied";
102819 } else if (mode === "safe") {
102820 mode = ecmaFeatures.globalReturn ? "global" : "function";
102821 }
102822 /**
102823 * Determines whether a reported error should be fixed, depending on the error type.
102824 * @param {string} errorType The type of error
102825 * @returns {boolean} `true` if the reported error should be fixed
102826 */
102827
102828
102829 function shouldFix(errorType) {
102830 return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses";
102831 }
102832 /**
102833 * Gets a fixer function to remove a given 'use strict' directive.
102834 * @param {ASTNode} node The directive that should be removed
102835 * @returns {Function} A fixer function
102836 */
102837
102838
102839 function getFixFunction(node) {
102840 return fixer => fixer.remove(node);
102841 }
102842 /**
102843 * Report a slice of an array of nodes with a given message.
102844 * @param {ASTNode[]} nodes Nodes.
102845 * @param {string} start Index to start from.
102846 * @param {string} end Index to end before.
102847 * @param {string} messageId Message to display.
102848 * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
102849 * @returns {void}
102850 */
102851
102852
102853 function reportSlice(nodes, start, end, messageId, fix) {
102854 nodes.slice(start, end).forEach(node => {
102855 context.report({
102856 node,
102857 messageId,
102858 fix: fix ? getFixFunction(node) : null
102859 });
102860 });
102861 }
102862 /**
102863 * Report all nodes in an array with a given message.
102864 * @param {ASTNode[]} nodes Nodes.
102865 * @param {string} messageId Message id to display.
102866 * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
102867 * @returns {void}
102868 */
102869
102870
102871 function reportAll(nodes, messageId, fix) {
102872 reportSlice(nodes, 0, nodes.length, messageId, fix);
102873 }
102874 /**
102875 * Report all nodes in an array, except the first, with a given message.
102876 * @param {ASTNode[]} nodes Nodes.
102877 * @param {string} messageId Message id to display.
102878 * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
102879 * @returns {void}
102880 */
102881
102882
102883 function reportAllExceptFirst(nodes, messageId, fix) {
102884 reportSlice(nodes, 1, nodes.length, messageId, fix);
102885 }
102886 /**
102887 * Entering a function in 'function' mode pushes a new nested scope onto the
102888 * stack. The new scope is true if the nested function is strict mode code.
102889 * @param {ASTNode} node The function declaration or expression.
102890 * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node.
102891 * @returns {void}
102892 */
102893
102894
102895 function enterFunctionInFunctionMode(node, useStrictDirectives) {
102896 const isInClass = classScopes.length > 0,
102897 isParentGlobal = scopes.length === 0 && classScopes.length === 0,
102898 isParentStrict = scopes.length > 0 && scopes[scopes.length - 1],
102899 isStrict = useStrictDirectives.length > 0;
102900
102901 if (isStrict) {
102902 if (!isSimpleParameterList(node.params)) {
102903 context.report({
102904 node: useStrictDirectives[0],
102905 messageId: "nonSimpleParameterList"
102906 });
102907 } else if (isParentStrict) {
102908 context.report({
102909 node: useStrictDirectives[0],
102910 messageId: "unnecessary",
102911 fix: getFixFunction(useStrictDirectives[0])
102912 });
102913 } else if (isInClass) {
102914 context.report({
102915 node: useStrictDirectives[0],
102916 messageId: "unnecessaryInClasses",
102917 fix: getFixFunction(useStrictDirectives[0])
102918 });
102919 }
102920
102921 reportAllExceptFirst(useStrictDirectives, "multiple", true);
102922 } else if (isParentGlobal) {
102923 if (isSimpleParameterList(node.params)) {
102924 context.report({
102925 node,
102926 messageId: "function"
102927 });
102928 } else {
102929 context.report({
102930 node,
102931 messageId: "wrap",
102932 data: {
102933 name: astUtils.getFunctionNameWithKind(node)
102934 }
102935 });
102936 }
102937 }
102938
102939 scopes.push(isParentStrict || isStrict);
102940 }
102941 /**
102942 * Exiting a function in 'function' mode pops its scope off the stack.
102943 * @returns {void}
102944 */
102945
102946
102947 function exitFunctionInFunctionMode() {
102948 scopes.pop();
102949 }
102950 /**
102951 * Enter a function and either:
102952 * - Push a new nested scope onto the stack (in 'function' mode).
102953 * - Report all the Use Strict Directives (in the other modes).
102954 * @param {ASTNode} node The function declaration or expression.
102955 * @returns {void}
102956 */
102957
102958
102959 function enterFunction(node) {
102960 const isBlock = node.body.type === "BlockStatement",
102961 useStrictDirectives = isBlock ? getUseStrictDirectives(node.body.body) : [];
102962
102963 if (mode === "function") {
102964 enterFunctionInFunctionMode(node, useStrictDirectives);
102965 } else if (useStrictDirectives.length > 0) {
102966 if (isSimpleParameterList(node.params)) {
102967 reportAll(useStrictDirectives, mode, shouldFix(mode));
102968 } else {
102969 context.report({
102970 node: useStrictDirectives[0],
102971 messageId: "nonSimpleParameterList"
102972 });
102973 reportAllExceptFirst(useStrictDirectives, "multiple", true);
102974 }
102975 }
102976 }
102977
102978 const rule = {
102979 Program(node) {
102980 const useStrictDirectives = getUseStrictDirectives(node.body);
102981
102982 if (node.sourceType === "module") {
102983 mode = "module";
102984 }
102985
102986 if (mode === "global") {
102987 if (node.body.length > 0 && useStrictDirectives.length === 0) {
102988 context.report({
102989 node,
102990 messageId: "global"
102991 });
102992 }
102993
102994 reportAllExceptFirst(useStrictDirectives, "multiple", true);
102995 } else {
102996 reportAll(useStrictDirectives, mode, shouldFix(mode));
102997 }
102998 },
102999
103000 FunctionDeclaration: enterFunction,
103001 FunctionExpression: enterFunction,
103002 ArrowFunctionExpression: enterFunction
103003 };
103004
103005 if (mode === "function") {
103006 Object.assign(rule, {
103007 // Inside of class bodies are always strict mode.
103008 ClassBody() {
103009 classScopes.push(true);
103010 },
103011
103012 "ClassBody:exit"() {
103013 classScopes.pop();
103014 },
103015
103016 "FunctionDeclaration:exit": exitFunctionInFunctionMode,
103017 "FunctionExpression:exit": exitFunctionInFunctionMode,
103018 "ArrowFunctionExpression:exit": exitFunctionInFunctionMode
103019 });
103020 }
103021
103022 return rule;
103023 }
103024
103025};
103026
103027/***/ }),
6a5a0f88 103028/* 710 */
eb39fafa
DC
103029/***/ (function(module, exports, __webpack_require__) {
103030
103031"use strict";
103032/**
103033 * @fileoverview Rule to enforce spacing around colons of switch statements.
103034 * @author Toru Nagashima
103035 */
103036 //------------------------------------------------------------------------------
103037// Requirements
103038//------------------------------------------------------------------------------
103039
103040const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
103041// Rule Definition
103042//------------------------------------------------------------------------------
103043
103044
103045module.exports = {
103046 meta: {
103047 type: "layout",
103048 docs: {
103049 description: "enforce spacing around colons of switch statements",
103050 category: "Stylistic Issues",
103051 recommended: false,
103052 url: "https://eslint.org/docs/rules/switch-colon-spacing"
103053 },
103054 schema: [{
103055 type: "object",
103056 properties: {
103057 before: {
103058 type: "boolean",
103059 default: false
103060 },
103061 after: {
103062 type: "boolean",
103063 default: true
103064 }
103065 },
103066 additionalProperties: false
103067 }],
103068 fixable: "whitespace",
103069 messages: {
103070 expectedBefore: "Expected space(s) before this colon.",
103071 expectedAfter: "Expected space(s) after this colon.",
103072 unexpectedBefore: "Unexpected space(s) before this colon.",
103073 unexpectedAfter: "Unexpected space(s) after this colon."
103074 }
103075 },
103076
103077 create(context) {
103078 const sourceCode = context.getSourceCode();
103079 const options = context.options[0] || {};
103080 const beforeSpacing = options.before === true; // false by default
103081
103082 const afterSpacing = options.after !== false; // true by default
103083
103084 /**
103085 * Get the colon token of the given SwitchCase node.
103086 * @param {ASTNode} node The SwitchCase node to get.
103087 * @returns {Token} The colon token of the node.
103088 */
103089
103090 function getColonToken(node) {
103091 if (node.test) {
103092 return sourceCode.getTokenAfter(node.test, astUtils.isColonToken);
103093 }
103094
103095 return sourceCode.getFirstToken(node, 1);
103096 }
103097 /**
103098 * Check whether the spacing between the given 2 tokens is valid or not.
103099 * @param {Token} left The left token to check.
103100 * @param {Token} right The right token to check.
103101 * @param {boolean} expected The expected spacing to check. `true` if there should be a space.
103102 * @returns {boolean} `true` if the spacing between the tokens is valid.
103103 */
103104
103105
103106 function isValidSpacing(left, right, expected) {
103107 return astUtils.isClosingBraceToken(right) || !astUtils.isTokenOnSameLine(left, right) || sourceCode.isSpaceBetweenTokens(left, right) === expected;
103108 }
103109 /**
103110 * Check whether comments exist between the given 2 tokens.
103111 * @param {Token} left The left token to check.
103112 * @param {Token} right The right token to check.
103113 * @returns {boolean} `true` if comments exist between the given 2 tokens.
103114 */
103115
103116
103117 function commentsExistBetween(left, right) {
103118 return sourceCode.getFirstTokenBetween(left, right, {
103119 includeComments: true,
103120 filter: astUtils.isCommentToken
103121 }) !== null;
103122 }
103123 /**
103124 * Fix the spacing between the given 2 tokens.
103125 * @param {RuleFixer} fixer The fixer to fix.
103126 * @param {Token} left The left token of fix range.
103127 * @param {Token} right The right token of fix range.
103128 * @param {boolean} spacing The spacing style. `true` if there should be a space.
103129 * @returns {Fix|null} The fix object.
103130 */
103131
103132
103133 function _fix(fixer, left, right, spacing) {
103134 if (commentsExistBetween(left, right)) {
103135 return null;
103136 }
103137
103138 if (spacing) {
103139 return fixer.insertTextAfter(left, " ");
103140 }
103141
103142 return fixer.removeRange([left.range[1], right.range[0]]);
103143 }
103144
103145 return {
103146 SwitchCase(node) {
103147 const colonToken = getColonToken(node);
103148 const beforeToken = sourceCode.getTokenBefore(colonToken);
103149 const afterToken = sourceCode.getTokenAfter(colonToken);
103150
103151 if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) {
103152 context.report({
103153 node,
103154 loc: colonToken.loc,
103155 messageId: beforeSpacing ? "expectedBefore" : "unexpectedBefore",
103156 fix: fixer => _fix(fixer, beforeToken, colonToken, beforeSpacing)
103157 });
103158 }
103159
103160 if (!isValidSpacing(colonToken, afterToken, afterSpacing)) {
103161 context.report({
103162 node,
103163 loc: colonToken.loc,
103164 messageId: afterSpacing ? "expectedAfter" : "unexpectedAfter",
103165 fix: fixer => _fix(fixer, colonToken, afterToken, afterSpacing)
103166 });
103167 }
103168 }
103169
103170 };
103171 }
103172
103173};
103174
103175/***/ }),
6a5a0f88 103176/* 711 */
eb39fafa
DC
103177/***/ (function(module, exports, __webpack_require__) {
103178
103179"use strict";
103180/**
103181 * @fileoverview Rule to enforce description with the `Symbol` object
103182 * @author Jarek Rencz
103183 */
103184 //------------------------------------------------------------------------------
103185// Requirements
103186//------------------------------------------------------------------------------
103187
103188const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
103189// Rule Definition
103190//------------------------------------------------------------------------------
103191
103192
103193module.exports = {
103194 meta: {
103195 type: "suggestion",
103196 docs: {
103197 description: "require symbol descriptions",
103198 category: "ECMAScript 6",
103199 recommended: false,
103200 url: "https://eslint.org/docs/rules/symbol-description"
103201 },
103202 fixable: null,
103203 schema: [],
103204 messages: {
103205 expected: "Expected Symbol to have a description."
103206 }
103207 },
103208
103209 create(context) {
103210 /**
103211 * Reports if node does not conform the rule in case rule is set to
103212 * report missing description
103213 * @param {ASTNode} node A CallExpression node to check.
103214 * @returns {void}
103215 */
103216 function checkArgument(node) {
103217 if (node.arguments.length === 0) {
103218 context.report({
103219 node,
103220 messageId: "expected"
103221 });
103222 }
103223 }
103224
103225 return {
103226 "Program:exit"() {
103227 const scope = context.getScope();
103228 const variable = astUtils.getVariableByName(scope, "Symbol");
103229
103230 if (variable && variable.defs.length === 0) {
103231 variable.references.forEach(reference => {
103232 const node = reference.identifier;
103233
103234 if (astUtils.isCallee(node)) {
103235 checkArgument(node.parent);
103236 }
103237 });
103238 }
103239 }
103240
103241 };
103242 }
103243
103244};
103245
103246/***/ }),
6a5a0f88 103247/* 712 */
eb39fafa
DC
103248/***/ (function(module, exports, __webpack_require__) {
103249
103250"use strict";
103251/**
103252 * @fileoverview Rule to enforce spacing around embedded expressions of template strings
103253 * @author Toru Nagashima
103254 */
103255 //------------------------------------------------------------------------------
103256// Requirements
103257//------------------------------------------------------------------------------
103258
103259const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
103260// Rule Definition
103261//------------------------------------------------------------------------------
103262
103263
103264module.exports = {
103265 meta: {
103266 type: "layout",
103267 docs: {
103268 description: "require or disallow spacing around embedded expressions of template strings",
103269 category: "ECMAScript 6",
103270 recommended: false,
103271 url: "https://eslint.org/docs/rules/template-curly-spacing"
103272 },
103273 fixable: "whitespace",
103274 schema: [{
103275 enum: ["always", "never"]
103276 }],
103277 messages: {
103278 expectedBefore: "Expected space(s) before '}'.",
103279 expectedAfter: "Expected space(s) after '${'.",
103280 unexpectedBefore: "Unexpected space(s) before '}'.",
103281 unexpectedAfter: "Unexpected space(s) after '${'."
103282 }
103283 },
103284
103285 create(context) {
103286 const sourceCode = context.getSourceCode();
103287 const always = context.options[0] === "always";
103288 /**
103289 * Checks spacing before `}` of a given token.
103290 * @param {Token} token A token to check. This is a Template token.
103291 * @returns {void}
103292 */
103293
103294 function checkSpacingBefore(token) {
103295 if (!token.value.startsWith("}")) {
103296 return; // starts with a backtick, this is the first template element in the template literal
103297 }
103298
103299 const prevToken = sourceCode.getTokenBefore(token, {
103300 includeComments: true
103301 }),
103302 hasSpace = sourceCode.isSpaceBetween(prevToken, token);
103303
103304 if (!astUtils.isTokenOnSameLine(prevToken, token)) {
103305 return;
103306 }
103307
103308 if (always && !hasSpace) {
103309 context.report({
103310 loc: {
103311 start: token.loc.start,
103312 end: {
103313 line: token.loc.start.line,
103314 column: token.loc.start.column + 1
103315 }
103316 },
103317 messageId: "expectedBefore",
103318 fix: fixer => fixer.insertTextBefore(token, " ")
103319 });
103320 }
103321
103322 if (!always && hasSpace) {
103323 context.report({
103324 loc: {
103325 start: prevToken.loc.end,
103326 end: token.loc.start
103327 },
103328 messageId: "unexpectedBefore",
103329 fix: fixer => fixer.removeRange([prevToken.range[1], token.range[0]])
103330 });
103331 }
103332 }
103333 /**
103334 * Checks spacing after `${` of a given token.
103335 * @param {Token} token A token to check. This is a Template token.
103336 * @returns {void}
103337 */
103338
103339
103340 function checkSpacingAfter(token) {
103341 if (!token.value.endsWith("${")) {
103342 return; // ends with a backtick, this is the last template element in the template literal
103343 }
103344
103345 const nextToken = sourceCode.getTokenAfter(token, {
103346 includeComments: true
103347 }),
103348 hasSpace = sourceCode.isSpaceBetween(token, nextToken);
103349
103350 if (!astUtils.isTokenOnSameLine(token, nextToken)) {
103351 return;
103352 }
103353
103354 if (always && !hasSpace) {
103355 context.report({
103356 loc: {
103357 start: {
103358 line: token.loc.end.line,
103359 column: token.loc.end.column - 2
103360 },
103361 end: token.loc.end
103362 },
103363 messageId: "expectedAfter",
103364 fix: fixer => fixer.insertTextAfter(token, " ")
103365 });
103366 }
103367
103368 if (!always && hasSpace) {
103369 context.report({
103370 loc: {
103371 start: token.loc.end,
103372 end: nextToken.loc.start
103373 },
103374 messageId: "unexpectedAfter",
103375 fix: fixer => fixer.removeRange([token.range[1], nextToken.range[0]])
103376 });
103377 }
103378 }
103379
103380 return {
103381 TemplateElement(node) {
103382 const token = sourceCode.getFirstToken(node);
103383 checkSpacingBefore(token);
103384 checkSpacingAfter(token);
103385 }
103386
103387 };
103388 }
103389
103390};
103391
103392/***/ }),
6a5a0f88 103393/* 713 */
eb39fafa
DC
103394/***/ (function(module, exports, __webpack_require__) {
103395
103396"use strict";
103397/**
103398 * @fileoverview Rule to check spacing between template tags and their literals
103399 * @author Jonathan Wilsson
103400 */
103401 //------------------------------------------------------------------------------
103402// Rule Definition
103403//------------------------------------------------------------------------------
103404
103405module.exports = {
103406 meta: {
103407 type: "layout",
103408 docs: {
103409 description: "require or disallow spacing between template tags and their literals",
103410 category: "Stylistic Issues",
103411 recommended: false,
103412 url: "https://eslint.org/docs/rules/template-tag-spacing"
103413 },
103414 fixable: "whitespace",
103415 schema: [{
103416 enum: ["always", "never"]
103417 }],
103418 messages: {
103419 unexpected: "Unexpected space between template tag and template literal.",
103420 missing: "Missing space between template tag and template literal."
103421 }
103422 },
103423
103424 create(context) {
103425 const never = context.options[0] !== "always";
103426 const sourceCode = context.getSourceCode();
103427 /**
103428 * Check if a space is present between a template tag and its literal
103429 * @param {ASTNode} node node to evaluate
103430 * @returns {void}
103431 * @private
103432 */
103433
103434 function checkSpacing(node) {
103435 const tagToken = sourceCode.getTokenBefore(node.quasi);
103436 const literalToken = sourceCode.getFirstToken(node.quasi);
103437 const hasWhitespace = sourceCode.isSpaceBetweenTokens(tagToken, literalToken);
103438
103439 if (never && hasWhitespace) {
103440 context.report({
103441 node,
103442 loc: tagToken.loc.start,
103443 messageId: "unexpected",
103444
103445 fix(fixer) {
103446 const comments = sourceCode.getCommentsBefore(node.quasi); // Don't fix anything if there's a single line comment after the template tag
103447
103448 if (comments.some(comment => comment.type === "Line")) {
103449 return null;
103450 }
103451
103452 return fixer.replaceTextRange([tagToken.range[1], literalToken.range[0]], comments.reduce((text, comment) => text + sourceCode.getText(comment), ""));
103453 }
103454
103455 });
103456 } else if (!never && !hasWhitespace) {
103457 context.report({
103458 node,
103459 loc: tagToken.loc.start,
103460 messageId: "missing",
103461
103462 fix(fixer) {
103463 return fixer.insertTextAfter(tagToken, " ");
103464 }
103465
103466 });
103467 }
103468 }
103469
103470 return {
103471 TaggedTemplateExpression: checkSpacing
103472 };
103473 }
103474
103475};
103476
103477/***/ }),
6a5a0f88 103478/* 714 */
eb39fafa
DC
103479/***/ (function(module, exports, __webpack_require__) {
103480
103481"use strict";
103482/**
103483 * @fileoverview Require or disallow Unicode BOM
103484 * @author Andrew Johnston <https://github.com/ehjay>
103485 */
103486 //------------------------------------------------------------------------------
103487// Rule Definition
103488//------------------------------------------------------------------------------
103489
103490module.exports = {
103491 meta: {
103492 type: "layout",
103493 docs: {
103494 description: "require or disallow Unicode byte order mark (BOM)",
103495 category: "Stylistic Issues",
103496 recommended: false,
103497 url: "https://eslint.org/docs/rules/unicode-bom"
103498 },
103499 fixable: "whitespace",
103500 schema: [{
103501 enum: ["always", "never"]
103502 }],
103503 messages: {
103504 expected: "Expected Unicode BOM (Byte Order Mark).",
103505 unexpected: "Unexpected Unicode BOM (Byte Order Mark)."
103506 }
103507 },
103508
103509 create(context) {
103510 //--------------------------------------------------------------------------
103511 // Public
103512 //--------------------------------------------------------------------------
103513 return {
103514 Program: function checkUnicodeBOM(node) {
103515 const sourceCode = context.getSourceCode(),
103516 location = {
103517 column: 0,
103518 line: 1
103519 },
103520 requireBOM = context.options[0] || "never";
103521
103522 if (!sourceCode.hasBOM && requireBOM === "always") {
103523 context.report({
103524 node,
103525 loc: location,
103526 messageId: "expected",
103527
103528 fix(fixer) {
103529 return fixer.insertTextBeforeRange([0, 1], "\uFEFF");
103530 }
103531
103532 });
103533 } else if (sourceCode.hasBOM && requireBOM === "never") {
103534 context.report({
103535 node,
103536 loc: location,
103537 messageId: "unexpected",
103538
103539 fix(fixer) {
103540 return fixer.removeRange([-1, 0]);
103541 }
103542
103543 });
103544 }
103545 }
103546 };
103547 }
103548
103549};
103550
103551/***/ }),
6a5a0f88 103552/* 715 */
eb39fafa
DC
103553/***/ (function(module, exports, __webpack_require__) {
103554
103555"use strict";
103556/**
103557 * @fileoverview Rule to flag comparisons to the value NaN
103558 * @author James Allardice
103559 */
103560 //------------------------------------------------------------------------------
103561// Requirements
103562//------------------------------------------------------------------------------
103563
103564const astUtils = __webpack_require__(426); //------------------------------------------------------------------------------
103565// Helpers
103566//------------------------------------------------------------------------------
103567
103568/**
103569 * Determines if the given node is a NaN `Identifier` node.
103570 * @param {ASTNode|null} node The node to check.
103571 * @returns {boolean} `true` if the node is 'NaN' identifier.
103572 */
103573
103574
103575function isNaNIdentifier(node) {
103576 return Boolean(node) && node.type === "Identifier" && node.name === "NaN";
103577} //------------------------------------------------------------------------------
103578// Rule Definition
103579//------------------------------------------------------------------------------
103580
103581
103582module.exports = {
103583 meta: {
103584 type: "problem",
103585 docs: {
103586 description: "require calls to `isNaN()` when checking for `NaN`",
103587 category: "Possible Errors",
103588 recommended: true,
103589 url: "https://eslint.org/docs/rules/use-isnan"
103590 },
103591 schema: [{
103592 type: "object",
103593 properties: {
103594 enforceForSwitchCase: {
103595 type: "boolean",
103596 default: true
103597 },
103598 enforceForIndexOf: {
103599 type: "boolean",
103600 default: false
103601 }
103602 },
103603 additionalProperties: false
103604 }],
103605 messages: {
103606 comparisonWithNaN: "Use the isNaN function to compare with NaN.",
103607 switchNaN: "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch.",
103608 caseNaN: "'case NaN' can never match. Use Number.isNaN before the switch.",
103609 indexOfNaN: "Array prototype method '{{ methodName }}' cannot find NaN."
103610 }
103611 },
103612
103613 create(context) {
103614 const enforceForSwitchCase = !context.options[0] || context.options[0].enforceForSwitchCase;
103615 const enforceForIndexOf = context.options[0] && context.options[0].enforceForIndexOf;
103616 /**
103617 * Checks the given `BinaryExpression` node for `foo === NaN` and other comparisons.
103618 * @param {ASTNode} node The node to check.
103619 * @returns {void}
103620 */
103621
103622 function checkBinaryExpression(node) {
103623 if (/^(?:[<>]|[!=]=)=?$/u.test(node.operator) && (isNaNIdentifier(node.left) || isNaNIdentifier(node.right))) {
103624 context.report({
103625 node,
103626 messageId: "comparisonWithNaN"
103627 });
103628 }
103629 }
103630 /**
103631 * Checks the discriminant and all case clauses of the given `SwitchStatement` node for `switch(NaN)` and `case NaN:`
103632 * @param {ASTNode} node The node to check.
103633 * @returns {void}
103634 */
103635
103636
103637 function checkSwitchStatement(node) {
103638 if (isNaNIdentifier(node.discriminant)) {
103639 context.report({
103640 node,
103641 messageId: "switchNaN"
103642 });
103643 }
103644
103645 for (const switchCase of node.cases) {
103646 if (isNaNIdentifier(switchCase.test)) {
103647 context.report({
103648 node: switchCase,
103649 messageId: "caseNaN"
103650 });
103651 }
103652 }
103653 }
103654 /**
103655 * Checks the the given `CallExpression` node for `.indexOf(NaN)` and `.lastIndexOf(NaN)`.
103656 * @param {ASTNode} node The node to check.
103657 * @returns {void}
103658 */
103659
103660
103661 function checkCallExpression(node) {
103662 const callee = node.callee;
103663
103664 if (callee.type === "MemberExpression") {
103665 const methodName = astUtils.getStaticPropertyName(callee);
103666
103667 if ((methodName === "indexOf" || methodName === "lastIndexOf") && node.arguments.length === 1 && isNaNIdentifier(node.arguments[0])) {
103668 context.report({
103669 node,
103670 messageId: "indexOfNaN",
103671 data: {
103672 methodName
103673 }
103674 });
103675 }
103676 }
103677 }
103678
103679 const listeners = {
103680 BinaryExpression: checkBinaryExpression
103681 };
103682
103683 if (enforceForSwitchCase) {
103684 listeners.SwitchStatement = checkSwitchStatement;
103685 }
103686
103687 if (enforceForIndexOf) {
103688 listeners.CallExpression = checkCallExpression;
103689 }
103690
103691 return listeners;
103692 }
103693
103694};
103695
103696/***/ }),
6a5a0f88 103697/* 716 */
eb39fafa
DC
103698/***/ (function(module, exports, __webpack_require__) {
103699
103700"use strict";
103701/**
103702 * @fileoverview Validates JSDoc comments are syntactically correct
103703 * @author Nicholas C. Zakas
103704 */
103705 //------------------------------------------------------------------------------
103706// Requirements
103707//------------------------------------------------------------------------------
103708
6a5a0f88 103709const doctrine = __webpack_require__(717); //------------------------------------------------------------------------------
eb39fafa
DC
103710// Rule Definition
103711//------------------------------------------------------------------------------
103712
103713
103714module.exports = {
103715 meta: {
103716 type: "suggestion",
103717 docs: {
103718 description: "enforce valid JSDoc comments",
103719 category: "Possible Errors",
103720 recommended: false,
103721 url: "https://eslint.org/docs/rules/valid-jsdoc"
103722 },
103723 schema: [{
103724 type: "object",
103725 properties: {
103726 prefer: {
103727 type: "object",
103728 additionalProperties: {
103729 type: "string"
103730 }
103731 },
103732 preferType: {
103733 type: "object",
103734 additionalProperties: {
103735 type: "string"
103736 }
103737 },
103738 requireReturn: {
103739 type: "boolean",
103740 default: true
103741 },
103742 requireParamDescription: {
103743 type: "boolean",
103744 default: true
103745 },
103746 requireReturnDescription: {
103747 type: "boolean",
103748 default: true
103749 },
103750 matchDescription: {
103751 type: "string"
103752 },
103753 requireReturnType: {
103754 type: "boolean",
103755 default: true
103756 },
103757 requireParamType: {
103758 type: "boolean",
103759 default: true
103760 }
103761 },
103762 additionalProperties: false
103763 }],
103764 fixable: "code",
103765 messages: {
103766 unexpectedTag: "Unexpected @{{title}} tag; function has no return statement.",
103767 expected: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.",
103768 use: "Use @{{name}} instead.",
103769 useType: "Use '{{expectedTypeName}}' instead of '{{currentTypeName}}'.",
103770 syntaxError: "JSDoc syntax error.",
103771 missingBrace: "JSDoc type missing brace.",
103772 missingParamDesc: "Missing JSDoc parameter description for '{{name}}'.",
103773 missingParamType: "Missing JSDoc parameter type for '{{name}}'.",
103774 missingReturnType: "Missing JSDoc return type.",
103775 missingReturnDesc: "Missing JSDoc return description.",
103776 missingReturn: "Missing JSDoc @{{returns}} for function.",
103777 missingParam: "Missing JSDoc for parameter '{{name}}'.",
103778 duplicateParam: "Duplicate JSDoc parameter '{{name}}'.",
103779 unsatisfiedDesc: "JSDoc description does not satisfy the regex pattern."
103780 },
103781 deprecated: true,
103782 replacedBy: []
103783 },
103784
103785 create(context) {
103786 const options = context.options[0] || {},
103787 prefer = options.prefer || {},
103788 sourceCode = context.getSourceCode(),
103789 // these both default to true, so you have to explicitly make them false
103790 requireReturn = options.requireReturn !== false,
103791 requireParamDescription = options.requireParamDescription !== false,
103792 requireReturnDescription = options.requireReturnDescription !== false,
103793 requireReturnType = options.requireReturnType !== false,
103794 requireParamType = options.requireParamType !== false,
103795 preferType = options.preferType || {},
103796 checkPreferType = Object.keys(preferType).length !== 0; //--------------------------------------------------------------------------
103797 // Helpers
103798 //--------------------------------------------------------------------------
103799 // Using a stack to store if a function returns or not (handling nested functions)
103800
103801 const fns = [];
103802 /**
103803 * Check if node type is a Class
103804 * @param {ASTNode} node node to check.
103805 * @returns {boolean} True is its a class
103806 * @private
103807 */
103808
103809 function isTypeClass(node) {
103810 return node.type === "ClassExpression" || node.type === "ClassDeclaration";
103811 }
103812 /**
103813 * When parsing a new function, store it in our function stack.
103814 * @param {ASTNode} node A function node to check.
103815 * @returns {void}
103816 * @private
103817 */
103818
103819
103820 function startFunction(node) {
103821 fns.push({
103822 returnPresent: node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement" || isTypeClass(node) || node.async
103823 });
103824 }
103825 /**
103826 * Indicate that return has been found in the current function.
103827 * @param {ASTNode} node The return node.
103828 * @returns {void}
103829 * @private
103830 */
103831
103832
103833 function addReturn(node) {
103834 const functionState = fns[fns.length - 1];
103835
103836 if (functionState && node.argument !== null) {
103837 functionState.returnPresent = true;
103838 }
103839 }
103840 /**
103841 * Check if return tag type is void or undefined
103842 * @param {Object} tag JSDoc tag
103843 * @returns {boolean} True if its of type void or undefined
103844 * @private
103845 */
103846
103847
103848 function isValidReturnType(tag) {
103849 return tag.type === null || tag.type.name === "void" || tag.type.type === "UndefinedLiteral";
103850 }
103851 /**
103852 * Check if type should be validated based on some exceptions
103853 * @param {Object} type JSDoc tag
103854 * @returns {boolean} True if it can be validated
103855 * @private
103856 */
103857
103858
103859 function canTypeBeValidated(type) {
103860 return type !== "UndefinedLiteral" && // {undefined} as there is no name property available.
103861 type !== "NullLiteral" && // {null}
103862 type !== "NullableLiteral" && // {?}
103863 type !== "FunctionType" && // {function(a)}
103864 type !== "AllLiteral"; // {*}
103865 }
103866 /**
103867 * Extract the current and expected type based on the input type object
103868 * @param {Object} type JSDoc tag
103869 * @returns {{currentType: Doctrine.Type, expectedTypeName: string}} The current type annotation and
103870 * the expected name of the annotation
103871 * @private
103872 */
103873
103874
103875 function getCurrentExpectedTypes(type) {
103876 let currentType;
103877
103878 if (type.name) {
103879 currentType = type;
103880 } else if (type.expression) {
103881 currentType = type.expression;
103882 }
103883
103884 return {
103885 currentType,
103886 expectedTypeName: currentType && preferType[currentType.name]
103887 };
103888 }
103889 /**
103890 * Gets the location of a JSDoc node in a file
103891 * @param {Token} jsdocComment The comment that this node is parsed from
103892 * @param {{range: number[]}} parsedJsdocNode A tag or other node which was parsed from this comment
103893 * @returns {{start: SourceLocation, end: SourceLocation}} The 0-based source location for the tag
103894 */
103895
103896
103897 function getAbsoluteRange(jsdocComment, parsedJsdocNode) {
103898 return {
103899 start: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[0]),
103900 end: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[1])
103901 };
103902 }
103903 /**
103904 * Validate type for a given JSDoc node
103905 * @param {Object} jsdocNode JSDoc node
103906 * @param {Object} type JSDoc tag
103907 * @returns {void}
103908 * @private
103909 */
103910
103911
103912 function validateType(jsdocNode, type) {
103913 if (!type || !canTypeBeValidated(type.type)) {
103914 return;
103915 }
103916
103917 const typesToCheck = [];
103918 let elements = [];
103919
103920 switch (type.type) {
103921 case "TypeApplication":
103922 // {Array.<String>}
103923 elements = type.applications[0].type === "UnionType" ? type.applications[0].elements : type.applications;
103924 typesToCheck.push(getCurrentExpectedTypes(type));
103925 break;
103926
103927 case "RecordType":
103928 // {{20:String}}
103929 elements = type.fields;
103930 break;
103931
103932 case "UnionType": // {String|number|Test}
103933
103934 case "ArrayType":
103935 // {[String, number, Test]}
103936 elements = type.elements;
103937 break;
103938
103939 case "FieldType":
103940 // Array.<{count: number, votes: number}>
103941 if (type.value) {
103942 typesToCheck.push(getCurrentExpectedTypes(type.value));
103943 }
103944
103945 break;
103946
103947 default:
103948 typesToCheck.push(getCurrentExpectedTypes(type));
103949 }
103950
103951 elements.forEach(validateType.bind(null, jsdocNode));
103952 typesToCheck.forEach(typeToCheck => {
103953 if (typeToCheck.expectedTypeName && typeToCheck.expectedTypeName !== typeToCheck.currentType.name) {
103954 context.report({
103955 node: jsdocNode,
103956 messageId: "useType",
103957 loc: getAbsoluteRange(jsdocNode, typeToCheck.currentType),
103958 data: {
103959 currentTypeName: typeToCheck.currentType.name,
103960 expectedTypeName: typeToCheck.expectedTypeName
103961 },
103962
103963 fix(fixer) {
103964 return fixer.replaceTextRange(typeToCheck.currentType.range.map(indexInComment => jsdocNode.range[0] + 2 + indexInComment), typeToCheck.expectedTypeName);
103965 }
103966
103967 });
103968 }
103969 });
103970 }
103971 /**
103972 * Validate the JSDoc node and output warnings if anything is wrong.
103973 * @param {ASTNode} node The AST node to check.
103974 * @returns {void}
103975 * @private
103976 */
103977
103978
103979 function checkJSDoc(node) {
103980 const jsdocNode = sourceCode.getJSDocComment(node),
103981 functionData = fns.pop(),
103982 paramTagsByName = Object.create(null),
103983 paramTags = [];
103984 let hasReturns = false,
103985 returnsTag,
103986 hasConstructor = false,
103987 isInterface = false,
103988 isOverride = false,
103989 isAbstract = false; // make sure only to validate JSDoc comments
103990
103991 if (jsdocNode) {
103992 let jsdoc;
103993
103994 try {
103995 jsdoc = doctrine.parse(jsdocNode.value, {
103996 strict: true,
103997 unwrap: true,
103998 sloppy: true,
103999 range: true
104000 });
104001 } catch (ex) {
104002 if (/braces/iu.test(ex.message)) {
104003 context.report({
104004 node: jsdocNode,
104005 messageId: "missingBrace"
104006 });
104007 } else {
104008 context.report({
104009 node: jsdocNode,
104010 messageId: "syntaxError"
104011 });
104012 }
104013
104014 return;
104015 }
104016
104017 jsdoc.tags.forEach(tag => {
104018 switch (tag.title.toLowerCase()) {
104019 case "param":
104020 case "arg":
104021 case "argument":
104022 paramTags.push(tag);
104023 break;
104024
104025 case "return":
104026 case "returns":
104027 hasReturns = true;
104028 returnsTag = tag;
104029 break;
104030
104031 case "constructor":
104032 case "class":
104033 hasConstructor = true;
104034 break;
104035
104036 case "override":
104037 case "inheritdoc":
104038 isOverride = true;
104039 break;
104040
104041 case "abstract":
104042 case "virtual":
104043 isAbstract = true;
104044 break;
104045
104046 case "interface":
104047 isInterface = true;
104048 break;
104049 // no default
104050 } // check tag preferences
104051
104052
104053 if (Object.prototype.hasOwnProperty.call(prefer, tag.title) && tag.title !== prefer[tag.title]) {
104054 const entireTagRange = getAbsoluteRange(jsdocNode, tag);
104055 context.report({
104056 node: jsdocNode,
104057 messageId: "use",
104058 loc: {
104059 start: entireTagRange.start,
104060 end: {
104061 line: entireTagRange.start.line,
104062 column: entireTagRange.start.column + "@".concat(tag.title).length
104063 }
104064 },
104065 data: {
104066 name: prefer[tag.title]
104067 },
104068
104069 fix(fixer) {
104070 return fixer.replaceTextRange([jsdocNode.range[0] + tag.range[0] + 3, jsdocNode.range[0] + tag.range[0] + tag.title.length + 3], prefer[tag.title]);
104071 }
104072
104073 });
104074 } // validate the types
104075
104076
104077 if (checkPreferType && tag.type) {
104078 validateType(jsdocNode, tag.type);
104079 }
104080 });
104081 paramTags.forEach(param => {
104082 if (requireParamType && !param.type) {
104083 context.report({
104084 node: jsdocNode,
104085 messageId: "missingParamType",
104086 loc: getAbsoluteRange(jsdocNode, param),
104087 data: {
104088 name: param.name
104089 }
104090 });
104091 }
104092
104093 if (!param.description && requireParamDescription) {
104094 context.report({
104095 node: jsdocNode,
104096 messageId: "missingParamDesc",
104097 loc: getAbsoluteRange(jsdocNode, param),
104098 data: {
104099 name: param.name
104100 }
104101 });
104102 }
104103
104104 if (paramTagsByName[param.name]) {
104105 context.report({
104106 node: jsdocNode,
104107 messageId: "duplicateParam",
104108 loc: getAbsoluteRange(jsdocNode, param),
104109 data: {
104110 name: param.name
104111 }
104112 });
104113 } else if (param.name.indexOf(".") === -1) {
104114 paramTagsByName[param.name] = param;
104115 }
104116 });
104117
104118 if (hasReturns) {
104119 if (!requireReturn && !functionData.returnPresent && (returnsTag.type === null || !isValidReturnType(returnsTag)) && !isAbstract) {
104120 context.report({
104121 node: jsdocNode,
104122 messageId: "unexpectedTag",
104123 loc: getAbsoluteRange(jsdocNode, returnsTag),
104124 data: {
104125 title: returnsTag.title
104126 }
104127 });
104128 } else {
104129 if (requireReturnType && !returnsTag.type) {
104130 context.report({
104131 node: jsdocNode,
104132 messageId: "missingReturnType"
104133 });
104134 }
104135
104136 if (!isValidReturnType(returnsTag) && !returnsTag.description && requireReturnDescription) {
104137 context.report({
104138 node: jsdocNode,
104139 messageId: "missingReturnDesc"
104140 });
104141 }
104142 }
104143 } // check for functions missing @returns
104144
104145
104146 if (!isOverride && !hasReturns && !hasConstructor && !isInterface && node.parent.kind !== "get" && node.parent.kind !== "constructor" && node.parent.kind !== "set" && !isTypeClass(node)) {
104147 if (requireReturn || functionData.returnPresent && !node.async) {
104148 context.report({
104149 node: jsdocNode,
104150 messageId: "missingReturn",
104151 data: {
104152 returns: prefer.returns || "returns"
104153 }
104154 });
104155 }
104156 } // check the parameters
104157
104158
104159 const jsdocParamNames = Object.keys(paramTagsByName);
104160
104161 if (node.params) {
104162 node.params.forEach((param, paramsIndex) => {
104163 const bindingParam = param.type === "AssignmentPattern" ? param.left : param; // TODO(nzakas): Figure out logical things to do with destructured, default, rest params
104164
104165 if (bindingParam.type === "Identifier") {
104166 const name = bindingParam.name;
104167
104168 if (jsdocParamNames[paramsIndex] && name !== jsdocParamNames[paramsIndex]) {
104169 context.report({
104170 node: jsdocNode,
104171 messageId: "expected",
104172 loc: getAbsoluteRange(jsdocNode, paramTagsByName[jsdocParamNames[paramsIndex]]),
104173 data: {
104174 name,
104175 jsdocName: jsdocParamNames[paramsIndex]
104176 }
104177 });
104178 } else if (!paramTagsByName[name] && !isOverride) {
104179 context.report({
104180 node: jsdocNode,
104181 messageId: "missingParam",
104182 data: {
104183 name
104184 }
104185 });
104186 }
104187 }
104188 });
104189 }
104190
104191 if (options.matchDescription) {
104192 const regex = new RegExp(options.matchDescription, "u");
104193
104194 if (!regex.test(jsdoc.description)) {
104195 context.report({
104196 node: jsdocNode,
104197 messageId: "unsatisfiedDesc"
104198 });
104199 }
104200 }
104201 }
104202 } //--------------------------------------------------------------------------
104203 // Public
104204 //--------------------------------------------------------------------------
104205
104206
104207 return {
104208 ArrowFunctionExpression: startFunction,
104209 FunctionExpression: startFunction,
104210 FunctionDeclaration: startFunction,
104211 ClassExpression: startFunction,
104212 ClassDeclaration: startFunction,
104213 "ArrowFunctionExpression:exit": checkJSDoc,
104214 "FunctionExpression:exit": checkJSDoc,
104215 "FunctionDeclaration:exit": checkJSDoc,
104216 "ClassExpression:exit": checkJSDoc,
104217 "ClassDeclaration:exit": checkJSDoc,
104218 ReturnStatement: addReturn
104219 };
104220 }
104221
104222};
104223
104224/***/ }),
6a5a0f88 104225/* 717 */
eb39fafa
DC
104226/***/ (function(module, exports, __webpack_require__) {
104227
104228/*
104229 * @fileoverview Main Doctrine object
104230 * @author Yusuke Suzuki <utatane.tea@gmail.com>
104231 * @author Dan Tao <daniel.tao@gmail.com>
104232 * @author Andrew Eisenberg <andrew@eisenberg.as>
104233 */
104234(function () {
104235 'use strict';
104236
104237 var typed, utility, jsdoc, esutils, hasOwnProperty;
104238 esutils = __webpack_require__(427);
6a5a0f88
TL
104239 typed = __webpack_require__(718);
104240 utility = __webpack_require__(719);
eb39fafa
DC
104241
104242 function sliceSource(source, index, last) {
104243 return source.slice(index, last);
104244 }
104245
104246 hasOwnProperty = function () {
104247 var func = Object.prototype.hasOwnProperty;
104248 return function hasOwnProperty(obj, name) {
104249 return func.call(obj, name);
104250 };
104251 }();
104252
104253 function shallowCopy(obj) {
104254 var ret = {},
104255 key;
104256
104257 for (key in obj) {
104258 if (obj.hasOwnProperty(key)) {
104259 ret[key] = obj[key];
104260 }
104261 }
104262
104263 return ret;
104264 }
104265
104266 function isASCIIAlphanumeric(ch) {
104267 return ch >= 0x61
104268 /* 'a' */
104269 && ch <= 0x7A
104270 /* 'z' */
104271 || ch >= 0x41
104272 /* 'A' */
104273 && ch <= 0x5A
104274 /* 'Z' */
104275 || ch >= 0x30
104276 /* '0' */
104277 && ch <= 0x39
104278 /* '9' */
104279 ;
104280 }
104281
104282 function isParamTitle(title) {
104283 return title === 'param' || title === 'argument' || title === 'arg';
104284 }
104285
104286 function isReturnTitle(title) {
104287 return title === 'return' || title === 'returns';
104288 }
104289
104290 function isProperty(title) {
104291 return title === 'property' || title === 'prop';
104292 }
104293
104294 function isNameParameterRequired(title) {
104295 return isParamTitle(title) || isProperty(title) || title === 'alias' || title === 'this' || title === 'mixes' || title === 'requires';
104296 }
104297
104298 function isAllowedName(title) {
104299 return isNameParameterRequired(title) || title === 'const' || title === 'constant';
104300 }
104301
104302 function isAllowedNested(title) {
104303 return isProperty(title) || isParamTitle(title);
104304 }
104305
104306 function isAllowedOptional(title) {
104307 return isProperty(title) || isParamTitle(title);
104308 }
104309
104310 function isTypeParameterRequired(title) {
104311 return isParamTitle(title) || isReturnTitle(title) || title === 'define' || title === 'enum' || title === 'implements' || title === 'this' || title === 'type' || title === 'typedef' || isProperty(title);
104312 } // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick when a type is optional/required
104313 // This would require changes to 'parseType'
104314
104315
104316 function isAllowedType(title) {
104317 return isTypeParameterRequired(title) || title === 'throws' || title === 'const' || title === 'constant' || title === 'namespace' || title === 'member' || title === 'var' || title === 'module' || title === 'constructor' || title === 'class' || title === 'extends' || title === 'augments' || title === 'public' || title === 'private' || title === 'protected';
104318 } // A regex character class that contains all whitespace except linebreak characters (\r, \n, \u2028, \u2029)
104319
104320
104321 var WHITESPACE = '[ \\f\\t\\v\\u00a0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]';
104322 var STAR_MATCHER = '(' + WHITESPACE + '*(?:\\*' + WHITESPACE + '?)?)(.+|[\r\n\u2028\u2029])';
104323
104324 function unwrapComment(doc) {
104325 // JSDoc comment is following form
104326 // /**
104327 // * .......
104328 // */
104329 return doc. // remove /**
104330 replace(/^\/\*\*?/, ''). // remove */
104331 replace(/\*\/$/, ''). // remove ' * ' at the beginning of a line
104332 replace(new RegExp(STAR_MATCHER, 'g'), '$2'). // remove trailing whitespace
104333 replace(/\s*$/, '');
104334 }
104335 /**
104336 * Converts an index in an "unwrapped" JSDoc comment to the corresponding index in the original "wrapped" version
104337 * @param {string} originalSource The original wrapped comment
104338 * @param {number} unwrappedIndex The index of a character in the unwrapped string
104339 * @returns {number} The index of the corresponding character in the original wrapped string
104340 */
104341
104342
104343 function convertUnwrappedCommentIndex(originalSource, unwrappedIndex) {
104344 var replacedSource = originalSource.replace(/^\/\*\*?/, '');
104345 var numSkippedChars = 0;
104346 var matcher = new RegExp(STAR_MATCHER, 'g');
104347 var match;
104348
104349 while (match = matcher.exec(replacedSource)) {
104350 numSkippedChars += match[1].length;
104351
104352 if (match.index + match[0].length > unwrappedIndex + numSkippedChars) {
104353 return unwrappedIndex + numSkippedChars + originalSource.length - replacedSource.length;
104354 }
104355 }
104356
104357 return originalSource.replace(/\*\/$/, '').replace(/\s*$/, '').length;
104358 } // JSDoc Tag Parser
104359
104360
104361 (function (exports) {
104362 var Rules, index, lineNumber, length, source, originalSource, recoverable, sloppy, strict;
104363
104364 function advance() {
104365 var ch = source.charCodeAt(index);
104366 index += 1;
104367
104368 if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D
104369 /* '\r' */
104370 && source.charCodeAt(index) === 0x0A
104371 /* '\n' */
104372 )) {
104373 lineNumber += 1;
104374 }
104375
104376 return String.fromCharCode(ch);
104377 }
104378
104379 function scanTitle() {
104380 var title = ''; // waste '@'
104381
104382 advance();
104383
104384 while (index < length && isASCIIAlphanumeric(source.charCodeAt(index))) {
104385 title += advance();
104386 }
104387
104388 return title;
104389 }
104390
104391 function seekContent() {
104392 var ch,
104393 waiting,
104394 last = index;
104395 waiting = false;
104396
104397 while (last < length) {
104398 ch = source.charCodeAt(last);
104399
104400 if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D
104401 /* '\r' */
104402 && source.charCodeAt(last + 1) === 0x0A
104403 /* '\n' */
104404 )) {
104405 waiting = true;
104406 } else if (waiting) {
104407 if (ch === 0x40
104408 /* '@' */
104409 ) {
104410 break;
104411 }
104412
104413 if (!esutils.code.isWhiteSpace(ch)) {
104414 waiting = false;
104415 }
104416 }
104417
104418 last += 1;
104419 }
104420
104421 return last;
104422 } // type expression may have nest brace, such as,
104423 // { { ok: string } }
104424 //
104425 // therefore, scanning type expression with balancing braces.
104426
104427
104428 function parseType(title, last, addRange) {
104429 var ch,
104430 brace,
104431 type,
104432 startIndex,
104433 direct = false; // search '{'
104434
104435 while (index < last) {
104436 ch = source.charCodeAt(index);
104437
104438 if (esutils.code.isWhiteSpace(ch)) {
104439 advance();
104440 } else if (ch === 0x7B
104441 /* '{' */
104442 ) {
104443 advance();
104444 break;
104445 } else {
104446 // this is direct pattern
104447 direct = true;
104448 break;
104449 }
104450 }
104451
104452 if (direct) {
104453 return null;
104454 } // type expression { is found
104455
104456
104457 brace = 1;
104458 type = '';
104459
104460 while (index < last) {
104461 ch = source.charCodeAt(index);
104462
104463 if (esutils.code.isLineTerminator(ch)) {
104464 advance();
104465 } else {
104466 if (ch === 0x7D
104467 /* '}' */
104468 ) {
104469 brace -= 1;
104470
104471 if (brace === 0) {
104472 advance();
104473 break;
104474 }
104475 } else if (ch === 0x7B
104476 /* '{' */
104477 ) {
104478 brace += 1;
104479 }
104480
104481 if (type === '') {
104482 startIndex = index;
104483 }
104484
104485 type += advance();
104486 }
104487 }
104488
104489 if (brace !== 0) {
104490 // braces is not balanced
104491 return utility.throwError('Braces are not balanced');
104492 }
104493
104494 if (isAllowedOptional(title)) {
104495 return typed.parseParamType(type, {
104496 startIndex: convertIndex(startIndex),
104497 range: addRange
104498 });
104499 }
104500
104501 return typed.parseType(type, {
104502 startIndex: convertIndex(startIndex),
104503 range: addRange
104504 });
104505 }
104506
104507 function scanIdentifier(last) {
104508 var identifier;
104509
104510 if (!esutils.code.isIdentifierStartES5(source.charCodeAt(index)) && !source[index].match(/[0-9]/)) {
104511 return null;
104512 }
104513
104514 identifier = advance();
104515
104516 while (index < last && esutils.code.isIdentifierPartES5(source.charCodeAt(index))) {
104517 identifier += advance();
104518 }
104519
104520 return identifier;
104521 }
104522
104523 function skipWhiteSpace(last) {
104524 while (index < last && (esutils.code.isWhiteSpace(source.charCodeAt(index)) || esutils.code.isLineTerminator(source.charCodeAt(index)))) {
104525 advance();
104526 }
104527 }
104528
104529 function parseName(last, allowBrackets, allowNestedParams) {
104530 var name = '',
104531 useBrackets,
104532 insideString;
104533 skipWhiteSpace(last);
104534
104535 if (index >= last) {
104536 return null;
104537 }
104538
104539 if (source.charCodeAt(index) === 0x5B
104540 /* '[' */
104541 ) {
104542 if (allowBrackets) {
104543 useBrackets = true;
104544 name = advance();
104545 } else {
104546 return null;
104547 }
104548 }
104549
104550 name += scanIdentifier(last);
104551
104552 if (allowNestedParams) {
104553 if (source.charCodeAt(index) === 0x3A
104554 /* ':' */
104555 && (name === 'module' || name === 'external' || name === 'event')) {
104556 name += advance();
104557 name += scanIdentifier(last);
104558 }
104559
104560 if (source.charCodeAt(index) === 0x5B
104561 /* '[' */
104562 && source.charCodeAt(index + 1) === 0x5D
104563 /* ']' */
104564 ) {
104565 name += advance();
104566 name += advance();
104567 }
104568
104569 while (source.charCodeAt(index) === 0x2E
104570 /* '.' */
104571 || source.charCodeAt(index) === 0x2F
104572 /* '/' */
104573 || source.charCodeAt(index) === 0x23
104574 /* '#' */
104575 || source.charCodeAt(index) === 0x2D
104576 /* '-' */
104577 || source.charCodeAt(index) === 0x7E
104578 /* '~' */
104579 ) {
104580 name += advance();
104581 name += scanIdentifier(last);
104582 }
104583 }
104584
104585 if (useBrackets) {
104586 skipWhiteSpace(last); // do we have a default value for this?
104587
104588 if (source.charCodeAt(index) === 0x3D
104589 /* '=' */
104590 ) {
104591 // consume the '='' symbol
104592 name += advance();
104593 skipWhiteSpace(last);
104594 var ch;
104595 var bracketDepth = 1; // scan in the default value
104596
104597 while (index < last) {
104598 ch = source.charCodeAt(index);
104599
104600 if (esutils.code.isWhiteSpace(ch)) {
104601 if (!insideString) {
104602 skipWhiteSpace(last);
104603 ch = source.charCodeAt(index);
104604 }
104605 }
104606
104607 if (ch === 0x27
104608 /* ''' */
104609 ) {
104610 if (!insideString) {
104611 insideString = '\'';
104612 } else {
104613 if (insideString === '\'') {
104614 insideString = '';
104615 }
104616 }
104617 }
104618
104619 if (ch === 0x22
104620 /* '"' */
104621 ) {
104622 if (!insideString) {
104623 insideString = '"';
104624 } else {
104625 if (insideString === '"') {
104626 insideString = '';
104627 }
104628 }
104629 }
104630
104631 if (ch === 0x5B
104632 /* '[' */
104633 ) {
104634 bracketDepth++;
104635 } else if (ch === 0x5D
104636 /* ']' */
104637 && --bracketDepth === 0) {
104638 break;
104639 }
104640
104641 name += advance();
104642 }
104643 }
104644
104645 skipWhiteSpace(last);
104646
104647 if (index >= last || source.charCodeAt(index) !== 0x5D
104648 /* ']' */
104649 ) {
104650 // we never found a closing ']'
104651 return null;
104652 } // collect the last ']'
104653
104654
104655 name += advance();
104656 }
104657
104658 return name;
104659 }
104660
104661 function skipToTag() {
104662 while (index < length && source.charCodeAt(index) !== 0x40
104663 /* '@' */
104664 ) {
104665 advance();
104666 }
104667
104668 if (index >= length) {
104669 return false;
104670 }
104671
104672 utility.assert(source.charCodeAt(index) === 0x40
104673 /* '@' */
104674 );
104675 return true;
104676 }
104677
104678 function convertIndex(rangeIndex) {
104679 if (source === originalSource) {
104680 return rangeIndex;
104681 }
104682
104683 return convertUnwrappedCommentIndex(originalSource, rangeIndex);
104684 }
104685
104686 function TagParser(options, title) {
104687 this._options = options;
104688 this._title = title.toLowerCase();
104689 this._tag = {
104690 title: title,
104691 description: null
104692 };
104693
104694 if (this._options.lineNumbers) {
104695 this._tag.lineNumber = lineNumber;
104696 }
104697
104698 this._first = index - title.length - 1;
104699 this._last = 0; // space to save special information for title parsers.
104700
104701 this._extra = {};
104702 } // addError(err, ...)
104703
104704
104705 TagParser.prototype.addError = function addError(errorText) {
104706 var args = Array.prototype.slice.call(arguments, 1),
104707 msg = errorText.replace(/%(\d)/g, function (whole, index) {
104708 utility.assert(index < args.length, 'Message reference must be in range');
104709 return args[index];
104710 });
104711
104712 if (!this._tag.errors) {
104713 this._tag.errors = [];
104714 }
104715
104716 if (strict) {
104717 utility.throwError(msg);
104718 }
104719
104720 this._tag.errors.push(msg);
104721
104722 return recoverable;
104723 };
104724
104725 TagParser.prototype.parseType = function () {
104726 // type required titles
104727 if (isTypeParameterRequired(this._title)) {
104728 try {
104729 this._tag.type = parseType(this._title, this._last, this._options.range);
104730
104731 if (!this._tag.type) {
104732 if (!isParamTitle(this._title) && !isReturnTitle(this._title)) {
104733 if (!this.addError('Missing or invalid tag type')) {
104734 return false;
104735 }
104736 }
104737 }
104738 } catch (error) {
104739 this._tag.type = null;
104740
104741 if (!this.addError(error.message)) {
104742 return false;
104743 }
104744 }
104745 } else if (isAllowedType(this._title)) {
104746 // optional types
104747 try {
104748 this._tag.type = parseType(this._title, this._last, this._options.range);
104749 } catch (e) {//For optional types, lets drop the thrown error when we hit the end of the file
104750 }
104751 }
104752
104753 return true;
104754 };
104755
104756 TagParser.prototype._parseNamePath = function (optional) {
104757 var name;
104758 name = parseName(this._last, sloppy && isAllowedOptional(this._title), true);
104759
104760 if (!name) {
104761 if (!optional) {
104762 if (!this.addError('Missing or invalid tag name')) {
104763 return false;
104764 }
104765 }
104766 }
104767
104768 this._tag.name = name;
104769 return true;
104770 };
104771
104772 TagParser.prototype.parseNamePath = function () {
104773 return this._parseNamePath(false);
104774 };
104775
104776 TagParser.prototype.parseNamePathOptional = function () {
104777 return this._parseNamePath(true);
104778 };
104779
104780 TagParser.prototype.parseName = function () {
104781 var assign, name; // param, property requires name
104782
104783 if (isAllowedName(this._title)) {
104784 this._tag.name = parseName(this._last, sloppy && isAllowedOptional(this._title), isAllowedNested(this._title));
104785
104786 if (!this._tag.name) {
104787 if (!isNameParameterRequired(this._title)) {
104788 return true;
104789 } // it's possible the name has already been parsed but interpreted as a type
104790 // it's also possible this is a sloppy declaration, in which case it will be
104791 // fixed at the end
104792
104793
104794 if (isParamTitle(this._title) && this._tag.type && this._tag.type.name) {
104795 this._extra.name = this._tag.type;
104796 this._tag.name = this._tag.type.name;
104797 this._tag.type = null;
104798 } else {
104799 if (!this.addError('Missing or invalid tag name')) {
104800 return false;
104801 }
104802 }
104803 } else {
104804 name = this._tag.name;
104805
104806 if (name.charAt(0) === '[' && name.charAt(name.length - 1) === ']') {
104807 // extract the default value if there is one
104808 // example: @param {string} [somebody=John Doe] description
104809 assign = name.substring(1, name.length - 1).split('=');
104810
104811 if (assign.length > 1) {
104812 this._tag['default'] = assign.slice(1).join('=');
104813 }
104814
104815 this._tag.name = assign[0]; // convert to an optional type
104816
104817 if (this._tag.type && this._tag.type.type !== 'OptionalType') {
104818 this._tag.type = {
104819 type: 'OptionalType',
104820 expression: this._tag.type
104821 };
104822 }
104823 }
104824 }
104825 }
104826
104827 return true;
104828 };
104829
104830 TagParser.prototype.parseDescription = function parseDescription() {
104831 var description = sliceSource(source, index, this._last).trim();
104832
104833 if (description) {
104834 if (/^-\s+/.test(description)) {
104835 description = description.substring(2);
104836 }
104837
104838 this._tag.description = description;
104839 }
104840
104841 return true;
104842 };
104843
104844 TagParser.prototype.parseCaption = function parseDescription() {
104845 var description = sliceSource(source, index, this._last).trim();
104846 var captionStartTag = '<caption>';
104847 var captionEndTag = '</caption>';
104848 var captionStart = description.indexOf(captionStartTag);
104849 var captionEnd = description.indexOf(captionEndTag);
104850
104851 if (captionStart >= 0 && captionEnd >= 0) {
104852 this._tag.caption = description.substring(captionStart + captionStartTag.length, captionEnd).trim();
104853 this._tag.description = description.substring(captionEnd + captionEndTag.length).trim();
104854 } else {
104855 this._tag.description = description;
104856 }
104857
104858 return true;
104859 };
104860
104861 TagParser.prototype.parseKind = function parseKind() {
104862 var kind, kinds;
104863 kinds = {
104864 'class': true,
104865 'constant': true,
104866 'event': true,
104867 'external': true,
104868 'file': true,
104869 'function': true,
104870 'member': true,
104871 'mixin': true,
104872 'module': true,
104873 'namespace': true,
104874 'typedef': true
104875 };
104876 kind = sliceSource(source, index, this._last).trim();
104877 this._tag.kind = kind;
104878
104879 if (!hasOwnProperty(kinds, kind)) {
104880 if (!this.addError('Invalid kind name \'%0\'', kind)) {
104881 return false;
104882 }
104883 }
104884
104885 return true;
104886 };
104887
104888 TagParser.prototype.parseAccess = function parseAccess() {
104889 var access;
104890 access = sliceSource(source, index, this._last).trim();
104891 this._tag.access = access;
104892
104893 if (access !== 'private' && access !== 'protected' && access !== 'public') {
104894 if (!this.addError('Invalid access name \'%0\'', access)) {
104895 return false;
104896 }
104897 }
104898
104899 return true;
104900 };
104901
104902 TagParser.prototype.parseThis = function parseThis() {
104903 // this name may be a name expression (e.g. {foo.bar}),
104904 // an union (e.g. {foo.bar|foo.baz}) or a name path (e.g. foo.bar)
104905 var value = sliceSource(source, index, this._last).trim();
104906
104907 if (value && value.charAt(0) === '{') {
104908 var gotType = this.parseType();
104909
104910 if (gotType && this._tag.type.type === 'NameExpression' || this._tag.type.type === 'UnionType') {
104911 this._tag.name = this._tag.type.name;
104912 return true;
104913 } else {
104914 return this.addError('Invalid name for this');
104915 }
104916 } else {
104917 return this.parseNamePath();
104918 }
104919 };
104920
104921 TagParser.prototype.parseVariation = function parseVariation() {
104922 var variation, text;
104923 text = sliceSource(source, index, this._last).trim();
104924 variation = parseFloat(text, 10);
104925 this._tag.variation = variation;
104926
104927 if (isNaN(variation)) {
104928 if (!this.addError('Invalid variation \'%0\'', text)) {
104929 return false;
104930 }
104931 }
104932
104933 return true;
104934 };
104935
104936 TagParser.prototype.ensureEnd = function () {
104937 var shouldBeEmpty = sliceSource(source, index, this._last).trim();
104938
104939 if (shouldBeEmpty) {
104940 if (!this.addError('Unknown content \'%0\'', shouldBeEmpty)) {
104941 return false;
104942 }
104943 }
104944
104945 return true;
104946 };
104947
104948 TagParser.prototype.epilogue = function epilogue() {
104949 var description;
104950 description = this._tag.description; // un-fix potentially sloppy declaration
104951
104952 if (isAllowedOptional(this._title) && !this._tag.type && description && description.charAt(0) === '[') {
104953 this._tag.type = this._extra.name;
104954
104955 if (!this._tag.name) {
104956 this._tag.name = undefined;
104957 }
104958
104959 if (!sloppy) {
104960 if (!this.addError('Missing or invalid tag name')) {
104961 return false;
104962 }
104963 }
104964 }
104965
104966 return true;
104967 };
104968
104969 Rules = {
104970 // http://usejsdoc.org/tags-access.html
104971 'access': ['parseAccess'],
104972 // http://usejsdoc.org/tags-alias.html
104973 'alias': ['parseNamePath', 'ensureEnd'],
104974 // http://usejsdoc.org/tags-augments.html
104975 'augments': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
104976 // http://usejsdoc.org/tags-constructor.html
104977 'constructor': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
104978 // Synonym: http://usejsdoc.org/tags-constructor.html
104979 'class': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
104980 // Synonym: http://usejsdoc.org/tags-extends.html
104981 'extends': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
104982 // http://usejsdoc.org/tags-example.html
104983 'example': ['parseCaption'],
104984 // http://usejsdoc.org/tags-deprecated.html
104985 'deprecated': ['parseDescription'],
104986 // http://usejsdoc.org/tags-global.html
104987 'global': ['ensureEnd'],
104988 // http://usejsdoc.org/tags-inner.html
104989 'inner': ['ensureEnd'],
104990 // http://usejsdoc.org/tags-instance.html
104991 'instance': ['ensureEnd'],
104992 // http://usejsdoc.org/tags-kind.html
104993 'kind': ['parseKind'],
104994 // http://usejsdoc.org/tags-mixes.html
104995 'mixes': ['parseNamePath', 'ensureEnd'],
104996 // http://usejsdoc.org/tags-mixin.html
104997 'mixin': ['parseNamePathOptional', 'ensureEnd'],
104998 // http://usejsdoc.org/tags-member.html
104999 'member': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
105000 // http://usejsdoc.org/tags-method.html
105001 'method': ['parseNamePathOptional', 'ensureEnd'],
105002 // http://usejsdoc.org/tags-module.html
105003 'module': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
105004 // Synonym: http://usejsdoc.org/tags-method.html
105005 'func': ['parseNamePathOptional', 'ensureEnd'],
105006 // Synonym: http://usejsdoc.org/tags-method.html
105007 'function': ['parseNamePathOptional', 'ensureEnd'],
105008 // Synonym: http://usejsdoc.org/tags-member.html
105009 'var': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
105010 // http://usejsdoc.org/tags-name.html
105011 'name': ['parseNamePath', 'ensureEnd'],
105012 // http://usejsdoc.org/tags-namespace.html
105013 'namespace': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
105014 // http://usejsdoc.org/tags-private.html
105015 'private': ['parseType', 'parseDescription'],
105016 // http://usejsdoc.org/tags-protected.html
105017 'protected': ['parseType', 'parseDescription'],
105018 // http://usejsdoc.org/tags-public.html
105019 'public': ['parseType', 'parseDescription'],
105020 // http://usejsdoc.org/tags-readonly.html
105021 'readonly': ['ensureEnd'],
105022 // http://usejsdoc.org/tags-requires.html
105023 'requires': ['parseNamePath', 'ensureEnd'],
105024 // http://usejsdoc.org/tags-since.html
105025 'since': ['parseDescription'],
105026 // http://usejsdoc.org/tags-static.html
105027 'static': ['ensureEnd'],
105028 // http://usejsdoc.org/tags-summary.html
105029 'summary': ['parseDescription'],
105030 // http://usejsdoc.org/tags-this.html
105031 'this': ['parseThis', 'ensureEnd'],
105032 // http://usejsdoc.org/tags-todo.html
105033 'todo': ['parseDescription'],
105034 // http://usejsdoc.org/tags-typedef.html
105035 'typedef': ['parseType', 'parseNamePathOptional'],
105036 // http://usejsdoc.org/tags-variation.html
105037 'variation': ['parseVariation'],
105038 // http://usejsdoc.org/tags-version.html
105039 'version': ['parseDescription']
105040 };
105041
105042 TagParser.prototype.parse = function parse() {
105043 var i, iz, sequences, method; // empty title
105044
105045 if (!this._title) {
105046 if (!this.addError('Missing or invalid title')) {
105047 return null;
105048 }
105049 } // Seek to content last index.
105050
105051
105052 this._last = seekContent(this._title);
105053
105054 if (this._options.range) {
105055 this._tag.range = [this._first, source.slice(0, this._last).replace(/\s*$/, '').length].map(convertIndex);
105056 }
105057
105058 if (hasOwnProperty(Rules, this._title)) {
105059 sequences = Rules[this._title];
105060 } else {
105061 // default sequences
105062 sequences = ['parseType', 'parseName', 'parseDescription', 'epilogue'];
105063 }
105064
105065 for (i = 0, iz = sequences.length; i < iz; ++i) {
105066 method = sequences[i];
105067
105068 if (!this[method]()) {
105069 return null;
105070 }
105071 }
105072
105073 return this._tag;
105074 };
105075
105076 function parseTag(options) {
105077 var title, parser, tag; // skip to tag
105078
105079 if (!skipToTag()) {
105080 return null;
105081 } // scan title
105082
105083
105084 title = scanTitle(); // construct tag parser
105085
105086 parser = new TagParser(options, title);
105087 tag = parser.parse(); // Seek global index to end of this tag.
105088
105089 while (index < parser._last) {
105090 advance();
105091 }
105092
105093 return tag;
105094 } //
105095 // Parse JSDoc
105096 //
105097
105098
105099 function scanJSDocDescription(preserveWhitespace) {
105100 var description = '',
105101 ch,
105102 atAllowed;
105103 atAllowed = true;
105104
105105 while (index < length) {
105106 ch = source.charCodeAt(index);
105107
105108 if (atAllowed && ch === 0x40
105109 /* '@' */
105110 ) {
105111 break;
105112 }
105113
105114 if (esutils.code.isLineTerminator(ch)) {
105115 atAllowed = true;
105116 } else if (atAllowed && !esutils.code.isWhiteSpace(ch)) {
105117 atAllowed = false;
105118 }
105119
105120 description += advance();
105121 }
105122
105123 return preserveWhitespace ? description : description.trim();
105124 }
105125
105126 function parse(comment, options) {
105127 var tags = [],
105128 tag,
105129 description,
105130 interestingTags,
105131 i,
105132 iz;
105133
105134 if (options === undefined) {
105135 options = {};
105136 }
105137
105138 if (typeof options.unwrap === 'boolean' && options.unwrap) {
105139 source = unwrapComment(comment);
105140 } else {
105141 source = comment;
105142 }
105143
105144 originalSource = comment; // array of relevant tags
105145
105146 if (options.tags) {
105147 if (Array.isArray(options.tags)) {
105148 interestingTags = {};
105149
105150 for (i = 0, iz = options.tags.length; i < iz; i++) {
105151 if (typeof options.tags[i] === 'string') {
105152 interestingTags[options.tags[i]] = true;
105153 } else {
105154 utility.throwError('Invalid "tags" parameter: ' + options.tags);
105155 }
105156 }
105157 } else {
105158 utility.throwError('Invalid "tags" parameter: ' + options.tags);
105159 }
105160 }
105161
105162 length = source.length;
105163 index = 0;
105164 lineNumber = 0;
105165 recoverable = options.recoverable;
105166 sloppy = options.sloppy;
105167 strict = options.strict;
105168 description = scanJSDocDescription(options.preserveWhitespace);
105169
105170 while (true) {
105171 tag = parseTag(options);
105172
105173 if (!tag) {
105174 break;
105175 }
105176
105177 if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) {
105178 tags.push(tag);
105179 }
105180 }
105181
105182 return {
105183 description: description,
105184 tags: tags
105185 };
105186 }
105187
105188 exports.parse = parse;
105189 })(jsdoc = {});
105190
105191 exports.version = utility.VERSION;
105192 exports.parse = jsdoc.parse;
105193 exports.parseType = typed.parseType;
105194 exports.parseParamType = typed.parseParamType;
105195 exports.unwrapComment = unwrapComment;
105196 exports.Syntax = shallowCopy(typed.Syntax);
105197 exports.Error = utility.DoctrineError;
105198 exports.type = {
105199 Syntax: exports.Syntax,
105200 parseType: typed.parseType,
105201 parseParamType: typed.parseParamType,
105202 stringify: typed.stringify
105203 };
105204})();
105205/* vim: set sw=4 ts=4 et tw=80 : */
105206
105207/***/ }),
6a5a0f88 105208/* 718 */
eb39fafa
DC
105209/***/ (function(module, exports, __webpack_require__) {
105210
105211/*
105212 * @fileoverview Type expression parser.
105213 * @author Yusuke Suzuki <utatane.tea@gmail.com>
105214 * @author Dan Tao <daniel.tao@gmail.com>
105215 * @author Andrew Eisenberg <andrew@eisenberg.as>
105216 */
105217// "typed", the Type Expression Parser for doctrine.
105218(function () {
105219 'use strict';
105220
105221 var Syntax, Token, source, length, index, previous, token, value, esutils, utility, rangeOffset, addRange;
105222 esutils = __webpack_require__(427);
6a5a0f88 105223 utility = __webpack_require__(719);
eb39fafa
DC
105224 Syntax = {
105225 NullableLiteral: 'NullableLiteral',
105226 AllLiteral: 'AllLiteral',
105227 NullLiteral: 'NullLiteral',
105228 UndefinedLiteral: 'UndefinedLiteral',
105229 VoidLiteral: 'VoidLiteral',
105230 UnionType: 'UnionType',
105231 ArrayType: 'ArrayType',
105232 RecordType: 'RecordType',
105233 FieldType: 'FieldType',
105234 FunctionType: 'FunctionType',
105235 ParameterType: 'ParameterType',
105236 RestType: 'RestType',
105237 NonNullableType: 'NonNullableType',
105238 OptionalType: 'OptionalType',
105239 NullableType: 'NullableType',
105240 NameExpression: 'NameExpression',
105241 TypeApplication: 'TypeApplication',
105242 StringLiteralType: 'StringLiteralType',
105243 NumericLiteralType: 'NumericLiteralType',
105244 BooleanLiteralType: 'BooleanLiteralType'
105245 };
105246 Token = {
105247 ILLEGAL: 0,
105248 // ILLEGAL
105249 DOT_LT: 1,
105250 // .<
105251 REST: 2,
105252 // ...
105253 LT: 3,
105254 // <
105255 GT: 4,
105256 // >
105257 LPAREN: 5,
105258 // (
105259 RPAREN: 6,
105260 // )
105261 LBRACE: 7,
105262 // {
105263 RBRACE: 8,
105264 // }
105265 LBRACK: 9,
105266 // [
105267 RBRACK: 10,
105268 // ]
105269 COMMA: 11,
105270 // ,
105271 COLON: 12,
105272 // :
105273 STAR: 13,
105274 // *
105275 PIPE: 14,
105276 // |
105277 QUESTION: 15,
105278 // ?
105279 BANG: 16,
105280 // !
105281 EQUAL: 17,
105282 // =
105283 NAME: 18,
105284 // name token
105285 STRING: 19,
105286 // string
105287 NUMBER: 20,
105288 // number
105289 EOF: 21
105290 };
105291
105292 function isTypeName(ch) {
105293 return '><(){}[],:*|?!='.indexOf(String.fromCharCode(ch)) === -1 && !esutils.code.isWhiteSpace(ch) && !esutils.code.isLineTerminator(ch);
105294 }
105295
105296 function Context(previous, index, token, value) {
105297 this._previous = previous;
105298 this._index = index;
105299 this._token = token;
105300 this._value = value;
105301 }
105302
105303 Context.prototype.restore = function () {
105304 previous = this._previous;
105305 index = this._index;
105306 token = this._token;
105307 value = this._value;
105308 };
105309
105310 Context.save = function () {
105311 return new Context(previous, index, token, value);
105312 };
105313
105314 function maybeAddRange(node, range) {
105315 if (addRange) {
105316 node.range = [range[0] + rangeOffset, range[1] + rangeOffset];
105317 }
105318
105319 return node;
105320 }
105321
105322 function advance() {
105323 var ch = source.charAt(index);
105324 index += 1;
105325 return ch;
105326 }
105327
105328 function scanHexEscape(prefix) {
105329 var i,
105330 len,
105331 ch,
105332 code = 0;
105333 len = prefix === 'u' ? 4 : 2;
105334
105335 for (i = 0; i < len; ++i) {
105336 if (index < length && esutils.code.isHexDigit(source.charCodeAt(index))) {
105337 ch = advance();
105338 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
105339 } else {
105340 return '';
105341 }
105342 }
105343
105344 return String.fromCharCode(code);
105345 }
105346
105347 function scanString() {
105348 var str = '',
105349 quote,
105350 ch,
105351 code,
105352 unescaped,
105353 restore; //TODO review removal octal = false
105354
105355 quote = source.charAt(index);
105356 ++index;
105357
105358 while (index < length) {
105359 ch = advance();
105360
105361 if (ch === quote) {
105362 quote = '';
105363 break;
105364 } else if (ch === '\\') {
105365 ch = advance();
105366
105367 if (!esutils.code.isLineTerminator(ch.charCodeAt(0))) {
105368 switch (ch) {
105369 case 'n':
105370 str += '\n';
105371 break;
105372
105373 case 'r':
105374 str += '\r';
105375 break;
105376
105377 case 't':
105378 str += '\t';
105379 break;
105380
105381 case 'u':
105382 case 'x':
105383 restore = index;
105384 unescaped = scanHexEscape(ch);
105385
105386 if (unescaped) {
105387 str += unescaped;
105388 } else {
105389 index = restore;
105390 str += ch;
105391 }
105392
105393 break;
105394
105395 case 'b':
105396 str += '\b';
105397 break;
105398
105399 case 'f':
105400 str += '\f';
105401 break;
105402
105403 case 'v':
105404 str += '\v';
105405 break;
105406
105407 default:
105408 if (esutils.code.isOctalDigit(ch.charCodeAt(0))) {
105409 code = '01234567'.indexOf(ch); // \0 is not octal escape sequence
105410 // Deprecating unused code. TODO review removal
105411 //if (code !== 0) {
105412 // octal = true;
105413 //}
105414
105415 if (index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) {
105416 //TODO Review Removal octal = true;
105417 code = code * 8 + '01234567'.indexOf(advance()); // 3 digits are only allowed when string starts
105418 // with 0, 1, 2, 3
105419
105420 if ('0123'.indexOf(ch) >= 0 && index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) {
105421 code = code * 8 + '01234567'.indexOf(advance());
105422 }
105423 }
105424
105425 str += String.fromCharCode(code);
105426 } else {
105427 str += ch;
105428 }
105429
105430 break;
105431 }
105432 } else {
105433 if (ch === '\r' && source.charCodeAt(index) === 0x0A
105434 /* '\n' */
105435 ) {
105436 ++index;
105437 }
105438 }
105439 } else if (esutils.code.isLineTerminator(ch.charCodeAt(0))) {
105440 break;
105441 } else {
105442 str += ch;
105443 }
105444 }
105445
105446 if (quote !== '') {
105447 utility.throwError('unexpected quote');
105448 }
105449
105450 value = str;
105451 return Token.STRING;
105452 }
105453
105454 function scanNumber() {
105455 var number, ch;
105456 number = '';
105457 ch = source.charCodeAt(index);
105458
105459 if (ch !== 0x2E
105460 /* '.' */
105461 ) {
105462 number = advance();
105463 ch = source.charCodeAt(index);
105464
105465 if (number === '0') {
105466 if (ch === 0x78
105467 /* 'x' */
105468 || ch === 0x58
105469 /* 'X' */
105470 ) {
105471 number += advance();
105472
105473 while (index < length) {
105474 ch = source.charCodeAt(index);
105475
105476 if (!esutils.code.isHexDigit(ch)) {
105477 break;
105478 }
105479
105480 number += advance();
105481 }
105482
105483 if (number.length <= 2) {
105484 // only 0x
105485 utility.throwError('unexpected token');
105486 }
105487
105488 if (index < length) {
105489 ch = source.charCodeAt(index);
105490
105491 if (esutils.code.isIdentifierStartES5(ch)) {
105492 utility.throwError('unexpected token');
105493 }
105494 }
105495
105496 value = parseInt(number, 16);
105497 return Token.NUMBER;
105498 }
105499
105500 if (esutils.code.isOctalDigit(ch)) {
105501 number += advance();
105502
105503 while (index < length) {
105504 ch = source.charCodeAt(index);
105505
105506 if (!esutils.code.isOctalDigit(ch)) {
105507 break;
105508 }
105509
105510 number += advance();
105511 }
105512
105513 if (index < length) {
105514 ch = source.charCodeAt(index);
105515
105516 if (esutils.code.isIdentifierStartES5(ch) || esutils.code.isDecimalDigit(ch)) {
105517 utility.throwError('unexpected token');
105518 }
105519 }
105520
105521 value = parseInt(number, 8);
105522 return Token.NUMBER;
105523 }
105524
105525 if (esutils.code.isDecimalDigit(ch)) {
105526 utility.throwError('unexpected token');
105527 }
105528 }
105529
105530 while (index < length) {
105531 ch = source.charCodeAt(index);
105532
105533 if (!esutils.code.isDecimalDigit(ch)) {
105534 break;
105535 }
105536
105537 number += advance();
105538 }
105539 }
105540
105541 if (ch === 0x2E
105542 /* '.' */
105543 ) {
105544 number += advance();
105545
105546 while (index < length) {
105547 ch = source.charCodeAt(index);
105548
105549 if (!esutils.code.isDecimalDigit(ch)) {
105550 break;
105551 }
105552
105553 number += advance();
105554 }
105555 }
105556
105557 if (ch === 0x65
105558 /* 'e' */
105559 || ch === 0x45
105560 /* 'E' */
105561 ) {
105562 number += advance();
105563 ch = source.charCodeAt(index);
105564
105565 if (ch === 0x2B
105566 /* '+' */
105567 || ch === 0x2D
105568 /* '-' */
105569 ) {
105570 number += advance();
105571 }
105572
105573 ch = source.charCodeAt(index);
105574
105575 if (esutils.code.isDecimalDigit(ch)) {
105576 number += advance();
105577
105578 while (index < length) {
105579 ch = source.charCodeAt(index);
105580
105581 if (!esutils.code.isDecimalDigit(ch)) {
105582 break;
105583 }
105584
105585 number += advance();
105586 }
105587 } else {
105588 utility.throwError('unexpected token');
105589 }
105590 }
105591
105592 if (index < length) {
105593 ch = source.charCodeAt(index);
105594
105595 if (esutils.code.isIdentifierStartES5(ch)) {
105596 utility.throwError('unexpected token');
105597 }
105598 }
105599
105600 value = parseFloat(number);
105601 return Token.NUMBER;
105602 }
105603
105604 function scanTypeName() {
105605 var ch, ch2;
105606 value = advance();
105607
105608 while (index < length && isTypeName(source.charCodeAt(index))) {
105609 ch = source.charCodeAt(index);
105610
105611 if (ch === 0x2E
105612 /* '.' */
105613 ) {
105614 if (index + 1 >= length) {
105615 return Token.ILLEGAL;
105616 }
105617
105618 ch2 = source.charCodeAt(index + 1);
105619
105620 if (ch2 === 0x3C
105621 /* '<' */
105622 ) {
105623 break;
105624 }
105625 }
105626
105627 value += advance();
105628 }
105629
105630 return Token.NAME;
105631 }
105632
105633 function next() {
105634 var ch;
105635 previous = index;
105636
105637 while (index < length && esutils.code.isWhiteSpace(source.charCodeAt(index))) {
105638 advance();
105639 }
105640
105641 if (index >= length) {
105642 token = Token.EOF;
105643 return token;
105644 }
105645
105646 ch = source.charCodeAt(index);
105647
105648 switch (ch) {
105649 case 0x27:
105650 /* ''' */
105651
105652 case 0x22:
105653 /* '"' */
105654 token = scanString();
105655 return token;
105656
105657 case 0x3A:
105658 /* ':' */
105659 advance();
105660 token = Token.COLON;
105661 return token;
105662
105663 case 0x2C:
105664 /* ',' */
105665 advance();
105666 token = Token.COMMA;
105667 return token;
105668
105669 case 0x28:
105670 /* '(' */
105671 advance();
105672 token = Token.LPAREN;
105673 return token;
105674
105675 case 0x29:
105676 /* ')' */
105677 advance();
105678 token = Token.RPAREN;
105679 return token;
105680
105681 case 0x5B:
105682 /* '[' */
105683 advance();
105684 token = Token.LBRACK;
105685 return token;
105686
105687 case 0x5D:
105688 /* ']' */
105689 advance();
105690 token = Token.RBRACK;
105691 return token;
105692
105693 case 0x7B:
105694 /* '{' */
105695 advance();
105696 token = Token.LBRACE;
105697 return token;
105698
105699 case 0x7D:
105700 /* '}' */
105701 advance();
105702 token = Token.RBRACE;
105703 return token;
105704
105705 case 0x2E:
105706 /* '.' */
105707 if (index + 1 < length) {
105708 ch = source.charCodeAt(index + 1);
105709
105710 if (ch === 0x3C
105711 /* '<' */
105712 ) {
105713 advance(); // '.'
105714
105715 advance(); // '<'
105716
105717 token = Token.DOT_LT;
105718 return token;
105719 }
105720
105721 if (ch === 0x2E
105722 /* '.' */
105723 && index + 2 < length && source.charCodeAt(index + 2) === 0x2E
105724 /* '.' */
105725 ) {
105726 advance(); // '.'
105727
105728 advance(); // '.'
105729
105730 advance(); // '.'
105731
105732 token = Token.REST;
105733 return token;
105734 }
105735
105736 if (esutils.code.isDecimalDigit(ch)) {
105737 token = scanNumber();
105738 return token;
105739 }
105740 }
105741
105742 token = Token.ILLEGAL;
105743 return token;
105744
105745 case 0x3C:
105746 /* '<' */
105747 advance();
105748 token = Token.LT;
105749 return token;
105750
105751 case 0x3E:
105752 /* '>' */
105753 advance();
105754 token = Token.GT;
105755 return token;
105756
105757 case 0x2A:
105758 /* '*' */
105759 advance();
105760 token = Token.STAR;
105761 return token;
105762
105763 case 0x7C:
105764 /* '|' */
105765 advance();
105766 token = Token.PIPE;
105767 return token;
105768
105769 case 0x3F:
105770 /* '?' */
105771 advance();
105772 token = Token.QUESTION;
105773 return token;
105774
105775 case 0x21:
105776 /* '!' */
105777 advance();
105778 token = Token.BANG;
105779 return token;
105780
105781 case 0x3D:
105782 /* '=' */
105783 advance();
105784 token = Token.EQUAL;
105785 return token;
105786
105787 case 0x2D:
105788 /* '-' */
105789 token = scanNumber();
105790 return token;
105791
105792 default:
105793 if (esutils.code.isDecimalDigit(ch)) {
105794 token = scanNumber();
105795 return token;
105796 } // type string permits following case,
105797 //
105798 // namespace.module.MyClass
105799 //
105800 // this reduced 1 token TK_NAME
105801
105802
105803 utility.assert(isTypeName(ch));
105804 token = scanTypeName();
105805 return token;
105806 }
105807 }
105808
105809 function consume(target, text) {
105810 utility.assert(token === target, text || 'consumed token not matched');
105811 next();
105812 }
105813
105814 function expect(target, message) {
105815 if (token !== target) {
105816 utility.throwError(message || 'unexpected token');
105817 }
105818
105819 next();
105820 } // UnionType := '(' TypeUnionList ')'
105821 //
105822 // TypeUnionList :=
105823 // <<empty>>
105824 // | NonemptyTypeUnionList
105825 //
105826 // NonemptyTypeUnionList :=
105827 // TypeExpression
105828 // | TypeExpression '|' NonemptyTypeUnionList
105829
105830
105831 function parseUnionType() {
105832 var elements,
105833 startIndex = index - 1;
105834 consume(Token.LPAREN, 'UnionType should start with (');
105835 elements = [];
105836
105837 if (token !== Token.RPAREN) {
105838 while (true) {
105839 elements.push(parseTypeExpression());
105840
105841 if (token === Token.RPAREN) {
105842 break;
105843 }
105844
105845 expect(Token.PIPE);
105846 }
105847 }
105848
105849 consume(Token.RPAREN, 'UnionType should end with )');
105850 return maybeAddRange({
105851 type: Syntax.UnionType,
105852 elements: elements
105853 }, [startIndex, previous]);
105854 } // ArrayType := '[' ElementTypeList ']'
105855 //
105856 // ElementTypeList :=
105857 // <<empty>>
105858 // | TypeExpression
105859 // | '...' TypeExpression
105860 // | TypeExpression ',' ElementTypeList
105861
105862
105863 function parseArrayType() {
105864 var elements,
105865 startIndex = index - 1,
105866 restStartIndex;
105867 consume(Token.LBRACK, 'ArrayType should start with [');
105868 elements = [];
105869
105870 while (token !== Token.RBRACK) {
105871 if (token === Token.REST) {
105872 restStartIndex = index - 3;
105873 consume(Token.REST);
105874 elements.push(maybeAddRange({
105875 type: Syntax.RestType,
105876 expression: parseTypeExpression()
105877 }, [restStartIndex, previous]));
105878 break;
105879 } else {
105880 elements.push(parseTypeExpression());
105881 }
105882
105883 if (token !== Token.RBRACK) {
105884 expect(Token.COMMA);
105885 }
105886 }
105887
105888 expect(Token.RBRACK);
105889 return maybeAddRange({
105890 type: Syntax.ArrayType,
105891 elements: elements
105892 }, [startIndex, previous]);
105893 }
105894
105895 function parseFieldName() {
105896 var v = value;
105897
105898 if (token === Token.NAME || token === Token.STRING) {
105899 next();
105900 return v;
105901 }
105902
105903 if (token === Token.NUMBER) {
105904 consume(Token.NUMBER);
105905 return String(v);
105906 }
105907
105908 utility.throwError('unexpected token');
105909 } // FieldType :=
105910 // FieldName
105911 // | FieldName ':' TypeExpression
105912 //
105913 // FieldName :=
105914 // NameExpression
105915 // | StringLiteral
105916 // | NumberLiteral
105917 // | ReservedIdentifier
105918
105919
105920 function parseFieldType() {
105921 var key,
105922 rangeStart = previous;
105923 key = parseFieldName();
105924
105925 if (token === Token.COLON) {
105926 consume(Token.COLON);
105927 return maybeAddRange({
105928 type: Syntax.FieldType,
105929 key: key,
105930 value: parseTypeExpression()
105931 }, [rangeStart, previous]);
105932 }
105933
105934 return maybeAddRange({
105935 type: Syntax.FieldType,
105936 key: key,
105937 value: null
105938 }, [rangeStart, previous]);
105939 } // RecordType := '{' FieldTypeList '}'
105940 //
105941 // FieldTypeList :=
105942 // <<empty>>
105943 // | FieldType
105944 // | FieldType ',' FieldTypeList
105945
105946
105947 function parseRecordType() {
105948 var fields,
105949 rangeStart = index - 1,
105950 rangeEnd;
105951 consume(Token.LBRACE, 'RecordType should start with {');
105952 fields = [];
105953
105954 if (token === Token.COMMA) {
105955 consume(Token.COMMA);
105956 } else {
105957 while (token !== Token.RBRACE) {
105958 fields.push(parseFieldType());
105959
105960 if (token !== Token.RBRACE) {
105961 expect(Token.COMMA);
105962 }
105963 }
105964 }
105965
105966 rangeEnd = index;
105967 expect(Token.RBRACE);
105968 return maybeAddRange({
105969 type: Syntax.RecordType,
105970 fields: fields
105971 }, [rangeStart, rangeEnd]);
105972 } // NameExpression :=
105973 // Identifier
105974 // | TagIdentifier ':' Identifier
105975 //
105976 // Tag identifier is one of "module", "external" or "event"
105977 // Identifier is the same as Token.NAME, including any dots, something like
105978 // namespace.module.MyClass
105979
105980
105981 function parseNameExpression() {
105982 var name = value,
105983 rangeStart = index - name.length;
105984 expect(Token.NAME);
105985
105986 if (token === Token.COLON && (name === 'module' || name === 'external' || name === 'event')) {
105987 consume(Token.COLON);
105988 name += ':' + value;
105989 expect(Token.NAME);
105990 }
105991
105992 return maybeAddRange({
105993 type: Syntax.NameExpression,
105994 name: name
105995 }, [rangeStart, previous]);
105996 } // TypeExpressionList :=
105997 // TopLevelTypeExpression
105998 // | TopLevelTypeExpression ',' TypeExpressionList
105999
106000
106001 function parseTypeExpressionList() {
106002 var elements = [];
106003 elements.push(parseTop());
106004
106005 while (token === Token.COMMA) {
106006 consume(Token.COMMA);
106007 elements.push(parseTop());
106008 }
106009
106010 return elements;
106011 } // TypeName :=
106012 // NameExpression
106013 // | NameExpression TypeApplication
106014 //
106015 // TypeApplication :=
106016 // '.<' TypeExpressionList '>'
106017 // | '<' TypeExpressionList '>' // this is extension of doctrine
106018
106019
106020 function parseTypeName() {
106021 var expr,
106022 applications,
106023 startIndex = index - value.length;
106024 expr = parseNameExpression();
106025
106026 if (token === Token.DOT_LT || token === Token.LT) {
106027 next();
106028 applications = parseTypeExpressionList();
106029 expect(Token.GT);
106030 return maybeAddRange({
106031 type: Syntax.TypeApplication,
106032 expression: expr,
106033 applications: applications
106034 }, [startIndex, previous]);
106035 }
106036
106037 return expr;
106038 } // ResultType :=
106039 // <<empty>>
106040 // | ':' void
106041 // | ':' TypeExpression
106042 //
106043 // BNF is above
106044 // but, we remove <<empty>> pattern, so token is always TypeToken::COLON
106045
106046
106047 function parseResultType() {
106048 consume(Token.COLON, 'ResultType should start with :');
106049
106050 if (token === Token.NAME && value === 'void') {
106051 consume(Token.NAME);
106052 return {
106053 type: Syntax.VoidLiteral
106054 };
106055 }
106056
106057 return parseTypeExpression();
106058 } // ParametersType :=
106059 // RestParameterType
106060 // | NonRestParametersType
106061 // | NonRestParametersType ',' RestParameterType
106062 //
106063 // RestParameterType :=
106064 // '...'
106065 // '...' Identifier
106066 //
106067 // NonRestParametersType :=
106068 // ParameterType ',' NonRestParametersType
106069 // | ParameterType
106070 // | OptionalParametersType
106071 //
106072 // OptionalParametersType :=
106073 // OptionalParameterType
106074 // | OptionalParameterType, OptionalParametersType
106075 //
106076 // OptionalParameterType := ParameterType=
106077 //
106078 // ParameterType := TypeExpression | Identifier ':' TypeExpression
106079 //
106080 // Identifier is "new" or "this"
106081
106082
106083 function parseParametersType() {
106084 var params = [],
106085 optionalSequence = false,
106086 expr,
106087 rest = false,
106088 startIndex,
106089 restStartIndex = index - 3,
106090 nameStartIndex;
106091
106092 while (token !== Token.RPAREN) {
106093 if (token === Token.REST) {
106094 // RestParameterType
106095 consume(Token.REST);
106096 rest = true;
106097 }
106098
106099 startIndex = previous;
106100 expr = parseTypeExpression();
106101
106102 if (expr.type === Syntax.NameExpression && token === Token.COLON) {
106103 nameStartIndex = previous - expr.name.length; // Identifier ':' TypeExpression
106104
106105 consume(Token.COLON);
106106 expr = maybeAddRange({
106107 type: Syntax.ParameterType,
106108 name: expr.name,
106109 expression: parseTypeExpression()
106110 }, [nameStartIndex, previous]);
106111 }
106112
106113 if (token === Token.EQUAL) {
106114 consume(Token.EQUAL);
106115 expr = maybeAddRange({
106116 type: Syntax.OptionalType,
106117 expression: expr
106118 }, [startIndex, previous]);
106119 optionalSequence = true;
106120 } else {
106121 if (optionalSequence) {
106122 utility.throwError('unexpected token');
106123 }
106124 }
106125
106126 if (rest) {
106127 expr = maybeAddRange({
106128 type: Syntax.RestType,
106129 expression: expr
106130 }, [restStartIndex, previous]);
106131 }
106132
106133 params.push(expr);
106134
106135 if (token !== Token.RPAREN) {
106136 expect(Token.COMMA);
106137 }
106138 }
106139
106140 return params;
106141 } // FunctionType := 'function' FunctionSignatureType
106142 //
106143 // FunctionSignatureType :=
106144 // | TypeParameters '(' ')' ResultType
106145 // | TypeParameters '(' ParametersType ')' ResultType
106146 // | TypeParameters '(' 'this' ':' TypeName ')' ResultType
106147 // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType
106148
106149
106150 function parseFunctionType() {
106151 var isNew,
106152 thisBinding,
106153 params,
106154 result,
106155 fnType,
106156 startIndex = index - value.length;
106157 utility.assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\'');
106158 consume(Token.NAME); // Google Closure Compiler is not implementing TypeParameters.
106159 // So we do not. if we don't get '(', we see it as error.
106160
106161 expect(Token.LPAREN);
106162 isNew = false;
106163 params = [];
106164 thisBinding = null;
106165
106166 if (token !== Token.RPAREN) {
106167 // ParametersType or 'this'
106168 if (token === Token.NAME && (value === 'this' || value === 'new')) {
106169 // 'this' or 'new'
106170 // 'new' is Closure Compiler extension
106171 isNew = value === 'new';
106172 consume(Token.NAME);
106173 expect(Token.COLON);
106174 thisBinding = parseTypeName();
106175
106176 if (token === Token.COMMA) {
106177 consume(Token.COMMA);
106178 params = parseParametersType();
106179 }
106180 } else {
106181 params = parseParametersType();
106182 }
106183 }
106184
106185 expect(Token.RPAREN);
106186 result = null;
106187
106188 if (token === Token.COLON) {
106189 result = parseResultType();
106190 }
106191
106192 fnType = maybeAddRange({
106193 type: Syntax.FunctionType,
106194 params: params,
106195 result: result
106196 }, [startIndex, previous]);
106197
106198 if (thisBinding) {
106199 // avoid adding null 'new' and 'this' properties
106200 fnType['this'] = thisBinding;
106201
106202 if (isNew) {
106203 fnType['new'] = true;
106204 }
106205 }
106206
106207 return fnType;
106208 } // BasicTypeExpression :=
106209 // '*'
106210 // | 'null'
106211 // | 'undefined'
106212 // | TypeName
106213 // | FunctionType
106214 // | UnionType
106215 // | RecordType
106216 // | ArrayType
106217
106218
106219 function parseBasicTypeExpression() {
106220 var context, startIndex;
106221
106222 switch (token) {
106223 case Token.STAR:
106224 consume(Token.STAR);
106225 return maybeAddRange({
106226 type: Syntax.AllLiteral
106227 }, [previous - 1, previous]);
106228
106229 case Token.LPAREN:
106230 return parseUnionType();
106231
106232 case Token.LBRACK:
106233 return parseArrayType();
106234
106235 case Token.LBRACE:
106236 return parseRecordType();
106237
106238 case Token.NAME:
106239 startIndex = index - value.length;
106240
106241 if (value === 'null') {
106242 consume(Token.NAME);
106243 return maybeAddRange({
106244 type: Syntax.NullLiteral
106245 }, [startIndex, previous]);
106246 }
106247
106248 if (value === 'undefined') {
106249 consume(Token.NAME);
106250 return maybeAddRange({
106251 type: Syntax.UndefinedLiteral
106252 }, [startIndex, previous]);
106253 }
106254
106255 if (value === 'true' || value === 'false') {
106256 consume(Token.NAME);
106257 return maybeAddRange({
106258 type: Syntax.BooleanLiteralType,
106259 value: value === 'true'
106260 }, [startIndex, previous]);
106261 }
106262
106263 context = Context.save();
106264
106265 if (value === 'function') {
106266 try {
106267 return parseFunctionType();
106268 } catch (e) {
106269 context.restore();
106270 }
106271 }
106272
106273 return parseTypeName();
106274
106275 case Token.STRING:
106276 next();
106277 return maybeAddRange({
106278 type: Syntax.StringLiteralType,
106279 value: value
106280 }, [previous - value.length - 2, previous]);
106281
106282 case Token.NUMBER:
106283 next();
106284 return maybeAddRange({
106285 type: Syntax.NumericLiteralType,
106286 value: value
106287 }, [previous - String(value).length, previous]);
106288
106289 default:
106290 utility.throwError('unexpected token');
106291 }
106292 } // TypeExpression :=
106293 // BasicTypeExpression
106294 // | '?' BasicTypeExpression
106295 // | '!' BasicTypeExpression
106296 // | BasicTypeExpression '?'
106297 // | BasicTypeExpression '!'
106298 // | '?'
106299 // | BasicTypeExpression '[]'
106300
106301
106302 function parseTypeExpression() {
106303 var expr, rangeStart;
106304
106305 if (token === Token.QUESTION) {
106306 rangeStart = index - 1;
106307 consume(Token.QUESTION);
106308
106309 if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE || token === Token.RPAREN || token === Token.PIPE || token === Token.EOF || token === Token.RBRACK || token === Token.GT) {
106310 return maybeAddRange({
106311 type: Syntax.NullableLiteral
106312 }, [rangeStart, previous]);
106313 }
106314
106315 return maybeAddRange({
106316 type: Syntax.NullableType,
106317 expression: parseBasicTypeExpression(),
106318 prefix: true
106319 }, [rangeStart, previous]);
106320 } else if (token === Token.BANG) {
106321 rangeStart = index - 1;
106322 consume(Token.BANG);
106323 return maybeAddRange({
106324 type: Syntax.NonNullableType,
106325 expression: parseBasicTypeExpression(),
106326 prefix: true
106327 }, [rangeStart, previous]);
106328 } else {
106329 rangeStart = previous;
106330 }
106331
106332 expr = parseBasicTypeExpression();
106333
106334 if (token === Token.BANG) {
106335 consume(Token.BANG);
106336 return maybeAddRange({
106337 type: Syntax.NonNullableType,
106338 expression: expr,
106339 prefix: false
106340 }, [rangeStart, previous]);
106341 }
106342
106343 if (token === Token.QUESTION) {
106344 consume(Token.QUESTION);
106345 return maybeAddRange({
106346 type: Syntax.NullableType,
106347 expression: expr,
106348 prefix: false
106349 }, [rangeStart, previous]);
106350 }
106351
106352 if (token === Token.LBRACK) {
106353 consume(Token.LBRACK);
106354 expect(Token.RBRACK, 'expected an array-style type declaration (' + value + '[])');
106355 return maybeAddRange({
106356 type: Syntax.TypeApplication,
106357 expression: maybeAddRange({
106358 type: Syntax.NameExpression,
106359 name: 'Array'
106360 }, [rangeStart, previous]),
106361 applications: [expr]
106362 }, [rangeStart, previous]);
106363 }
106364
106365 return expr;
106366 } // TopLevelTypeExpression :=
106367 // TypeExpression
106368 // | TypeUnionList
106369 //
106370 // This rule is Google Closure Compiler extension, not ES4
106371 // like,
106372 // { number | string }
106373 // If strict to ES4, we should write it as
106374 // { (number|string) }
106375
106376
106377 function parseTop() {
106378 var expr, elements;
106379 expr = parseTypeExpression();
106380
106381 if (token !== Token.PIPE) {
106382 return expr;
106383 }
106384
106385 elements = [expr];
106386 consume(Token.PIPE);
106387
106388 while (true) {
106389 elements.push(parseTypeExpression());
106390
106391 if (token !== Token.PIPE) {
106392 break;
106393 }
106394
106395 consume(Token.PIPE);
106396 }
106397
106398 return maybeAddRange({
106399 type: Syntax.UnionType,
106400 elements: elements
106401 }, [0, index]);
106402 }
106403
106404 function parseTopParamType() {
106405 var expr;
106406
106407 if (token === Token.REST) {
106408 consume(Token.REST);
106409 return maybeAddRange({
106410 type: Syntax.RestType,
106411 expression: parseTop()
106412 }, [0, index]);
106413 }
106414
106415 expr = parseTop();
106416
106417 if (token === Token.EQUAL) {
106418 consume(Token.EQUAL);
106419 return maybeAddRange({
106420 type: Syntax.OptionalType,
106421 expression: expr
106422 }, [0, index]);
106423 }
106424
106425 return expr;
106426 }
106427
106428 function parseType(src, opt) {
106429 var expr;
106430 source = src;
106431 length = source.length;
106432 index = 0;
106433 previous = 0;
106434 addRange = opt && opt.range;
106435 rangeOffset = opt && opt.startIndex || 0;
106436 next();
106437 expr = parseTop();
106438
106439 if (opt && opt.midstream) {
106440 return {
106441 expression: expr,
106442 index: previous
106443 };
106444 }
106445
106446 if (token !== Token.EOF) {
106447 utility.throwError('not reach to EOF');
106448 }
106449
106450 return expr;
106451 }
106452
106453 function parseParamType(src, opt) {
106454 var expr;
106455 source = src;
106456 length = source.length;
106457 index = 0;
106458 previous = 0;
106459 addRange = opt && opt.range;
106460 rangeOffset = opt && opt.startIndex || 0;
106461 next();
106462 expr = parseTopParamType();
106463
106464 if (opt && opt.midstream) {
106465 return {
106466 expression: expr,
106467 index: previous
106468 };
106469 }
106470
106471 if (token !== Token.EOF) {
106472 utility.throwError('not reach to EOF');
106473 }
106474
106475 return expr;
106476 }
106477
106478 function stringifyImpl(node, compact, topLevel) {
106479 var result, i, iz;
106480
106481 switch (node.type) {
106482 case Syntax.NullableLiteral:
106483 result = '?';
106484 break;
106485
106486 case Syntax.AllLiteral:
106487 result = '*';
106488 break;
106489
106490 case Syntax.NullLiteral:
106491 result = 'null';
106492 break;
106493
106494 case Syntax.UndefinedLiteral:
106495 result = 'undefined';
106496 break;
106497
106498 case Syntax.VoidLiteral:
106499 result = 'void';
106500 break;
106501
106502 case Syntax.UnionType:
106503 if (!topLevel) {
106504 result = '(';
106505 } else {
106506 result = '';
106507 }
106508
106509 for (i = 0, iz = node.elements.length; i < iz; ++i) {
106510 result += stringifyImpl(node.elements[i], compact);
106511
106512 if (i + 1 !== iz) {
106513 result += compact ? '|' : ' | ';
106514 }
106515 }
106516
106517 if (!topLevel) {
106518 result += ')';
106519 }
106520
106521 break;
106522
106523 case Syntax.ArrayType:
106524 result = '[';
106525
106526 for (i = 0, iz = node.elements.length; i < iz; ++i) {
106527 result += stringifyImpl(node.elements[i], compact);
106528
106529 if (i + 1 !== iz) {
106530 result += compact ? ',' : ', ';
106531 }
106532 }
106533
106534 result += ']';
106535 break;
106536
106537 case Syntax.RecordType:
106538 result = '{';
106539
106540 for (i = 0, iz = node.fields.length; i < iz; ++i) {
106541 result += stringifyImpl(node.fields[i], compact);
106542
106543 if (i + 1 !== iz) {
106544 result += compact ? ',' : ', ';
106545 }
106546 }
106547
106548 result += '}';
106549 break;
106550
106551 case Syntax.FieldType:
106552 if (node.value) {
106553 result = node.key + (compact ? ':' : ': ') + stringifyImpl(node.value, compact);
106554 } else {
106555 result = node.key;
106556 }
106557
106558 break;
106559
106560 case Syntax.FunctionType:
106561 result = compact ? 'function(' : 'function (';
106562
106563 if (node['this']) {
106564 if (node['new']) {
106565 result += compact ? 'new:' : 'new: ';
106566 } else {
106567 result += compact ? 'this:' : 'this: ';
106568 }
106569
106570 result += stringifyImpl(node['this'], compact);
106571
106572 if (node.params.length !== 0) {
106573 result += compact ? ',' : ', ';
106574 }
106575 }
106576
106577 for (i = 0, iz = node.params.length; i < iz; ++i) {
106578 result += stringifyImpl(node.params[i], compact);
106579
106580 if (i + 1 !== iz) {
106581 result += compact ? ',' : ', ';
106582 }
106583 }
106584
106585 result += ')';
106586
106587 if (node.result) {
106588 result += (compact ? ':' : ': ') + stringifyImpl(node.result, compact);
106589 }
106590
106591 break;
106592
106593 case Syntax.ParameterType:
106594 result = node.name + (compact ? ':' : ': ') + stringifyImpl(node.expression, compact);
106595 break;
106596
106597 case Syntax.RestType:
106598 result = '...';
106599
106600 if (node.expression) {
106601 result += stringifyImpl(node.expression, compact);
106602 }
106603
106604 break;
106605
106606 case Syntax.NonNullableType:
106607 if (node.prefix) {
106608 result = '!' + stringifyImpl(node.expression, compact);
106609 } else {
106610 result = stringifyImpl(node.expression, compact) + '!';
106611 }
106612
106613 break;
106614
106615 case Syntax.OptionalType:
106616 result = stringifyImpl(node.expression, compact) + '=';
106617 break;
106618
106619 case Syntax.NullableType:
106620 if (node.prefix) {
106621 result = '?' + stringifyImpl(node.expression, compact);
106622 } else {
106623 result = stringifyImpl(node.expression, compact) + '?';
106624 }
106625
106626 break;
106627
106628 case Syntax.NameExpression:
106629 result = node.name;
106630 break;
106631
106632 case Syntax.TypeApplication:
106633 result = stringifyImpl(node.expression, compact) + '.<';
106634
106635 for (i = 0, iz = node.applications.length; i < iz; ++i) {
106636 result += stringifyImpl(node.applications[i], compact);
106637
106638 if (i + 1 !== iz) {
106639 result += compact ? ',' : ', ';
106640 }
106641 }
106642
106643 result += '>';
106644 break;
106645
106646 case Syntax.StringLiteralType:
106647 result = '"' + node.value + '"';
106648 break;
106649
106650 case Syntax.NumericLiteralType:
106651 result = String(node.value);
106652 break;
106653
106654 case Syntax.BooleanLiteralType:
106655 result = String(node.value);
106656 break;
106657
106658 default:
106659 utility.throwError('Unknown type ' + node.type);
106660 }
106661
106662 return result;
106663 }
106664
106665 function stringify(node, options) {
106666 if (options == null) {
106667 options = {};
106668 }
106669
106670 return stringifyImpl(node, options.compact, options.topLevel);
106671 }
106672
106673 exports.parseType = parseType;
106674 exports.parseParamType = parseParamType;
106675 exports.stringify = stringify;
106676 exports.Syntax = Syntax;
106677})();
106678/* vim: set sw=4 ts=4 et tw=80 : */
106679
106680/***/ }),
6a5a0f88 106681/* 719 */
eb39fafa
DC
106682/***/ (function(module, exports, __webpack_require__) {
106683
106684/*
106685 * @fileoverview Utilities for Doctrine
106686 * @author Yusuke Suzuki <utatane.tea@gmail.com>
106687 */
106688(function () {
106689 'use strict';
106690
106691 var VERSION;
6a5a0f88 106692 VERSION = __webpack_require__(720).version;
eb39fafa
DC
106693 exports.VERSION = VERSION;
106694
106695 function DoctrineError(message) {
106696 this.name = 'DoctrineError';
106697 this.message = message;
106698 }
106699
106700 DoctrineError.prototype = function () {
106701 var Middle = function Middle() {};
106702
106703 Middle.prototype = Error.prototype;
106704 return new Middle();
106705 }();
106706
106707 DoctrineError.prototype.constructor = DoctrineError;
106708 exports.DoctrineError = DoctrineError;
106709
106710 function throwError(message) {
106711 throw new DoctrineError(message);
106712 }
106713
106714 exports.throwError = throwError;
106715 exports.assert = __webpack_require__(379);
106716})();
106717/* vim: set sw=4 ts=4 et tw=80 : */
106718
106719/***/ }),
6a5a0f88 106720/* 720 */
eb39fafa
DC
106721/***/ (function(module) {
106722
6a5a0f88 106723module.exports = JSON.parse("{\"_from\":\"doctrine@^3.0.0\",\"_id\":\"doctrine@3.0.0\",\"_inBundle\":false,\"_integrity\":\"sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==\",\"_location\":\"/doctrine\",\"_phantomChildren\":{},\"_requested\":{\"type\":\"range\",\"registry\":true,\"raw\":\"doctrine@^3.0.0\",\"name\":\"doctrine\",\"escapedName\":\"doctrine\",\"rawSpec\":\"^3.0.0\",\"saveSpec\":null,\"fetchSpec\":\"^3.0.0\"},\"_requiredBy\":[\"/\",\"/eslint\"],\"_resolved\":\"https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz\",\"_shasum\":\"addebead72a6574db783639dc87a121773973961\",\"_spec\":\"doctrine@^3.0.0\",\"_where\":\"/root/sources/pve/pve-eslint/eslint-v7.1.0\",\"bugs\":{\"url\":\"https://github.com/eslint/doctrine/issues\"},\"bundleDependencies\":false,\"dependencies\":{\"esutils\":\"^2.0.2\"},\"deprecated\":false,\"description\":\"JSDoc parser\",\"devDependencies\":{\"coveralls\":\"^3.0.1\",\"dateformat\":\"^1.0.11\",\"eslint\":\"^1.10.3\",\"eslint-release\":\"^1.0.0\",\"linefix\":\"^0.1.1\",\"mocha\":\"^3.4.2\",\"npm-license\":\"^0.3.1\",\"nyc\":\"^10.3.2\",\"semver\":\"^5.0.3\",\"shelljs\":\"^0.5.3\",\"shelljs-nodecli\":\"^0.1.1\",\"should\":\"^5.0.1\"},\"directories\":{\"lib\":\"./lib\"},\"engines\":{\"node\":\">=6.0.0\"},\"files\":[\"lib\"],\"homepage\":\"https://github.com/eslint/doctrine\",\"license\":\"Apache-2.0\",\"main\":\"lib/doctrine.js\",\"maintainers\":[{\"name\":\"Nicholas C. Zakas\",\"email\":\"nicholas+npm@nczconsulting.com\",\"url\":\"https://www.nczonline.net\"},{\"name\":\"Yusuke Suzuki\",\"email\":\"utatane.tea@gmail.com\",\"url\":\"https://github.com/Constellation\"}],\"name\":\"doctrine\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/eslint/doctrine.git\"},\"scripts\":{\"coveralls\":\"nyc report --reporter=text-lcov | coveralls\",\"generate-alpharelease\":\"eslint-generate-prerelease alpha\",\"generate-betarelease\":\"eslint-generate-prerelease beta\",\"generate-rcrelease\":\"eslint-generate-prerelease rc\",\"generate-release\":\"eslint-generate-release\",\"lint\":\"eslint lib/\",\"pretest\":\"npm run lint\",\"publish-release\":\"eslint-publish-release\",\"test\":\"nyc mocha\"},\"version\":\"3.0.0\"}");
eb39fafa
DC
106724
106725/***/ }),
6a5a0f88 106726/* 721 */
eb39fafa
DC
106727/***/ (function(module, exports, __webpack_require__) {
106728
106729"use strict";
106730/**
106731 * @fileoverview Ensures that the results of typeof are compared against a valid string
106732 * @author Ian Christian Myers
106733 */
106734 //------------------------------------------------------------------------------
106735// Rule Definition
106736//------------------------------------------------------------------------------
106737
106738module.exports = {
106739 meta: {
106740 type: "problem",
106741 docs: {
106742 description: "enforce comparing `typeof` expressions against valid strings",
106743 category: "Possible Errors",
106744 recommended: true,
106745 url: "https://eslint.org/docs/rules/valid-typeof"
106746 },
106747 schema: [{
106748 type: "object",
106749 properties: {
106750 requireStringLiterals: {
106751 type: "boolean",
106752 default: false
106753 }
106754 },
106755 additionalProperties: false
106756 }],
106757 messages: {
106758 invalidValue: "Invalid typeof comparison value.",
106759 notString: "Typeof comparisons should be to string literals."
106760 }
106761 },
106762
106763 create(context) {
106764 const VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function", "bigint"],
106765 OPERATORS = ["==", "===", "!=", "!=="];
106766 const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals;
106767 /**
106768 * Determines whether a node is a typeof expression.
106769 * @param {ASTNode} node The node
106770 * @returns {boolean} `true` if the node is a typeof expression
106771 */
106772
106773 function isTypeofExpression(node) {
106774 return node.type === "UnaryExpression" && node.operator === "typeof";
106775 } //--------------------------------------------------------------------------
106776 // Public
106777 //--------------------------------------------------------------------------
106778
106779
106780 return {
106781 UnaryExpression(node) {
106782 if (isTypeofExpression(node)) {
106783 const parent = context.getAncestors().pop();
106784
106785 if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) {
106786 const sibling = parent.left === node ? parent.right : parent.left;
106787
106788 if (sibling.type === "Literal" || sibling.type === "TemplateLiteral" && !sibling.expressions.length) {
106789 const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked;
106790
106791 if (VALID_TYPES.indexOf(value) === -1) {
106792 context.report({
106793 node: sibling,
106794 messageId: "invalidValue"
106795 });
106796 }
106797 } else if (requireStringLiterals && !isTypeofExpression(sibling)) {
106798 context.report({
106799 node: sibling,
106800 messageId: "notString"
106801 });
106802 }
106803 }
106804 }
106805 }
106806
106807 };
106808 }
106809
106810};
106811
106812/***/ }),
6a5a0f88 106813/* 722 */
eb39fafa
DC
106814/***/ (function(module, exports, __webpack_require__) {
106815
106816"use strict";
106817/**
106818 * @fileoverview Rule to enforce var declarations are only at the top of a function.
106819 * @author Danny Fritz
106820 * @author Gyandeep Singh
106821 */
106822 //------------------------------------------------------------------------------
106823// Rule Definition
106824//------------------------------------------------------------------------------
106825
106826module.exports = {
106827 meta: {
106828 type: "suggestion",
106829 docs: {
106830 description: "require `var` declarations be placed at the top of their containing scope",
106831 category: "Best Practices",
106832 recommended: false,
106833 url: "https://eslint.org/docs/rules/vars-on-top"
106834 },
106835 schema: [],
106836 messages: {
106837 top: "All 'var' declarations must be at the top of the function scope."
106838 }
106839 },
106840
106841 create(context) {
106842 //--------------------------------------------------------------------------
106843 // Helpers
106844 //--------------------------------------------------------------------------
106845 // eslint-disable-next-line jsdoc/require-description
106846
106847 /**
106848 * @param {ASTNode} node any node
106849 * @returns {boolean} whether the given node structurally represents a directive
106850 */
106851 function looksLikeDirective(node) {
106852 return node.type === "ExpressionStatement" && node.expression.type === "Literal" && typeof node.expression.value === "string";
106853 }
106854 /**
106855 * Check to see if its a ES6 import declaration
106856 * @param {ASTNode} node any node
106857 * @returns {boolean} whether the given node represents a import declaration
106858 */
106859
106860
106861 function looksLikeImport(node) {
106862 return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" || node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier";
106863 }
106864 /**
106865 * Checks whether a given node is a variable declaration or not.
106866 * @param {ASTNode} node any node
106867 * @returns {boolean} `true` if the node is a variable declaration.
106868 */
106869
106870
106871 function isVariableDeclaration(node) {
106872 return node.type === "VariableDeclaration" || node.type === "ExportNamedDeclaration" && node.declaration && node.declaration.type === "VariableDeclaration";
106873 }
106874 /**
106875 * Checks whether this variable is on top of the block body
106876 * @param {ASTNode} node The node to check
106877 * @param {ASTNode[]} statements collection of ASTNodes for the parent node block
106878 * @returns {boolean} True if var is on top otherwise false
106879 */
106880
106881
106882 function isVarOnTop(node, statements) {
106883 const l = statements.length;
106884 let i = 0; // skip over directives
106885
106886 for (; i < l; ++i) {
106887 if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) {
106888 break;
106889 }
106890 }
106891
106892 for (; i < l; ++i) {
106893 if (!isVariableDeclaration(statements[i])) {
106894 return false;
106895 }
106896
106897 if (statements[i] === node) {
106898 return true;
106899 }
106900 }
106901
106902 return false;
106903 }
106904 /**
106905 * Checks whether variable is on top at the global level
106906 * @param {ASTNode} node The node to check
106907 * @param {ASTNode} parent Parent of the node
106908 * @returns {void}
106909 */
106910
106911
106912 function globalVarCheck(node, parent) {
106913 if (!isVarOnTop(node, parent.body)) {
106914 context.report({
106915 node,
106916 messageId: "top"
106917 });
106918 }
106919 }
106920 /**
106921 * Checks whether variable is on top at functional block scope level
106922 * @param {ASTNode} node The node to check
106923 * @param {ASTNode} parent Parent of the node
106924 * @param {ASTNode} grandParent Parent of the node's parent
106925 * @returns {void}
106926 */
106927
106928
106929 function blockScopeVarCheck(node, parent, grandParent) {
106930 if (!(/Function/u.test(grandParent.type) && parent.type === "BlockStatement" && isVarOnTop(node, parent.body))) {
106931 context.report({
106932 node,
106933 messageId: "top"
106934 });
106935 }
106936 } //--------------------------------------------------------------------------
106937 // Public API
106938 //--------------------------------------------------------------------------
106939
106940
106941 return {
106942 "VariableDeclaration[kind='var']"(node) {
106943 if (node.parent.type === "ExportNamedDeclaration") {
106944 globalVarCheck(node.parent, node.parent.parent);
106945 } else if (node.parent.type === "Program") {
106946 globalVarCheck(node, node.parent);
106947 } else {
106948 blockScopeVarCheck(node, node.parent, node.parent.parent);
106949 }
106950 }
106951
106952 };
106953 }
106954
106955};
106956
106957/***/ }),
6a5a0f88 106958/* 723 */
eb39fafa
DC
106959/***/ (function(module, exports, __webpack_require__) {
106960
106961"use strict";
106962/**
106963 * @fileoverview Rule to flag when IIFE is not wrapped in parens
106964 * @author Ilya Volodin
106965 */
106966 //------------------------------------------------------------------------------
106967// Requirements
106968//------------------------------------------------------------------------------
106969
106970const astUtils = __webpack_require__(426);
106971
106972const eslintUtils = __webpack_require__(549); //----------------------------------------------------------------------
106973// Helpers
106974//----------------------------------------------------------------------
106975
106976/**
106977 * Check if the given node is callee of a `NewExpression` node
106978 * @param {ASTNode} node node to check
106979 * @returns {boolean} True if the node is callee of a `NewExpression` node
106980 * @private
106981 */
106982
106983
106984function isCalleeOfNewExpression(node) {
106985 return node.parent.type === "NewExpression" && node.parent.callee === node;
106986} //------------------------------------------------------------------------------
106987// Rule Definition
106988//------------------------------------------------------------------------------
106989
106990
106991module.exports = {
106992 meta: {
106993 type: "layout",
106994 docs: {
106995 description: "require parentheses around immediate `function` invocations",
106996 category: "Best Practices",
106997 recommended: false,
106998 url: "https://eslint.org/docs/rules/wrap-iife"
106999 },
107000 schema: [{
107001 enum: ["outside", "inside", "any"]
107002 }, {
107003 type: "object",
107004 properties: {
107005 functionPrototypeMethods: {
107006 type: "boolean",
107007 default: false
107008 }
107009 },
107010 additionalProperties: false
107011 }],
107012 fixable: "code",
107013 messages: {
107014 wrapInvocation: "Wrap an immediate function invocation in parentheses.",
107015 wrapExpression: "Wrap only the function expression in parens.",
107016 moveInvocation: "Move the invocation into the parens that contain the function."
107017 }
107018 },
107019
107020 create(context) {
107021 const style = context.options[0] || "outside";
107022 const includeFunctionPrototypeMethods = context.options[1] && context.options[1].functionPrototypeMethods;
107023 const sourceCode = context.getSourceCode();
107024 /**
107025 * Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if()
107026 * @param {ASTNode} node node to evaluate
107027 * @returns {boolean} True if it is wrapped in any parens
107028 * @private
107029 */
107030
107031 function isWrappedInAnyParens(node) {
107032 return astUtils.isParenthesised(sourceCode, node);
107033 }
107034 /**
107035 * Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count
107036 * @param {ASTNode} node node to evaluate
107037 * @returns {boolean} True if it is wrapped in grouping parens
107038 * @private
107039 */
107040
107041
107042 function isWrappedInGroupingParens(node) {
107043 return eslintUtils.isParenthesized(1, node, sourceCode);
107044 }
107045 /**
107046 * Get the function node from an IIFE
107047 * @param {ASTNode} node node to evaluate
107048 * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist
107049 */
107050
107051
107052 function getFunctionNodeFromIIFE(node) {
107053 const callee = node.callee;
107054
107055 if (callee.type === "FunctionExpression") {
107056 return callee;
107057 }
107058
107059 if (includeFunctionPrototypeMethods && callee.type === "MemberExpression" && callee.object.type === "FunctionExpression" && (astUtils.getStaticPropertyName(callee) === "call" || astUtils.getStaticPropertyName(callee) === "apply")) {
107060 return callee.object;
107061 }
107062
107063 return null;
107064 }
107065
107066 return {
107067 CallExpression(node) {
107068 const innerNode = getFunctionNodeFromIIFE(node);
107069
107070 if (!innerNode) {
107071 return;
107072 }
107073
107074 const isCallExpressionWrapped = isWrappedInAnyParens(node),
107075 isFunctionExpressionWrapped = isWrappedInAnyParens(innerNode);
107076
107077 if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) {
107078 context.report({
107079 node,
107080 messageId: "wrapInvocation",
107081
107082 fix(fixer) {
107083 const nodeToSurround = style === "inside" ? innerNode : node;
107084 return fixer.replaceText(nodeToSurround, "(".concat(sourceCode.getText(nodeToSurround), ")"));
107085 }
107086
107087 });
107088 } else if (style === "inside" && !isFunctionExpressionWrapped) {
107089 context.report({
107090 node,
107091 messageId: "wrapExpression",
107092
107093 fix(fixer) {
107094 // The outer call expression will always be wrapped at this point.
107095 if (isWrappedInGroupingParens(node) && !isCalleeOfNewExpression(node)) {
107096 /*
107097 * Parenthesize the function expression and remove unnecessary grouping parens around the call expression.
107098 * Replace the range between the end of the function expression and the end of the call expression.
107099 * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`.
107100 */
107101 const parenAfter = sourceCode.getTokenAfter(node);
107102 return fixer.replaceTextRange([innerNode.range[1], parenAfter.range[1]], ")".concat(sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])));
107103 }
107104 /*
107105 * Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens.
107106 * These parens cannot be removed, so just parenthesize the function expression.
107107 */
107108
107109
107110 return fixer.replaceText(innerNode, "(".concat(sourceCode.getText(innerNode), ")"));
107111 }
107112
107113 });
107114 } else if (style === "outside" && !isCallExpressionWrapped) {
107115 context.report({
107116 node,
107117 messageId: "moveInvocation",
107118
107119 fix(fixer) {
107120 /*
107121 * The inner function expression will always be wrapped at this point.
107122 * It's only necessary to replace the range between the end of the function expression
107123 * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)`
107124 * should get replaced with `(bar))`.
107125 */
107126 const parenAfter = sourceCode.getTokenAfter(innerNode);
107127 return fixer.replaceTextRange([parenAfter.range[0], node.range[1]], "".concat(sourceCode.getText().slice(parenAfter.range[1], node.range[1]), ")"));
107128 }
107129
107130 });
107131 }
107132 }
107133
107134 };
107135 }
107136
107137};
107138
107139/***/ }),
6a5a0f88 107140/* 724 */
eb39fafa
DC
107141/***/ (function(module, exports, __webpack_require__) {
107142
107143"use strict";
107144/**
107145 * @fileoverview Rule to flag when regex literals are not wrapped in parens
107146 * @author Matt DuVall <http://www.mattduvall.com>
107147 */
107148 //------------------------------------------------------------------------------
107149// Rule Definition
107150//------------------------------------------------------------------------------
107151
107152module.exports = {
107153 meta: {
107154 type: "layout",
107155 docs: {
107156 description: "require parenthesis around regex literals",
107157 category: "Stylistic Issues",
107158 recommended: false,
107159 url: "https://eslint.org/docs/rules/wrap-regex"
107160 },
107161 schema: [],
107162 fixable: "code",
107163 messages: {
107164 requireParens: "Wrap the regexp literal in parens to disambiguate the slash."
107165 }
107166 },
107167
107168 create(context) {
107169 const sourceCode = context.getSourceCode();
107170 return {
107171 Literal(node) {
107172 const token = sourceCode.getFirstToken(node),
107173 nodeType = token.type;
107174
107175 if (nodeType === "RegularExpression") {
107176 const beforeToken = sourceCode.getTokenBefore(node);
107177 const afterToken = sourceCode.getTokenAfter(node);
107178 const ancestors = context.getAncestors();
107179 const grandparent = ancestors[ancestors.length - 1];
107180
107181 if (grandparent.type === "MemberExpression" && grandparent.object === node && !(beforeToken && beforeToken.value === "(" && afterToken && afterToken.value === ")")) {
107182 context.report({
107183 node,
107184 messageId: "requireParens",
107185 fix: fixer => fixer.replaceText(node, "(".concat(sourceCode.getText(node), ")"))
107186 });
107187 }
107188 }
107189 }
107190
107191 };
107192 }
107193
107194};
107195
107196/***/ }),
6a5a0f88 107197/* 725 */
eb39fafa
DC
107198/***/ (function(module, exports, __webpack_require__) {
107199
107200"use strict";
107201/**
107202 * @fileoverview Rule to check the spacing around the * in yield* expressions.
107203 * @author Bryan Smith
107204 */
107205 //------------------------------------------------------------------------------
107206// Rule Definition
107207//------------------------------------------------------------------------------
107208
107209module.exports = {
107210 meta: {
107211 type: "layout",
107212 docs: {
107213 description: "require or disallow spacing around the `*` in `yield*` expressions",
107214 category: "ECMAScript 6",
107215 recommended: false,
107216 url: "https://eslint.org/docs/rules/yield-star-spacing"
107217 },
107218 fixable: "whitespace",
107219 schema: [{
107220 oneOf: [{
107221 enum: ["before", "after", "both", "neither"]
107222 }, {
107223 type: "object",
107224 properties: {
107225 before: {
107226 type: "boolean"
107227 },
107228 after: {
107229 type: "boolean"
107230 }
107231 },
107232 additionalProperties: false
107233 }]
107234 }],
107235 messages: {
107236 missingBefore: "Missing space before *.",
107237 missingAfter: "Missing space after *.",
107238 unexpectedBefore: "Unexpected space before *.",
107239 unexpectedAfter: "Unexpected space after *."
107240 }
107241 },
107242
107243 create(context) {
107244 const sourceCode = context.getSourceCode();
107245
107246 const mode = function (option) {
107247 if (!option || typeof option === "string") {
107248 return {
107249 before: {
107250 before: true,
107251 after: false
107252 },
107253 after: {
107254 before: false,
107255 after: true
107256 },
107257 both: {
107258 before: true,
107259 after: true
107260 },
107261 neither: {
107262 before: false,
107263 after: false
107264 }
107265 }[option || "after"];
107266 }
107267
107268 return option;
107269 }(context.options[0]);
107270 /**
107271 * Checks the spacing between two tokens before or after the star token.
107272 * @param {string} side Either "before" or "after".
107273 * @param {Token} leftToken `function` keyword token if side is "before", or
107274 * star token if side is "after".
107275 * @param {Token} rightToken Star token if side is "before", or identifier
107276 * token if side is "after".
107277 * @returns {void}
107278 */
107279
107280
107281 function checkSpacing(side, leftToken, rightToken) {
107282 if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken) !== mode[side]) {
107283 const after = leftToken.value === "*";
107284 const spaceRequired = mode[side];
107285 const node = after ? leftToken : rightToken;
107286 let messageId = "";
107287
107288 if (spaceRequired) {
107289 messageId = side === "before" ? "missingBefore" : "missingAfter";
107290 } else {
107291 messageId = side === "before" ? "unexpectedBefore" : "unexpectedAfter";
107292 }
107293
107294 context.report({
107295 node,
107296 messageId,
107297
107298 fix(fixer) {
107299 if (spaceRequired) {
107300 if (after) {
107301 return fixer.insertTextAfter(node, " ");
107302 }
107303
107304 return fixer.insertTextBefore(node, " ");
107305 }
107306
107307 return fixer.removeRange([leftToken.range[1], rightToken.range[0]]);
107308 }
107309
107310 });
107311 }
107312 }
107313 /**
107314 * Enforces the spacing around the star if node is a yield* expression.
107315 * @param {ASTNode} node A yield expression node.
107316 * @returns {void}
107317 */
107318
107319
107320 function checkExpression(node) {
107321 if (!node.delegate) {
107322 return;
107323 }
107324
107325 const tokens = sourceCode.getFirstTokens(node, 3);
107326 const yieldToken = tokens[0];
107327 const starToken = tokens[1];
107328 const nextToken = tokens[2];
107329 checkSpacing("before", yieldToken, starToken);
107330 checkSpacing("after", starToken, nextToken);
107331 }
107332
107333 return {
107334 YieldExpression: checkExpression
107335 };
107336 }
107337
107338};
107339
107340/***/ }),
6a5a0f88 107341/* 726 */
eb39fafa
DC
107342/***/ (function(module, exports, __webpack_require__) {
107343
107344"use strict";
107345/**
107346 * @fileoverview Rule to require or disallow yoda comparisons
107347 * @author Nicholas C. Zakas
107348 */
107349 //--------------------------------------------------------------------------
107350// Requirements
107351//--------------------------------------------------------------------------
107352
107353const astUtils = __webpack_require__(426); //--------------------------------------------------------------------------
107354// Helpers
107355//--------------------------------------------------------------------------
107356
107357/**
107358 * Determines whether an operator is a comparison operator.
107359 * @param {string} operator The operator to check.
107360 * @returns {boolean} Whether or not it is a comparison operator.
107361 */
107362
107363
107364function isComparisonOperator(operator) {
107365 return /^(==|===|!=|!==|<|>|<=|>=)$/u.test(operator);
107366}
107367/**
107368 * Determines whether an operator is an equality operator.
107369 * @param {string} operator The operator to check.
107370 * @returns {boolean} Whether or not it is an equality operator.
107371 */
107372
107373
107374function isEqualityOperator(operator) {
107375 return /^(==|===)$/u.test(operator);
107376}
107377/**
107378 * Determines whether an operator is one used in a range test.
107379 * Allowed operators are `<` and `<=`.
107380 * @param {string} operator The operator to check.
107381 * @returns {boolean} Whether the operator is used in range tests.
107382 */
107383
107384
107385function isRangeTestOperator(operator) {
107386 return ["<", "<="].indexOf(operator) >= 0;
107387}
107388/**
107389 * Determines whether a non-Literal node is a negative number that should be
107390 * treated as if it were a single Literal node.
107391 * @param {ASTNode} node Node to test.
107392 * @returns {boolean} True if the node is a negative number that looks like a
107393 * real literal and should be treated as such.
107394 */
107395
107396
107397function isNegativeNumericLiteral(node) {
107398 return node.type === "UnaryExpression" && node.operator === "-" && node.prefix && astUtils.isNumericLiteral(node.argument);
107399}
107400/**
107401 * Determines whether a node is a Template Literal which can be determined statically.
107402 * @param {ASTNode} node Node to test
107403 * @returns {boolean} True if the node is a Template Literal without expression.
107404 */
107405
107406
107407function isStaticTemplateLiteral(node) {
107408 return node.type === "TemplateLiteral" && node.expressions.length === 0;
107409}
107410/**
107411 * Determines whether a non-Literal node should be treated as a single Literal node.
107412 * @param {ASTNode} node Node to test
107413 * @returns {boolean} True if the node should be treated as a single Literal node.
107414 */
107415
107416
107417function looksLikeLiteral(node) {
107418 return isNegativeNumericLiteral(node) || isStaticTemplateLiteral(node);
107419}
107420/**
107421 * Attempts to derive a Literal node from nodes that are treated like literals.
107422 * @param {ASTNode} node Node to normalize.
eb39fafa
DC
107423 * @returns {ASTNode} One of the following options.
107424 * 1. The original node if the node is already a Literal
107425 * 2. A normalized Literal node with the negative number as the value if the
107426 * node represents a negative number literal.
107427 * 3. A normalized Literal node with the string as the value if the node is
107428 * a Template Literal without expression.
56c4a2cb 107429 * 4. Otherwise `null`.
eb39fafa
DC
107430 */
107431
107432
56c4a2cb 107433function getNormalizedLiteral(node) {
eb39fafa
DC
107434 if (node.type === "Literal") {
107435 return node;
107436 }
107437
107438 if (isNegativeNumericLiteral(node)) {
107439 return {
107440 type: "Literal",
107441 value: -node.argument.value,
107442 raw: "-".concat(node.argument.value)
107443 };
107444 }
107445
107446 if (isStaticTemplateLiteral(node)) {
107447 return {
107448 type: "Literal",
107449 value: node.quasis[0].value.cooked,
107450 raw: node.quasis[0].value.raw
107451 };
107452 }
107453
eb39fafa
DC
107454 return null;
107455}
107456/**
107457 * Checks whether two expressions reference the same value. For example:
107458 * a = a
107459 * a.b = a.b
107460 * a[0] = a[0]
107461 * a['b'] = a['b']
107462 * @param {ASTNode} a Left side of the comparison.
107463 * @param {ASTNode} b Right side of the comparison.
107464 * @returns {boolean} True if both sides match and reference the same value.
107465 */
107466
107467
107468function same(a, b) {
107469 if (a.type !== b.type) {
107470 return false;
107471 }
107472
107473 switch (a.type) {
107474 case "Identifier":
107475 return a.name === b.name;
107476
107477 case "Literal":
107478 return a.value === b.value;
107479
107480 case "MemberExpression":
107481 {
107482 const nameA = astUtils.getStaticPropertyName(a); // x.y = x["y"]
107483
107484 if (nameA !== null) {
107485 return same(a.object, b.object) && nameA === astUtils.getStaticPropertyName(b);
107486 }
107487 /*
107488 * x[0] = x[0]
107489 * x[y] = x[y]
107490 * x.y = x.y
107491 */
107492
107493
107494 return a.computed === b.computed && same(a.object, b.object) && same(a.property, b.property);
107495 }
107496
107497 case "ThisExpression":
107498 return true;
107499
107500 default:
107501 return false;
107502 }
107503} //------------------------------------------------------------------------------
107504// Rule Definition
107505//------------------------------------------------------------------------------
107506
107507
107508module.exports = {
107509 meta: {
107510 type: "suggestion",
107511 docs: {
56c4a2cb 107512 description: 'require or disallow "Yoda" conditions',
eb39fafa
DC
107513 category: "Best Practices",
107514 recommended: false,
107515 url: "https://eslint.org/docs/rules/yoda"
107516 },
107517 schema: [{
107518 enum: ["always", "never"]
107519 }, {
107520 type: "object",
107521 properties: {
107522 exceptRange: {
107523 type: "boolean",
107524 default: false
107525 },
107526 onlyEquality: {
107527 type: "boolean",
107528 default: false
107529 }
107530 },
107531 additionalProperties: false
107532 }],
107533 fixable: "code",
107534 messages: {
107535 expected: "Expected literal to be on the {{expectedSide}} side of {{operator}}."
107536 }
107537 },
107538
107539 create(context) {
107540 // Default to "never" (!always) if no option
107541 const always = context.options[0] === "always";
107542 const exceptRange = context.options[1] && context.options[1].exceptRange;
107543 const onlyEquality = context.options[1] && context.options[1].onlyEquality;
107544 const sourceCode = context.getSourceCode();
107545 /**
107546 * Determines whether node represents a range test.
107547 * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside"
107548 * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and
107549 * both operators must be `<` or `<=`. Finally, the literal on the left side
107550 * must be less than or equal to the literal on the right side so that the
107551 * test makes any sense.
107552 * @param {ASTNode} node LogicalExpression node to test.
107553 * @returns {boolean} Whether node is a range test.
107554 */
107555
107556 function isRangeTest(node) {
107557 const left = node.left,
107558 right = node.right;
107559 /**
107560 * Determines whether node is of the form `0 <= x && x < 1`.
107561 * @returns {boolean} Whether node is a "between" range test.
107562 */
107563
107564 function isBetweenTest() {
56c4a2cb
DC
107565 if (node.operator === "&&" && same(left.right, right.left)) {
107566 const leftLiteral = getNormalizedLiteral(left.left);
107567 const rightLiteral = getNormalizedLiteral(right.right);
107568
107569 if (leftLiteral === null && rightLiteral === null) {
107570 return false;
107571 }
107572
107573 if (rightLiteral === null || leftLiteral === null) {
107574 return true;
107575 }
107576
107577 if (leftLiteral.value <= rightLiteral.value) {
107578 return true;
107579 }
107580 }
107581
107582 return false;
eb39fafa
DC
107583 }
107584 /**
107585 * Determines whether node is of the form `x < 0 || 1 <= x`.
107586 * @returns {boolean} Whether node is an "outside" range test.
107587 */
107588
107589
107590 function isOutsideTest() {
56c4a2cb
DC
107591 if (node.operator === "||" && same(left.left, right.right)) {
107592 const leftLiteral = getNormalizedLiteral(left.right);
107593 const rightLiteral = getNormalizedLiteral(right.left);
107594
107595 if (leftLiteral === null && rightLiteral === null) {
107596 return false;
107597 }
107598
107599 if (rightLiteral === null || leftLiteral === null) {
107600 return true;
107601 }
107602
107603 if (leftLiteral.value <= rightLiteral.value) {
107604 return true;
107605 }
107606 }
107607
107608 return false;
eb39fafa
DC
107609 }
107610 /**
107611 * Determines whether node is wrapped in parentheses.
107612 * @returns {boolean} Whether node is preceded immediately by an open
107613 * paren token and followed immediately by a close
107614 * paren token.
107615 */
107616
107617
107618 function isParenWrapped() {
107619 return astUtils.isParenthesised(sourceCode, node);
107620 }
107621
107622 return node.type === "LogicalExpression" && left.type === "BinaryExpression" && right.type === "BinaryExpression" && isRangeTestOperator(left.operator) && isRangeTestOperator(right.operator) && (isBetweenTest() || isOutsideTest()) && isParenWrapped();
107623 }
107624
107625 const OPERATOR_FLIP_MAP = {
107626 "===": "===",
107627 "!==": "!==",
107628 "==": "==",
107629 "!=": "!=",
107630 "<": ">",
107631 ">": "<",
107632 "<=": ">=",
107633 ">=": "<="
107634 };
107635 /**
107636 * Returns a string representation of a BinaryExpression node with its sides/operator flipped around.
107637 * @param {ASTNode} node The BinaryExpression node
107638 * @returns {string} A string representation of the node with the sides and operator flipped
107639 */
107640
107641 function getFlippedString(node) {
107642 const tokenBefore = sourceCode.getTokenBefore(node);
107643 const operatorToken = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
107644 const textBeforeOperator = sourceCode.getText().slice(sourceCode.getTokenBefore(operatorToken).range[1], operatorToken.range[0]);
107645 const textAfterOperator = sourceCode.getText().slice(operatorToken.range[1], sourceCode.getTokenAfter(operatorToken).range[0]);
107646 const leftText = sourceCode.getText().slice(node.range[0], sourceCode.getTokenBefore(operatorToken).range[1]);
107647 const firstRightToken = sourceCode.getTokenAfter(operatorToken);
107648 const rightText = sourceCode.getText().slice(firstRightToken.range[0], node.range[1]);
107649 let prefix = "";
107650
107651 if (tokenBefore && tokenBefore.range[1] === node.range[0] && !astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken)) {
107652 prefix = " ";
107653 }
107654
107655 return prefix + rightText + textBeforeOperator + OPERATOR_FLIP_MAP[operatorToken.value] + textAfterOperator + leftText;
107656 } //--------------------------------------------------------------------------
107657 // Public
107658 //--------------------------------------------------------------------------
107659
107660
107661 return {
107662 BinaryExpression(node) {
107663 const expectedLiteral = always ? node.left : node.right;
107664 const expectedNonLiteral = always ? node.right : node.left; // If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error.
107665
107666 if ((expectedNonLiteral.type === "Literal" || looksLikeLiteral(expectedNonLiteral)) && !(expectedLiteral.type === "Literal" || looksLikeLiteral(expectedLiteral)) && !(!isEqualityOperator(node.operator) && onlyEquality) && isComparisonOperator(node.operator) && !(exceptRange && isRangeTest(context.getAncestors().pop()))) {
107667 context.report({
107668 node,
107669 messageId: "expected",
107670 data: {
107671 operator: node.operator,
107672 expectedSide: always ? "left" : "right"
107673 },
107674 fix: fixer => fixer.replaceText(node, getFlippedString(node))
107675 });
107676 }
107677 }
107678
107679 };
107680 }
107681
107682};
107683
107684/***/ }),
6a5a0f88 107685/* 727 */
eb39fafa
DC
107686/***/ (function(module, exports, __webpack_require__) {
107687
107688"use strict";
107689/**
107690 * @fileoverview Provide the function that emits deprecation warnings.
107691 * @author Toru Nagashima <http://github.com/mysticatea>
107692 */
107693 //------------------------------------------------------------------------------
107694// Requirements
107695//------------------------------------------------------------------------------
107696
107697const path = __webpack_require__(377);
107698
107699const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
107700// Private
107701//------------------------------------------------------------------------------
107702// Defitions for deprecation warnings.
107703
107704
107705const deprecationWarningMessages = {
107706 ESLINT_LEGACY_ECMAFEATURES: "The 'ecmaFeatures' config file property is deprecated and has no effect.",
107707 ESLINT_PERSONAL_CONFIG_LOAD: "'~/.eslintrc.*' config files have been deprecated. " + "Please use a config file per project or the '--config' option.",
107708 ESLINT_PERSONAL_CONFIG_SUPPRESS: "'~/.eslintrc.*' config files have been deprecated. " + "Please remove it or add 'root:true' to the config files in your " + "projects in order to avoid loading '~/.eslintrc.*' accidentally."
107709};
107710/**
107711 * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
107712 * for each unique file path, but repeated invocations with the same file path have no effect.
107713 * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
107714 * @param {string} source The name of the configuration source to report the warning for.
107715 * @param {string} errorCode The warning message to show.
107716 * @returns {void}
107717 */
107718
107719const emitDeprecationWarning = lodash.memoize((source, errorCode) => {
107720 const rel = path.relative(process.cwd(), source);
107721 const message = deprecationWarningMessages[errorCode];
107722 process.emitWarning("".concat(message, " (found in \"").concat(rel, "\")"), "DeprecationWarning", errorCode);
107723}, (...args) => JSON.stringify(args)); //------------------------------------------------------------------------------
107724// Public Interface
107725//------------------------------------------------------------------------------
107726
107727module.exports = {
107728 emitDeprecationWarning
107729};
107730
107731/***/ }),
6a5a0f88 107732/* 728 */
eb39fafa
DC
107733/***/ (function(module, exports, __webpack_require__) {
107734
107735"use strict";
107736/**
107737 * @fileoverview The instance of Ajv validator.
107738 * @author Evgeny Poberezkin
107739 */
107740 //------------------------------------------------------------------------------
107741// Requirements
107742//------------------------------------------------------------------------------
107743
107744function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
107745
107746function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
107747
107748function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
107749
6a5a0f88
TL
107750const Ajv = __webpack_require__(729),
107751 metaSchema = __webpack_require__(775); //------------------------------------------------------------------------------
eb39fafa
DC
107752// Public Interface
107753//------------------------------------------------------------------------------
107754
107755
107756module.exports = (additionalOptions = {}) => {
107757 const ajv = new Ajv(_objectSpread({
107758 meta: false,
107759 useDefaults: true,
107760 validateSchema: false,
107761 missingRefs: "ignore",
107762 verbose: true,
107763 schemaId: "auto"
107764 }, additionalOptions));
107765 ajv.addMetaSchema(metaSchema); // eslint-disable-next-line no-underscore-dangle
107766
107767 ajv._opts.defaultMeta = metaSchema.id;
107768 return ajv;
107769};
107770
107771/***/ }),
6a5a0f88 107772/* 729 */
eb39fafa
DC
107773/***/ (function(module, exports, __webpack_require__) {
107774
107775"use strict";
107776
107777
6a5a0f88
TL
107778var compileSchema = __webpack_require__(730),
107779 resolve = __webpack_require__(731),
107780 Cache = __webpack_require__(741),
107781 SchemaObject = __webpack_require__(736),
107782 stableStringify = __webpack_require__(739),
107783 formats = __webpack_require__(742),
107784 rules = __webpack_require__(743),
107785 $dataMetaSchema = __webpack_require__(768),
107786 util = __webpack_require__(734);
eb39fafa
DC
107787
107788module.exports = Ajv;
107789Ajv.prototype.validate = validate;
107790Ajv.prototype.compile = compile;
107791Ajv.prototype.addSchema = addSchema;
107792Ajv.prototype.addMetaSchema = addMetaSchema;
107793Ajv.prototype.validateSchema = validateSchema;
107794Ajv.prototype.getSchema = getSchema;
107795Ajv.prototype.removeSchema = removeSchema;
107796Ajv.prototype.addFormat = addFormat;
107797Ajv.prototype.errorsText = errorsText;
107798Ajv.prototype._addSchema = _addSchema;
107799Ajv.prototype._compile = _compile;
6a5a0f88 107800Ajv.prototype.compileAsync = __webpack_require__(769);
eb39fafa 107801
6a5a0f88 107802var customKeyword = __webpack_require__(770);
eb39fafa
DC
107803
107804Ajv.prototype.addKeyword = customKeyword.add;
107805Ajv.prototype.getKeyword = customKeyword.get;
107806Ajv.prototype.removeKeyword = customKeyword.remove;
107807Ajv.prototype.validateKeyword = customKeyword.validate;
107808
6a5a0f88 107809var errorClasses = __webpack_require__(738);
eb39fafa
DC
107810
107811Ajv.ValidationError = errorClasses.Validation;
107812Ajv.MissingRefError = errorClasses.MissingRef;
107813Ajv.$dataMetaSchema = $dataMetaSchema;
107814var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
107815var META_IGNORE_OPTIONS = ['removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults'];
107816var META_SUPPORT_DATA = ['/properties'];
107817/**
107818 * Creates validator instance.
107819 * Usage: `Ajv(opts)`
107820 * @param {Object} opts optional options
107821 * @return {Object} ajv instance
107822 */
107823
107824function Ajv(opts) {
107825 if (!(this instanceof Ajv)) return new Ajv(opts);
107826 opts = this._opts = util.copy(opts) || {};
107827 setLogger(this);
107828 this._schemas = {};
107829 this._refs = {};
107830 this._fragments = {};
107831 this._formats = formats(opts.format);
107832 this._cache = opts.cache || new Cache();
107833 this._loadingSchemas = {};
107834 this._compilations = [];
107835 this.RULES = rules();
107836 this._getId = chooseGetId(opts);
107837 opts.loopRequired = opts.loopRequired || Infinity;
107838 if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
107839 if (opts.serialize === undefined) opts.serialize = stableStringify;
107840 this._metaOpts = getMetaSchemaOptions(this);
107841 if (opts.formats) addInitialFormats(this);
107842 if (opts.keywords) addInitialKeywords(this);
107843 addDefaultMetaSchema(this);
107844 if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
107845 if (opts.nullable) this.addKeyword('nullable', {
107846 metaSchema: {
107847 type: 'boolean'
107848 }
107849 });
107850 addInitialSchemas(this);
107851}
107852/**
107853 * Validate data using schema
107854 * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
107855 * @this Ajv
107856 * @param {String|Object} schemaKeyRef key, ref or schema object
107857 * @param {Any} data to be validated
107858 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
107859 */
107860
107861
107862function validate(schemaKeyRef, data) {
107863 var v;
107864
107865 if (typeof schemaKeyRef == 'string') {
107866 v = this.getSchema(schemaKeyRef);
107867 if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
107868 } else {
107869 var schemaObj = this._addSchema(schemaKeyRef);
107870
107871 v = schemaObj.validate || this._compile(schemaObj);
107872 }
107873
107874 var valid = v(data);
107875 if (v.$async !== true) this.errors = v.errors;
107876 return valid;
107877}
107878/**
107879 * Create validating function for passed schema.
107880 * @this Ajv
107881 * @param {Object} schema schema object
107882 * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
107883 * @return {Function} validating function
107884 */
107885
107886
107887function compile(schema, _meta) {
107888 var schemaObj = this._addSchema(schema, undefined, _meta);
107889
107890 return schemaObj.validate || this._compile(schemaObj);
107891}
107892/**
107893 * Adds schema to the instance.
107894 * @this Ajv
107895 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
107896 * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
107897 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
107898 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
107899 * @return {Ajv} this for method chaining
107900 */
107901
107902
107903function addSchema(schema, key, _skipValidation, _meta) {
107904 if (Array.isArray(schema)) {
107905 for (var i = 0; i < schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
107906
107907 return this;
107908 }
107909
107910 var id = this._getId(schema);
107911
107912 if (id !== undefined && typeof id != 'string') throw new Error('schema id must be string');
107913 key = resolve.normalizeId(key || id);
107914 checkUnique(this, key);
107915 this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
107916 return this;
107917}
107918/**
107919 * Add schema that will be used to validate other schemas
107920 * options in META_IGNORE_OPTIONS are alway set to false
107921 * @this Ajv
107922 * @param {Object} schema schema object
107923 * @param {String} key optional schema key
107924 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
107925 * @return {Ajv} this for method chaining
107926 */
107927
107928
107929function addMetaSchema(schema, key, skipValidation) {
107930 this.addSchema(schema, key, skipValidation, true);
107931 return this;
107932}
107933/**
107934 * Validate schema
107935 * @this Ajv
107936 * @param {Object} schema schema to validate
107937 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
107938 * @return {Boolean} true if schema is valid
107939 */
107940
107941
107942function validateSchema(schema, throwOrLogError) {
107943 var $schema = schema.$schema;
107944 if ($schema !== undefined && typeof $schema != 'string') throw new Error('$schema must be a string');
107945 $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
107946
107947 if (!$schema) {
107948 this.logger.warn('meta-schema not available');
107949 this.errors = null;
107950 return true;
107951 }
107952
107953 var valid = this.validate($schema, schema);
107954
107955 if (!valid && throwOrLogError) {
107956 var message = 'schema is invalid: ' + this.errorsText();
107957 if (this._opts.validateSchema == 'log') this.logger.error(message);else throw new Error(message);
107958 }
107959
107960 return valid;
107961}
107962
107963function defaultMeta(self) {
107964 var meta = self._opts.meta;
107965 self._opts.defaultMeta = typeof meta == 'object' ? self._getId(meta) || meta : self.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined;
107966 return self._opts.defaultMeta;
107967}
107968/**
107969 * Get compiled schema from the instance by `key` or `ref`.
107970 * @this Ajv
107971 * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
107972 * @return {Function} schema validating function (with property `schema`).
107973 */
107974
107975
107976function getSchema(keyRef) {
107977 var schemaObj = _getSchemaObj(this, keyRef);
107978
107979 switch (typeof schemaObj) {
107980 case 'object':
107981 return schemaObj.validate || this._compile(schemaObj);
107982
107983 case 'string':
107984 return this.getSchema(schemaObj);
107985
107986 case 'undefined':
107987 return _getSchemaFragment(this, keyRef);
107988 }
107989}
107990
107991function _getSchemaFragment(self, ref) {
107992 var res = resolve.schema.call(self, {
107993 schema: {}
107994 }, ref);
107995
107996 if (res) {
107997 var schema = res.schema,
107998 root = res.root,
107999 baseId = res.baseId;
108000 var v = compileSchema.call(self, schema, root, undefined, baseId);
108001 self._fragments[ref] = new SchemaObject({
108002 ref: ref,
108003 fragment: true,
108004 schema: schema,
108005 root: root,
108006 baseId: baseId,
108007 validate: v
108008 });
108009 return v;
108010 }
108011}
108012
108013function _getSchemaObj(self, keyRef) {
108014 keyRef = resolve.normalizeId(keyRef);
108015 return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
108016}
108017/**
108018 * Remove cached schema(s).
108019 * If no parameter is passed all schemas but meta-schemas are removed.
108020 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
108021 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
108022 * @this Ajv
108023 * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
108024 * @return {Ajv} this for method chaining
108025 */
108026
108027
108028function removeSchema(schemaKeyRef) {
108029 if (schemaKeyRef instanceof RegExp) {
108030 _removeAllSchemas(this, this._schemas, schemaKeyRef);
108031
108032 _removeAllSchemas(this, this._refs, schemaKeyRef);
108033
108034 return this;
108035 }
108036
108037 switch (typeof schemaKeyRef) {
108038 case 'undefined':
108039 _removeAllSchemas(this, this._schemas);
108040
108041 _removeAllSchemas(this, this._refs);
108042
108043 this._cache.clear();
108044
108045 return this;
108046
108047 case 'string':
108048 var schemaObj = _getSchemaObj(this, schemaKeyRef);
108049
108050 if (schemaObj) this._cache.del(schemaObj.cacheKey);
108051 delete this._schemas[schemaKeyRef];
108052 delete this._refs[schemaKeyRef];
108053 return this;
108054
108055 case 'object':
108056 var serialize = this._opts.serialize;
108057 var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
108058
108059 this._cache.del(cacheKey);
108060
108061 var id = this._getId(schemaKeyRef);
108062
108063 if (id) {
108064 id = resolve.normalizeId(id);
108065 delete this._schemas[id];
108066 delete this._refs[id];
108067 }
108068
108069 }
108070
108071 return this;
108072}
108073
108074function _removeAllSchemas(self, schemas, regex) {
108075 for (var keyRef in schemas) {
108076 var schemaObj = schemas[keyRef];
108077
108078 if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
108079 self._cache.del(schemaObj.cacheKey);
108080
108081 delete schemas[keyRef];
108082 }
108083 }
108084}
108085/* @this Ajv */
108086
108087
108088function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
108089 if (typeof schema != 'object' && typeof schema != 'boolean') throw new Error('schema should be object or boolean');
108090 var serialize = this._opts.serialize;
108091 var cacheKey = serialize ? serialize(schema) : schema;
108092
108093 var cached = this._cache.get(cacheKey);
108094
108095 if (cached) return cached;
108096 shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
108097 var id = resolve.normalizeId(this._getId(schema));
108098 if (id && shouldAddSchema) checkUnique(this, id);
108099 var willValidate = this._opts.validateSchema !== false && !skipValidation;
108100 var recursiveMeta;
108101 if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) this.validateSchema(schema, true);
108102 var localRefs = resolve.ids.call(this, schema);
108103 var schemaObj = new SchemaObject({
108104 id: id,
108105 schema: schema,
108106 localRefs: localRefs,
108107 cacheKey: cacheKey,
108108 meta: meta
108109 });
108110 if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
108111
108112 this._cache.put(cacheKey, schemaObj);
108113
108114 if (willValidate && recursiveMeta) this.validateSchema(schema, true);
108115 return schemaObj;
108116}
108117/* @this Ajv */
108118
108119
108120function _compile(schemaObj, root) {
108121 if (schemaObj.compiling) {
108122 schemaObj.validate = callValidate;
108123 callValidate.schema = schemaObj.schema;
108124 callValidate.errors = null;
108125 callValidate.root = root ? root : callValidate;
108126 if (schemaObj.schema.$async === true) callValidate.$async = true;
108127 return callValidate;
108128 }
108129
108130 schemaObj.compiling = true;
108131 var currentOpts;
108132
108133 if (schemaObj.meta) {
108134 currentOpts = this._opts;
108135 this._opts = this._metaOpts;
108136 }
108137
108138 var v;
108139
108140 try {
108141 v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs);
108142 } catch (e) {
108143 delete schemaObj.validate;
108144 throw e;
108145 } finally {
108146 schemaObj.compiling = false;
108147 if (schemaObj.meta) this._opts = currentOpts;
108148 }
108149
108150 schemaObj.validate = v;
108151 schemaObj.refs = v.refs;
108152 schemaObj.refVal = v.refVal;
108153 schemaObj.root = v.root;
108154 return v;
108155 /* @this {*} - custom context, see passContext option */
108156
108157 function callValidate() {
108158 /* jshint validthis: true */
108159 var _validate = schemaObj.validate;
108160
108161 var result = _validate.apply(this, arguments);
108162
108163 callValidate.errors = _validate.errors;
108164 return result;
108165 }
108166}
108167
108168function chooseGetId(opts) {
108169 switch (opts.schemaId) {
108170 case 'auto':
108171 return _get$IdOrId;
108172
108173 case 'id':
108174 return _getId;
108175
108176 default:
108177 return _get$Id;
108178 }
108179}
108180/* @this Ajv */
108181
108182
108183function _getId(schema) {
108184 if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
108185 return schema.id;
108186}
108187/* @this Ajv */
108188
108189
108190function _get$Id(schema) {
108191 if (schema.id) this.logger.warn('schema id ignored', schema.id);
108192 return schema.$id;
108193}
108194
108195function _get$IdOrId(schema) {
108196 if (schema.$id && schema.id && schema.$id != schema.id) throw new Error('schema $id is different from id');
108197 return schema.$id || schema.id;
108198}
108199/**
108200 * Convert array of error message objects to string
108201 * @this Ajv
108202 * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
108203 * @param {Object} options optional options with properties `separator` and `dataVar`.
108204 * @return {String} human readable string with all errors descriptions
108205 */
108206
108207
108208function errorsText(errors, options) {
108209 errors = errors || this.errors;
108210 if (!errors) return 'No errors';
108211 options = options || {};
108212 var separator = options.separator === undefined ? ', ' : options.separator;
108213 var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
108214 var text = '';
108215
108216 for (var i = 0; i < errors.length; i++) {
108217 var e = errors[i];
108218 if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
108219 }
108220
108221 return text.slice(0, -separator.length);
108222}
108223/**
108224 * Add custom format
108225 * @this Ajv
108226 * @param {String} name format name
108227 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
108228 * @return {Ajv} this for method chaining
108229 */
108230
108231
108232function addFormat(name, format) {
108233 if (typeof format == 'string') format = new RegExp(format);
108234 this._formats[name] = format;
108235 return this;
108236}
108237
108238function addDefaultMetaSchema(self) {
108239 var $dataSchema;
108240
108241 if (self._opts.$data) {
6a5a0f88 108242 $dataSchema = __webpack_require__(774);
eb39fafa
DC
108243 self.addMetaSchema($dataSchema, $dataSchema.$id, true);
108244 }
108245
108246 if (self._opts.meta === false) return;
108247
6a5a0f88 108248 var metaSchema = __webpack_require__(773);
eb39fafa
DC
108249
108250 if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
108251 self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
108252 self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
108253}
108254
108255function addInitialSchemas(self) {
108256 var optsSchemas = self._opts.schemas;
108257 if (!optsSchemas) return;
108258 if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
108259}
108260
108261function addInitialFormats(self) {
108262 for (var name in self._opts.formats) {
108263 var format = self._opts.formats[name];
108264 self.addFormat(name, format);
108265 }
108266}
108267
108268function addInitialKeywords(self) {
108269 for (var name in self._opts.keywords) {
108270 var keyword = self._opts.keywords[name];
108271 self.addKeyword(name, keyword);
108272 }
108273}
108274
108275function checkUnique(self, id) {
108276 if (self._schemas[id] || self._refs[id]) throw new Error('schema with key or id "' + id + '" already exists');
108277}
108278
108279function getMetaSchemaOptions(self) {
108280 var metaOpts = util.copy(self._opts);
108281
108282 for (var i = 0; i < META_IGNORE_OPTIONS.length; i++) delete metaOpts[META_IGNORE_OPTIONS[i]];
108283
108284 return metaOpts;
108285}
108286
108287function setLogger(self) {
108288 var logger = self._opts.logger;
108289
108290 if (logger === false) {
108291 self.logger = {
108292 log: noop,
108293 warn: noop,
108294 error: noop
108295 };
108296 } else {
108297 if (logger === undefined) logger = console;
108298 if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error)) throw new Error('logger must implement log, warn and error methods');
108299 self.logger = logger;
108300 }
108301}
108302
108303function noop() {}
108304
108305/***/ }),
6a5a0f88 108306/* 730 */
eb39fafa
DC
108307/***/ (function(module, exports, __webpack_require__) {
108308
108309"use strict";
108310
108311
6a5a0f88
TL
108312var resolve = __webpack_require__(731),
108313 util = __webpack_require__(734),
108314 errorClasses = __webpack_require__(738),
108315 stableStringify = __webpack_require__(739);
eb39fafa 108316
6a5a0f88 108317var validateGenerator = __webpack_require__(740);
eb39fafa
DC
108318/**
108319 * Functions below are used inside compiled validations function
108320 */
108321
108322
108323var ucs2length = util.ucs2length;
108324
6a5a0f88 108325var equal = __webpack_require__(733); // this error is thrown by async schemas to return validation errors via exception
eb39fafa
DC
108326
108327
108328var ValidationError = errorClasses.Validation;
108329module.exports = compile;
108330/**
108331 * Compiles schema to validation function
108332 * @this Ajv
108333 * @param {Object} schema schema object
108334 * @param {Object} root object with information about the root schema for this schema
108335 * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
108336 * @param {String} baseId base ID for IDs in the schema
108337 * @return {Function} validation function
108338 */
108339
108340function compile(schema, root, localRefs, baseId) {
108341 /* jshint validthis: true, evil: true */
108342
108343 /* eslint no-shadow: 0 */
108344 var self = this,
108345 opts = this._opts,
108346 refVal = [undefined],
108347 refs = {},
108348 patterns = [],
108349 patternsHash = {},
108350 defaults = [],
108351 defaultsHash = {},
108352 customRules = [];
108353 root = root || {
108354 schema: schema,
108355 refVal: refVal,
108356 refs: refs
108357 };
108358 var c = checkCompiling.call(this, schema, root, baseId);
108359 var compilation = this._compilations[c.index];
108360 if (c.compiling) return compilation.callValidate = callValidate;
108361 var formats = this._formats;
108362 var RULES = this.RULES;
108363
108364 try {
108365 var v = localCompile(schema, root, localRefs, baseId);
108366 compilation.validate = v;
108367 var cv = compilation.callValidate;
108368
108369 if (cv) {
108370 cv.schema = v.schema;
108371 cv.errors = null;
108372 cv.refs = v.refs;
108373 cv.refVal = v.refVal;
108374 cv.root = v.root;
108375 cv.$async = v.$async;
108376 if (opts.sourceCode) cv.source = v.source;
108377 }
108378
108379 return v;
108380 } finally {
108381 endCompiling.call(this, schema, root, baseId);
108382 }
108383 /* @this {*} - custom context, see passContext option */
108384
108385
108386 function callValidate() {
108387 /* jshint validthis: true */
108388 var validate = compilation.validate;
108389 var result = validate.apply(this, arguments);
108390 callValidate.errors = validate.errors;
108391 return result;
108392 }
108393
108394 function localCompile(_schema, _root, localRefs, baseId) {
108395 var isRoot = !_root || _root && _root.schema == _schema;
108396 if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId);
108397 var $async = _schema.$async === true;
108398 var sourceCode = validateGenerator({
108399 isTop: true,
108400 schema: _schema,
108401 isRoot: isRoot,
108402 baseId: baseId,
108403 root: _root,
108404 schemaPath: '',
108405 errSchemaPath: '#',
108406 errorPath: '""',
108407 MissingRefError: errorClasses.MissingRef,
108408 RULES: RULES,
108409 validate: validateGenerator,
108410 util: util,
108411 resolve: resolve,
108412 resolveRef: resolveRef,
108413 usePattern: usePattern,
108414 useDefault: useDefault,
108415 useCustomRule: useCustomRule,
108416 opts: opts,
108417 formats: formats,
108418 logger: self.logger,
108419 self: self
108420 });
108421 sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode;
108422 if (opts.processCode) sourceCode = opts.processCode(sourceCode); // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
108423
108424 var validate;
108425
108426 try {
108427 var makeValidate = new Function('self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'equal', 'ucs2length', 'ValidationError', sourceCode);
108428 validate = makeValidate(self, RULES, formats, root, refVal, defaults, customRules, equal, ucs2length, ValidationError);
108429 refVal[0] = validate;
108430 } catch (e) {
108431 self.logger.error('Error compiling schema, function code:', sourceCode);
108432 throw e;
108433 }
108434
108435 validate.schema = _schema;
108436 validate.errors = null;
108437 validate.refs = refs;
108438 validate.refVal = refVal;
108439 validate.root = isRoot ? validate : _root;
108440 if ($async) validate.$async = true;
108441
108442 if (opts.sourceCode === true) {
108443 validate.source = {
108444 code: sourceCode,
108445 patterns: patterns,
108446 defaults: defaults
108447 };
108448 }
108449
108450 return validate;
108451 }
108452
108453 function resolveRef(baseId, ref, isRoot) {
108454 ref = resolve.url(baseId, ref);
108455 var refIndex = refs[ref];
108456
108457 var _refVal, refCode;
108458
108459 if (refIndex !== undefined) {
108460 _refVal = refVal[refIndex];
108461 refCode = 'refVal[' + refIndex + ']';
108462 return resolvedRef(_refVal, refCode);
108463 }
108464
108465 if (!isRoot && root.refs) {
108466 var rootRefId = root.refs[ref];
108467
108468 if (rootRefId !== undefined) {
108469 _refVal = root.refVal[rootRefId];
108470 refCode = addLocalRef(ref, _refVal);
108471 return resolvedRef(_refVal, refCode);
108472 }
108473 }
108474
108475 refCode = addLocalRef(ref);
108476 var v = resolve.call(self, localCompile, root, ref);
108477
108478 if (v === undefined) {
108479 var localSchema = localRefs && localRefs[ref];
108480
108481 if (localSchema) {
108482 v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId);
108483 }
108484 }
108485
108486 if (v === undefined) {
108487 removeLocalRef(ref);
108488 } else {
108489 replaceLocalRef(ref, v);
108490 return resolvedRef(v, refCode);
108491 }
108492 }
108493
108494 function addLocalRef(ref, v) {
108495 var refId = refVal.length;
108496 refVal[refId] = v;
108497 refs[ref] = refId;
108498 return 'refVal' + refId;
108499 }
108500
108501 function removeLocalRef(ref) {
108502 delete refs[ref];
108503 }
108504
108505 function replaceLocalRef(ref, v) {
108506 var refId = refs[ref];
108507 refVal[refId] = v;
108508 }
108509
108510 function resolvedRef(refVal, code) {
108511 return typeof refVal == 'object' || typeof refVal == 'boolean' ? {
108512 code: code,
108513 schema: refVal,
108514 inline: true
108515 } : {
108516 code: code,
108517 $async: refVal && !!refVal.$async
108518 };
108519 }
108520
108521 function usePattern(regexStr) {
108522 var index = patternsHash[regexStr];
108523
108524 if (index === undefined) {
108525 index = patternsHash[regexStr] = patterns.length;
108526 patterns[index] = regexStr;
108527 }
108528
108529 return 'pattern' + index;
108530 }
108531
108532 function useDefault(value) {
108533 switch (typeof value) {
108534 case 'boolean':
108535 case 'number':
108536 return '' + value;
108537
108538 case 'string':
108539 return util.toQuotedString(value);
108540
108541 case 'object':
108542 if (value === null) return 'null';
108543 var valueStr = stableStringify(value);
108544 var index = defaultsHash[valueStr];
108545
108546 if (index === undefined) {
108547 index = defaultsHash[valueStr] = defaults.length;
108548 defaults[index] = value;
108549 }
108550
108551 return 'default' + index;
108552 }
108553 }
108554
108555 function useCustomRule(rule, schema, parentSchema, it) {
108556 if (self._opts.validateSchema !== false) {
108557 var deps = rule.definition.dependencies;
108558 if (deps && !deps.every(function (keyword) {
108559 return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
108560 })) throw new Error('parent schema must have all required keywords: ' + deps.join(','));
108561 var validateSchema = rule.definition.validateSchema;
108562
108563 if (validateSchema) {
108564 var valid = validateSchema(schema);
108565
108566 if (!valid) {
108567 var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
108568 if (self._opts.validateSchema == 'log') self.logger.error(message);else throw new Error(message);
108569 }
108570 }
108571 }
108572
108573 var compile = rule.definition.compile,
108574 inline = rule.definition.inline,
108575 macro = rule.definition.macro;
108576 var validate;
108577
108578 if (compile) {
108579 validate = compile.call(self, schema, parentSchema, it);
108580 } else if (macro) {
108581 validate = macro.call(self, schema, parentSchema, it);
108582 if (opts.validateSchema !== false) self.validateSchema(validate, true);
108583 } else if (inline) {
108584 validate = inline.call(self, it, rule.keyword, schema, parentSchema);
108585 } else {
108586 validate = rule.definition.validate;
108587 if (!validate) return;
108588 }
108589
108590 if (validate === undefined) throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
108591 var index = customRules.length;
108592 customRules[index] = validate;
108593 return {
108594 code: 'customRule' + index,
108595 validate: validate
108596 };
108597 }
108598}
108599/**
108600 * Checks if the schema is currently compiled
108601 * @this Ajv
108602 * @param {Object} schema schema to compile
108603 * @param {Object} root root object
108604 * @param {String} baseId base schema ID
108605 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
108606 */
108607
108608
108609function checkCompiling(schema, root, baseId) {
108610 /* jshint validthis: true */
108611 var index = compIndex.call(this, schema, root, baseId);
108612 if (index >= 0) return {
108613 index: index,
108614 compiling: true
108615 };
108616 index = this._compilations.length;
108617 this._compilations[index] = {
108618 schema: schema,
108619 root: root,
108620 baseId: baseId
108621 };
108622 return {
108623 index: index,
108624 compiling: false
108625 };
108626}
108627/**
108628 * Removes the schema from the currently compiled list
108629 * @this Ajv
108630 * @param {Object} schema schema to compile
108631 * @param {Object} root root object
108632 * @param {String} baseId base schema ID
108633 */
108634
108635
108636function endCompiling(schema, root, baseId) {
108637 /* jshint validthis: true */
108638 var i = compIndex.call(this, schema, root, baseId);
108639 if (i >= 0) this._compilations.splice(i, 1);
108640}
108641/**
108642 * Index of schema compilation in the currently compiled list
108643 * @this Ajv
108644 * @param {Object} schema schema to compile
108645 * @param {Object} root root object
108646 * @param {String} baseId base schema ID
108647 * @return {Integer} compilation index
108648 */
108649
108650
108651function compIndex(schema, root, baseId) {
108652 /* jshint validthis: true */
108653 for (var i = 0; i < this._compilations.length; i++) {
108654 var c = this._compilations[i];
108655 if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
108656 }
108657
108658 return -1;
108659}
108660
108661function patternCode(i, patterns) {
108662 return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
108663}
108664
108665function defaultCode(i) {
108666 return 'var default' + i + ' = defaults[' + i + '];';
108667}
108668
108669function refValCode(i, refVal) {
108670 return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
108671}
108672
108673function customRuleCode(i) {
108674 return 'var customRule' + i + ' = customRules[' + i + '];';
108675}
108676
108677function vars(arr, statement) {
108678 if (!arr.length) return '';
108679 var code = '';
108680
108681 for (var i = 0; i < arr.length; i++) code += statement(i, arr);
108682
108683 return code;
108684}
108685
108686/***/ }),
6a5a0f88 108687/* 731 */
eb39fafa
DC
108688/***/ (function(module, exports, __webpack_require__) {
108689
108690"use strict";
108691
108692
6a5a0f88
TL
108693var URI = __webpack_require__(732),
108694 equal = __webpack_require__(733),
108695 util = __webpack_require__(734),
108696 SchemaObject = __webpack_require__(736),
108697 traverse = __webpack_require__(737);
eb39fafa
DC
108698
108699module.exports = resolve;
108700resolve.normalizeId = normalizeId;
108701resolve.fullPath = getFullPath;
108702resolve.url = resolveUrl;
108703resolve.ids = resolveIds;
108704resolve.inlineRef = inlineRef;
108705resolve.schema = resolveSchema;
108706/**
108707 * [resolve and compile the references ($ref)]
108708 * @this Ajv
108709 * @param {Function} compile reference to schema compilation funciton (localCompile)
108710 * @param {Object} root object with information about the root schema for the current schema
108711 * @param {String} ref reference to resolve
108712 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
108713 */
108714
108715function resolve(compile, root, ref) {
108716 /* jshint validthis: true */
108717 var refVal = this._refs[ref];
108718
108719 if (typeof refVal == 'string') {
108720 if (this._refs[refVal]) refVal = this._refs[refVal];else return resolve.call(this, compile, root, refVal);
108721 }
108722
108723 refVal = refVal || this._schemas[ref];
108724
108725 if (refVal instanceof SchemaObject) {
108726 return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal);
108727 }
108728
108729 var res = resolveSchema.call(this, root, ref);
108730 var schema, v, baseId;
108731
108732 if (res) {
108733 schema = res.schema;
108734 root = res.root;
108735 baseId = res.baseId;
108736 }
108737
108738 if (schema instanceof SchemaObject) {
108739 v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
108740 } else if (schema !== undefined) {
108741 v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, undefined, baseId);
108742 }
108743
108744 return v;
108745}
108746/**
108747 * Resolve schema, its root and baseId
108748 * @this Ajv
108749 * @param {Object} root root object with properties schema, refVal, refs
108750 * @param {String} ref reference to resolve
108751 * @return {Object} object with properties schema, root, baseId
108752 */
108753
108754
108755function resolveSchema(root, ref) {
108756 /* jshint validthis: true */
108757 var p = URI.parse(ref),
108758 refPath = _getFullPath(p),
108759 baseId = getFullPath(this._getId(root.schema));
108760
108761 if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
108762 var id = normalizeId(refPath);
108763 var refVal = this._refs[id];
108764
108765 if (typeof refVal == 'string') {
108766 return resolveRecursive.call(this, root, refVal, p);
108767 } else if (refVal instanceof SchemaObject) {
108768 if (!refVal.validate) this._compile(refVal);
108769 root = refVal;
108770 } else {
108771 refVal = this._schemas[id];
108772
108773 if (refVal instanceof SchemaObject) {
108774 if (!refVal.validate) this._compile(refVal);
108775 if (id == normalizeId(ref)) return {
108776 schema: refVal,
108777 root: root,
108778 baseId: baseId
108779 };
108780 root = refVal;
108781 } else {
108782 return;
108783 }
108784 }
108785
108786 if (!root.schema) return;
108787 baseId = getFullPath(this._getId(root.schema));
108788 }
108789
108790 return getJsonPointer.call(this, p, baseId, root.schema, root);
108791}
108792/* @this Ajv */
108793
108794
108795function resolveRecursive(root, ref, parsedRef) {
108796 /* jshint validthis: true */
108797 var res = resolveSchema.call(this, root, ref);
108798
108799 if (res) {
108800 var schema = res.schema;
108801 var baseId = res.baseId;
108802 root = res.root;
108803
108804 var id = this._getId(schema);
108805
108806 if (id) baseId = resolveUrl(baseId, id);
108807 return getJsonPointer.call(this, parsedRef, baseId, schema, root);
108808 }
108809}
108810
108811var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
108812/* @this Ajv */
108813
108814function getJsonPointer(parsedRef, baseId, schema, root) {
108815 /* jshint validthis: true */
108816 parsedRef.fragment = parsedRef.fragment || '';
108817 if (parsedRef.fragment.slice(0, 1) != '/') return;
108818 var parts = parsedRef.fragment.split('/');
108819
108820 for (var i = 1; i < parts.length; i++) {
108821 var part = parts[i];
108822
108823 if (part) {
108824 part = util.unescapeFragment(part);
108825 schema = schema[part];
108826 if (schema === undefined) break;
108827 var id;
108828
108829 if (!PREVENT_SCOPE_CHANGE[part]) {
108830 id = this._getId(schema);
108831 if (id) baseId = resolveUrl(baseId, id);
108832
108833 if (schema.$ref) {
108834 var $ref = resolveUrl(baseId, schema.$ref);
108835 var res = resolveSchema.call(this, root, $ref);
108836
108837 if (res) {
108838 schema = res.schema;
108839 root = res.root;
108840 baseId = res.baseId;
108841 }
108842 }
108843 }
108844 }
108845 }
108846
108847 if (schema !== undefined && schema !== root.schema) return {
108848 schema: schema,
108849 root: root,
108850 baseId: baseId
108851 };
108852}
108853
108854var SIMPLE_INLINED = util.toHash(['type', 'format', 'pattern', 'maxLength', 'minLength', 'maxProperties', 'minProperties', 'maxItems', 'minItems', 'maximum', 'minimum', 'uniqueItems', 'multipleOf', 'required', 'enum']);
108855
108856function inlineRef(schema, limit) {
108857 if (limit === false) return false;
108858 if (limit === undefined || limit === true) return checkNoRef(schema);else if (limit) return countKeys(schema) <= limit;
108859}
108860
108861function checkNoRef(schema) {
108862 var item;
108863
108864 if (Array.isArray(schema)) {
108865 for (var i = 0; i < schema.length; i++) {
108866 item = schema[i];
108867 if (typeof item == 'object' && !checkNoRef(item)) return false;
108868 }
108869 } else {
108870 for (var key in schema) {
108871 if (key == '$ref') return false;
108872 item = schema[key];
108873 if (typeof item == 'object' && !checkNoRef(item)) return false;
108874 }
108875 }
108876
108877 return true;
108878}
108879
108880function countKeys(schema) {
108881 var count = 0,
108882 item;
108883
108884 if (Array.isArray(schema)) {
108885 for (var i = 0; i < schema.length; i++) {
108886 item = schema[i];
108887 if (typeof item == 'object') count += countKeys(item);
108888 if (count == Infinity) return Infinity;
108889 }
108890 } else {
108891 for (var key in schema) {
108892 if (key == '$ref') return Infinity;
108893
108894 if (SIMPLE_INLINED[key]) {
108895 count++;
108896 } else {
108897 item = schema[key];
108898 if (typeof item == 'object') count += countKeys(item) + 1;
108899 if (count == Infinity) return Infinity;
108900 }
108901 }
108902 }
108903
108904 return count;
108905}
108906
108907function getFullPath(id, normalize) {
108908 if (normalize !== false) id = normalizeId(id);
108909 var p = URI.parse(id);
108910 return _getFullPath(p);
108911}
108912
108913function _getFullPath(p) {
108914 return URI.serialize(p).split('#')[0] + '#';
108915}
108916
108917var TRAILING_SLASH_HASH = /#\/?$/;
108918
108919function normalizeId(id) {
108920 return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
108921}
108922
108923function resolveUrl(baseId, id) {
108924 id = normalizeId(id);
108925 return URI.resolve(baseId, id);
108926}
108927/* @this Ajv */
108928
108929
108930function resolveIds(schema) {
108931 var schemaId = normalizeId(this._getId(schema));
108932 var baseIds = {
108933 '': schemaId
108934 };
108935 var fullPaths = {
108936 '': getFullPath(schemaId, false)
108937 };
108938 var localRefs = {};
108939 var self = this;
108940 traverse(schema, {
108941 allKeys: true
108942 }, function (sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
108943 if (jsonPtr === '') return;
108944
108945 var id = self._getId(sch);
108946
108947 var baseId = baseIds[parentJsonPtr];
108948 var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
108949 if (keyIndex !== undefined) fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
108950
108951 if (typeof id == 'string') {
108952 id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
108953 var refVal = self._refs[id];
108954 if (typeof refVal == 'string') refVal = self._refs[refVal];
108955
108956 if (refVal && refVal.schema) {
108957 if (!equal(sch, refVal.schema)) throw new Error('id "' + id + '" resolves to more than one schema');
108958 } else if (id != normalizeId(fullPath)) {
108959 if (id[0] == '#') {
108960 if (localRefs[id] && !equal(sch, localRefs[id])) throw new Error('id "' + id + '" resolves to more than one schema');
108961 localRefs[id] = sch;
108962 } else {
108963 self._refs[id] = fullPath;
108964 }
108965 }
108966 }
108967
108968 baseIds[jsonPtr] = baseId;
108969 fullPaths[jsonPtr] = fullPath;
108970 });
108971 return localRefs;
108972}
108973
108974/***/ }),
6a5a0f88 108975/* 732 */
eb39fafa
DC
108976/***/ (function(module, exports, __webpack_require__) {
108977
108978/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
108979(function (global, factory) {
108980 true ? factory(exports) : undefined;
108981})(this, function (exports) {
108982 'use strict';
108983
108984 function merge() {
108985 for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
108986 sets[_key] = arguments[_key];
108987 }
108988
108989 if (sets.length > 1) {
108990 sets[0] = sets[0].slice(0, -1);
108991 var xl = sets.length - 1;
108992
108993 for (var x = 1; x < xl; ++x) {
108994 sets[x] = sets[x].slice(1, -1);
108995 }
108996
108997 sets[xl] = sets[xl].slice(1);
108998 return sets.join('');
108999 } else {
109000 return sets[0];
109001 }
109002 }
109003
109004 function subexp(str) {
109005 return "(?:" + str + ")";
109006 }
109007
109008 function typeOf(o) {
109009 return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
109010 }
109011
109012 function toUpperCase(str) {
109013 return str.toUpperCase();
109014 }
109015
109016 function toArray(obj) {
109017 return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
109018 }
109019
109020 function assign(target, source) {
109021 var obj = target;
109022
109023 if (source) {
109024 for (var key in source) {
109025 obj[key] = source[key];
109026 }
109027 }
109028
109029 return obj;
109030 }
109031
109032 function buildExps(isIRI) {
109033 var ALPHA$$ = "[A-Za-z]",
109034 CR$ = "[\\x0D]",
109035 DIGIT$$ = "[0-9]",
109036 DQUOTE$$ = "[\\x22]",
109037 HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
109038 //case-insensitive
109039 LF$$ = "[\\x0A]",
109040 SP$$ = "[\\x20]",
109041 PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
109042 //expanded
109043 GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
109044 SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
109045 RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
109046 UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
109047 //subset, excludes bidi control characters
109048 IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
109049 //subset
109050 UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
109051 SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
109052 USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
109053 DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
109054 DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$),
109055 //relaxed parsing rules
109056 IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
109057 H16$ = subexp(HEXDIG$$ + "{1,4}"),
109058 LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
109059 IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
109060 // 6( h16 ":" ) ls32
109061 IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
109062 // "::" 5( h16 ":" ) ls32
109063 IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
109064 //[ h16 ] "::" 4( h16 ":" ) ls32
109065 IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
109066 //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
109067 IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
109068 //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
109069 IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
109070 //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
109071 IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
109072 //[ *4( h16 ":" ) h16 ] "::" ls32
109073 IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
109074 //[ *5( h16 ":" ) h16 ] "::" h16
109075 IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
109076 //[ *6( h16 ":" ) h16 ] "::"
109077 IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
109078 ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
109079 //RFC 6874
109080 IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
109081 //RFC 6874
109082 IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
109083 //RFC 6874, with relaxed parsing rules
109084 IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
109085 IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
109086 //RFC 6874
109087 REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
109088 HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
109089 PORT$ = subexp(DIGIT$$ + "*"),
109090 AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
109091 PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
109092 SEGMENT$ = subexp(PCHAR$ + "*"),
109093 SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
109094 SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
109095 PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
109096 PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
109097 //simplified
109098 PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
109099 //simplified
109100 PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
109101 //simplified
109102 PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
109103 PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
109104 QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
109105 FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
109106 HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
109107 URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
109108 RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
109109 RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
109110 URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
109111 ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
109112 GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
109113 RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
109114 ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
109115 SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
109116 AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
109117 return {
109118 NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
109119 NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
109120 NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
109121 NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
109122 NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
109123 NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
109124 NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
109125 ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
109126 UNRESERVED: new RegExp(UNRESERVED$$, "g"),
109127 OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
109128 PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
109129 IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
109130 IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
109131
109132 };
109133 }
109134
109135 var URI_PROTOCOL = buildExps(false);
109136 var IRI_PROTOCOL = buildExps(true);
109137
109138 var slicedToArray = function () {
109139 function sliceIterator(arr, i) {
109140 var _arr = [];
109141 var _n = true;
109142 var _d = false;
109143 var _e = undefined;
109144
109145 try {
109146 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
109147 _arr.push(_s.value);
109148
109149 if (i && _arr.length === i) break;
109150 }
109151 } catch (err) {
109152 _d = true;
109153 _e = err;
109154 } finally {
109155 try {
109156 if (!_n && _i["return"]) _i["return"]();
109157 } finally {
109158 if (_d) throw _e;
109159 }
109160 }
109161
109162 return _arr;
109163 }
109164
109165 return function (arr, i) {
109166 if (Array.isArray(arr)) {
109167 return arr;
109168 } else if (Symbol.iterator in Object(arr)) {
109169 return sliceIterator(arr, i);
109170 } else {
109171 throw new TypeError("Invalid attempt to destructure non-iterable instance");
109172 }
109173 };
109174 }();
109175
109176 var toConsumableArray = function toConsumableArray(arr) {
109177 if (Array.isArray(arr)) {
109178 for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
109179
109180 return arr2;
109181 } else {
109182 return Array.from(arr);
109183 }
109184 };
109185 /** Highest positive signed 32-bit float value */
109186
109187
109188 var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
109189
109190 /** Bootstring parameters */
109191
109192 var base = 36;
109193 var tMin = 1;
109194 var tMax = 26;
109195 var skew = 38;
109196 var damp = 700;
109197 var initialBias = 72;
109198 var initialN = 128; // 0x80
109199
109200 var delimiter = '-'; // '\x2D'
109201
109202 /** Regular expressions */
109203
109204 var regexPunycode = /^xn--/;
109205 var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
109206
109207 var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
109208
109209 /** Error messages */
109210
109211 var errors = {
109212 'overflow': 'Overflow: input needs wider integers to process',
109213 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
109214 'invalid-input': 'Invalid input'
109215 };
109216 /** Convenience shortcuts */
109217
109218 var baseMinusTMin = base - tMin;
109219 var floor = Math.floor;
109220 var stringFromCharCode = String.fromCharCode;
109221 /*--------------------------------------------------------------------------*/
109222
109223 /**
109224 * A generic error utility function.
109225 * @private
109226 * @param {String} type The error type.
109227 * @returns {Error} Throws a `RangeError` with the applicable error message.
109228 */
109229
109230 function error$1(type) {
109231 throw new RangeError(errors[type]);
109232 }
109233 /**
109234 * A generic `Array#map` utility function.
109235 * @private
109236 * @param {Array} array The array to iterate over.
109237 * @param {Function} callback The function that gets called for every array
109238 * item.
109239 * @returns {Array} A new array of values returned by the callback function.
109240 */
109241
109242
109243 function map(array, fn) {
109244 var result = [];
109245 var length = array.length;
109246
109247 while (length--) {
109248 result[length] = fn(array[length]);
109249 }
109250
109251 return result;
109252 }
109253 /**
109254 * A simple `Array#map`-like wrapper to work with domain name strings or email
109255 * addresses.
109256 * @private
109257 * @param {String} domain The domain name or email address.
109258 * @param {Function} callback The function that gets called for every
109259 * character.
109260 * @returns {Array} A new string of characters returned by the callback
109261 * function.
109262 */
109263
109264
109265 function mapDomain(string, fn) {
109266 var parts = string.split('@');
109267 var result = '';
109268
109269 if (parts.length > 1) {
109270 // In email addresses, only the domain name should be punycoded. Leave
109271 // the local part (i.e. everything up to `@`) intact.
109272 result = parts[0] + '@';
109273 string = parts[1];
109274 } // Avoid `split(regex)` for IE8 compatibility. See #17.
109275
109276
109277 string = string.replace(regexSeparators, '\x2E');
109278 var labels = string.split('.');
109279 var encoded = map(labels, fn).join('.');
109280 return result + encoded;
109281 }
109282 /**
109283 * Creates an array containing the numeric code points of each Unicode
109284 * character in the string. While JavaScript uses UCS-2 internally,
109285 * this function will convert a pair of surrogate halves (each of which
109286 * UCS-2 exposes as separate characters) into a single code point,
109287 * matching UTF-16.
109288 * @see `punycode.ucs2.encode`
109289 * @see <https://mathiasbynens.be/notes/javascript-encoding>
109290 * @memberOf punycode.ucs2
109291 * @name decode
109292 * @param {String} string The Unicode input string (UCS-2).
109293 * @returns {Array} The new array of code points.
109294 */
109295
109296
109297 function ucs2decode(string) {
109298 var output = [];
109299 var counter = 0;
109300 var length = string.length;
109301
109302 while (counter < length) {
109303 var value = string.charCodeAt(counter++);
109304
109305 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
109306 // It's a high surrogate, and there is a next character.
109307 var extra = string.charCodeAt(counter++);
109308
109309 if ((extra & 0xFC00) == 0xDC00) {
109310 // Low surrogate.
109311 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
109312 } else {
109313 // It's an unmatched surrogate; only append this code unit, in case the
109314 // next code unit is the high surrogate of a surrogate pair.
109315 output.push(value);
109316 counter--;
109317 }
109318 } else {
109319 output.push(value);
109320 }
109321 }
109322
109323 return output;
109324 }
109325 /**
109326 * Creates a string based on an array of numeric code points.
109327 * @see `punycode.ucs2.decode`
109328 * @memberOf punycode.ucs2
109329 * @name encode
109330 * @param {Array} codePoints The array of numeric code points.
109331 * @returns {String} The new Unicode string (UCS-2).
109332 */
109333
109334
109335 var ucs2encode = function ucs2encode(array) {
109336 return String.fromCodePoint.apply(String, toConsumableArray(array));
109337 };
109338 /**
109339 * Converts a basic code point into a digit/integer.
109340 * @see `digitToBasic()`
109341 * @private
109342 * @param {Number} codePoint The basic numeric code point value.
109343 * @returns {Number} The numeric value of a basic code point (for use in
109344 * representing integers) in the range `0` to `base - 1`, or `base` if
109345 * the code point does not represent a value.
109346 */
109347
109348
109349 var basicToDigit = function basicToDigit(codePoint) {
109350 if (codePoint - 0x30 < 0x0A) {
109351 return codePoint - 0x16;
109352 }
109353
109354 if (codePoint - 0x41 < 0x1A) {
109355 return codePoint - 0x41;
109356 }
109357
109358 if (codePoint - 0x61 < 0x1A) {
109359 return codePoint - 0x61;
109360 }
109361
109362 return base;
109363 };
109364 /**
109365 * Converts a digit/integer into a basic code point.
109366 * @see `basicToDigit()`
109367 * @private
109368 * @param {Number} digit The numeric value of a basic code point.
109369 * @returns {Number} The basic code point whose value (when used for
109370 * representing integers) is `digit`, which needs to be in the range
109371 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
109372 * used; else, the lowercase form is used. The behavior is undefined
109373 * if `flag` is non-zero and `digit` has no uppercase form.
109374 */
109375
109376
109377 var digitToBasic = function digitToBasic(digit, flag) {
109378 // 0..25 map to ASCII a..z or A..Z
109379 // 26..35 map to ASCII 0..9
109380 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
109381 };
109382 /**
109383 * Bias adaptation function as per section 3.4 of RFC 3492.
109384 * https://tools.ietf.org/html/rfc3492#section-3.4
109385 * @private
109386 */
109387
109388
109389 var adapt = function adapt(delta, numPoints, firstTime) {
109390 var k = 0;
109391 delta = firstTime ? floor(delta / damp) : delta >> 1;
109392 delta += floor(delta / numPoints);
109393
109394 for (;
109395 /* no initialization */
109396 delta > baseMinusTMin * tMax >> 1; k += base) {
109397 delta = floor(delta / baseMinusTMin);
109398 }
109399
109400 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
109401 };
109402 /**
109403 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
109404 * symbols.
109405 * @memberOf punycode
109406 * @param {String} input The Punycode string of ASCII-only symbols.
109407 * @returns {String} The resulting string of Unicode symbols.
109408 */
109409
109410
109411 var decode = function decode(input) {
109412 // Don't use UCS-2.
109413 var output = [];
109414 var inputLength = input.length;
109415 var i = 0;
109416 var n = initialN;
109417 var bias = initialBias; // Handle the basic code points: let `basic` be the number of input code
109418 // points before the last delimiter, or `0` if there is none, then copy
109419 // the first basic code points to the output.
109420
109421 var basic = input.lastIndexOf(delimiter);
109422
109423 if (basic < 0) {
109424 basic = 0;
109425 }
109426
109427 for (var j = 0; j < basic; ++j) {
109428 // if it's not a basic code point
109429 if (input.charCodeAt(j) >= 0x80) {
109430 error$1('not-basic');
109431 }
109432
109433 output.push(input.charCodeAt(j));
109434 } // Main decoding loop: start just after the last delimiter if any basic code
109435 // points were copied; start at the beginning otherwise.
109436
109437
109438 for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;)
109439 /* no final expression */
109440 {
109441 // `index` is the index of the next character to be consumed.
109442 // Decode a generalized variable-length integer into `delta`,
109443 // which gets added to `i`. The overflow checking is easier
109444 // if we increase `i` as we go, then subtract off its starting
109445 // value at the end to obtain `delta`.
109446 var oldi = i;
109447
109448 for (var w = 1, k = base;;
109449 /* no condition */
109450 k += base) {
109451 if (index >= inputLength) {
109452 error$1('invalid-input');
109453 }
109454
109455 var digit = basicToDigit(input.charCodeAt(index++));
109456
109457 if (digit >= base || digit > floor((maxInt - i) / w)) {
109458 error$1('overflow');
109459 }
109460
109461 i += digit * w;
109462 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
109463
109464 if (digit < t) {
109465 break;
109466 }
109467
109468 var baseMinusT = base - t;
109469
109470 if (w > floor(maxInt / baseMinusT)) {
109471 error$1('overflow');
109472 }
109473
109474 w *= baseMinusT;
109475 }
109476
109477 var out = output.length + 1;
109478 bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`,
109479 // incrementing `n` each time, so we'll fix that now:
109480
109481 if (floor(i / out) > maxInt - n) {
109482 error$1('overflow');
109483 }
109484
109485 n += floor(i / out);
109486 i %= out; // Insert `n` at position `i` of the output.
109487
109488 output.splice(i++, 0, n);
109489 }
109490
109491 return String.fromCodePoint.apply(String, output);
109492 };
109493 /**
109494 * Converts a string of Unicode symbols (e.g. a domain name label) to a
109495 * Punycode string of ASCII-only symbols.
109496 * @memberOf punycode
109497 * @param {String} input The string of Unicode symbols.
109498 * @returns {String} The resulting Punycode string of ASCII-only symbols.
109499 */
109500
109501
109502 var encode = function encode(input) {
109503 var output = []; // Convert the input in UCS-2 to an array of Unicode code points.
109504
109505 input = ucs2decode(input); // Cache the length.
109506
109507 var inputLength = input.length; // Initialize the state.
109508
109509 var n = initialN;
109510 var delta = 0;
109511 var bias = initialBias; // Handle the basic code points.
109512
109513 var _iteratorNormalCompletion = true;
109514 var _didIteratorError = false;
109515 var _iteratorError = undefined;
109516
109517 try {
109518 for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
109519 var _currentValue2 = _step.value;
109520
109521 if (_currentValue2 < 0x80) {
109522 output.push(stringFromCharCode(_currentValue2));
109523 }
109524 }
109525 } catch (err) {
109526 _didIteratorError = true;
109527 _iteratorError = err;
109528 } finally {
109529 try {
109530 if (!_iteratorNormalCompletion && _iterator.return) {
109531 _iterator.return();
109532 }
109533 } finally {
109534 if (_didIteratorError) {
109535 throw _iteratorError;
109536 }
109537 }
109538 }
109539
109540 var basicLength = output.length;
109541 var handledCPCount = basicLength; // `handledCPCount` is the number of code points that have been handled;
109542 // `basicLength` is the number of basic code points.
109543 // Finish the basic string with a delimiter unless it's empty.
109544
109545 if (basicLength) {
109546 output.push(delimiter);
109547 } // Main encoding loop:
109548
109549
109550 while (handledCPCount < inputLength) {
109551 // All non-basic code points < n have been handled already. Find the next
109552 // larger one:
109553 var m = maxInt;
109554 var _iteratorNormalCompletion2 = true;
109555 var _didIteratorError2 = false;
109556 var _iteratorError2 = undefined;
109557
109558 try {
109559 for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
109560 var currentValue = _step2.value;
109561
109562 if (currentValue >= n && currentValue < m) {
109563 m = currentValue;
109564 }
109565 } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
109566 // but guard against overflow.
109567
109568 } catch (err) {
109569 _didIteratorError2 = true;
109570 _iteratorError2 = err;
109571 } finally {
109572 try {
109573 if (!_iteratorNormalCompletion2 && _iterator2.return) {
109574 _iterator2.return();
109575 }
109576 } finally {
109577 if (_didIteratorError2) {
109578 throw _iteratorError2;
109579 }
109580 }
109581 }
109582
109583 var handledCPCountPlusOne = handledCPCount + 1;
109584
109585 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
109586 error$1('overflow');
109587 }
109588
109589 delta += (m - n) * handledCPCountPlusOne;
109590 n = m;
109591 var _iteratorNormalCompletion3 = true;
109592 var _didIteratorError3 = false;
109593 var _iteratorError3 = undefined;
109594
109595 try {
109596 for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
109597 var _currentValue = _step3.value;
109598
109599 if (_currentValue < n && ++delta > maxInt) {
109600 error$1('overflow');
109601 }
109602
109603 if (_currentValue == n) {
109604 // Represent delta as a generalized variable-length integer.
109605 var q = delta;
109606
109607 for (var k = base;;
109608 /* no condition */
109609 k += base) {
109610 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
109611
109612 if (q < t) {
109613 break;
109614 }
109615
109616 var qMinusT = q - t;
109617 var baseMinusT = base - t;
109618 output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
109619 q = floor(qMinusT / baseMinusT);
109620 }
109621
109622 output.push(stringFromCharCode(digitToBasic(q, 0)));
109623 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
109624 delta = 0;
109625 ++handledCPCount;
109626 }
109627 }
109628 } catch (err) {
109629 _didIteratorError3 = true;
109630 _iteratorError3 = err;
109631 } finally {
109632 try {
109633 if (!_iteratorNormalCompletion3 && _iterator3.return) {
109634 _iterator3.return();
109635 }
109636 } finally {
109637 if (_didIteratorError3) {
109638 throw _iteratorError3;
109639 }
109640 }
109641 }
109642
109643 ++delta;
109644 ++n;
109645 }
109646
109647 return output.join('');
109648 };
109649 /**
109650 * Converts a Punycode string representing a domain name or an email address
109651 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
109652 * it doesn't matter if you call it on a string that has already been
109653 * converted to Unicode.
109654 * @memberOf punycode
109655 * @param {String} input The Punycoded domain name or email address to
109656 * convert to Unicode.
109657 * @returns {String} The Unicode representation of the given Punycode
109658 * string.
109659 */
109660
109661
109662 var toUnicode = function toUnicode(input) {
109663 return mapDomain(input, function (string) {
109664 return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
109665 });
109666 };
109667 /**
109668 * Converts a Unicode string representing a domain name or an email address to
109669 * Punycode. Only the non-ASCII parts of the domain name will be converted,
109670 * i.e. it doesn't matter if you call it with a domain that's already in
109671 * ASCII.
109672 * @memberOf punycode
109673 * @param {String} input The domain name or email address to convert, as a
109674 * Unicode string.
109675 * @returns {String} The Punycode representation of the given domain name or
109676 * email address.
109677 */
109678
109679
109680 var toASCII = function toASCII(input) {
109681 return mapDomain(input, function (string) {
109682 return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
109683 });
109684 };
109685 /*--------------------------------------------------------------------------*/
109686
109687 /** Define the public API */
109688
109689
109690 var punycode = {
109691 /**
109692 * A string representing the current Punycode.js version number.
109693 * @memberOf punycode
109694 * @type String
109695 */
109696 'version': '2.1.0',
109697
109698 /**
109699 * An object of methods to convert from JavaScript's internal character
109700 * representation (UCS-2) to Unicode code points, and back.
109701 * @see <https://mathiasbynens.be/notes/javascript-encoding>
109702 * @memberOf punycode
109703 * @type Object
109704 */
109705 'ucs2': {
109706 'decode': ucs2decode,
109707 'encode': ucs2encode
109708 },
109709 'decode': decode,
109710 'encode': encode,
109711 'toASCII': toASCII,
109712 'toUnicode': toUnicode
109713 };
109714 /**
109715 * URI.js
109716 *
109717 * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
109718 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
109719 * @see http://github.com/garycourt/uri-js
109720 */
109721
109722 /**
109723 * Copyright 2011 Gary Court. All rights reserved.
109724 *
109725 * Redistribution and use in source and binary forms, with or without modification, are
109726 * permitted provided that the following conditions are met:
109727 *
109728 * 1. Redistributions of source code must retain the above copyright notice, this list of
109729 * conditions and the following disclaimer.
109730 *
109731 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
109732 * of conditions and the following disclaimer in the documentation and/or other materials
109733 * provided with the distribution.
109734 *
109735 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
109736 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
109737 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
109738 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
109739 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
109740 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
109741 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
109742 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
109743 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109744 *
109745 * The views and conclusions contained in the software and documentation are those of the
109746 * authors and should not be interpreted as representing official policies, either expressed
109747 * or implied, of Gary Court.
109748 */
109749
109750 var SCHEMES = {};
109751
109752 function pctEncChar(chr) {
109753 var c = chr.charCodeAt(0);
109754 var e = void 0;
109755 if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
109756 return e;
109757 }
109758
109759 function pctDecChars(str) {
109760 var newStr = "";
109761 var i = 0;
109762 var il = str.length;
109763
109764 while (i < il) {
109765 var c = parseInt(str.substr(i + 1, 2), 16);
109766
109767 if (c < 128) {
109768 newStr += String.fromCharCode(c);
109769 i += 3;
109770 } else if (c >= 194 && c < 224) {
109771 if (il - i >= 6) {
109772 var c2 = parseInt(str.substr(i + 4, 2), 16);
109773 newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
109774 } else {
109775 newStr += str.substr(i, 6);
109776 }
109777
109778 i += 6;
109779 } else if (c >= 224) {
109780 if (il - i >= 9) {
109781 var _c = parseInt(str.substr(i + 4, 2), 16);
109782
109783 var c3 = parseInt(str.substr(i + 7, 2), 16);
109784 newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
109785 } else {
109786 newStr += str.substr(i, 9);
109787 }
109788
109789 i += 9;
109790 } else {
109791 newStr += str.substr(i, 3);
109792 i += 3;
109793 }
109794 }
109795
109796 return newStr;
109797 }
109798
109799 function _normalizeComponentEncoding(components, protocol) {
109800 function decodeUnreserved(str) {
109801 var decStr = pctDecChars(str);
109802 return !decStr.match(protocol.UNRESERVED) ? str : decStr;
109803 }
109804
109805 if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
109806 if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
109807 if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
109808 if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
109809 if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
109810 if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
109811 return components;
109812 }
109813
109814 function _stripLeadingZeros(str) {
109815 return str.replace(/^0*(.*)/, "$1") || "0";
109816 }
109817
109818 function _normalizeIPv4(host, protocol) {
109819 var matches = host.match(protocol.IPV4ADDRESS) || [];
109820
109821 var _matches = slicedToArray(matches, 2),
109822 address = _matches[1];
109823
109824 if (address) {
109825 return address.split(".").map(_stripLeadingZeros).join(".");
109826 } else {
109827 return host;
109828 }
109829 }
109830
109831 function _normalizeIPv6(host, protocol) {
109832 var matches = host.match(protocol.IPV6ADDRESS) || [];
109833
109834 var _matches2 = slicedToArray(matches, 3),
109835 address = _matches2[1],
109836 zone = _matches2[2];
109837
109838 if (address) {
109839 var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
109840 _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
109841 last = _address$toLowerCase$2[0],
109842 first = _address$toLowerCase$2[1];
109843
109844 var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
109845 var lastFields = last.split(":").map(_stripLeadingZeros);
109846 var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
109847 var fieldCount = isLastFieldIPv4Address ? 7 : 8;
109848 var lastFieldsStart = lastFields.length - fieldCount;
109849 var fields = Array(fieldCount);
109850
109851 for (var x = 0; x < fieldCount; ++x) {
109852 fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
109853 }
109854
109855 if (isLastFieldIPv4Address) {
109856 fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
109857 }
109858
109859 var allZeroFields = fields.reduce(function (acc, field, index) {
109860 if (!field || field === "0") {
109861 var lastLongest = acc[acc.length - 1];
109862
109863 if (lastLongest && lastLongest.index + lastLongest.length === index) {
109864 lastLongest.length++;
109865 } else {
109866 acc.push({
109867 index: index,
109868 length: 1
109869 });
109870 }
109871 }
109872
109873 return acc;
109874 }, []);
109875 var longestZeroFields = allZeroFields.sort(function (a, b) {
109876 return b.length - a.length;
109877 })[0];
109878 var newHost = void 0;
109879
109880 if (longestZeroFields && longestZeroFields.length > 1) {
109881 var newFirst = fields.slice(0, longestZeroFields.index);
109882 var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
109883 newHost = newFirst.join(":") + "::" + newLast.join(":");
109884 } else {
109885 newHost = fields.join(":");
109886 }
109887
109888 if (zone) {
109889 newHost += "%" + zone;
109890 }
109891
109892 return newHost;
109893 } else {
109894 return host;
109895 }
109896 }
109897
109898 var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
109899 var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
109900
109901 function parse(uriString) {
109902 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
109903 var components = {};
109904 var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
109905 if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
109906 var matches = uriString.match(URI_PARSE);
109907
109908 if (matches) {
109909 if (NO_MATCH_IS_UNDEFINED) {
109910 //store each component
109911 components.scheme = matches[1];
109912 components.userinfo = matches[3];
109913 components.host = matches[4];
109914 components.port = parseInt(matches[5], 10);
109915 components.path = matches[6] || "";
109916 components.query = matches[7];
109917 components.fragment = matches[8]; //fix port number
109918
109919 if (isNaN(components.port)) {
109920 components.port = matches[5];
109921 }
109922 } else {
109923 //IE FIX for improper RegExp matching
109924 //store each component
109925 components.scheme = matches[1] || undefined;
109926 components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
109927 components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
109928 components.port = parseInt(matches[5], 10);
109929 components.path = matches[6] || "";
109930 components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
109931 components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; //fix port number
109932
109933 if (isNaN(components.port)) {
109934 components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
109935 }
109936 }
109937
109938 if (components.host) {
109939 //normalize IP hosts
109940 components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
109941 } //determine reference type
109942
109943
109944 if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
109945 components.reference = "same-document";
109946 } else if (components.scheme === undefined) {
109947 components.reference = "relative";
109948 } else if (components.fragment === undefined) {
109949 components.reference = "absolute";
109950 } else {
109951 components.reference = "uri";
109952 } //check for reference errors
109953
109954
109955 if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
109956 components.error = components.error || "URI is not a " + options.reference + " reference.";
109957 } //find scheme handler
109958
109959
109960 var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; //check if scheme can't handle IRIs
109961
109962 if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
109963 //if host component is a domain name
109964 if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
109965 //convert Unicode IDN -> ASCII IDN
109966 try {
109967 components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
109968 } catch (e) {
109969 components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
109970 }
109971 } //convert IRI -> URI
109972
109973
109974 _normalizeComponentEncoding(components, URI_PROTOCOL);
109975 } else {
109976 //normalize encodings
109977 _normalizeComponentEncoding(components, protocol);
109978 } //perform scheme specific parsing
109979
109980
109981 if (schemeHandler && schemeHandler.parse) {
109982 schemeHandler.parse(components, options);
109983 }
109984 } else {
109985 components.error = components.error || "URI can not be parsed.";
109986 }
109987
109988 return components;
109989 }
109990
109991 function _recomposeAuthority(components, options) {
109992 var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
109993 var uriTokens = [];
109994
109995 if (components.userinfo !== undefined) {
109996 uriTokens.push(components.userinfo);
109997 uriTokens.push("@");
109998 }
109999
110000 if (components.host !== undefined) {
110001 //normalize IP hosts, add brackets and escape zone separator for IPv6
110002 uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
110003 return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
110004 }));
110005 }
110006
110007 if (typeof components.port === "number") {
110008 uriTokens.push(":");
110009 uriTokens.push(components.port.toString(10));
110010 }
110011
110012 return uriTokens.length ? uriTokens.join("") : undefined;
110013 }
110014
110015 var RDS1 = /^\.\.?\//;
110016 var RDS2 = /^\/\.(\/|$)/;
110017 var RDS3 = /^\/\.\.(\/|$)/;
110018 var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
110019
110020 function removeDotSegments(input) {
110021 var output = [];
110022
110023 while (input.length) {
110024 if (input.match(RDS1)) {
110025 input = input.replace(RDS1, "");
110026 } else if (input.match(RDS2)) {
110027 input = input.replace(RDS2, "/");
110028 } else if (input.match(RDS3)) {
110029 input = input.replace(RDS3, "/");
110030 output.pop();
110031 } else if (input === "." || input === "..") {
110032 input = "";
110033 } else {
110034 var im = input.match(RDS5);
110035
110036 if (im) {
110037 var s = im[0];
110038 input = input.slice(s.length);
110039 output.push(s);
110040 } else {
110041 throw new Error("Unexpected dot segment condition");
110042 }
110043 }
110044 }
110045
110046 return output.join("");
110047 }
110048
110049 function serialize(components) {
110050 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
110051 var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
110052 var uriTokens = []; //find scheme handler
110053
110054 var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; //perform scheme specific serialization
110055
110056 if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
110057
110058 if (components.host) {
110059 //if host component is an IPv6 address
110060 if (protocol.IPV6ADDRESS.test(components.host)) {} //TODO: normalize IPv6 address as per RFC 5952
110061 //if host component is a domain name
110062 else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
110063 //convert IDN via punycode
110064 try {
110065 components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
110066 } catch (e) {
110067 components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
110068 }
110069 }
110070 } //normalize encoding
110071
110072
110073 _normalizeComponentEncoding(components, protocol);
110074
110075 if (options.reference !== "suffix" && components.scheme) {
110076 uriTokens.push(components.scheme);
110077 uriTokens.push(":");
110078 }
110079
110080 var authority = _recomposeAuthority(components, options);
110081
110082 if (authority !== undefined) {
110083 if (options.reference !== "suffix") {
110084 uriTokens.push("//");
110085 }
110086
110087 uriTokens.push(authority);
110088
110089 if (components.path && components.path.charAt(0) !== "/") {
110090 uriTokens.push("/");
110091 }
110092 }
110093
110094 if (components.path !== undefined) {
110095 var s = components.path;
110096
110097 if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
110098 s = removeDotSegments(s);
110099 }
110100
110101 if (authority === undefined) {
110102 s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
110103 }
110104
110105 uriTokens.push(s);
110106 }
110107
110108 if (components.query !== undefined) {
110109 uriTokens.push("?");
110110 uriTokens.push(components.query);
110111 }
110112
110113 if (components.fragment !== undefined) {
110114 uriTokens.push("#");
110115 uriTokens.push(components.fragment);
110116 }
110117
110118 return uriTokens.join(""); //merge tokens into a string
110119 }
110120
110121 function resolveComponents(base, relative) {
110122 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
110123 var skipNormalization = arguments[3];
110124 var target = {};
110125
110126 if (!skipNormalization) {
110127 base = parse(serialize(base, options), options); //normalize base components
110128
110129 relative = parse(serialize(relative, options), options); //normalize relative components
110130 }
110131
110132 options = options || {};
110133
110134 if (!options.tolerant && relative.scheme) {
110135 target.scheme = relative.scheme; //target.authority = relative.authority;
110136
110137 target.userinfo = relative.userinfo;
110138 target.host = relative.host;
110139 target.port = relative.port;
110140 target.path = removeDotSegments(relative.path || "");
110141 target.query = relative.query;
110142 } else {
110143 if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
110144 //target.authority = relative.authority;
110145 target.userinfo = relative.userinfo;
110146 target.host = relative.host;
110147 target.port = relative.port;
110148 target.path = removeDotSegments(relative.path || "");
110149 target.query = relative.query;
110150 } else {
110151 if (!relative.path) {
110152 target.path = base.path;
110153
110154 if (relative.query !== undefined) {
110155 target.query = relative.query;
110156 } else {
110157 target.query = base.query;
110158 }
110159 } else {
110160 if (relative.path.charAt(0) === "/") {
110161 target.path = removeDotSegments(relative.path);
110162 } else {
110163 if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
110164 target.path = "/" + relative.path;
110165 } else if (!base.path) {
110166 target.path = relative.path;
110167 } else {
110168 target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
110169 }
110170
110171 target.path = removeDotSegments(target.path);
110172 }
110173
110174 target.query = relative.query;
110175 } //target.authority = base.authority;
110176
110177
110178 target.userinfo = base.userinfo;
110179 target.host = base.host;
110180 target.port = base.port;
110181 }
110182
110183 target.scheme = base.scheme;
110184 }
110185
110186 target.fragment = relative.fragment;
110187 return target;
110188 }
110189
110190 function resolve(baseURI, relativeURI, options) {
110191 var schemelessOptions = assign({
110192 scheme: 'null'
110193 }, options);
110194 return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
110195 }
110196
110197 function normalize(uri, options) {
110198 if (typeof uri === "string") {
110199 uri = serialize(parse(uri, options), options);
110200 } else if (typeOf(uri) === "object") {
110201 uri = parse(serialize(uri, options), options);
110202 }
110203
110204 return uri;
110205 }
110206
110207 function equal(uriA, uriB, options) {
110208 if (typeof uriA === "string") {
110209 uriA = serialize(parse(uriA, options), options);
110210 } else if (typeOf(uriA) === "object") {
110211 uriA = serialize(uriA, options);
110212 }
110213
110214 if (typeof uriB === "string") {
110215 uriB = serialize(parse(uriB, options), options);
110216 } else if (typeOf(uriB) === "object") {
110217 uriB = serialize(uriB, options);
110218 }
110219
110220 return uriA === uriB;
110221 }
110222
110223 function escapeComponent(str, options) {
110224 return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
110225 }
110226
110227 function unescapeComponent(str, options) {
110228 return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
110229 }
110230
110231 var handler = {
110232 scheme: "http",
110233 domainHost: true,
110234 parse: function parse(components, options) {
110235 //report missing host
110236 if (!components.host) {
110237 components.error = components.error || "HTTP URIs must have a host.";
110238 }
110239
110240 return components;
110241 },
110242 serialize: function serialize(components, options) {
110243 //normalize the default port
110244 if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") {
110245 components.port = undefined;
110246 } //normalize the empty path
110247
110248
110249 if (!components.path) {
110250 components.path = "/";
110251 } //NOTE: We do not parse query strings for HTTP URIs
110252 //as WWW Form Url Encoded query strings are part of the HTML4+ spec,
110253 //and not the HTTP spec.
110254
110255
110256 return components;
110257 }
110258 };
110259 var handler$1 = {
110260 scheme: "https",
110261 domainHost: handler.domainHost,
110262 parse: handler.parse,
110263 serialize: handler.serialize
110264 };
110265 var O = {};
110266 var isIRI = true; //RFC 3986
110267
110268 var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
110269 var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
110270
110271 var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
110272 //RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
110273 //const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
110274 //const WSP$$ = "[\\x20\\x09]";
110275 //const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127)
110276 //const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext
110277 //const VCHAR$$ = "[\\x21-\\x7E]";
110278 //const WSP$$ = "[\\x20\\x09]";
110279 //const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext
110280 //const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
110281 //const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
110282 //const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
110283
110284 var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
110285 var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
110286 var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
110287 var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
110288 var UNRESERVED = new RegExp(UNRESERVED$$, "g");
110289 var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
110290 var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
110291 var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
110292 var NOT_HFVALUE = NOT_HFNAME;
110293
110294 function decodeUnreserved(str) {
110295 var decStr = pctDecChars(str);
110296 return !decStr.match(UNRESERVED) ? str : decStr;
110297 }
110298
110299 var handler$2 = {
110300 scheme: "mailto",
110301 parse: function parse$$1(components, options) {
110302 var mailtoComponents = components;
110303 var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
110304 mailtoComponents.path = undefined;
110305
110306 if (mailtoComponents.query) {
110307 var unknownHeaders = false;
110308 var headers = {};
110309 var hfields = mailtoComponents.query.split("&");
110310
110311 for (var x = 0, xl = hfields.length; x < xl; ++x) {
110312 var hfield = hfields[x].split("=");
110313
110314 switch (hfield[0]) {
110315 case "to":
110316 var toAddrs = hfield[1].split(",");
110317
110318 for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
110319 to.push(toAddrs[_x]);
110320 }
110321
110322 break;
110323
110324 case "subject":
110325 mailtoComponents.subject = unescapeComponent(hfield[1], options);
110326 break;
110327
110328 case "body":
110329 mailtoComponents.body = unescapeComponent(hfield[1], options);
110330 break;
110331
110332 default:
110333 unknownHeaders = true;
110334 headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
110335 break;
110336 }
110337 }
110338
110339 if (unknownHeaders) mailtoComponents.headers = headers;
110340 }
110341
110342 mailtoComponents.query = undefined;
110343
110344 for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
110345 var addr = to[_x2].split("@");
110346
110347 addr[0] = unescapeComponent(addr[0]);
110348
110349 if (!options.unicodeSupport) {
110350 //convert Unicode IDN -> ASCII IDN
110351 try {
110352 addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
110353 } catch (e) {
110354 mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
110355 }
110356 } else {
110357 addr[1] = unescapeComponent(addr[1], options).toLowerCase();
110358 }
110359
110360 to[_x2] = addr.join("@");
110361 }
110362
110363 return mailtoComponents;
110364 },
110365 serialize: function serialize$$1(mailtoComponents, options) {
110366 var components = mailtoComponents;
110367 var to = toArray(mailtoComponents.to);
110368
110369 if (to) {
110370 for (var x = 0, xl = to.length; x < xl; ++x) {
110371 var toAddr = String(to[x]);
110372 var atIdx = toAddr.lastIndexOf("@");
110373 var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
110374 var domain = toAddr.slice(atIdx + 1); //convert IDN via punycode
110375
110376 try {
110377 domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
110378 } catch (e) {
110379 components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
110380 }
110381
110382 to[x] = localPart + "@" + domain;
110383 }
110384
110385 components.path = to.join(",");
110386 }
110387
110388 var headers = mailtoComponents.headers = mailtoComponents.headers || {};
110389 if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
110390 if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
110391 var fields = [];
110392
110393 for (var name in headers) {
110394 if (headers[name] !== O[name]) {
110395 fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
110396 }
110397 }
110398
110399 if (fields.length) {
110400 components.query = fields.join("&");
110401 }
110402
110403 return components;
110404 }
110405 };
110406 var URN_PARSE = /^([^\:]+)\:(.*)/; //RFC 2141
110407
110408 var handler$3 = {
110409 scheme: "urn",
110410 parse: function parse$$1(components, options) {
110411 var matches = components.path && components.path.match(URN_PARSE);
110412 var urnComponents = components;
110413
110414 if (matches) {
110415 var scheme = options.scheme || urnComponents.scheme || "urn";
110416 var nid = matches[1].toLowerCase();
110417 var nss = matches[2];
110418 var urnScheme = scheme + ":" + (options.nid || nid);
110419 var schemeHandler = SCHEMES[urnScheme];
110420 urnComponents.nid = nid;
110421 urnComponents.nss = nss;
110422 urnComponents.path = undefined;
110423
110424 if (schemeHandler) {
110425 urnComponents = schemeHandler.parse(urnComponents, options);
110426 }
110427 } else {
110428 urnComponents.error = urnComponents.error || "URN can not be parsed.";
110429 }
110430
110431 return urnComponents;
110432 },
110433 serialize: function serialize$$1(urnComponents, options) {
110434 var scheme = options.scheme || urnComponents.scheme || "urn";
110435 var nid = urnComponents.nid;
110436 var urnScheme = scheme + ":" + (options.nid || nid);
110437 var schemeHandler = SCHEMES[urnScheme];
110438
110439 if (schemeHandler) {
110440 urnComponents = schemeHandler.serialize(urnComponents, options);
110441 }
110442
110443 var uriComponents = urnComponents;
110444 var nss = urnComponents.nss;
110445 uriComponents.path = (nid || options.nid) + ":" + nss;
110446 return uriComponents;
110447 }
110448 };
110449 var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; //RFC 4122
110450
110451 var handler$4 = {
110452 scheme: "urn:uuid",
110453 parse: function parse(urnComponents, options) {
110454 var uuidComponents = urnComponents;
110455 uuidComponents.uuid = uuidComponents.nss;
110456 uuidComponents.nss = undefined;
110457
110458 if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
110459 uuidComponents.error = uuidComponents.error || "UUID is not valid.";
110460 }
110461
110462 return uuidComponents;
110463 },
110464 serialize: function serialize(uuidComponents, options) {
110465 var urnComponents = uuidComponents; //normalize UUID
110466
110467 urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
110468 return urnComponents;
110469 }
110470 };
110471 SCHEMES[handler.scheme] = handler;
110472 SCHEMES[handler$1.scheme] = handler$1;
110473 SCHEMES[handler$2.scheme] = handler$2;
110474 SCHEMES[handler$3.scheme] = handler$3;
110475 SCHEMES[handler$4.scheme] = handler$4;
110476 exports.SCHEMES = SCHEMES;
110477 exports.pctEncChar = pctEncChar;
110478 exports.pctDecChars = pctDecChars;
110479 exports.parse = parse;
110480 exports.removeDotSegments = removeDotSegments;
110481 exports.serialize = serialize;
110482 exports.resolveComponents = resolveComponents;
110483 exports.resolve = resolve;
110484 exports.normalize = normalize;
110485 exports.equal = equal;
110486 exports.escapeComponent = escapeComponent;
110487 exports.unescapeComponent = unescapeComponent;
110488 Object.defineProperty(exports, '__esModule', {
110489 value: true
110490 });
110491});
110492
110493/***/ }),
6a5a0f88 110494/* 733 */
eb39fafa
DC
110495/***/ (function(module, exports, __webpack_require__) {
110496
110497"use strict";
110498 // do not edit .js files directly - edit src/index.jst
110499
110500module.exports = function equal(a, b) {
110501 if (a === b) return true;
110502
110503 if (a && b && typeof a == 'object' && typeof b == 'object') {
110504 if (a.constructor !== b.constructor) return false;
110505 var length, i, keys;
110506
110507 if (Array.isArray(a)) {
110508 length = a.length;
110509 if (length != b.length) return false;
110510
110511 for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
110512
110513 return true;
110514 }
110515
110516 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
110517 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
110518 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
110519 keys = Object.keys(a);
110520 length = keys.length;
110521 if (length !== Object.keys(b).length) return false;
110522
110523 for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
110524
110525 for (i = length; i-- !== 0;) {
110526 var key = keys[i];
110527 if (!equal(a[key], b[key])) return false;
110528 }
110529
110530 return true;
110531 } // true if both NaN, false otherwise
110532
110533
110534 return a !== a && b !== b;
110535};
110536
110537/***/ }),
6a5a0f88 110538/* 734 */
eb39fafa
DC
110539/***/ (function(module, exports, __webpack_require__) {
110540
110541"use strict";
110542
110543
110544module.exports = {
110545 copy: copy,
110546 checkDataType: checkDataType,
110547 checkDataTypes: checkDataTypes,
110548 coerceToTypes: coerceToTypes,
110549 toHash: toHash,
110550 getProperty: getProperty,
110551 escapeQuotes: escapeQuotes,
6a5a0f88
TL
110552 equal: __webpack_require__(733),
110553 ucs2length: __webpack_require__(735),
eb39fafa
DC
110554 varOccurences: varOccurences,
110555 varReplace: varReplace,
110556 cleanUpCode: cleanUpCode,
110557 finalCleanUpCode: finalCleanUpCode,
110558 schemaHasRules: schemaHasRules,
110559 schemaHasRulesExcept: schemaHasRulesExcept,
110560 schemaUnknownRules: schemaUnknownRules,
110561 toQuotedString: toQuotedString,
110562 getPathExpr: getPathExpr,
110563 getPath: getPath,
110564 getData: getData,
110565 unescapeFragment: unescapeFragment,
110566 unescapeJsonPointer: unescapeJsonPointer,
110567 escapeFragment: escapeFragment,
110568 escapeJsonPointer: escapeJsonPointer
110569};
110570
110571function copy(o, to) {
110572 to = to || {};
110573
110574 for (var key in o) to[key] = o[key];
110575
110576 return to;
110577}
110578
110579function checkDataType(dataType, data, negate) {
110580 var EQUAL = negate ? ' !== ' : ' === ',
110581 AND = negate ? ' || ' : ' && ',
110582 OK = negate ? '!' : '',
110583 NOT = negate ? '' : '!';
110584
110585 switch (dataType) {
110586 case 'null':
110587 return data + EQUAL + 'null';
110588
110589 case 'array':
110590 return OK + 'Array.isArray(' + data + ')';
110591
110592 case 'object':
110593 return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))';
110594
110595 case 'integer':
110596 return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + ')';
110597
110598 default:
110599 return 'typeof ' + data + EQUAL + '"' + dataType + '"';
110600 }
110601}
110602
110603function checkDataTypes(dataTypes, data) {
110604 switch (dataTypes.length) {
110605 case 1:
110606 return checkDataType(dataTypes[0], data, true);
110607
110608 default:
110609 var code = '';
110610 var types = toHash(dataTypes);
110611
110612 if (types.array && types.object) {
110613 code = types.null ? '(' : '(!' + data + ' || ';
110614 code += 'typeof ' + data + ' !== "object")';
110615 delete types.null;
110616 delete types.array;
110617 delete types.object;
110618 }
110619
110620 if (types.number) delete types.integer;
110621
110622 for (var t in types) code += (code ? ' && ' : '') + checkDataType(t, data, true);
110623
110624 return code;
110625 }
110626}
110627
110628var COERCE_TO_TYPES = toHash(['string', 'number', 'integer', 'boolean', 'null']);
110629
110630function coerceToTypes(optionCoerceTypes, dataTypes) {
110631 if (Array.isArray(dataTypes)) {
110632 var types = [];
110633
110634 for (var i = 0; i < dataTypes.length; i++) {
110635 var t = dataTypes[i];
110636 if (COERCE_TO_TYPES[t]) types[types.length] = t;else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
110637 }
110638
110639 if (types.length) return types;
110640 } else if (COERCE_TO_TYPES[dataTypes]) {
110641 return [dataTypes];
110642 } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
110643 return ['array'];
110644 }
110645}
110646
110647function toHash(arr) {
110648 var hash = {};
110649
110650 for (var i = 0; i < arr.length; i++) hash[arr[i]] = true;
110651
110652 return hash;
110653}
110654
110655var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
110656var SINGLE_QUOTE = /'|\\/g;
110657
110658function getProperty(key) {
110659 return typeof key == 'number' ? '[' + key + ']' : IDENTIFIER.test(key) ? '.' + key : "['" + escapeQuotes(key) + "']";
110660}
110661
110662function escapeQuotes(str) {
110663 return str.replace(SINGLE_QUOTE, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\f/g, '\\f').replace(/\t/g, '\\t');
110664}
110665
110666function varOccurences(str, dataVar) {
110667 dataVar += '[^0-9]';
110668 var matches = str.match(new RegExp(dataVar, 'g'));
110669 return matches ? matches.length : 0;
110670}
110671
110672function varReplace(str, dataVar, expr) {
110673 dataVar += '([^0-9])';
110674 expr = expr.replace(/\$/g, '$$$$');
110675 return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
110676}
110677
110678var EMPTY_ELSE = /else\s*{\s*}/g,
110679 EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g,
110680 EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
110681
110682function cleanUpCode(out) {
110683 return out.replace(EMPTY_ELSE, '').replace(EMPTY_IF_NO_ELSE, '').replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
110684}
110685
110686var ERRORS_REGEXP = /[^v.]errors/g,
110687 REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g,
110688 REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g,
110689 RETURN_VALID = 'return errors === 0;',
110690 RETURN_TRUE = 'validate.errors = null; return true;',
110691 RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/,
110692 RETURN_DATA_ASYNC = 'return data;',
110693 ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g,
110694 REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;
110695
110696function finalCleanUpCode(out, async) {
110697 var matches = out.match(ERRORS_REGEXP);
110698
110699 if (matches && matches.length == 2) {
110700 out = async ? out.replace(REMOVE_ERRORS_ASYNC, '').replace(RETURN_ASYNC, RETURN_DATA_ASYNC) : out.replace(REMOVE_ERRORS, '').replace(RETURN_VALID, RETURN_TRUE);
110701 }
110702
110703 matches = out.match(ROOTDATA_REGEXP);
110704 if (!matches || matches.length !== 3) return out;
110705 return out.replace(REMOVE_ROOTDATA, '');
110706}
110707
110708function schemaHasRules(schema, rules) {
110709 if (typeof schema == 'boolean') return !schema;
110710
110711 for (var key in schema) if (rules[key]) return true;
110712}
110713
110714function schemaHasRulesExcept(schema, rules, exceptKeyword) {
110715 if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
110716
110717 for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
110718}
110719
110720function schemaUnknownRules(schema, rules) {
110721 if (typeof schema == 'boolean') return;
110722
110723 for (var key in schema) if (!rules[key]) return key;
110724}
110725
110726function toQuotedString(str) {
110727 return '\'' + escapeQuotes(str) + '\'';
110728}
110729
110730function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
110731 var path = jsonPointers // false by default
110732 ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') : isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'';
110733 return joinPaths(currentPath, path);
110734}
110735
110736function getPath(currentPath, prop, jsonPointers) {
110737 var path = jsonPointers // false by default
110738 ? toQuotedString('/' + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
110739 return joinPaths(currentPath, path);
110740}
110741
110742var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
110743var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
110744
110745function getData($data, lvl, paths) {
110746 var up, jsonPointer, data, matches;
110747 if ($data === '') return 'rootData';
110748
110749 if ($data[0] == '/') {
110750 if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
110751 jsonPointer = $data;
110752 data = 'rootData';
110753 } else {
110754 matches = $data.match(RELATIVE_JSON_POINTER);
110755 if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
110756 up = +matches[1];
110757 jsonPointer = matches[2];
110758
110759 if (jsonPointer == '#') {
110760 if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
110761 return paths[lvl - up];
110762 }
110763
110764 if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
110765 data = 'data' + (lvl - up || '');
110766 if (!jsonPointer) return data;
110767 }
110768
110769 var expr = data;
110770 var segments = jsonPointer.split('/');
110771
110772 for (var i = 0; i < segments.length; i++) {
110773 var segment = segments[i];
110774
110775 if (segment) {
110776 data += getProperty(unescapeJsonPointer(segment));
110777 expr += ' && ' + data;
110778 }
110779 }
110780
110781 return expr;
110782}
110783
110784function joinPaths(a, b) {
110785 if (a == '""') return b;
110786 return (a + ' + ' + b).replace(/' \+ '/g, '');
110787}
110788
110789function unescapeFragment(str) {
110790 return unescapeJsonPointer(decodeURIComponent(str));
110791}
110792
110793function escapeFragment(str) {
110794 return encodeURIComponent(escapeJsonPointer(str));
110795}
110796
110797function escapeJsonPointer(str) {
110798 return str.replace(/~/g, '~0').replace(/\//g, '~1');
110799}
110800
110801function unescapeJsonPointer(str) {
110802 return str.replace(/~1/g, '/').replace(/~0/g, '~');
110803}
110804
110805/***/ }),
6a5a0f88 110806/* 735 */
eb39fafa
DC
110807/***/ (function(module, exports, __webpack_require__) {
110808
110809"use strict";
110810 // https://mathiasbynens.be/notes/javascript-encoding
110811// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
110812
110813module.exports = function ucs2length(str) {
110814 var length = 0,
110815 len = str.length,
110816 pos = 0,
110817 value;
110818
110819 while (pos < len) {
110820 length++;
110821 value = str.charCodeAt(pos++);
110822
110823 if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
110824 // high surrogate, and there is a next character
110825 value = str.charCodeAt(pos);
110826 if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
110827 }
110828 }
110829
110830 return length;
110831};
110832
110833/***/ }),
6a5a0f88 110834/* 736 */
eb39fafa
DC
110835/***/ (function(module, exports, __webpack_require__) {
110836
110837"use strict";
110838
110839
6a5a0f88 110840var util = __webpack_require__(734);
eb39fafa
DC
110841
110842module.exports = SchemaObject;
110843
110844function SchemaObject(obj) {
110845 util.copy(obj, this);
110846}
110847
110848/***/ }),
6a5a0f88 110849/* 737 */
eb39fafa
DC
110850/***/ (function(module, exports, __webpack_require__) {
110851
110852"use strict";
110853
110854
110855var traverse = module.exports = function (schema, opts, cb) {
110856 // Legacy support for v0.3.1 and earlier.
110857 if (typeof opts == 'function') {
110858 cb = opts;
110859 opts = {};
110860 }
110861
110862 cb = opts.cb || cb;
110863 var pre = typeof cb == 'function' ? cb : cb.pre || function () {};
110864
110865 var post = cb.post || function () {};
110866
110867 _traverse(opts, pre, post, schema, '', schema);
110868};
110869
110870traverse.keywords = {
110871 additionalItems: true,
110872 items: true,
110873 contains: true,
110874 additionalProperties: true,
110875 propertyNames: true,
110876 not: true
110877};
110878traverse.arrayKeywords = {
110879 items: true,
110880 allOf: true,
110881 anyOf: true,
110882 oneOf: true
110883};
110884traverse.propsKeywords = {
110885 definitions: true,
110886 properties: true,
110887 patternProperties: true,
110888 dependencies: true
110889};
110890traverse.skipKeywords = {
110891 default: true,
110892 enum: true,
110893 const: true,
110894 required: true,
110895 maximum: true,
110896 minimum: true,
110897 exclusiveMaximum: true,
110898 exclusiveMinimum: true,
110899 multipleOf: true,
110900 maxLength: true,
110901 minLength: true,
110902 pattern: true,
110903 format: true,
110904 maxItems: true,
110905 minItems: true,
110906 uniqueItems: true,
110907 maxProperties: true,
110908 minProperties: true
110909};
110910
110911function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
110912 if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
110913 pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
110914
110915 for (var key in schema) {
110916 var sch = schema[key];
110917
110918 if (Array.isArray(sch)) {
110919 if (key in traverse.arrayKeywords) {
110920 for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
110921 }
110922 } else if (key in traverse.propsKeywords) {
110923 if (sch && typeof sch == 'object') {
110924 for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
110925 }
110926 } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
110927 _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
110928 }
110929 }
110930
110931 post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
110932 }
110933}
110934
110935function escapeJsonPtr(str) {
110936 return str.replace(/~/g, '~0').replace(/\//g, '~1');
110937}
110938
110939/***/ }),
6a5a0f88 110940/* 738 */
eb39fafa
DC
110941/***/ (function(module, exports, __webpack_require__) {
110942
110943"use strict";
110944
110945
6a5a0f88 110946var resolve = __webpack_require__(731);
eb39fafa
DC
110947
110948module.exports = {
110949 Validation: errorSubclass(ValidationError),
110950 MissingRef: errorSubclass(MissingRefError)
110951};
110952
110953function ValidationError(errors) {
110954 this.message = 'validation failed';
110955 this.errors = errors;
110956 this.ajv = this.validation = true;
110957}
110958
110959MissingRefError.message = function (baseId, ref) {
110960 return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
110961};
110962
110963function MissingRefError(baseId, ref, message) {
110964 this.message = message || MissingRefError.message(baseId, ref);
110965 this.missingRef = resolve.url(baseId, ref);
110966 this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
110967}
110968
110969function errorSubclass(Subclass) {
110970 Subclass.prototype = Object.create(Error.prototype);
110971 Subclass.prototype.constructor = Subclass;
110972 return Subclass;
110973}
110974
110975/***/ }),
6a5a0f88 110976/* 739 */
eb39fafa
DC
110977/***/ (function(module, exports, __webpack_require__) {
110978
110979"use strict";
110980
110981
110982module.exports = function (data, opts) {
110983 if (!opts) opts = {};
110984 if (typeof opts === 'function') opts = {
110985 cmp: opts
110986 };
110987 var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
110988
110989 var cmp = opts.cmp && function (f) {
110990 return function (node) {
110991 return function (a, b) {
110992 var aobj = {
110993 key: a,
110994 value: node[a]
110995 };
110996 var bobj = {
110997 key: b,
110998 value: node[b]
110999 };
111000 return f(aobj, bobj);
111001 };
111002 };
111003 }(opts.cmp);
111004
111005 var seen = [];
111006 return function stringify(node) {
111007 if (node && node.toJSON && typeof node.toJSON === 'function') {
111008 node = node.toJSON();
111009 }
111010
111011 if (node === undefined) return;
111012 if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
111013 if (typeof node !== 'object') return JSON.stringify(node);
111014 var i, out;
111015
111016 if (Array.isArray(node)) {
111017 out = '[';
111018
111019 for (i = 0; i < node.length; i++) {
111020 if (i) out += ',';
111021 out += stringify(node[i]) || 'null';
111022 }
111023
111024 return out + ']';
111025 }
111026
111027 if (node === null) return 'null';
111028
111029 if (seen.indexOf(node) !== -1) {
111030 if (cycles) return JSON.stringify('__cycle__');
111031 throw new TypeError('Converting circular structure to JSON');
111032 }
111033
111034 var seenIndex = seen.push(node) - 1;
111035 var keys = Object.keys(node).sort(cmp && cmp(node));
111036 out = '';
111037
111038 for (i = 0; i < keys.length; i++) {
111039 var key = keys[i];
111040 var value = stringify(node[key]);
111041 if (!value) continue;
111042 if (out) out += ',';
111043 out += JSON.stringify(key) + ':' + value;
111044 }
111045
111046 seen.splice(seenIndex, 1);
111047 return '{' + out + '}';
111048 }(data);
111049};
111050
111051/***/ }),
6a5a0f88 111052/* 740 */
eb39fafa
DC
111053/***/ (function(module, exports, __webpack_require__) {
111054
111055"use strict";
111056
111057
111058module.exports = function generate_validate(it, $keyword, $ruleType) {
111059 var out = '';
111060
111061 var $async = it.schema.$async === true,
111062 $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
111063 $id = it.self._getId(it.schema);
111064
111065 if (it.opts.strictKeywords) {
111066 var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
111067
111068 if ($unknownKwd) {
111069 var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
111070 if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);else throw new Error($keywordsMsg);
111071 }
111072 }
111073
111074 if (it.isTop) {
111075 out += ' var validate = ';
111076
111077 if ($async) {
111078 it.async = true;
111079 out += 'async ';
111080 }
111081
111082 out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
111083
111084 if ($id && (it.opts.sourceCode || it.opts.processCode)) {
111085 out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
111086 }
111087 }
111088
111089 if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
111090 var $keyword = 'false schema';
111091 var $lvl = it.level;
111092 var $dataLvl = it.dataLevel;
111093 var $schema = it.schema[$keyword];
111094 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
111095 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
111096 var $breakOnError = !it.opts.allErrors;
111097 var $errorKeyword;
111098 var $data = 'data' + ($dataLvl || '');
111099 var $valid = 'valid' + $lvl;
111100
111101 if (it.schema === false) {
111102 if (it.isTop) {
111103 $breakOnError = true;
111104 } else {
111105 out += ' var ' + $valid + ' = false; ';
111106 }
111107
111108 var $$outStack = $$outStack || [];
111109 $$outStack.push(out);
111110 out = '';
111111 /* istanbul ignore else */
111112
111113 if (it.createErrors !== false) {
111114 out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
111115
111116 if (it.opts.messages !== false) {
111117 out += ' , message: \'boolean schema is false\' ';
111118 }
111119
111120 if (it.opts.verbose) {
111121 out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
111122 }
111123
111124 out += ' } ';
111125 } else {
111126 out += ' {} ';
111127 }
111128
111129 var __err = out;
111130 out = $$outStack.pop();
111131
111132 if (!it.compositeRule && $breakOnError) {
111133 /* istanbul ignore if */
111134 if (it.async) {
111135 out += ' throw new ValidationError([' + __err + ']); ';
111136 } else {
111137 out += ' validate.errors = [' + __err + ']; return false; ';
111138 }
111139 } else {
111140 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
111141 }
111142 } else {
111143 if (it.isTop) {
111144 if ($async) {
111145 out += ' return data; ';
111146 } else {
111147 out += ' validate.errors = null; return true; ';
111148 }
111149 } else {
111150 out += ' var ' + $valid + ' = true; ';
111151 }
111152 }
111153
111154 if (it.isTop) {
111155 out += ' }; return validate; ';
111156 }
111157
111158 return out;
111159 }
111160
111161 if (it.isTop) {
111162 var $top = it.isTop,
111163 $lvl = it.level = 0,
111164 $dataLvl = it.dataLevel = 0,
111165 $data = 'data';
111166 it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
111167 it.baseId = it.baseId || it.rootId;
111168 delete it.isTop;
111169 it.dataPathArr = [undefined];
111170
111171 if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
111172 var $defaultMsg = 'default is ignored in the schema root';
111173 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);else throw new Error($defaultMsg);
111174 }
111175
111176 out += ' var vErrors = null; ';
111177 out += ' var errors = 0; ';
111178 out += ' if (rootData === undefined) rootData = data; ';
111179 } else {
111180 var $lvl = it.level,
111181 $dataLvl = it.dataLevel,
111182 $data = 'data' + ($dataLvl || '');
111183 if ($id) it.baseId = it.resolve.url(it.baseId, $id);
111184 if ($async && !it.async) throw new Error('async schema in sync schema');
111185 out += ' var errs_' + $lvl + ' = errors;';
111186 }
111187
111188 var $valid = 'valid' + $lvl,
111189 $breakOnError = !it.opts.allErrors,
111190 $closingBraces1 = '',
111191 $closingBraces2 = '';
111192 var $errorKeyword;
111193 var $typeSchema = it.schema.type,
111194 $typeIsArray = Array.isArray($typeSchema);
111195
111196 if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
111197 if ($typeIsArray) {
111198 if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
111199 } else if ($typeSchema != 'null') {
111200 $typeSchema = [$typeSchema, 'null'];
111201 $typeIsArray = true;
111202 }
111203 }
111204
111205 if ($typeIsArray && $typeSchema.length == 1) {
111206 $typeSchema = $typeSchema[0];
111207 $typeIsArray = false;
111208 }
111209
111210 if (it.schema.$ref && $refKeywords) {
111211 if (it.opts.extendRefs == 'fail') {
111212 throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
111213 } else if (it.opts.extendRefs !== true) {
111214 $refKeywords = false;
111215 it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
111216 }
111217 }
111218
111219 if (it.schema.$comment && it.opts.$comment) {
111220 out += ' ' + it.RULES.all.$comment.code(it, '$comment');
111221 }
111222
111223 if ($typeSchema) {
111224 if (it.opts.coerceTypes) {
111225 var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
111226 }
111227
111228 var $rulesGroup = it.RULES.types[$typeSchema];
111229
111230 if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
111231 var $schemaPath = it.schemaPath + '.type',
111232 $errSchemaPath = it.errSchemaPath + '/type';
111233 var $schemaPath = it.schemaPath + '.type',
111234 $errSchemaPath = it.errSchemaPath + '/type',
111235 $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
111236 out += ' if (' + it.util[$method]($typeSchema, $data, true) + ') { ';
111237
111238 if ($coerceToTypes) {
111239 var $dataType = 'dataType' + $lvl,
111240 $coerced = 'coerced' + $lvl;
111241 out += ' var ' + $dataType + ' = typeof ' + $data + '; ';
111242
111243 if (it.opts.coerceTypes == 'array') {
111244 out += ' if (' + $dataType + ' == \'object\' && Array.isArray(' + $data + ')) ' + $dataType + ' = \'array\'; ';
111245 }
111246
111247 out += ' var ' + $coerced + ' = undefined; ';
111248 var $bracesCoercion = '';
111249 var arr1 = $coerceToTypes;
111250
111251 if (arr1) {
111252 var $type,
111253 $i = -1,
111254 l1 = arr1.length - 1;
111255
111256 while ($i < l1) {
111257 $type = arr1[$i += 1];
111258
111259 if ($i) {
111260 out += ' if (' + $coerced + ' === undefined) { ';
111261 $bracesCoercion += '}';
111262 }
111263
111264 if (it.opts.coerceTypes == 'array' && $type != 'array') {
111265 out += ' if (' + $dataType + ' == \'array\' && ' + $data + '.length == 1) { ' + $coerced + ' = ' + $data + ' = ' + $data + '[0]; ' + $dataType + ' = typeof ' + $data + '; } ';
111266 }
111267
111268 if ($type == 'string') {
111269 out += ' if (' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\') ' + $coerced + ' = \'\' + ' + $data + '; else if (' + $data + ' === null) ' + $coerced + ' = \'\'; ';
111270 } else if ($type == 'number' || $type == 'integer') {
111271 out += ' if (' + $dataType + ' == \'boolean\' || ' + $data + ' === null || (' + $dataType + ' == \'string\' && ' + $data + ' && ' + $data + ' == +' + $data + ' ';
111272
111273 if ($type == 'integer') {
111274 out += ' && !(' + $data + ' % 1)';
111275 }
111276
111277 out += ')) ' + $coerced + ' = +' + $data + '; ';
111278 } else if ($type == 'boolean') {
111279 out += ' if (' + $data + ' === \'false\' || ' + $data + ' === 0 || ' + $data + ' === null) ' + $coerced + ' = false; else if (' + $data + ' === \'true\' || ' + $data + ' === 1) ' + $coerced + ' = true; ';
111280 } else if ($type == 'null') {
111281 out += ' if (' + $data + ' === \'\' || ' + $data + ' === 0 || ' + $data + ' === false) ' + $coerced + ' = null; ';
111282 } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
111283 out += ' if (' + $dataType + ' == \'string\' || ' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\' || ' + $data + ' == null) ' + $coerced + ' = [' + $data + ']; ';
111284 }
111285 }
111286 }
111287
111288 out += ' ' + $bracesCoercion + ' if (' + $coerced + ' === undefined) { ';
111289 var $$outStack = $$outStack || [];
111290 $$outStack.push(out);
111291 out = '';
111292 /* istanbul ignore else */
111293
111294 if (it.createErrors !== false) {
111295 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \'';
111296
111297 if ($typeIsArray) {
111298 out += '' + $typeSchema.join(",");
111299 } else {
111300 out += '' + $typeSchema;
111301 }
111302
111303 out += '\' } ';
111304
111305 if (it.opts.messages !== false) {
111306 out += ' , message: \'should be ';
111307
111308 if ($typeIsArray) {
111309 out += '' + $typeSchema.join(",");
111310 } else {
111311 out += '' + $typeSchema;
111312 }
111313
111314 out += '\' ';
111315 }
111316
111317 if (it.opts.verbose) {
111318 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
111319 }
111320
111321 out += ' } ';
111322 } else {
111323 out += ' {} ';
111324 }
111325
111326 var __err = out;
111327 out = $$outStack.pop();
111328
111329 if (!it.compositeRule && $breakOnError) {
111330 /* istanbul ignore if */
111331 if (it.async) {
111332 out += ' throw new ValidationError([' + __err + ']); ';
111333 } else {
111334 out += ' validate.errors = [' + __err + ']; return false; ';
111335 }
111336 } else {
111337 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
111338 }
111339
111340 out += ' } else { ';
111341 var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData',
111342 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
111343 out += ' ' + $data + ' = ' + $coerced + '; ';
111344
111345 if (!$dataLvl) {
111346 out += 'if (' + $parentData + ' !== undefined)';
111347 }
111348
111349 out += ' ' + $parentData + '[' + $parentDataProperty + '] = ' + $coerced + '; } ';
111350 } else {
111351 var $$outStack = $$outStack || [];
111352 $$outStack.push(out);
111353 out = '';
111354 /* istanbul ignore else */
111355
111356 if (it.createErrors !== false) {
111357 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \'';
111358
111359 if ($typeIsArray) {
111360 out += '' + $typeSchema.join(",");
111361 } else {
111362 out += '' + $typeSchema;
111363 }
111364
111365 out += '\' } ';
111366
111367 if (it.opts.messages !== false) {
111368 out += ' , message: \'should be ';
111369
111370 if ($typeIsArray) {
111371 out += '' + $typeSchema.join(",");
111372 } else {
111373 out += '' + $typeSchema;
111374 }
111375
111376 out += '\' ';
111377 }
111378
111379 if (it.opts.verbose) {
111380 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
111381 }
111382
111383 out += ' } ';
111384 } else {
111385 out += ' {} ';
111386 }
111387
111388 var __err = out;
111389 out = $$outStack.pop();
111390
111391 if (!it.compositeRule && $breakOnError) {
111392 /* istanbul ignore if */
111393 if (it.async) {
111394 out += ' throw new ValidationError([' + __err + ']); ';
111395 } else {
111396 out += ' validate.errors = [' + __err + ']; return false; ';
111397 }
111398 } else {
111399 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
111400 }
111401 }
111402
111403 out += ' } ';
111404 }
111405 }
111406
111407 if (it.schema.$ref && !$refKeywords) {
111408 out += ' ' + it.RULES.all.$ref.code(it, '$ref') + ' ';
111409
111410 if ($breakOnError) {
111411 out += ' } if (errors === ';
111412
111413 if ($top) {
111414 out += '0';
111415 } else {
111416 out += 'errs_' + $lvl;
111417 }
111418
111419 out += ') { ';
111420 $closingBraces2 += '}';
111421 }
111422 } else {
111423 var arr2 = it.RULES;
111424
111425 if (arr2) {
111426 var $rulesGroup,
111427 i2 = -1,
111428 l2 = arr2.length - 1;
111429
111430 while (i2 < l2) {
111431 $rulesGroup = arr2[i2 += 1];
111432
111433 if ($shouldUseGroup($rulesGroup)) {
111434 if ($rulesGroup.type) {
111435 out += ' if (' + it.util.checkDataType($rulesGroup.type, $data) + ') { ';
111436 }
111437
111438 if (it.opts.useDefaults) {
111439 if ($rulesGroup.type == 'object' && it.schema.properties) {
111440 var $schema = it.schema.properties,
111441 $schemaKeys = Object.keys($schema);
111442 var arr3 = $schemaKeys;
111443
111444 if (arr3) {
111445 var $propertyKey,
111446 i3 = -1,
111447 l3 = arr3.length - 1;
111448
111449 while (i3 < l3) {
111450 $propertyKey = arr3[i3 += 1];
111451 var $sch = $schema[$propertyKey];
111452
111453 if ($sch.default !== undefined) {
111454 var $passData = $data + it.util.getProperty($propertyKey);
111455
111456 if (it.compositeRule) {
111457 if (it.opts.strictDefaults) {
111458 var $defaultMsg = 'default is ignored for: ' + $passData;
111459 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);else throw new Error($defaultMsg);
111460 }
111461 } else {
111462 out += ' if (' + $passData + ' === undefined ';
111463
111464 if (it.opts.useDefaults == 'empty') {
111465 out += ' || ' + $passData + ' === null || ' + $passData + ' === \'\' ';
111466 }
111467
111468 out += ' ) ' + $passData + ' = ';
111469
111470 if (it.opts.useDefaults == 'shared') {
111471 out += ' ' + it.useDefault($sch.default) + ' ';
111472 } else {
111473 out += ' ' + JSON.stringify($sch.default) + ' ';
111474 }
111475
111476 out += '; ';
111477 }
111478 }
111479 }
111480 }
111481 } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
111482 var arr4 = it.schema.items;
111483
111484 if (arr4) {
111485 var $sch,
111486 $i = -1,
111487 l4 = arr4.length - 1;
111488
111489 while ($i < l4) {
111490 $sch = arr4[$i += 1];
111491
111492 if ($sch.default !== undefined) {
111493 var $passData = $data + '[' + $i + ']';
111494
111495 if (it.compositeRule) {
111496 if (it.opts.strictDefaults) {
111497 var $defaultMsg = 'default is ignored for: ' + $passData;
111498 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);else throw new Error($defaultMsg);
111499 }
111500 } else {
111501 out += ' if (' + $passData + ' === undefined ';
111502
111503 if (it.opts.useDefaults == 'empty') {
111504 out += ' || ' + $passData + ' === null || ' + $passData + ' === \'\' ';
111505 }
111506
111507 out += ' ) ' + $passData + ' = ';
111508
111509 if (it.opts.useDefaults == 'shared') {
111510 out += ' ' + it.useDefault($sch.default) + ' ';
111511 } else {
111512 out += ' ' + JSON.stringify($sch.default) + ' ';
111513 }
111514
111515 out += '; ';
111516 }
111517 }
111518 }
111519 }
111520 }
111521 }
111522
111523 var arr5 = $rulesGroup.rules;
111524
111525 if (arr5) {
111526 var $rule,
111527 i5 = -1,
111528 l5 = arr5.length - 1;
111529
111530 while (i5 < l5) {
111531 $rule = arr5[i5 += 1];
111532
111533 if ($shouldUseRule($rule)) {
111534 var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
111535
111536 if ($code) {
111537 out += ' ' + $code + ' ';
111538
111539 if ($breakOnError) {
111540 $closingBraces1 += '}';
111541 }
111542 }
111543 }
111544 }
111545 }
111546
111547 if ($breakOnError) {
111548 out += ' ' + $closingBraces1 + ' ';
111549 $closingBraces1 = '';
111550 }
111551
111552 if ($rulesGroup.type) {
111553 out += ' } ';
111554
111555 if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
111556 out += ' else { ';
111557 var $schemaPath = it.schemaPath + '.type',
111558 $errSchemaPath = it.errSchemaPath + '/type';
111559 var $$outStack = $$outStack || [];
111560 $$outStack.push(out);
111561 out = '';
111562 /* istanbul ignore else */
111563
111564 if (it.createErrors !== false) {
111565 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \'';
111566
111567 if ($typeIsArray) {
111568 out += '' + $typeSchema.join(",");
111569 } else {
111570 out += '' + $typeSchema;
111571 }
111572
111573 out += '\' } ';
111574
111575 if (it.opts.messages !== false) {
111576 out += ' , message: \'should be ';
111577
111578 if ($typeIsArray) {
111579 out += '' + $typeSchema.join(",");
111580 } else {
111581 out += '' + $typeSchema;
111582 }
111583
111584 out += '\' ';
111585 }
111586
111587 if (it.opts.verbose) {
111588 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
111589 }
111590
111591 out += ' } ';
111592 } else {
111593 out += ' {} ';
111594 }
111595
111596 var __err = out;
111597 out = $$outStack.pop();
111598
111599 if (!it.compositeRule && $breakOnError) {
111600 /* istanbul ignore if */
111601 if (it.async) {
111602 out += ' throw new ValidationError([' + __err + ']); ';
111603 } else {
111604 out += ' validate.errors = [' + __err + ']; return false; ';
111605 }
111606 } else {
111607 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
111608 }
111609
111610 out += ' } ';
111611 }
111612 }
111613
111614 if ($breakOnError) {
111615 out += ' if (errors === ';
111616
111617 if ($top) {
111618 out += '0';
111619 } else {
111620 out += 'errs_' + $lvl;
111621 }
111622
111623 out += ') { ';
111624 $closingBraces2 += '}';
111625 }
111626 }
111627 }
111628 }
111629 }
111630
111631 if ($breakOnError) {
111632 out += ' ' + $closingBraces2 + ' ';
111633 }
111634
111635 if ($top) {
111636 if ($async) {
111637 out += ' if (errors === 0) return data; ';
111638 out += ' else throw new ValidationError(vErrors); ';
111639 } else {
111640 out += ' validate.errors = vErrors; ';
111641 out += ' return errors === 0; ';
111642 }
111643
111644 out += ' }; return validate;';
111645 } else {
111646 out += ' var ' + $valid + ' = errors === errs_' + $lvl + ';';
111647 }
111648
111649 out = it.util.cleanUpCode(out);
111650
111651 if ($top) {
111652 out = it.util.finalCleanUpCode(out, $async);
111653 }
111654
111655 function $shouldUseGroup($rulesGroup) {
111656 var rules = $rulesGroup.rules;
111657
111658 for (var i = 0; i < rules.length; i++) if ($shouldUseRule(rules[i])) return true;
111659 }
111660
111661 function $shouldUseRule($rule) {
111662 return it.schema[$rule.keyword] !== undefined || $rule.implements && $ruleImplementsSomeKeyword($rule);
111663 }
111664
111665 function $ruleImplementsSomeKeyword($rule) {
111666 var impl = $rule.implements;
111667
111668 for (var i = 0; i < impl.length; i++) if (it.schema[impl[i]] !== undefined) return true;
111669 }
111670
111671 return out;
111672};
111673
111674/***/ }),
6a5a0f88 111675/* 741 */
eb39fafa
DC
111676/***/ (function(module, exports, __webpack_require__) {
111677
111678"use strict";
111679
111680
111681var Cache = module.exports = function Cache() {
111682 this._cache = {};
111683};
111684
111685Cache.prototype.put = function Cache_put(key, value) {
111686 this._cache[key] = value;
111687};
111688
111689Cache.prototype.get = function Cache_get(key) {
111690 return this._cache[key];
111691};
111692
111693Cache.prototype.del = function Cache_del(key) {
111694 delete this._cache[key];
111695};
111696
111697Cache.prototype.clear = function Cache_clear() {
111698 this._cache = {};
111699};
111700
111701/***/ }),
6a5a0f88 111702/* 742 */
eb39fafa
DC
111703/***/ (function(module, exports, __webpack_require__) {
111704
111705"use strict";
111706
111707
6a5a0f88 111708var util = __webpack_require__(734);
eb39fafa
DC
111709
111710var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
111711var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
111712var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
111713var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
111714var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
111715var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; // uri-template: https://tools.ietf.org/html/rfc6570
111716
111717var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; // For the source: https://gist.github.com/dperini/729294
111718// For test cases: https://mathiasbynens.be/demo/url-regex
111719// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
111720// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
111721
111722var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
111723var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
111724var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
111725var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
111726var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
111727module.exports = formats;
111728
111729function formats(mode) {
111730 mode = mode == 'full' ? 'full' : 'fast';
111731 return util.copy(formats[mode]);
111732}
111733
111734formats.fast = {
111735 // date: http://tools.ietf.org/html/rfc3339#section-5.6
111736 date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
111737 // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
111738 time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
111739 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
111740 // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
111741 uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
111742 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
111743 'uri-template': URITEMPLATE,
111744 url: URL,
111745 // email (sources from jsen validator):
111746 // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
111747 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
111748 email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
111749 hostname: HOSTNAME,
111750 // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
111751 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
111752 // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
111753 ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
111754 regex: regex,
111755 // uuid: http://tools.ietf.org/html/rfc4122
111756 uuid: UUID,
111757 // JSON-pointer: https://tools.ietf.org/html/rfc6901
111758 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
111759 'json-pointer': JSON_POINTER,
111760 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
111761 // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
111762 'relative-json-pointer': RELATIVE_JSON_POINTER
111763};
111764formats.full = {
111765 date: date,
111766 time: time,
111767 'date-time': date_time,
111768 uri: uri,
111769 'uri-reference': URIREF,
111770 'uri-template': URITEMPLATE,
111771 url: URL,
111772 email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
111773 hostname: HOSTNAME,
111774 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
111775 ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
111776 regex: regex,
111777 uuid: UUID,
111778 'json-pointer': JSON_POINTER,
111779 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
111780 'relative-json-pointer': RELATIVE_JSON_POINTER
111781};
111782
111783function isLeapYear(year) {
111784 // https://tools.ietf.org/html/rfc3339#appendix-C
111785 return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
111786}
111787
111788function date(str) {
111789 // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
111790 var matches = str.match(DATE);
111791 if (!matches) return false;
111792 var year = +matches[1];
111793 var month = +matches[2];
111794 var day = +matches[3];
111795 return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
111796}
111797
111798function time(str, full) {
111799 var matches = str.match(TIME);
111800 if (!matches) return false;
111801 var hour = matches[1];
111802 var minute = matches[2];
111803 var second = matches[3];
111804 var timeZone = matches[5];
111805 return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone);
111806}
111807
111808var DATE_TIME_SEPARATOR = /t|\s/i;
111809
111810function date_time(str) {
111811 // http://tools.ietf.org/html/rfc3339#section-5.6
111812 var dateTime = str.split(DATE_TIME_SEPARATOR);
111813 return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
111814}
111815
111816var NOT_URI_FRAGMENT = /\/|:/;
111817
111818function uri(str) {
111819 // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
111820 return NOT_URI_FRAGMENT.test(str) && URI.test(str);
111821}
111822
111823var Z_ANCHOR = /[^\\]\\Z/;
111824
111825function regex(str) {
111826 if (Z_ANCHOR.test(str)) return false;
111827
111828 try {
111829 new RegExp(str);
111830 return true;
111831 } catch (e) {
111832 return false;
111833 }
111834}
111835
111836/***/ }),
6a5a0f88 111837/* 743 */
eb39fafa
DC
111838/***/ (function(module, exports, __webpack_require__) {
111839
111840"use strict";
111841
111842
6a5a0f88
TL
111843var ruleModules = __webpack_require__(744),
111844 toHash = __webpack_require__(734).toHash;
eb39fafa
DC
111845
111846module.exports = function rules() {
111847 var RULES = [{
111848 type: 'number',
111849 rules: [{
111850 'maximum': ['exclusiveMaximum']
111851 }, {
111852 'minimum': ['exclusiveMinimum']
111853 }, 'multipleOf', 'format']
111854 }, {
111855 type: 'string',
111856 rules: ['maxLength', 'minLength', 'pattern', 'format']
111857 }, {
111858 type: 'array',
111859 rules: ['maxItems', 'minItems', 'items', 'contains', 'uniqueItems']
111860 }, {
111861 type: 'object',
111862 rules: ['maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', {
111863 'properties': ['additionalProperties', 'patternProperties']
111864 }]
111865 }, {
111866 rules: ['$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if']
111867 }];
111868 var ALL = ['type', '$comment'];
111869 var KEYWORDS = ['$schema', '$id', 'id', '$data', '$async', 'title', 'description', 'default', 'definitions', 'examples', 'readOnly', 'writeOnly', 'contentMediaType', 'contentEncoding', 'additionalItems', 'then', 'else'];
111870 var TYPES = ['number', 'integer', 'string', 'array', 'object', 'boolean', 'null'];
111871 RULES.all = toHash(ALL);
111872 RULES.types = toHash(TYPES);
111873 RULES.forEach(function (group) {
111874 group.rules = group.rules.map(function (keyword) {
111875 var implKeywords;
111876
111877 if (typeof keyword == 'object') {
111878 var key = Object.keys(keyword)[0];
111879 implKeywords = keyword[key];
111880 keyword = key;
111881 implKeywords.forEach(function (k) {
111882 ALL.push(k);
111883 RULES.all[k] = true;
111884 });
111885 }
111886
111887 ALL.push(keyword);
111888 var rule = RULES.all[keyword] = {
111889 keyword: keyword,
111890 code: ruleModules[keyword],
111891 implements: implKeywords
111892 };
111893 return rule;
111894 });
111895 RULES.all.$comment = {
111896 keyword: '$comment',
111897 code: ruleModules.$comment
111898 };
111899 if (group.type) RULES.types[group.type] = group;
111900 });
111901 RULES.keywords = toHash(ALL.concat(KEYWORDS));
111902 RULES.custom = {};
111903 return RULES;
111904};
111905
111906/***/ }),
6a5a0f88 111907/* 744 */
eb39fafa
DC
111908/***/ (function(module, exports, __webpack_require__) {
111909
111910"use strict";
111911 //all requires must be explicit because browserify won't work with dynamic requires
111912
111913module.exports = {
6a5a0f88
TL
111914 '$ref': __webpack_require__(745),
111915 allOf: __webpack_require__(746),
111916 anyOf: __webpack_require__(747),
111917 '$comment': __webpack_require__(748),
111918 const: __webpack_require__(749),
111919 contains: __webpack_require__(750),
111920 dependencies: __webpack_require__(751),
111921 'enum': __webpack_require__(752),
111922 format: __webpack_require__(753),
111923 'if': __webpack_require__(754),
111924 items: __webpack_require__(755),
111925 maximum: __webpack_require__(756),
111926 minimum: __webpack_require__(756),
111927 maxItems: __webpack_require__(757),
111928 minItems: __webpack_require__(757),
111929 maxLength: __webpack_require__(758),
111930 minLength: __webpack_require__(758),
111931 maxProperties: __webpack_require__(759),
111932 minProperties: __webpack_require__(759),
111933 multipleOf: __webpack_require__(760),
111934 not: __webpack_require__(761),
111935 oneOf: __webpack_require__(762),
111936 pattern: __webpack_require__(763),
111937 properties: __webpack_require__(764),
111938 propertyNames: __webpack_require__(765),
111939 required: __webpack_require__(766),
111940 uniqueItems: __webpack_require__(767),
111941 validate: __webpack_require__(740)
eb39fafa
DC
111942};
111943
111944/***/ }),
6a5a0f88 111945/* 745 */
eb39fafa
DC
111946/***/ (function(module, exports, __webpack_require__) {
111947
111948"use strict";
111949
111950
111951module.exports = function generate_ref(it, $keyword, $ruleType) {
111952 var out = ' ';
111953 var $lvl = it.level;
111954 var $dataLvl = it.dataLevel;
111955 var $schema = it.schema[$keyword];
111956 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
111957 var $breakOnError = !it.opts.allErrors;
111958 var $data = 'data' + ($dataLvl || '');
111959 var $valid = 'valid' + $lvl;
111960 var $async, $refCode;
111961
111962 if ($schema == '#' || $schema == '#/') {
111963 if (it.isRoot) {
111964 $async = it.async;
111965 $refCode = 'validate';
111966 } else {
111967 $async = it.root.schema.$async === true;
111968 $refCode = 'root.refVal[0]';
111969 }
111970 } else {
111971 var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
111972
111973 if ($refVal === undefined) {
111974 var $message = it.MissingRefError.message(it.baseId, $schema);
111975
111976 if (it.opts.missingRefs == 'fail') {
111977 it.logger.error($message);
111978 var $$outStack = $$outStack || [];
111979 $$outStack.push(out);
111980 out = '';
111981 /* istanbul ignore else */
111982
111983 if (it.createErrors !== false) {
111984 out += ' { keyword: \'' + '$ref' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { ref: \'' + it.util.escapeQuotes($schema) + '\' } ';
111985
111986 if (it.opts.messages !== false) {
111987 out += ' , message: \'can\\\'t resolve reference ' + it.util.escapeQuotes($schema) + '\' ';
111988 }
111989
111990 if (it.opts.verbose) {
111991 out += ' , schema: ' + it.util.toQuotedString($schema) + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
111992 }
111993
111994 out += ' } ';
111995 } else {
111996 out += ' {} ';
111997 }
111998
111999 var __err = out;
112000 out = $$outStack.pop();
112001
112002 if (!it.compositeRule && $breakOnError) {
112003 /* istanbul ignore if */
112004 if (it.async) {
112005 out += ' throw new ValidationError([' + __err + ']); ';
112006 } else {
112007 out += ' validate.errors = [' + __err + ']; return false; ';
112008 }
112009 } else {
112010 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112011 }
112012
112013 if ($breakOnError) {
112014 out += ' if (false) { ';
112015 }
112016 } else if (it.opts.missingRefs == 'ignore') {
112017 it.logger.warn($message);
112018
112019 if ($breakOnError) {
112020 out += ' if (true) { ';
112021 }
112022 } else {
112023 throw new it.MissingRefError(it.baseId, $schema, $message);
112024 }
112025 } else if ($refVal.inline) {
112026 var $it = it.util.copy(it);
112027 $it.level++;
112028 var $nextValid = 'valid' + $it.level;
112029 $it.schema = $refVal.schema;
112030 $it.schemaPath = '';
112031 $it.errSchemaPath = $schema;
112032 var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
112033 out += ' ' + $code + ' ';
112034
112035 if ($breakOnError) {
112036 out += ' if (' + $nextValid + ') { ';
112037 }
112038 } else {
112039 $async = $refVal.$async === true || it.async && $refVal.$async !== false;
112040 $refCode = $refVal.code;
112041 }
112042 }
112043
112044 if ($refCode) {
112045 var $$outStack = $$outStack || [];
112046 $$outStack.push(out);
112047 out = '';
112048
112049 if (it.opts.passContext) {
112050 out += ' ' + $refCode + '.call(this, ';
112051 } else {
112052 out += ' ' + $refCode + '( ';
112053 }
112054
112055 out += ' ' + $data + ', (dataPath || \'\')';
112056
112057 if (it.errorPath != '""') {
112058 out += ' + ' + it.errorPath;
112059 }
112060
112061 var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData',
112062 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
112063 out += ' , ' + $parentData + ' , ' + $parentDataProperty + ', rootData) ';
112064 var __callValidate = out;
112065 out = $$outStack.pop();
112066
112067 if ($async) {
112068 if (!it.async) throw new Error('async schema referenced by sync schema');
112069
112070 if ($breakOnError) {
112071 out += ' var ' + $valid + '; ';
112072 }
112073
112074 out += ' try { await ' + __callValidate + '; ';
112075
112076 if ($breakOnError) {
112077 out += ' ' + $valid + ' = true; ';
112078 }
112079
112080 out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
112081
112082 if ($breakOnError) {
112083 out += ' ' + $valid + ' = false; ';
112084 }
112085
112086 out += ' } ';
112087
112088 if ($breakOnError) {
112089 out += ' if (' + $valid + ') { ';
112090 }
112091 } else {
112092 out += ' if (!' + __callValidate + ') { if (vErrors === null) vErrors = ' + $refCode + '.errors; else vErrors = vErrors.concat(' + $refCode + '.errors); errors = vErrors.length; } ';
112093
112094 if ($breakOnError) {
112095 out += ' else { ';
112096 }
112097 }
112098 }
112099
112100 return out;
112101};
112102
112103/***/ }),
6a5a0f88 112104/* 746 */
eb39fafa
DC
112105/***/ (function(module, exports, __webpack_require__) {
112106
112107"use strict";
112108
112109
112110module.exports = function generate_allOf(it, $keyword, $ruleType) {
112111 var out = ' ';
112112 var $schema = it.schema[$keyword];
112113 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112114 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112115 var $breakOnError = !it.opts.allErrors;
112116 var $it = it.util.copy(it);
112117 var $closingBraces = '';
112118 $it.level++;
112119 var $nextValid = 'valid' + $it.level;
112120 var $currentBaseId = $it.baseId,
112121 $allSchemasEmpty = true;
112122 var arr1 = $schema;
112123
112124 if (arr1) {
112125 var $sch,
112126 $i = -1,
112127 l1 = arr1.length - 1;
112128
112129 while ($i < l1) {
112130 $sch = arr1[$i += 1];
112131
112132 if (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)) {
112133 $allSchemasEmpty = false;
112134 $it.schema = $sch;
112135 $it.schemaPath = $schemaPath + '[' + $i + ']';
112136 $it.errSchemaPath = $errSchemaPath + '/' + $i;
112137 out += ' ' + it.validate($it) + ' ';
112138 $it.baseId = $currentBaseId;
112139
112140 if ($breakOnError) {
112141 out += ' if (' + $nextValid + ') { ';
112142 $closingBraces += '}';
112143 }
112144 }
112145 }
112146 }
112147
112148 if ($breakOnError) {
112149 if ($allSchemasEmpty) {
112150 out += ' if (true) { ';
112151 } else {
112152 out += ' ' + $closingBraces.slice(0, -1) + ' ';
112153 }
112154 }
112155
112156 out = it.util.cleanUpCode(out);
112157 return out;
112158};
112159
112160/***/ }),
6a5a0f88 112161/* 747 */
eb39fafa
DC
112162/***/ (function(module, exports, __webpack_require__) {
112163
112164"use strict";
112165
112166
112167module.exports = function generate_anyOf(it, $keyword, $ruleType) {
112168 var out = ' ';
112169 var $lvl = it.level;
112170 var $dataLvl = it.dataLevel;
112171 var $schema = it.schema[$keyword];
112172 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112173 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112174 var $breakOnError = !it.opts.allErrors;
112175 var $data = 'data' + ($dataLvl || '');
112176 var $valid = 'valid' + $lvl;
112177 var $errs = 'errs__' + $lvl;
112178 var $it = it.util.copy(it);
112179 var $closingBraces = '';
112180 $it.level++;
112181 var $nextValid = 'valid' + $it.level;
112182 var $noEmptySchema = $schema.every(function ($sch) {
112183 return it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all);
112184 });
112185
112186 if ($noEmptySchema) {
112187 var $currentBaseId = $it.baseId;
112188 out += ' var ' + $errs + ' = errors; var ' + $valid + ' = false; ';
112189 var $wasComposite = it.compositeRule;
112190 it.compositeRule = $it.compositeRule = true;
112191 var arr1 = $schema;
112192
112193 if (arr1) {
112194 var $sch,
112195 $i = -1,
112196 l1 = arr1.length - 1;
112197
112198 while ($i < l1) {
112199 $sch = arr1[$i += 1];
112200 $it.schema = $sch;
112201 $it.schemaPath = $schemaPath + '[' + $i + ']';
112202 $it.errSchemaPath = $errSchemaPath + '/' + $i;
112203 out += ' ' + it.validate($it) + ' ';
112204 $it.baseId = $currentBaseId;
112205 out += ' ' + $valid + ' = ' + $valid + ' || ' + $nextValid + '; if (!' + $valid + ') { ';
112206 $closingBraces += '}';
112207 }
112208 }
112209
112210 it.compositeRule = $it.compositeRule = $wasComposite;
112211 out += ' ' + $closingBraces + ' if (!' + $valid + ') { var err = ';
112212 /* istanbul ignore else */
112213
112214 if (it.createErrors !== false) {
112215 out += ' { keyword: \'' + 'anyOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
112216
112217 if (it.opts.messages !== false) {
112218 out += ' , message: \'should match some schema in anyOf\' ';
112219 }
112220
112221 if (it.opts.verbose) {
112222 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112223 }
112224
112225 out += ' } ';
112226 } else {
112227 out += ' {} ';
112228 }
112229
112230 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112231
112232 if (!it.compositeRule && $breakOnError) {
112233 /* istanbul ignore if */
112234 if (it.async) {
112235 out += ' throw new ValidationError(vErrors); ';
112236 } else {
112237 out += ' validate.errors = vErrors; return false; ';
112238 }
112239 }
112240
112241 out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
112242
112243 if (it.opts.allErrors) {
112244 out += ' } ';
112245 }
112246
112247 out = it.util.cleanUpCode(out);
112248 } else {
112249 if ($breakOnError) {
112250 out += ' if (true) { ';
112251 }
112252 }
112253
112254 return out;
112255};
112256
112257/***/ }),
6a5a0f88 112258/* 748 */
eb39fafa
DC
112259/***/ (function(module, exports, __webpack_require__) {
112260
112261"use strict";
112262
112263
112264module.exports = function generate_comment(it, $keyword, $ruleType) {
112265 var out = ' ';
112266 var $schema = it.schema[$keyword];
112267 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112268 var $breakOnError = !it.opts.allErrors;
112269 var $comment = it.util.toQuotedString($schema);
112270
112271 if (it.opts.$comment === true) {
112272 out += ' console.log(' + $comment + ');';
112273 } else if (typeof it.opts.$comment == 'function') {
112274 out += ' self._opts.$comment(' + $comment + ', ' + it.util.toQuotedString($errSchemaPath) + ', validate.root.schema);';
112275 }
112276
112277 return out;
112278};
112279
112280/***/ }),
6a5a0f88 112281/* 749 */
eb39fafa
DC
112282/***/ (function(module, exports, __webpack_require__) {
112283
112284"use strict";
112285
112286
112287module.exports = function generate_const(it, $keyword, $ruleType) {
112288 var out = ' ';
112289 var $lvl = it.level;
112290 var $dataLvl = it.dataLevel;
112291 var $schema = it.schema[$keyword];
112292 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112293 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112294 var $breakOnError = !it.opts.allErrors;
112295 var $data = 'data' + ($dataLvl || '');
112296 var $valid = 'valid' + $lvl;
112297 var $isData = it.opts.$data && $schema && $schema.$data,
112298 $schemaValue;
112299
112300 if ($isData) {
112301 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
112302 $schemaValue = 'schema' + $lvl;
112303 } else {
112304 $schemaValue = $schema;
112305 }
112306
112307 if (!$isData) {
112308 out += ' var schema' + $lvl + ' = validate.schema' + $schemaPath + ';';
112309 }
112310
112311 out += 'var ' + $valid + ' = equal(' + $data + ', schema' + $lvl + '); if (!' + $valid + ') { ';
112312 var $$outStack = $$outStack || [];
112313 $$outStack.push(out);
112314 out = '';
112315 /* istanbul ignore else */
112316
112317 if (it.createErrors !== false) {
112318 out += ' { keyword: \'' + 'const' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValue: schema' + $lvl + ' } ';
112319
112320 if (it.opts.messages !== false) {
112321 out += ' , message: \'should be equal to constant\' ';
112322 }
112323
112324 if (it.opts.verbose) {
112325 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112326 }
112327
112328 out += ' } ';
112329 } else {
112330 out += ' {} ';
112331 }
112332
112333 var __err = out;
112334 out = $$outStack.pop();
112335
112336 if (!it.compositeRule && $breakOnError) {
112337 /* istanbul ignore if */
112338 if (it.async) {
112339 out += ' throw new ValidationError([' + __err + ']); ';
112340 } else {
112341 out += ' validate.errors = [' + __err + ']; return false; ';
112342 }
112343 } else {
112344 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112345 }
112346
112347 out += ' }';
112348
112349 if ($breakOnError) {
112350 out += ' else { ';
112351 }
112352
112353 return out;
112354};
112355
112356/***/ }),
6a5a0f88 112357/* 750 */
eb39fafa
DC
112358/***/ (function(module, exports, __webpack_require__) {
112359
112360"use strict";
112361
112362
112363module.exports = function generate_contains(it, $keyword, $ruleType) {
112364 var out = ' ';
112365 var $lvl = it.level;
112366 var $dataLvl = it.dataLevel;
112367 var $schema = it.schema[$keyword];
112368 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112369 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112370 var $breakOnError = !it.opts.allErrors;
112371 var $data = 'data' + ($dataLvl || '');
112372 var $valid = 'valid' + $lvl;
112373 var $errs = 'errs__' + $lvl;
112374 var $it = it.util.copy(it);
112375 var $closingBraces = '';
112376 $it.level++;
112377 var $nextValid = 'valid' + $it.level;
112378 var $idx = 'i' + $lvl,
112379 $dataNxt = $it.dataLevel = it.dataLevel + 1,
112380 $nextData = 'data' + $dataNxt,
112381 $currentBaseId = it.baseId,
112382 $nonEmptySchema = it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all);
112383 out += 'var ' + $errs + ' = errors;var ' + $valid + ';';
112384
112385 if ($nonEmptySchema) {
112386 var $wasComposite = it.compositeRule;
112387 it.compositeRule = $it.compositeRule = true;
112388 $it.schema = $schema;
112389 $it.schemaPath = $schemaPath;
112390 $it.errSchemaPath = $errSchemaPath;
112391 out += ' var ' + $nextValid + ' = false; for (var ' + $idx + ' = 0; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { ';
112392 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
112393 var $passData = $data + '[' + $idx + ']';
112394 $it.dataPathArr[$dataNxt] = $idx;
112395 var $code = it.validate($it);
112396 $it.baseId = $currentBaseId;
112397
112398 if (it.util.varOccurences($code, $nextData) < 2) {
112399 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
112400 } else {
112401 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
112402 }
112403
112404 out += ' if (' + $nextValid + ') break; } ';
112405 it.compositeRule = $it.compositeRule = $wasComposite;
112406 out += ' ' + $closingBraces + ' if (!' + $nextValid + ') {';
112407 } else {
112408 out += ' if (' + $data + '.length == 0) {';
112409 }
112410
112411 var $$outStack = $$outStack || [];
112412 $$outStack.push(out);
112413 out = '';
112414 /* istanbul ignore else */
112415
112416 if (it.createErrors !== false) {
112417 out += ' { keyword: \'' + 'contains' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
112418
112419 if (it.opts.messages !== false) {
112420 out += ' , message: \'should contain a valid item\' ';
112421 }
112422
112423 if (it.opts.verbose) {
112424 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112425 }
112426
112427 out += ' } ';
112428 } else {
112429 out += ' {} ';
112430 }
112431
112432 var __err = out;
112433 out = $$outStack.pop();
112434
112435 if (!it.compositeRule && $breakOnError) {
112436 /* istanbul ignore if */
112437 if (it.async) {
112438 out += ' throw new ValidationError([' + __err + ']); ';
112439 } else {
112440 out += ' validate.errors = [' + __err + ']; return false; ';
112441 }
112442 } else {
112443 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112444 }
112445
112446 out += ' } else { ';
112447
112448 if ($nonEmptySchema) {
112449 out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
112450 }
112451
112452 if (it.opts.allErrors) {
112453 out += ' } ';
112454 }
112455
112456 out = it.util.cleanUpCode(out);
112457 return out;
112458};
112459
112460/***/ }),
6a5a0f88 112461/* 751 */
eb39fafa
DC
112462/***/ (function(module, exports, __webpack_require__) {
112463
112464"use strict";
112465
112466
112467module.exports = function generate_dependencies(it, $keyword, $ruleType) {
112468 var out = ' ';
112469 var $lvl = it.level;
112470 var $dataLvl = it.dataLevel;
112471 var $schema = it.schema[$keyword];
112472 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112473 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112474 var $breakOnError = !it.opts.allErrors;
112475 var $data = 'data' + ($dataLvl || '');
112476 var $errs = 'errs__' + $lvl;
112477 var $it = it.util.copy(it);
112478 var $closingBraces = '';
112479 $it.level++;
112480 var $nextValid = 'valid' + $it.level;
112481 var $schemaDeps = {},
112482 $propertyDeps = {},
112483 $ownProperties = it.opts.ownProperties;
112484
112485 for ($property in $schema) {
112486 var $sch = $schema[$property];
112487 var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
112488 $deps[$property] = $sch;
112489 }
112490
112491 out += 'var ' + $errs + ' = errors;';
112492 var $currentErrorPath = it.errorPath;
112493 out += 'var missing' + $lvl + ';';
112494
112495 for (var $property in $propertyDeps) {
112496 $deps = $propertyDeps[$property];
112497
112498 if ($deps.length) {
112499 out += ' if ( ' + $data + it.util.getProperty($property) + ' !== undefined ';
112500
112501 if ($ownProperties) {
112502 out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') ';
112503 }
112504
112505 if ($breakOnError) {
112506 out += ' && ( ';
112507 var arr1 = $deps;
112508
112509 if (arr1) {
112510 var $propertyKey,
112511 $i = -1,
112512 l1 = arr1.length - 1;
112513
112514 while ($i < l1) {
112515 $propertyKey = arr1[$i += 1];
112516
112517 if ($i) {
112518 out += ' || ';
112519 }
112520
112521 var $prop = it.util.getProperty($propertyKey),
112522 $useData = $data + $prop;
112523 out += ' ( ( ' + $useData + ' === undefined ';
112524
112525 if ($ownProperties) {
112526 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
112527 }
112528
112529 out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) ';
112530 }
112531 }
112532
112533 out += ')) { ';
112534 var $propertyPath = 'missing' + $lvl,
112535 $missingProperty = '\' + ' + $propertyPath + ' + \'';
112536
112537 if (it.opts._errorDataPathProperty) {
112538 it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
112539 }
112540
112541 var $$outStack = $$outStack || [];
112542 $$outStack.push(out);
112543 out = '';
112544 /* istanbul ignore else */
112545
112546 if (it.createErrors !== false) {
112547 out += ' { keyword: \'' + 'dependencies' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + '\' } ';
112548
112549 if (it.opts.messages !== false) {
112550 out += ' , message: \'should have ';
112551
112552 if ($deps.length == 1) {
112553 out += 'property ' + it.util.escapeQuotes($deps[0]);
112554 } else {
112555 out += 'properties ' + it.util.escapeQuotes($deps.join(", "));
112556 }
112557
112558 out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' ';
112559 }
112560
112561 if (it.opts.verbose) {
112562 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112563 }
112564
112565 out += ' } ';
112566 } else {
112567 out += ' {} ';
112568 }
112569
112570 var __err = out;
112571 out = $$outStack.pop();
112572
112573 if (!it.compositeRule && $breakOnError) {
112574 /* istanbul ignore if */
112575 if (it.async) {
112576 out += ' throw new ValidationError([' + __err + ']); ';
112577 } else {
112578 out += ' validate.errors = [' + __err + ']; return false; ';
112579 }
112580 } else {
112581 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112582 }
112583 } else {
112584 out += ' ) { ';
112585 var arr2 = $deps;
112586
112587 if (arr2) {
112588 var $propertyKey,
112589 i2 = -1,
112590 l2 = arr2.length - 1;
112591
112592 while (i2 < l2) {
112593 $propertyKey = arr2[i2 += 1];
112594 var $prop = it.util.getProperty($propertyKey),
112595 $missingProperty = it.util.escapeQuotes($propertyKey),
112596 $useData = $data + $prop;
112597
112598 if (it.opts._errorDataPathProperty) {
112599 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
112600 }
112601
112602 out += ' if ( ' + $useData + ' === undefined ';
112603
112604 if ($ownProperties) {
112605 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
112606 }
112607
112608 out += ') { var err = ';
112609 /* istanbul ignore else */
112610
112611 if (it.createErrors !== false) {
112612 out += ' { keyword: \'' + 'dependencies' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + '\' } ';
112613
112614 if (it.opts.messages !== false) {
112615 out += ' , message: \'should have ';
112616
112617 if ($deps.length == 1) {
112618 out += 'property ' + it.util.escapeQuotes($deps[0]);
112619 } else {
112620 out += 'properties ' + it.util.escapeQuotes($deps.join(", "));
112621 }
112622
112623 out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' ';
112624 }
112625
112626 if (it.opts.verbose) {
112627 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112628 }
112629
112630 out += ' } ';
112631 } else {
112632 out += ' {} ';
112633 }
112634
112635 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
112636 }
112637 }
112638 }
112639
112640 out += ' } ';
112641
112642 if ($breakOnError) {
112643 $closingBraces += '}';
112644 out += ' else { ';
112645 }
112646 }
112647 }
112648
112649 it.errorPath = $currentErrorPath;
112650 var $currentBaseId = $it.baseId;
112651
112652 for (var $property in $schemaDeps) {
112653 var $sch = $schemaDeps[$property];
112654
112655 if (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)) {
112656 out += ' ' + $nextValid + ' = true; if ( ' + $data + it.util.getProperty($property) + ' !== undefined ';
112657
112658 if ($ownProperties) {
112659 out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') ';
112660 }
112661
112662 out += ') { ';
112663 $it.schema = $sch;
112664 $it.schemaPath = $schemaPath + it.util.getProperty($property);
112665 $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
112666 out += ' ' + it.validate($it) + ' ';
112667 $it.baseId = $currentBaseId;
112668 out += ' } ';
112669
112670 if ($breakOnError) {
112671 out += ' if (' + $nextValid + ') { ';
112672 $closingBraces += '}';
112673 }
112674 }
112675 }
112676
112677 if ($breakOnError) {
112678 out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
112679 }
112680
112681 out = it.util.cleanUpCode(out);
112682 return out;
112683};
112684
112685/***/ }),
6a5a0f88 112686/* 752 */
eb39fafa
DC
112687/***/ (function(module, exports, __webpack_require__) {
112688
112689"use strict";
112690
112691
112692module.exports = function generate_enum(it, $keyword, $ruleType) {
112693 var out = ' ';
112694 var $lvl = it.level;
112695 var $dataLvl = it.dataLevel;
112696 var $schema = it.schema[$keyword];
112697 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112698 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112699 var $breakOnError = !it.opts.allErrors;
112700 var $data = 'data' + ($dataLvl || '');
112701 var $valid = 'valid' + $lvl;
112702 var $isData = it.opts.$data && $schema && $schema.$data,
112703 $schemaValue;
112704
112705 if ($isData) {
112706 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
112707 $schemaValue = 'schema' + $lvl;
112708 } else {
112709 $schemaValue = $schema;
112710 }
112711
112712 var $i = 'i' + $lvl,
112713 $vSchema = 'schema' + $lvl;
112714
112715 if (!$isData) {
112716 out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + ';';
112717 }
112718
112719 out += 'var ' + $valid + ';';
112720
112721 if ($isData) {
112722 out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {';
112723 }
112724
112725 out += '' + $valid + ' = false;for (var ' + $i + '=0; ' + $i + '<' + $vSchema + '.length; ' + $i + '++) if (equal(' + $data + ', ' + $vSchema + '[' + $i + '])) { ' + $valid + ' = true; break; }';
112726
112727 if ($isData) {
112728 out += ' } ';
112729 }
112730
112731 out += ' if (!' + $valid + ') { ';
112732 var $$outStack = $$outStack || [];
112733 $$outStack.push(out);
112734 out = '';
112735 /* istanbul ignore else */
112736
112737 if (it.createErrors !== false) {
112738 out += ' { keyword: \'' + 'enum' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValues: schema' + $lvl + ' } ';
112739
112740 if (it.opts.messages !== false) {
112741 out += ' , message: \'should be equal to one of the allowed values\' ';
112742 }
112743
112744 if (it.opts.verbose) {
112745 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112746 }
112747
112748 out += ' } ';
112749 } else {
112750 out += ' {} ';
112751 }
112752
112753 var __err = out;
112754 out = $$outStack.pop();
112755
112756 if (!it.compositeRule && $breakOnError) {
112757 /* istanbul ignore if */
112758 if (it.async) {
112759 out += ' throw new ValidationError([' + __err + ']); ';
112760 } else {
112761 out += ' validate.errors = [' + __err + ']; return false; ';
112762 }
112763 } else {
112764 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112765 }
112766
112767 out += ' }';
112768
112769 if ($breakOnError) {
112770 out += ' else { ';
112771 }
112772
112773 return out;
112774};
112775
112776/***/ }),
6a5a0f88 112777/* 753 */
eb39fafa
DC
112778/***/ (function(module, exports, __webpack_require__) {
112779
112780"use strict";
112781
112782
112783module.exports = function generate_format(it, $keyword, $ruleType) {
112784 var out = ' ';
112785 var $lvl = it.level;
112786 var $dataLvl = it.dataLevel;
112787 var $schema = it.schema[$keyword];
112788 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112789 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112790 var $breakOnError = !it.opts.allErrors;
112791 var $data = 'data' + ($dataLvl || '');
112792
112793 if (it.opts.format === false) {
112794 if ($breakOnError) {
112795 out += ' if (true) { ';
112796 }
112797
112798 return out;
112799 }
112800
112801 var $isData = it.opts.$data && $schema && $schema.$data,
112802 $schemaValue;
112803
112804 if ($isData) {
112805 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
112806 $schemaValue = 'schema' + $lvl;
112807 } else {
112808 $schemaValue = $schema;
112809 }
112810
112811 var $unknownFormats = it.opts.unknownFormats,
112812 $allowUnknown = Array.isArray($unknownFormats);
112813
112814 if ($isData) {
112815 var $format = 'format' + $lvl,
112816 $isObject = 'isObject' + $lvl,
112817 $formatType = 'formatType' + $lvl;
112818 out += ' var ' + $format + ' = formats[' + $schemaValue + ']; var ' + $isObject + ' = typeof ' + $format + ' == \'object\' && !(' + $format + ' instanceof RegExp) && ' + $format + '.validate; var ' + $formatType + ' = ' + $isObject + ' && ' + $format + '.type || \'string\'; if (' + $isObject + ') { ';
112819
112820 if (it.async) {
112821 out += ' var async' + $lvl + ' = ' + $format + '.async; ';
112822 }
112823
112824 out += ' ' + $format + ' = ' + $format + '.validate; } if ( ';
112825
112826 if ($isData) {
112827 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || ';
112828 }
112829
112830 out += ' (';
112831
112832 if ($unknownFormats != 'ignore') {
112833 out += ' (' + $schemaValue + ' && !' + $format + ' ';
112834
112835 if ($allowUnknown) {
112836 out += ' && self._opts.unknownFormats.indexOf(' + $schemaValue + ') == -1 ';
112837 }
112838
112839 out += ') || ';
112840 }
112841
112842 out += ' (' + $format + ' && ' + $formatType + ' == \'' + $ruleType + '\' && !(typeof ' + $format + ' == \'function\' ? ';
112843
112844 if (it.async) {
112845 out += ' (async' + $lvl + ' ? await ' + $format + '(' + $data + ') : ' + $format + '(' + $data + ')) ';
112846 } else {
112847 out += ' ' + $format + '(' + $data + ') ';
112848 }
112849
112850 out += ' : ' + $format + '.test(' + $data + '))))) {';
112851 } else {
112852 var $format = it.formats[$schema];
112853
112854 if (!$format) {
112855 if ($unknownFormats == 'ignore') {
112856 it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
112857
112858 if ($breakOnError) {
112859 out += ' if (true) { ';
112860 }
112861
112862 return out;
112863 } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
112864 if ($breakOnError) {
112865 out += ' if (true) { ';
112866 }
112867
112868 return out;
112869 } else {
112870 throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
112871 }
112872 }
112873
112874 var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
112875 var $formatType = $isObject && $format.type || 'string';
112876
112877 if ($isObject) {
112878 var $async = $format.async === true;
112879 $format = $format.validate;
112880 }
112881
112882 if ($formatType != $ruleType) {
112883 if ($breakOnError) {
112884 out += ' if (true) { ';
112885 }
112886
112887 return out;
112888 }
112889
112890 if ($async) {
112891 if (!it.async) throw new Error('async format in sync schema');
112892 var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
112893 out += ' if (!(await ' + $formatRef + '(' + $data + '))) { ';
112894 } else {
112895 out += ' if (! ';
112896 var $formatRef = 'formats' + it.util.getProperty($schema);
112897 if ($isObject) $formatRef += '.validate';
112898
112899 if (typeof $format == 'function') {
112900 out += ' ' + $formatRef + '(' + $data + ') ';
112901 } else {
112902 out += ' ' + $formatRef + '.test(' + $data + ') ';
112903 }
112904
112905 out += ') { ';
112906 }
112907 }
112908
112909 var $$outStack = $$outStack || [];
112910 $$outStack.push(out);
112911 out = '';
112912 /* istanbul ignore else */
112913
112914 if (it.createErrors !== false) {
112915 out += ' { keyword: \'' + 'format' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { format: ';
112916
112917 if ($isData) {
112918 out += '' + $schemaValue;
112919 } else {
112920 out += '' + it.util.toQuotedString($schema);
112921 }
112922
112923 out += ' } ';
112924
112925 if (it.opts.messages !== false) {
112926 out += ' , message: \'should match format "';
112927
112928 if ($isData) {
112929 out += '\' + ' + $schemaValue + ' + \'';
112930 } else {
112931 out += '' + it.util.escapeQuotes($schema);
112932 }
112933
112934 out += '"\' ';
112935 }
112936
112937 if (it.opts.verbose) {
112938 out += ' , schema: ';
112939
112940 if ($isData) {
112941 out += 'validate.schema' + $schemaPath;
112942 } else {
112943 out += '' + it.util.toQuotedString($schema);
112944 }
112945
112946 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
112947 }
112948
112949 out += ' } ';
112950 } else {
112951 out += ' {} ';
112952 }
112953
112954 var __err = out;
112955 out = $$outStack.pop();
112956
112957 if (!it.compositeRule && $breakOnError) {
112958 /* istanbul ignore if */
112959 if (it.async) {
112960 out += ' throw new ValidationError([' + __err + ']); ';
112961 } else {
112962 out += ' validate.errors = [' + __err + ']; return false; ';
112963 }
112964 } else {
112965 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
112966 }
112967
112968 out += ' } ';
112969
112970 if ($breakOnError) {
112971 out += ' else { ';
112972 }
112973
112974 return out;
112975};
112976
112977/***/ }),
6a5a0f88 112978/* 754 */
eb39fafa
DC
112979/***/ (function(module, exports, __webpack_require__) {
112980
112981"use strict";
112982
112983
112984module.exports = function generate_if(it, $keyword, $ruleType) {
112985 var out = ' ';
112986 var $lvl = it.level;
112987 var $dataLvl = it.dataLevel;
112988 var $schema = it.schema[$keyword];
112989 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
112990 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
112991 var $breakOnError = !it.opts.allErrors;
112992 var $data = 'data' + ($dataLvl || '');
112993 var $valid = 'valid' + $lvl;
112994 var $errs = 'errs__' + $lvl;
112995 var $it = it.util.copy(it);
112996 $it.level++;
112997 var $nextValid = 'valid' + $it.level;
112998 var $thenSch = it.schema['then'],
112999 $elseSch = it.schema['else'],
113000 $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? typeof $thenSch == 'object' && Object.keys($thenSch).length > 0 : it.util.schemaHasRules($thenSch, it.RULES.all)),
113001 $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? typeof $elseSch == 'object' && Object.keys($elseSch).length > 0 : it.util.schemaHasRules($elseSch, it.RULES.all)),
113002 $currentBaseId = $it.baseId;
113003
113004 if ($thenPresent || $elsePresent) {
113005 var $ifClause;
113006 $it.createErrors = false;
113007 $it.schema = $schema;
113008 $it.schemaPath = $schemaPath;
113009 $it.errSchemaPath = $errSchemaPath;
113010 out += ' var ' + $errs + ' = errors; var ' + $valid + ' = true; ';
113011 var $wasComposite = it.compositeRule;
113012 it.compositeRule = $it.compositeRule = true;
113013 out += ' ' + it.validate($it) + ' ';
113014 $it.baseId = $currentBaseId;
113015 $it.createErrors = true;
113016 out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
113017 it.compositeRule = $it.compositeRule = $wasComposite;
113018
113019 if ($thenPresent) {
113020 out += ' if (' + $nextValid + ') { ';
113021 $it.schema = it.schema['then'];
113022 $it.schemaPath = it.schemaPath + '.then';
113023 $it.errSchemaPath = it.errSchemaPath + '/then';
113024 out += ' ' + it.validate($it) + ' ';
113025 $it.baseId = $currentBaseId;
113026 out += ' ' + $valid + ' = ' + $nextValid + '; ';
113027
113028 if ($thenPresent && $elsePresent) {
113029 $ifClause = 'ifClause' + $lvl;
113030 out += ' var ' + $ifClause + ' = \'then\'; ';
113031 } else {
113032 $ifClause = '\'then\'';
113033 }
113034
113035 out += ' } ';
113036
113037 if ($elsePresent) {
113038 out += ' else { ';
113039 }
113040 } else {
113041 out += ' if (!' + $nextValid + ') { ';
113042 }
113043
113044 if ($elsePresent) {
113045 $it.schema = it.schema['else'];
113046 $it.schemaPath = it.schemaPath + '.else';
113047 $it.errSchemaPath = it.errSchemaPath + '/else';
113048 out += ' ' + it.validate($it) + ' ';
113049 $it.baseId = $currentBaseId;
113050 out += ' ' + $valid + ' = ' + $nextValid + '; ';
113051
113052 if ($thenPresent && $elsePresent) {
113053 $ifClause = 'ifClause' + $lvl;
113054 out += ' var ' + $ifClause + ' = \'else\'; ';
113055 } else {
113056 $ifClause = '\'else\'';
113057 }
113058
113059 out += ' } ';
113060 }
113061
113062 out += ' if (!' + $valid + ') { var err = ';
113063 /* istanbul ignore else */
113064
113065 if (it.createErrors !== false) {
113066 out += ' { keyword: \'' + 'if' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { failingKeyword: ' + $ifClause + ' } ';
113067
113068 if (it.opts.messages !== false) {
113069 out += ' , message: \'should match "\' + ' + $ifClause + ' + \'" schema\' ';
113070 }
113071
113072 if (it.opts.verbose) {
113073 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113074 }
113075
113076 out += ' } ';
113077 } else {
113078 out += ' {} ';
113079 }
113080
113081 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113082
113083 if (!it.compositeRule && $breakOnError) {
113084 /* istanbul ignore if */
113085 if (it.async) {
113086 out += ' throw new ValidationError(vErrors); ';
113087 } else {
113088 out += ' validate.errors = vErrors; return false; ';
113089 }
113090 }
113091
113092 out += ' } ';
113093
113094 if ($breakOnError) {
113095 out += ' else { ';
113096 }
113097
113098 out = it.util.cleanUpCode(out);
113099 } else {
113100 if ($breakOnError) {
113101 out += ' if (true) { ';
113102 }
113103 }
113104
113105 return out;
113106};
113107
113108/***/ }),
6a5a0f88 113109/* 755 */
eb39fafa
DC
113110/***/ (function(module, exports, __webpack_require__) {
113111
113112"use strict";
113113
113114
113115module.exports = function generate_items(it, $keyword, $ruleType) {
113116 var out = ' ';
113117 var $lvl = it.level;
113118 var $dataLvl = it.dataLevel;
113119 var $schema = it.schema[$keyword];
113120 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113121 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113122 var $breakOnError = !it.opts.allErrors;
113123 var $data = 'data' + ($dataLvl || '');
113124 var $valid = 'valid' + $lvl;
113125 var $errs = 'errs__' + $lvl;
113126 var $it = it.util.copy(it);
113127 var $closingBraces = '';
113128 $it.level++;
113129 var $nextValid = 'valid' + $it.level;
113130 var $idx = 'i' + $lvl,
113131 $dataNxt = $it.dataLevel = it.dataLevel + 1,
113132 $nextData = 'data' + $dataNxt,
113133 $currentBaseId = it.baseId;
113134 out += 'var ' + $errs + ' = errors;var ' + $valid + ';';
113135
113136 if (Array.isArray($schema)) {
113137 var $additionalItems = it.schema.additionalItems;
113138
113139 if ($additionalItems === false) {
113140 out += ' ' + $valid + ' = ' + $data + '.length <= ' + $schema.length + '; ';
113141 var $currErrSchemaPath = $errSchemaPath;
113142 $errSchemaPath = it.errSchemaPath + '/additionalItems';
113143 out += ' if (!' + $valid + ') { ';
113144 var $$outStack = $$outStack || [];
113145 $$outStack.push(out);
113146 out = '';
113147 /* istanbul ignore else */
113148
113149 if (it.createErrors !== false) {
113150 out += ' { keyword: \'' + 'additionalItems' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schema.length + ' } ';
113151
113152 if (it.opts.messages !== false) {
113153 out += ' , message: \'should NOT have more than ' + $schema.length + ' items\' ';
113154 }
113155
113156 if (it.opts.verbose) {
113157 out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113158 }
113159
113160 out += ' } ';
113161 } else {
113162 out += ' {} ';
113163 }
113164
113165 var __err = out;
113166 out = $$outStack.pop();
113167
113168 if (!it.compositeRule && $breakOnError) {
113169 /* istanbul ignore if */
113170 if (it.async) {
113171 out += ' throw new ValidationError([' + __err + ']); ';
113172 } else {
113173 out += ' validate.errors = [' + __err + ']; return false; ';
113174 }
113175 } else {
113176 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113177 }
113178
113179 out += ' } ';
113180 $errSchemaPath = $currErrSchemaPath;
113181
113182 if ($breakOnError) {
113183 $closingBraces += '}';
113184 out += ' else { ';
113185 }
113186 }
113187
113188 var arr1 = $schema;
113189
113190 if (arr1) {
113191 var $sch,
113192 $i = -1,
113193 l1 = arr1.length - 1;
113194
113195 while ($i < l1) {
113196 $sch = arr1[$i += 1];
113197
113198 if (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)) {
113199 out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $i + ') { ';
113200 var $passData = $data + '[' + $i + ']';
113201 $it.schema = $sch;
113202 $it.schemaPath = $schemaPath + '[' + $i + ']';
113203 $it.errSchemaPath = $errSchemaPath + '/' + $i;
113204 $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
113205 $it.dataPathArr[$dataNxt] = $i;
113206 var $code = it.validate($it);
113207 $it.baseId = $currentBaseId;
113208
113209 if (it.util.varOccurences($code, $nextData) < 2) {
113210 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
113211 } else {
113212 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
113213 }
113214
113215 out += ' } ';
113216
113217 if ($breakOnError) {
113218 out += ' if (' + $nextValid + ') { ';
113219 $closingBraces += '}';
113220 }
113221 }
113222 }
113223 }
113224
113225 if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0 : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
113226 $it.schema = $additionalItems;
113227 $it.schemaPath = it.schemaPath + '.additionalItems';
113228 $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
113229 out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $schema.length + ') { for (var ' + $idx + ' = ' + $schema.length + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { ';
113230 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
113231 var $passData = $data + '[' + $idx + ']';
113232 $it.dataPathArr[$dataNxt] = $idx;
113233 var $code = it.validate($it);
113234 $it.baseId = $currentBaseId;
113235
113236 if (it.util.varOccurences($code, $nextData) < 2) {
113237 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
113238 } else {
113239 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
113240 }
113241
113242 if ($breakOnError) {
113243 out += ' if (!' + $nextValid + ') break; ';
113244 }
113245
113246 out += ' } } ';
113247
113248 if ($breakOnError) {
113249 out += ' if (' + $nextValid + ') { ';
113250 $closingBraces += '}';
113251 }
113252 }
113253 } else if (it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all)) {
113254 $it.schema = $schema;
113255 $it.schemaPath = $schemaPath;
113256 $it.errSchemaPath = $errSchemaPath;
113257 out += ' for (var ' + $idx + ' = ' + 0 + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { ';
113258 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
113259 var $passData = $data + '[' + $idx + ']';
113260 $it.dataPathArr[$dataNxt] = $idx;
113261 var $code = it.validate($it);
113262 $it.baseId = $currentBaseId;
113263
113264 if (it.util.varOccurences($code, $nextData) < 2) {
113265 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
113266 } else {
113267 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
113268 }
113269
113270 if ($breakOnError) {
113271 out += ' if (!' + $nextValid + ') break; ';
113272 }
113273
113274 out += ' }';
113275 }
113276
113277 if ($breakOnError) {
113278 out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
113279 }
113280
113281 out = it.util.cleanUpCode(out);
113282 return out;
113283};
113284
113285/***/ }),
6a5a0f88 113286/* 756 */
eb39fafa
DC
113287/***/ (function(module, exports, __webpack_require__) {
113288
113289"use strict";
113290
113291
113292module.exports = function generate__limit(it, $keyword, $ruleType) {
113293 var out = ' ';
113294 var $lvl = it.level;
113295 var $dataLvl = it.dataLevel;
113296 var $schema = it.schema[$keyword];
113297 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113298 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113299 var $breakOnError = !it.opts.allErrors;
113300 var $errorKeyword;
113301 var $data = 'data' + ($dataLvl || '');
113302 var $isData = it.opts.$data && $schema && $schema.$data,
113303 $schemaValue;
113304
113305 if ($isData) {
113306 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
113307 $schemaValue = 'schema' + $lvl;
113308 } else {
113309 $schemaValue = $schema;
113310 }
113311
113312 var $isMax = $keyword == 'maximum',
113313 $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
113314 $schemaExcl = it.schema[$exclusiveKeyword],
113315 $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
113316 $op = $isMax ? '<' : '>',
113317 $notOp = $isMax ? '>' : '<',
113318 $errorKeyword = undefined;
113319
113320 if ($isDataExcl) {
113321 var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
113322 $exclusive = 'exclusive' + $lvl,
113323 $exclType = 'exclType' + $lvl,
113324 $exclIsNumber = 'exclIsNumber' + $lvl,
113325 $opExpr = 'op' + $lvl,
113326 $opStr = '\' + ' + $opExpr + ' + \'';
113327 out += ' var schemaExcl' + $lvl + ' = ' + $schemaValueExcl + '; ';
113328 $schemaValueExcl = 'schemaExcl' + $lvl;
113329 out += ' var ' + $exclusive + '; var ' + $exclType + ' = typeof ' + $schemaValueExcl + '; if (' + $exclType + ' != \'boolean\' && ' + $exclType + ' != \'undefined\' && ' + $exclType + ' != \'number\') { ';
113330 var $errorKeyword = $exclusiveKeyword;
113331 var $$outStack = $$outStack || [];
113332 $$outStack.push(out);
113333 out = '';
113334 /* istanbul ignore else */
113335
113336 if (it.createErrors !== false) {
113337 out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
113338
113339 if (it.opts.messages !== false) {
113340 out += ' , message: \'' + $exclusiveKeyword + ' should be boolean\' ';
113341 }
113342
113343 if (it.opts.verbose) {
113344 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113345 }
113346
113347 out += ' } ';
113348 } else {
113349 out += ' {} ';
113350 }
113351
113352 var __err = out;
113353 out = $$outStack.pop();
113354
113355 if (!it.compositeRule && $breakOnError) {
113356 /* istanbul ignore if */
113357 if (it.async) {
113358 out += ' throw new ValidationError([' + __err + ']); ';
113359 } else {
113360 out += ' validate.errors = [' + __err + ']; return false; ';
113361 }
113362 } else {
113363 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113364 }
113365
113366 out += ' } else if ( ';
113367
113368 if ($isData) {
113369 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
113370 }
113371
113372 out += ' ' + $exclType + ' == \'number\' ? ( (' + $exclusive + ' = ' + $schemaValue + ' === undefined || ' + $schemaValueExcl + ' ' + $op + '= ' + $schemaValue + ') ? ' + $data + ' ' + $notOp + '= ' + $schemaValueExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) : ( (' + $exclusive + ' = ' + $schemaValueExcl + ' === true) ? ' + $data + ' ' + $notOp + '= ' + $schemaValue + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { var op' + $lvl + ' = ' + $exclusive + ' ? \'' + $op + '\' : \'' + $op + '=\'; ';
113373
113374 if ($schema === undefined) {
113375 $errorKeyword = $exclusiveKeyword;
113376 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
113377 $schemaValue = $schemaValueExcl;
113378 $isData = $isDataExcl;
113379 }
113380 } else {
113381 var $exclIsNumber = typeof $schemaExcl == 'number',
113382 $opStr = $op;
113383
113384 if ($exclIsNumber && $isData) {
113385 var $opExpr = '\'' + $opStr + '\'';
113386 out += ' if ( ';
113387
113388 if ($isData) {
113389 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
113390 }
113391
113392 out += ' ( ' + $schemaValue + ' === undefined || ' + $schemaExcl + ' ' + $op + '= ' + $schemaValue + ' ? ' + $data + ' ' + $notOp + '= ' + $schemaExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { ';
113393 } else {
113394 if ($exclIsNumber && $schema === undefined) {
113395 $exclusive = true;
113396 $errorKeyword = $exclusiveKeyword;
113397 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
113398 $schemaValue = $schemaExcl;
113399 $notOp += '=';
113400 } else {
113401 if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
113402
113403 if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
113404 $exclusive = true;
113405 $errorKeyword = $exclusiveKeyword;
113406 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
113407 $notOp += '=';
113408 } else {
113409 $exclusive = false;
113410 $opStr += '=';
113411 }
113412 }
113413
113414 var $opExpr = '\'' + $opStr + '\'';
113415 out += ' if ( ';
113416
113417 if ($isData) {
113418 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
113419 }
113420
113421 out += ' ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' || ' + $data + ' !== ' + $data + ') { ';
113422 }
113423 }
113424
113425 $errorKeyword = $errorKeyword || $keyword;
113426 var $$outStack = $$outStack || [];
113427 $$outStack.push(out);
113428 out = '';
113429 /* istanbul ignore else */
113430
113431 if (it.createErrors !== false) {
113432 out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { comparison: ' + $opExpr + ', limit: ' + $schemaValue + ', exclusive: ' + $exclusive + ' } ';
113433
113434 if (it.opts.messages !== false) {
113435 out += ' , message: \'should be ' + $opStr + ' ';
113436
113437 if ($isData) {
113438 out += '\' + ' + $schemaValue;
113439 } else {
113440 out += '' + $schemaValue + '\'';
113441 }
113442 }
113443
113444 if (it.opts.verbose) {
113445 out += ' , schema: ';
113446
113447 if ($isData) {
113448 out += 'validate.schema' + $schemaPath;
113449 } else {
113450 out += '' + $schema;
113451 }
113452
113453 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113454 }
113455
113456 out += ' } ';
113457 } else {
113458 out += ' {} ';
113459 }
113460
113461 var __err = out;
113462 out = $$outStack.pop();
113463
113464 if (!it.compositeRule && $breakOnError) {
113465 /* istanbul ignore if */
113466 if (it.async) {
113467 out += ' throw new ValidationError([' + __err + ']); ';
113468 } else {
113469 out += ' validate.errors = [' + __err + ']; return false; ';
113470 }
113471 } else {
113472 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113473 }
113474
113475 out += ' } ';
113476
113477 if ($breakOnError) {
113478 out += ' else { ';
113479 }
113480
113481 return out;
113482};
113483
113484/***/ }),
6a5a0f88 113485/* 757 */
eb39fafa
DC
113486/***/ (function(module, exports, __webpack_require__) {
113487
113488"use strict";
113489
113490
113491module.exports = function generate__limitItems(it, $keyword, $ruleType) {
113492 var out = ' ';
113493 var $lvl = it.level;
113494 var $dataLvl = it.dataLevel;
113495 var $schema = it.schema[$keyword];
113496 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113497 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113498 var $breakOnError = !it.opts.allErrors;
113499 var $errorKeyword;
113500 var $data = 'data' + ($dataLvl || '');
113501 var $isData = it.opts.$data && $schema && $schema.$data,
113502 $schemaValue;
113503
113504 if ($isData) {
113505 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
113506 $schemaValue = 'schema' + $lvl;
113507 } else {
113508 $schemaValue = $schema;
113509 }
113510
113511 var $op = $keyword == 'maxItems' ? '>' : '<';
113512 out += 'if ( ';
113513
113514 if ($isData) {
113515 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
113516 }
113517
113518 out += ' ' + $data + '.length ' + $op + ' ' + $schemaValue + ') { ';
113519 var $errorKeyword = $keyword;
113520 var $$outStack = $$outStack || [];
113521 $$outStack.push(out);
113522 out = '';
113523 /* istanbul ignore else */
113524
113525 if (it.createErrors !== false) {
113526 out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } ';
113527
113528 if (it.opts.messages !== false) {
113529 out += ' , message: \'should NOT have ';
113530
113531 if ($keyword == 'maxItems') {
113532 out += 'more';
113533 } else {
113534 out += 'fewer';
113535 }
113536
113537 out += ' than ';
113538
113539 if ($isData) {
113540 out += '\' + ' + $schemaValue + ' + \'';
113541 } else {
113542 out += '' + $schema;
113543 }
113544
113545 out += ' items\' ';
113546 }
113547
113548 if (it.opts.verbose) {
113549 out += ' , schema: ';
113550
113551 if ($isData) {
113552 out += 'validate.schema' + $schemaPath;
113553 } else {
113554 out += '' + $schema;
113555 }
113556
113557 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113558 }
113559
113560 out += ' } ';
113561 } else {
113562 out += ' {} ';
113563 }
113564
113565 var __err = out;
113566 out = $$outStack.pop();
113567
113568 if (!it.compositeRule && $breakOnError) {
113569 /* istanbul ignore if */
113570 if (it.async) {
113571 out += ' throw new ValidationError([' + __err + ']); ';
113572 } else {
113573 out += ' validate.errors = [' + __err + ']; return false; ';
113574 }
113575 } else {
113576 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113577 }
113578
113579 out += '} ';
113580
113581 if ($breakOnError) {
113582 out += ' else { ';
113583 }
113584
113585 return out;
113586};
113587
113588/***/ }),
6a5a0f88 113589/* 758 */
eb39fafa
DC
113590/***/ (function(module, exports, __webpack_require__) {
113591
113592"use strict";
113593
113594
113595module.exports = function generate__limitLength(it, $keyword, $ruleType) {
113596 var out = ' ';
113597 var $lvl = it.level;
113598 var $dataLvl = it.dataLevel;
113599 var $schema = it.schema[$keyword];
113600 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113601 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113602 var $breakOnError = !it.opts.allErrors;
113603 var $errorKeyword;
113604 var $data = 'data' + ($dataLvl || '');
113605 var $isData = it.opts.$data && $schema && $schema.$data,
113606 $schemaValue;
113607
113608 if ($isData) {
113609 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
113610 $schemaValue = 'schema' + $lvl;
113611 } else {
113612 $schemaValue = $schema;
113613 }
113614
113615 var $op = $keyword == 'maxLength' ? '>' : '<';
113616 out += 'if ( ';
113617
113618 if ($isData) {
113619 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
113620 }
113621
113622 if (it.opts.unicode === false) {
113623 out += ' ' + $data + '.length ';
113624 } else {
113625 out += ' ucs2length(' + $data + ') ';
113626 }
113627
113628 out += ' ' + $op + ' ' + $schemaValue + ') { ';
113629 var $errorKeyword = $keyword;
113630 var $$outStack = $$outStack || [];
113631 $$outStack.push(out);
113632 out = '';
113633 /* istanbul ignore else */
113634
113635 if (it.createErrors !== false) {
113636 out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } ';
113637
113638 if (it.opts.messages !== false) {
113639 out += ' , message: \'should NOT be ';
113640
113641 if ($keyword == 'maxLength') {
113642 out += 'longer';
113643 } else {
113644 out += 'shorter';
113645 }
113646
113647 out += ' than ';
113648
113649 if ($isData) {
113650 out += '\' + ' + $schemaValue + ' + \'';
113651 } else {
113652 out += '' + $schema;
113653 }
113654
113655 out += ' characters\' ';
113656 }
113657
113658 if (it.opts.verbose) {
113659 out += ' , schema: ';
113660
113661 if ($isData) {
113662 out += 'validate.schema' + $schemaPath;
113663 } else {
113664 out += '' + $schema;
113665 }
113666
113667 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113668 }
113669
113670 out += ' } ';
113671 } else {
113672 out += ' {} ';
113673 }
113674
113675 var __err = out;
113676 out = $$outStack.pop();
113677
113678 if (!it.compositeRule && $breakOnError) {
113679 /* istanbul ignore if */
113680 if (it.async) {
113681 out += ' throw new ValidationError([' + __err + ']); ';
113682 } else {
113683 out += ' validate.errors = [' + __err + ']; return false; ';
113684 }
113685 } else {
113686 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113687 }
113688
113689 out += '} ';
113690
113691 if ($breakOnError) {
113692 out += ' else { ';
113693 }
113694
113695 return out;
113696};
113697
113698/***/ }),
6a5a0f88 113699/* 759 */
eb39fafa
DC
113700/***/ (function(module, exports, __webpack_require__) {
113701
113702"use strict";
113703
113704
113705module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
113706 var out = ' ';
113707 var $lvl = it.level;
113708 var $dataLvl = it.dataLevel;
113709 var $schema = it.schema[$keyword];
113710 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113711 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113712 var $breakOnError = !it.opts.allErrors;
113713 var $errorKeyword;
113714 var $data = 'data' + ($dataLvl || '');
113715 var $isData = it.opts.$data && $schema && $schema.$data,
113716 $schemaValue;
113717
113718 if ($isData) {
113719 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
113720 $schemaValue = 'schema' + $lvl;
113721 } else {
113722 $schemaValue = $schema;
113723 }
113724
113725 var $op = $keyword == 'maxProperties' ? '>' : '<';
113726 out += 'if ( ';
113727
113728 if ($isData) {
113729 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
113730 }
113731
113732 out += ' Object.keys(' + $data + ').length ' + $op + ' ' + $schemaValue + ') { ';
113733 var $errorKeyword = $keyword;
113734 var $$outStack = $$outStack || [];
113735 $$outStack.push(out);
113736 out = '';
113737 /* istanbul ignore else */
113738
113739 if (it.createErrors !== false) {
113740 out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } ';
113741
113742 if (it.opts.messages !== false) {
113743 out += ' , message: \'should NOT have ';
113744
113745 if ($keyword == 'maxProperties') {
113746 out += 'more';
113747 } else {
113748 out += 'fewer';
113749 }
113750
113751 out += ' than ';
113752
113753 if ($isData) {
113754 out += '\' + ' + $schemaValue + ' + \'';
113755 } else {
113756 out += '' + $schema;
113757 }
113758
113759 out += ' properties\' ';
113760 }
113761
113762 if (it.opts.verbose) {
113763 out += ' , schema: ';
113764
113765 if ($isData) {
113766 out += 'validate.schema' + $schemaPath;
113767 } else {
113768 out += '' + $schema;
113769 }
113770
113771 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113772 }
113773
113774 out += ' } ';
113775 } else {
113776 out += ' {} ';
113777 }
113778
113779 var __err = out;
113780 out = $$outStack.pop();
113781
113782 if (!it.compositeRule && $breakOnError) {
113783 /* istanbul ignore if */
113784 if (it.async) {
113785 out += ' throw new ValidationError([' + __err + ']); ';
113786 } else {
113787 out += ' validate.errors = [' + __err + ']; return false; ';
113788 }
113789 } else {
113790 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113791 }
113792
113793 out += '} ';
113794
113795 if ($breakOnError) {
113796 out += ' else { ';
113797 }
113798
113799 return out;
113800};
113801
113802/***/ }),
6a5a0f88 113803/* 760 */
eb39fafa
DC
113804/***/ (function(module, exports, __webpack_require__) {
113805
113806"use strict";
113807
113808
113809module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
113810 var out = ' ';
113811 var $lvl = it.level;
113812 var $dataLvl = it.dataLevel;
113813 var $schema = it.schema[$keyword];
113814 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113815 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113816 var $breakOnError = !it.opts.allErrors;
113817 var $data = 'data' + ($dataLvl || '');
113818 var $isData = it.opts.$data && $schema && $schema.$data,
113819 $schemaValue;
113820
113821 if ($isData) {
113822 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
113823 $schemaValue = 'schema' + $lvl;
113824 } else {
113825 $schemaValue = $schema;
113826 }
113827
113828 out += 'var division' + $lvl + ';if (';
113829
113830 if ($isData) {
113831 out += ' ' + $schemaValue + ' !== undefined && ( typeof ' + $schemaValue + ' != \'number\' || ';
113832 }
113833
113834 out += ' (division' + $lvl + ' = ' + $data + ' / ' + $schemaValue + ', ';
113835
113836 if (it.opts.multipleOfPrecision) {
113837 out += ' Math.abs(Math.round(division' + $lvl + ') - division' + $lvl + ') > 1e-' + it.opts.multipleOfPrecision + ' ';
113838 } else {
113839 out += ' division' + $lvl + ' !== parseInt(division' + $lvl + ') ';
113840 }
113841
113842 out += ' ) ';
113843
113844 if ($isData) {
113845 out += ' ) ';
113846 }
113847
113848 out += ' ) { ';
113849 var $$outStack = $$outStack || [];
113850 $$outStack.push(out);
113851 out = '';
113852 /* istanbul ignore else */
113853
113854 if (it.createErrors !== false) {
113855 out += ' { keyword: \'' + 'multipleOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { multipleOf: ' + $schemaValue + ' } ';
113856
113857 if (it.opts.messages !== false) {
113858 out += ' , message: \'should be multiple of ';
113859
113860 if ($isData) {
113861 out += '\' + ' + $schemaValue;
113862 } else {
113863 out += '' + $schemaValue + '\'';
113864 }
113865 }
113866
113867 if (it.opts.verbose) {
113868 out += ' , schema: ';
113869
113870 if ($isData) {
113871 out += 'validate.schema' + $schemaPath;
113872 } else {
113873 out += '' + $schema;
113874 }
113875
113876 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113877 }
113878
113879 out += ' } ';
113880 } else {
113881 out += ' {} ';
113882 }
113883
113884 var __err = out;
113885 out = $$outStack.pop();
113886
113887 if (!it.compositeRule && $breakOnError) {
113888 /* istanbul ignore if */
113889 if (it.async) {
113890 out += ' throw new ValidationError([' + __err + ']); ';
113891 } else {
113892 out += ' validate.errors = [' + __err + ']; return false; ';
113893 }
113894 } else {
113895 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113896 }
113897
113898 out += '} ';
113899
113900 if ($breakOnError) {
113901 out += ' else { ';
113902 }
113903
113904 return out;
113905};
113906
113907/***/ }),
6a5a0f88 113908/* 761 */
eb39fafa
DC
113909/***/ (function(module, exports, __webpack_require__) {
113910
113911"use strict";
113912
113913
113914module.exports = function generate_not(it, $keyword, $ruleType) {
113915 var out = ' ';
113916 var $lvl = it.level;
113917 var $dataLvl = it.dataLevel;
113918 var $schema = it.schema[$keyword];
113919 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
113920 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
113921 var $breakOnError = !it.opts.allErrors;
113922 var $data = 'data' + ($dataLvl || '');
113923 var $errs = 'errs__' + $lvl;
113924 var $it = it.util.copy(it);
113925 $it.level++;
113926 var $nextValid = 'valid' + $it.level;
113927
113928 if (it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all)) {
113929 $it.schema = $schema;
113930 $it.schemaPath = $schemaPath;
113931 $it.errSchemaPath = $errSchemaPath;
113932 out += ' var ' + $errs + ' = errors; ';
113933 var $wasComposite = it.compositeRule;
113934 it.compositeRule = $it.compositeRule = true;
113935 $it.createErrors = false;
113936 var $allErrorsOption;
113937
113938 if ($it.opts.allErrors) {
113939 $allErrorsOption = $it.opts.allErrors;
113940 $it.opts.allErrors = false;
113941 }
113942
113943 out += ' ' + it.validate($it) + ' ';
113944 $it.createErrors = true;
113945 if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
113946 it.compositeRule = $it.compositeRule = $wasComposite;
113947 out += ' if (' + $nextValid + ') { ';
113948 var $$outStack = $$outStack || [];
113949 $$outStack.push(out);
113950 out = '';
113951 /* istanbul ignore else */
113952
113953 if (it.createErrors !== false) {
113954 out += ' { keyword: \'' + 'not' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
113955
113956 if (it.opts.messages !== false) {
113957 out += ' , message: \'should NOT be valid\' ';
113958 }
113959
113960 if (it.opts.verbose) {
113961 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
113962 }
113963
113964 out += ' } ';
113965 } else {
113966 out += ' {} ';
113967 }
113968
113969 var __err = out;
113970 out = $$outStack.pop();
113971
113972 if (!it.compositeRule && $breakOnError) {
113973 /* istanbul ignore if */
113974 if (it.async) {
113975 out += ' throw new ValidationError([' + __err + ']); ';
113976 } else {
113977 out += ' validate.errors = [' + __err + ']; return false; ';
113978 }
113979 } else {
113980 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
113981 }
113982
113983 out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
113984
113985 if (it.opts.allErrors) {
113986 out += ' } ';
113987 }
113988 } else {
113989 out += ' var err = ';
113990 /* istanbul ignore else */
113991
113992 if (it.createErrors !== false) {
113993 out += ' { keyword: \'' + 'not' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
113994
113995 if (it.opts.messages !== false) {
113996 out += ' , message: \'should NOT be valid\' ';
113997 }
113998
113999 if (it.opts.verbose) {
114000 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114001 }
114002
114003 out += ' } ';
114004 } else {
114005 out += ' {} ';
114006 }
114007
114008 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114009
114010 if ($breakOnError) {
114011 out += ' if (false) { ';
114012 }
114013 }
114014
114015 return out;
114016};
114017
114018/***/ }),
6a5a0f88 114019/* 762 */
eb39fafa
DC
114020/***/ (function(module, exports, __webpack_require__) {
114021
114022"use strict";
114023
114024
114025module.exports = function generate_oneOf(it, $keyword, $ruleType) {
114026 var out = ' ';
114027 var $lvl = it.level;
114028 var $dataLvl = it.dataLevel;
114029 var $schema = it.schema[$keyword];
114030 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
114031 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
114032 var $breakOnError = !it.opts.allErrors;
114033 var $data = 'data' + ($dataLvl || '');
114034 var $valid = 'valid' + $lvl;
114035 var $errs = 'errs__' + $lvl;
114036 var $it = it.util.copy(it);
114037 var $closingBraces = '';
114038 $it.level++;
114039 var $nextValid = 'valid' + $it.level;
114040 var $currentBaseId = $it.baseId,
114041 $prevValid = 'prevValid' + $lvl,
114042 $passingSchemas = 'passingSchemas' + $lvl;
114043 out += 'var ' + $errs + ' = errors , ' + $prevValid + ' = false , ' + $valid + ' = false , ' + $passingSchemas + ' = null; ';
114044 var $wasComposite = it.compositeRule;
114045 it.compositeRule = $it.compositeRule = true;
114046 var arr1 = $schema;
114047
114048 if (arr1) {
114049 var $sch,
114050 $i = -1,
114051 l1 = arr1.length - 1;
114052
114053 while ($i < l1) {
114054 $sch = arr1[$i += 1];
114055
114056 if (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)) {
114057 $it.schema = $sch;
114058 $it.schemaPath = $schemaPath + '[' + $i + ']';
114059 $it.errSchemaPath = $errSchemaPath + '/' + $i;
114060 out += ' ' + it.validate($it) + ' ';
114061 $it.baseId = $currentBaseId;
114062 } else {
114063 out += ' var ' + $nextValid + ' = true; ';
114064 }
114065
114066 if ($i) {
114067 out += ' if (' + $nextValid + ' && ' + $prevValid + ') { ' + $valid + ' = false; ' + $passingSchemas + ' = [' + $passingSchemas + ', ' + $i + ']; } else { ';
114068 $closingBraces += '}';
114069 }
114070
114071 out += ' if (' + $nextValid + ') { ' + $valid + ' = ' + $prevValid + ' = true; ' + $passingSchemas + ' = ' + $i + '; }';
114072 }
114073 }
114074
114075 it.compositeRule = $it.compositeRule = $wasComposite;
114076 out += '' + $closingBraces + 'if (!' + $valid + ') { var err = ';
114077 /* istanbul ignore else */
114078
114079 if (it.createErrors !== false) {
114080 out += ' { keyword: \'' + 'oneOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { passingSchemas: ' + $passingSchemas + ' } ';
114081
114082 if (it.opts.messages !== false) {
114083 out += ' , message: \'should match exactly one schema in oneOf\' ';
114084 }
114085
114086 if (it.opts.verbose) {
114087 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114088 }
114089
114090 out += ' } ';
114091 } else {
114092 out += ' {} ';
114093 }
114094
114095 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114096
114097 if (!it.compositeRule && $breakOnError) {
114098 /* istanbul ignore if */
114099 if (it.async) {
114100 out += ' throw new ValidationError(vErrors); ';
114101 } else {
114102 out += ' validate.errors = vErrors; return false; ';
114103 }
114104 }
114105
114106 out += '} else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; }';
114107
114108 if (it.opts.allErrors) {
114109 out += ' } ';
114110 }
114111
114112 return out;
114113};
114114
114115/***/ }),
6a5a0f88 114116/* 763 */
eb39fafa
DC
114117/***/ (function(module, exports, __webpack_require__) {
114118
114119"use strict";
114120
114121
114122module.exports = function generate_pattern(it, $keyword, $ruleType) {
114123 var out = ' ';
114124 var $lvl = it.level;
114125 var $dataLvl = it.dataLevel;
114126 var $schema = it.schema[$keyword];
114127 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
114128 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
114129 var $breakOnError = !it.opts.allErrors;
114130 var $data = 'data' + ($dataLvl || '');
114131 var $isData = it.opts.$data && $schema && $schema.$data,
114132 $schemaValue;
114133
114134 if ($isData) {
114135 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
114136 $schemaValue = 'schema' + $lvl;
114137 } else {
114138 $schemaValue = $schema;
114139 }
114140
114141 var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
114142 out += 'if ( ';
114143
114144 if ($isData) {
114145 out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || ';
114146 }
114147
114148 out += ' !' + $regexp + '.test(' + $data + ') ) { ';
114149 var $$outStack = $$outStack || [];
114150 $$outStack.push(out);
114151 out = '';
114152 /* istanbul ignore else */
114153
114154 if (it.createErrors !== false) {
114155 out += ' { keyword: \'' + 'pattern' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { pattern: ';
114156
114157 if ($isData) {
114158 out += '' + $schemaValue;
114159 } else {
114160 out += '' + it.util.toQuotedString($schema);
114161 }
114162
114163 out += ' } ';
114164
114165 if (it.opts.messages !== false) {
114166 out += ' , message: \'should match pattern "';
114167
114168 if ($isData) {
114169 out += '\' + ' + $schemaValue + ' + \'';
114170 } else {
114171 out += '' + it.util.escapeQuotes($schema);
114172 }
114173
114174 out += '"\' ';
114175 }
114176
114177 if (it.opts.verbose) {
114178 out += ' , schema: ';
114179
114180 if ($isData) {
114181 out += 'validate.schema' + $schemaPath;
114182 } else {
114183 out += '' + it.util.toQuotedString($schema);
114184 }
114185
114186 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114187 }
114188
114189 out += ' } ';
114190 } else {
114191 out += ' {} ';
114192 }
114193
114194 var __err = out;
114195 out = $$outStack.pop();
114196
114197 if (!it.compositeRule && $breakOnError) {
114198 /* istanbul ignore if */
114199 if (it.async) {
114200 out += ' throw new ValidationError([' + __err + ']); ';
114201 } else {
114202 out += ' validate.errors = [' + __err + ']; return false; ';
114203 }
114204 } else {
114205 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114206 }
114207
114208 out += '} ';
114209
114210 if ($breakOnError) {
114211 out += ' else { ';
114212 }
114213
114214 return out;
114215};
114216
114217/***/ }),
6a5a0f88 114218/* 764 */
eb39fafa
DC
114219/***/ (function(module, exports, __webpack_require__) {
114220
114221"use strict";
114222
114223
114224module.exports = function generate_properties(it, $keyword, $ruleType) {
114225 var out = ' ';
114226 var $lvl = it.level;
114227 var $dataLvl = it.dataLevel;
114228 var $schema = it.schema[$keyword];
114229 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
114230 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
114231 var $breakOnError = !it.opts.allErrors;
114232 var $data = 'data' + ($dataLvl || '');
114233 var $errs = 'errs__' + $lvl;
114234 var $it = it.util.copy(it);
114235 var $closingBraces = '';
114236 $it.level++;
114237 var $nextValid = 'valid' + $it.level;
114238 var $key = 'key' + $lvl,
114239 $idx = 'idx' + $lvl,
114240 $dataNxt = $it.dataLevel = it.dataLevel + 1,
114241 $nextData = 'data' + $dataNxt,
114242 $dataProperties = 'dataProperties' + $lvl;
114243 var $schemaKeys = Object.keys($schema || {}),
114244 $pProperties = it.schema.patternProperties || {},
114245 $pPropertyKeys = Object.keys($pProperties),
114246 $aProperties = it.schema.additionalProperties,
114247 $someProperties = $schemaKeys.length || $pPropertyKeys.length,
114248 $noAdditional = $aProperties === false,
114249 $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
114250 $removeAdditional = it.opts.removeAdditional,
114251 $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
114252 $ownProperties = it.opts.ownProperties,
114253 $currentBaseId = it.baseId;
114254 var $required = it.schema.required;
114255 if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
114256 out += 'var ' + $errs + ' = errors;var ' + $nextValid + ' = true;';
114257
114258 if ($ownProperties) {
114259 out += ' var ' + $dataProperties + ' = undefined;';
114260 }
114261
114262 if ($checkAdditional) {
114263 if ($ownProperties) {
114264 out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; ';
114265 } else {
114266 out += ' for (var ' + $key + ' in ' + $data + ') { ';
114267 }
114268
114269 if ($someProperties) {
114270 out += ' var isAdditional' + $lvl + ' = !(false ';
114271
114272 if ($schemaKeys.length) {
114273 if ($schemaKeys.length > 8) {
114274 out += ' || validate.schema' + $schemaPath + '.hasOwnProperty(' + $key + ') ';
114275 } else {
114276 var arr1 = $schemaKeys;
114277
114278 if (arr1) {
114279 var $propertyKey,
114280 i1 = -1,
114281 l1 = arr1.length - 1;
114282
114283 while (i1 < l1) {
114284 $propertyKey = arr1[i1 += 1];
114285 out += ' || ' + $key + ' == ' + it.util.toQuotedString($propertyKey) + ' ';
114286 }
114287 }
114288 }
114289 }
114290
114291 if ($pPropertyKeys.length) {
114292 var arr2 = $pPropertyKeys;
114293
114294 if (arr2) {
114295 var $pProperty,
114296 $i = -1,
114297 l2 = arr2.length - 1;
114298
114299 while ($i < l2) {
114300 $pProperty = arr2[$i += 1];
114301 out += ' || ' + it.usePattern($pProperty) + '.test(' + $key + ') ';
114302 }
114303 }
114304 }
114305
114306 out += ' ); if (isAdditional' + $lvl + ') { ';
114307 }
114308
114309 if ($removeAdditional == 'all') {
114310 out += ' delete ' + $data + '[' + $key + ']; ';
114311 } else {
114312 var $currentErrorPath = it.errorPath;
114313 var $additionalProperty = '\' + ' + $key + ' + \'';
114314
114315 if (it.opts._errorDataPathProperty) {
114316 it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
114317 }
114318
114319 if ($noAdditional) {
114320 if ($removeAdditional) {
114321 out += ' delete ' + $data + '[' + $key + ']; ';
114322 } else {
114323 out += ' ' + $nextValid + ' = false; ';
114324 var $currErrSchemaPath = $errSchemaPath;
114325 $errSchemaPath = it.errSchemaPath + '/additionalProperties';
114326 var $$outStack = $$outStack || [];
114327 $$outStack.push(out);
114328 out = '';
114329 /* istanbul ignore else */
114330
114331 if (it.createErrors !== false) {
114332 out += ' { keyword: \'' + 'additionalProperties' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { additionalProperty: \'' + $additionalProperty + '\' } ';
114333
114334 if (it.opts.messages !== false) {
114335 out += ' , message: \'';
114336
114337 if (it.opts._errorDataPathProperty) {
114338 out += 'is an invalid additional property';
114339 } else {
114340 out += 'should NOT have additional properties';
114341 }
114342
114343 out += '\' ';
114344 }
114345
114346 if (it.opts.verbose) {
114347 out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114348 }
114349
114350 out += ' } ';
114351 } else {
114352 out += ' {} ';
114353 }
114354
114355 var __err = out;
114356 out = $$outStack.pop();
114357
114358 if (!it.compositeRule && $breakOnError) {
114359 /* istanbul ignore if */
114360 if (it.async) {
114361 out += ' throw new ValidationError([' + __err + ']); ';
114362 } else {
114363 out += ' validate.errors = [' + __err + ']; return false; ';
114364 }
114365 } else {
114366 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114367 }
114368
114369 $errSchemaPath = $currErrSchemaPath;
114370
114371 if ($breakOnError) {
114372 out += ' break; ';
114373 }
114374 }
114375 } else if ($additionalIsSchema) {
114376 if ($removeAdditional == 'failing') {
114377 out += ' var ' + $errs + ' = errors; ';
114378 var $wasComposite = it.compositeRule;
114379 it.compositeRule = $it.compositeRule = true;
114380 $it.schema = $aProperties;
114381 $it.schemaPath = it.schemaPath + '.additionalProperties';
114382 $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
114383 $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
114384 var $passData = $data + '[' + $key + ']';
114385 $it.dataPathArr[$dataNxt] = $key;
114386 var $code = it.validate($it);
114387 $it.baseId = $currentBaseId;
114388
114389 if (it.util.varOccurences($code, $nextData) < 2) {
114390 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
114391 } else {
114392 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
114393 }
114394
114395 out += ' if (!' + $nextValid + ') { errors = ' + $errs + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + $data + '[' + $key + ']; } ';
114396 it.compositeRule = $it.compositeRule = $wasComposite;
114397 } else {
114398 $it.schema = $aProperties;
114399 $it.schemaPath = it.schemaPath + '.additionalProperties';
114400 $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
114401 $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
114402 var $passData = $data + '[' + $key + ']';
114403 $it.dataPathArr[$dataNxt] = $key;
114404 var $code = it.validate($it);
114405 $it.baseId = $currentBaseId;
114406
114407 if (it.util.varOccurences($code, $nextData) < 2) {
114408 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
114409 } else {
114410 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
114411 }
114412
114413 if ($breakOnError) {
114414 out += ' if (!' + $nextValid + ') break; ';
114415 }
114416 }
114417 }
114418
114419 it.errorPath = $currentErrorPath;
114420 }
114421
114422 if ($someProperties) {
114423 out += ' } ';
114424 }
114425
114426 out += ' } ';
114427
114428 if ($breakOnError) {
114429 out += ' if (' + $nextValid + ') { ';
114430 $closingBraces += '}';
114431 }
114432 }
114433
114434 var $useDefaults = it.opts.useDefaults && !it.compositeRule;
114435
114436 if ($schemaKeys.length) {
114437 var arr3 = $schemaKeys;
114438
114439 if (arr3) {
114440 var $propertyKey,
114441 i3 = -1,
114442 l3 = arr3.length - 1;
114443
114444 while (i3 < l3) {
114445 $propertyKey = arr3[i3 += 1];
114446 var $sch = $schema[$propertyKey];
114447
114448 if (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)) {
114449 var $prop = it.util.getProperty($propertyKey),
114450 $passData = $data + $prop,
114451 $hasDefault = $useDefaults && $sch.default !== undefined;
114452 $it.schema = $sch;
114453 $it.schemaPath = $schemaPath + $prop;
114454 $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
114455 $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
114456 $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
114457 var $code = it.validate($it);
114458 $it.baseId = $currentBaseId;
114459
114460 if (it.util.varOccurences($code, $nextData) < 2) {
114461 $code = it.util.varReplace($code, $nextData, $passData);
114462 var $useData = $passData;
114463 } else {
114464 var $useData = $nextData;
114465 out += ' var ' + $nextData + ' = ' + $passData + '; ';
114466 }
114467
114468 if ($hasDefault) {
114469 out += ' ' + $code + ' ';
114470 } else {
114471 if ($requiredHash && $requiredHash[$propertyKey]) {
114472 out += ' if ( ' + $useData + ' === undefined ';
114473
114474 if ($ownProperties) {
114475 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
114476 }
114477
114478 out += ') { ' + $nextValid + ' = false; ';
114479 var $currentErrorPath = it.errorPath,
114480 $currErrSchemaPath = $errSchemaPath,
114481 $missingProperty = it.util.escapeQuotes($propertyKey);
114482
114483 if (it.opts._errorDataPathProperty) {
114484 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
114485 }
114486
114487 $errSchemaPath = it.errSchemaPath + '/required';
114488 var $$outStack = $$outStack || [];
114489 $$outStack.push(out);
114490 out = '';
114491 /* istanbul ignore else */
114492
114493 if (it.createErrors !== false) {
114494 out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
114495
114496 if (it.opts.messages !== false) {
114497 out += ' , message: \'';
114498
114499 if (it.opts._errorDataPathProperty) {
114500 out += 'is a required property';
114501 } else {
114502 out += 'should have required property \\\'' + $missingProperty + '\\\'';
114503 }
114504
114505 out += '\' ';
114506 }
114507
114508 if (it.opts.verbose) {
114509 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114510 }
114511
114512 out += ' } ';
114513 } else {
114514 out += ' {} ';
114515 }
114516
114517 var __err = out;
114518 out = $$outStack.pop();
114519
114520 if (!it.compositeRule && $breakOnError) {
114521 /* istanbul ignore if */
114522 if (it.async) {
114523 out += ' throw new ValidationError([' + __err + ']); ';
114524 } else {
114525 out += ' validate.errors = [' + __err + ']; return false; ';
114526 }
114527 } else {
114528 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114529 }
114530
114531 $errSchemaPath = $currErrSchemaPath;
114532 it.errorPath = $currentErrorPath;
114533 out += ' } else { ';
114534 } else {
114535 if ($breakOnError) {
114536 out += ' if ( ' + $useData + ' === undefined ';
114537
114538 if ($ownProperties) {
114539 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
114540 }
114541
114542 out += ') { ' + $nextValid + ' = true; } else { ';
114543 } else {
114544 out += ' if (' + $useData + ' !== undefined ';
114545
114546 if ($ownProperties) {
114547 out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
114548 }
114549
114550 out += ' ) { ';
114551 }
114552 }
114553
114554 out += ' ' + $code + ' } ';
114555 }
114556 }
114557
114558 if ($breakOnError) {
114559 out += ' if (' + $nextValid + ') { ';
114560 $closingBraces += '}';
114561 }
114562 }
114563 }
114564 }
114565
114566 if ($pPropertyKeys.length) {
114567 var arr4 = $pPropertyKeys;
114568
114569 if (arr4) {
114570 var $pProperty,
114571 i4 = -1,
114572 l4 = arr4.length - 1;
114573
114574 while (i4 < l4) {
114575 $pProperty = arr4[i4 += 1];
114576 var $sch = $pProperties[$pProperty];
114577
114578 if (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)) {
114579 $it.schema = $sch;
114580 $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
114581 $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
114582
114583 if ($ownProperties) {
114584 out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; ';
114585 } else {
114586 out += ' for (var ' + $key + ' in ' + $data + ') { ';
114587 }
114588
114589 out += ' if (' + it.usePattern($pProperty) + '.test(' + $key + ')) { ';
114590 $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
114591 var $passData = $data + '[' + $key + ']';
114592 $it.dataPathArr[$dataNxt] = $key;
114593 var $code = it.validate($it);
114594 $it.baseId = $currentBaseId;
114595
114596 if (it.util.varOccurences($code, $nextData) < 2) {
114597 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
114598 } else {
114599 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
114600 }
114601
114602 if ($breakOnError) {
114603 out += ' if (!' + $nextValid + ') break; ';
114604 }
114605
114606 out += ' } ';
114607
114608 if ($breakOnError) {
114609 out += ' else ' + $nextValid + ' = true; ';
114610 }
114611
114612 out += ' } ';
114613
114614 if ($breakOnError) {
114615 out += ' if (' + $nextValid + ') { ';
114616 $closingBraces += '}';
114617 }
114618 }
114619 }
114620 }
114621 }
114622
114623 if ($breakOnError) {
114624 out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
114625 }
114626
114627 out = it.util.cleanUpCode(out);
114628 return out;
114629};
114630
114631/***/ }),
6a5a0f88 114632/* 765 */
eb39fafa
DC
114633/***/ (function(module, exports, __webpack_require__) {
114634
114635"use strict";
114636
114637
114638module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
114639 var out = ' ';
114640 var $lvl = it.level;
114641 var $dataLvl = it.dataLevel;
114642 var $schema = it.schema[$keyword];
114643 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
114644 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
114645 var $breakOnError = !it.opts.allErrors;
114646 var $data = 'data' + ($dataLvl || '');
114647 var $errs = 'errs__' + $lvl;
114648 var $it = it.util.copy(it);
114649 var $closingBraces = '';
114650 $it.level++;
114651 var $nextValid = 'valid' + $it.level;
114652 out += 'var ' + $errs + ' = errors;';
114653
114654 if (it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all)) {
114655 $it.schema = $schema;
114656 $it.schemaPath = $schemaPath;
114657 $it.errSchemaPath = $errSchemaPath;
114658 var $key = 'key' + $lvl,
114659 $idx = 'idx' + $lvl,
114660 $i = 'i' + $lvl,
114661 $invalidName = '\' + ' + $key + ' + \'',
114662 $dataNxt = $it.dataLevel = it.dataLevel + 1,
114663 $nextData = 'data' + $dataNxt,
114664 $dataProperties = 'dataProperties' + $lvl,
114665 $ownProperties = it.opts.ownProperties,
114666 $currentBaseId = it.baseId;
114667
114668 if ($ownProperties) {
114669 out += ' var ' + $dataProperties + ' = undefined; ';
114670 }
114671
114672 if ($ownProperties) {
114673 out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; ';
114674 } else {
114675 out += ' for (var ' + $key + ' in ' + $data + ') { ';
114676 }
114677
114678 out += ' var startErrs' + $lvl + ' = errors; ';
114679 var $passData = $key;
114680 var $wasComposite = it.compositeRule;
114681 it.compositeRule = $it.compositeRule = true;
114682 var $code = it.validate($it);
114683 $it.baseId = $currentBaseId;
114684
114685 if (it.util.varOccurences($code, $nextData) < 2) {
114686 out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
114687 } else {
114688 out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
114689 }
114690
114691 it.compositeRule = $it.compositeRule = $wasComposite;
114692 out += ' if (!' + $nextValid + ') { for (var ' + $i + '=startErrs' + $lvl + '; ' + $i + '<errors; ' + $i + '++) { vErrors[' + $i + '].propertyName = ' + $key + '; } var err = ';
114693 /* istanbul ignore else */
114694
114695 if (it.createErrors !== false) {
114696 out += ' { keyword: \'' + 'propertyNames' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { propertyName: \'' + $invalidName + '\' } ';
114697
114698 if (it.opts.messages !== false) {
114699 out += ' , message: \'property name \\\'' + $invalidName + '\\\' is invalid\' ';
114700 }
114701
114702 if (it.opts.verbose) {
114703 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114704 }
114705
114706 out += ' } ';
114707 } else {
114708 out += ' {} ';
114709 }
114710
114711 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114712
114713 if (!it.compositeRule && $breakOnError) {
114714 /* istanbul ignore if */
114715 if (it.async) {
114716 out += ' throw new ValidationError(vErrors); ';
114717 } else {
114718 out += ' validate.errors = vErrors; return false; ';
114719 }
114720 }
114721
114722 if ($breakOnError) {
114723 out += ' break; ';
114724 }
114725
114726 out += ' } }';
114727 }
114728
114729 if ($breakOnError) {
114730 out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
114731 }
114732
114733 out = it.util.cleanUpCode(out);
114734 return out;
114735};
114736
114737/***/ }),
6a5a0f88 114738/* 766 */
eb39fafa
DC
114739/***/ (function(module, exports, __webpack_require__) {
114740
114741"use strict";
114742
114743
114744module.exports = function generate_required(it, $keyword, $ruleType) {
114745 var out = ' ';
114746 var $lvl = it.level;
114747 var $dataLvl = it.dataLevel;
114748 var $schema = it.schema[$keyword];
114749 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
114750 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
114751 var $breakOnError = !it.opts.allErrors;
114752 var $data = 'data' + ($dataLvl || '');
114753 var $valid = 'valid' + $lvl;
114754 var $isData = it.opts.$data && $schema && $schema.$data,
114755 $schemaValue;
114756
114757 if ($isData) {
114758 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
114759 $schemaValue = 'schema' + $lvl;
114760 } else {
114761 $schemaValue = $schema;
114762 }
114763
114764 var $vSchema = 'schema' + $lvl;
114765
114766 if (!$isData) {
114767 if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
114768 var $required = [];
114769 var arr1 = $schema;
114770
114771 if (arr1) {
114772 var $property,
114773 i1 = -1,
114774 l1 = arr1.length - 1;
114775
114776 while (i1 < l1) {
114777 $property = arr1[i1 += 1];
114778 var $propertySch = it.schema.properties[$property];
114779
114780 if (!($propertySch && (it.opts.strictKeywords ? typeof $propertySch == 'object' && Object.keys($propertySch).length > 0 : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
114781 $required[$required.length] = $property;
114782 }
114783 }
114784 }
114785 } else {
114786 var $required = $schema;
114787 }
114788 }
114789
114790 if ($isData || $required.length) {
114791 var $currentErrorPath = it.errorPath,
114792 $loopRequired = $isData || $required.length >= it.opts.loopRequired,
114793 $ownProperties = it.opts.ownProperties;
114794
114795 if ($breakOnError) {
114796 out += ' var missing' + $lvl + '; ';
114797
114798 if ($loopRequired) {
114799 if (!$isData) {
114800 out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; ';
114801 }
114802
114803 var $i = 'i' + $lvl,
114804 $propertyPath = 'schema' + $lvl + '[' + $i + ']',
114805 $missingProperty = '\' + ' + $propertyPath + ' + \'';
114806
114807 if (it.opts._errorDataPathProperty) {
114808 it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
114809 }
114810
114811 out += ' var ' + $valid + ' = true; ';
114812
114813 if ($isData) {
114814 out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {';
114815 }
114816
114817 out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { ' + $valid + ' = ' + $data + '[' + $vSchema + '[' + $i + ']] !== undefined ';
114818
114819 if ($ownProperties) {
114820 out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) ';
114821 }
114822
114823 out += '; if (!' + $valid + ') break; } ';
114824
114825 if ($isData) {
114826 out += ' } ';
114827 }
114828
114829 out += ' if (!' + $valid + ') { ';
114830 var $$outStack = $$outStack || [];
114831 $$outStack.push(out);
114832 out = '';
114833 /* istanbul ignore else */
114834
114835 if (it.createErrors !== false) {
114836 out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
114837
114838 if (it.opts.messages !== false) {
114839 out += ' , message: \'';
114840
114841 if (it.opts._errorDataPathProperty) {
114842 out += 'is a required property';
114843 } else {
114844 out += 'should have required property \\\'' + $missingProperty + '\\\'';
114845 }
114846
114847 out += '\' ';
114848 }
114849
114850 if (it.opts.verbose) {
114851 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114852 }
114853
114854 out += ' } ';
114855 } else {
114856 out += ' {} ';
114857 }
114858
114859 var __err = out;
114860 out = $$outStack.pop();
114861
114862 if (!it.compositeRule && $breakOnError) {
114863 /* istanbul ignore if */
114864 if (it.async) {
114865 out += ' throw new ValidationError([' + __err + ']); ';
114866 } else {
114867 out += ' validate.errors = [' + __err + ']; return false; ';
114868 }
114869 } else {
114870 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114871 }
114872
114873 out += ' } else { ';
114874 } else {
114875 out += ' if ( ';
114876 var arr2 = $required;
114877
114878 if (arr2) {
114879 var $propertyKey,
114880 $i = -1,
114881 l2 = arr2.length - 1;
114882
114883 while ($i < l2) {
114884 $propertyKey = arr2[$i += 1];
114885
114886 if ($i) {
114887 out += ' || ';
114888 }
114889
114890 var $prop = it.util.getProperty($propertyKey),
114891 $useData = $data + $prop;
114892 out += ' ( ( ' + $useData + ' === undefined ';
114893
114894 if ($ownProperties) {
114895 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
114896 }
114897
114898 out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) ';
114899 }
114900 }
114901
114902 out += ') { ';
114903 var $propertyPath = 'missing' + $lvl,
114904 $missingProperty = '\' + ' + $propertyPath + ' + \'';
114905
114906 if (it.opts._errorDataPathProperty) {
114907 it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
114908 }
114909
114910 var $$outStack = $$outStack || [];
114911 $$outStack.push(out);
114912 out = '';
114913 /* istanbul ignore else */
114914
114915 if (it.createErrors !== false) {
114916 out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
114917
114918 if (it.opts.messages !== false) {
114919 out += ' , message: \'';
114920
114921 if (it.opts._errorDataPathProperty) {
114922 out += 'is a required property';
114923 } else {
114924 out += 'should have required property \\\'' + $missingProperty + '\\\'';
114925 }
114926
114927 out += '\' ';
114928 }
114929
114930 if (it.opts.verbose) {
114931 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114932 }
114933
114934 out += ' } ';
114935 } else {
114936 out += ' {} ';
114937 }
114938
114939 var __err = out;
114940 out = $$outStack.pop();
114941
114942 if (!it.compositeRule && $breakOnError) {
114943 /* istanbul ignore if */
114944 if (it.async) {
114945 out += ' throw new ValidationError([' + __err + ']); ';
114946 } else {
114947 out += ' validate.errors = [' + __err + ']; return false; ';
114948 }
114949 } else {
114950 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
114951 }
114952
114953 out += ' } else { ';
114954 }
114955 } else {
114956 if ($loopRequired) {
114957 if (!$isData) {
114958 out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; ';
114959 }
114960
114961 var $i = 'i' + $lvl,
114962 $propertyPath = 'schema' + $lvl + '[' + $i + ']',
114963 $missingProperty = '\' + ' + $propertyPath + ' + \'';
114964
114965 if (it.opts._errorDataPathProperty) {
114966 it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
114967 }
114968
114969 if ($isData) {
114970 out += ' if (' + $vSchema + ' && !Array.isArray(' + $vSchema + ')) { var err = ';
114971 /* istanbul ignore else */
114972
114973 if (it.createErrors !== false) {
114974 out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
114975
114976 if (it.opts.messages !== false) {
114977 out += ' , message: \'';
114978
114979 if (it.opts._errorDataPathProperty) {
114980 out += 'is a required property';
114981 } else {
114982 out += 'should have required property \\\'' + $missingProperty + '\\\'';
114983 }
114984
114985 out += '\' ';
114986 }
114987
114988 if (it.opts.verbose) {
114989 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
114990 }
114991
114992 out += ' } ';
114993 } else {
114994 out += ' {} ';
114995 }
114996
114997 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + $vSchema + ' !== undefined) { ';
114998 }
114999
115000 out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { if (' + $data + '[' + $vSchema + '[' + $i + ']] === undefined ';
115001
115002 if ($ownProperties) {
115003 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) ';
115004 }
115005
115006 out += ') { var err = ';
115007 /* istanbul ignore else */
115008
115009 if (it.createErrors !== false) {
115010 out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
115011
115012 if (it.opts.messages !== false) {
115013 out += ' , message: \'';
115014
115015 if (it.opts._errorDataPathProperty) {
115016 out += 'is a required property';
115017 } else {
115018 out += 'should have required property \\\'' + $missingProperty + '\\\'';
115019 }
115020
115021 out += '\' ';
115022 }
115023
115024 if (it.opts.verbose) {
115025 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
115026 }
115027
115028 out += ' } ';
115029 } else {
115030 out += ' {} ';
115031 }
115032
115033 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
115034
115035 if ($isData) {
115036 out += ' } ';
115037 }
115038 } else {
115039 var arr3 = $required;
115040
115041 if (arr3) {
115042 var $propertyKey,
115043 i3 = -1,
115044 l3 = arr3.length - 1;
115045
115046 while (i3 < l3) {
115047 $propertyKey = arr3[i3 += 1];
115048 var $prop = it.util.getProperty($propertyKey),
115049 $missingProperty = it.util.escapeQuotes($propertyKey),
115050 $useData = $data + $prop;
115051
115052 if (it.opts._errorDataPathProperty) {
115053 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
115054 }
115055
115056 out += ' if ( ' + $useData + ' === undefined ';
115057
115058 if ($ownProperties) {
115059 out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
115060 }
115061
115062 out += ') { var err = ';
115063 /* istanbul ignore else */
115064
115065 if (it.createErrors !== false) {
115066 out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
115067
115068 if (it.opts.messages !== false) {
115069 out += ' , message: \'';
115070
115071 if (it.opts._errorDataPathProperty) {
115072 out += 'is a required property';
115073 } else {
115074 out += 'should have required property \\\'' + $missingProperty + '\\\'';
115075 }
115076
115077 out += '\' ';
115078 }
115079
115080 if (it.opts.verbose) {
115081 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
115082 }
115083
115084 out += ' } ';
115085 } else {
115086 out += ' {} ';
115087 }
115088
115089 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
115090 }
115091 }
115092 }
115093 }
115094
115095 it.errorPath = $currentErrorPath;
115096 } else if ($breakOnError) {
115097 out += ' if (true) {';
115098 }
115099
115100 return out;
115101};
115102
115103/***/ }),
6a5a0f88 115104/* 767 */
eb39fafa
DC
115105/***/ (function(module, exports, __webpack_require__) {
115106
115107"use strict";
115108
115109
115110module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
115111 var out = ' ';
115112 var $lvl = it.level;
115113 var $dataLvl = it.dataLevel;
115114 var $schema = it.schema[$keyword];
115115 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
115116 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
115117 var $breakOnError = !it.opts.allErrors;
115118 var $data = 'data' + ($dataLvl || '');
115119 var $valid = 'valid' + $lvl;
115120 var $isData = it.opts.$data && $schema && $schema.$data,
115121 $schemaValue;
115122
115123 if ($isData) {
115124 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
115125 $schemaValue = 'schema' + $lvl;
115126 } else {
115127 $schemaValue = $schema;
115128 }
115129
115130 if (($schema || $isData) && it.opts.uniqueItems !== false) {
115131 if ($isData) {
115132 out += ' var ' + $valid + '; if (' + $schemaValue + ' === false || ' + $schemaValue + ' === undefined) ' + $valid + ' = true; else if (typeof ' + $schemaValue + ' != \'boolean\') ' + $valid + ' = false; else { ';
115133 }
115134
115135 out += ' var i = ' + $data + '.length , ' + $valid + ' = true , j; if (i > 1) { ';
115136 var $itemType = it.schema.items && it.schema.items.type,
115137 $typeIsArray = Array.isArray($itemType);
115138
115139 if (!$itemType || $itemType == 'object' || $itemType == 'array' || $typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) {
115140 out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + $data + '[i], ' + $data + '[j])) { ' + $valid + ' = false; break outer; } } } ';
115141 } else {
115142 out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + $data + '[i]; ';
115143 var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
115144 out += ' if (' + it.util[$method]($itemType, 'item', true) + ') continue; ';
115145
115146 if ($typeIsArray) {
115147 out += ' if (typeof item == \'string\') item = \'"\' + item; ';
115148 }
115149
115150 out += ' if (typeof itemIndices[item] == \'number\') { ' + $valid + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
115151 }
115152
115153 out += ' } ';
115154
115155 if ($isData) {
115156 out += ' } ';
115157 }
115158
115159 out += ' if (!' + $valid + ') { ';
115160 var $$outStack = $$outStack || [];
115161 $$outStack.push(out);
115162 out = '';
115163 /* istanbul ignore else */
115164
115165 if (it.createErrors !== false) {
115166 out += ' { keyword: \'' + 'uniqueItems' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { i: i, j: j } ';
115167
115168 if (it.opts.messages !== false) {
115169 out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
115170 }
115171
115172 if (it.opts.verbose) {
115173 out += ' , schema: ';
115174
115175 if ($isData) {
115176 out += 'validate.schema' + $schemaPath;
115177 } else {
115178 out += '' + $schema;
115179 }
115180
115181 out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
115182 }
115183
115184 out += ' } ';
115185 } else {
115186 out += ' {} ';
115187 }
115188
115189 var __err = out;
115190 out = $$outStack.pop();
115191
115192 if (!it.compositeRule && $breakOnError) {
115193 /* istanbul ignore if */
115194 if (it.async) {
115195 out += ' throw new ValidationError([' + __err + ']); ';
115196 } else {
115197 out += ' validate.errors = [' + __err + ']; return false; ';
115198 }
115199 } else {
115200 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
115201 }
115202
115203 out += ' } ';
115204
115205 if ($breakOnError) {
115206 out += ' else { ';
115207 }
115208 } else {
115209 if ($breakOnError) {
115210 out += ' if (true) { ';
115211 }
115212 }
115213
115214 return out;
115215};
115216
115217/***/ }),
6a5a0f88 115218/* 768 */
eb39fafa
DC
115219/***/ (function(module, exports, __webpack_require__) {
115220
115221"use strict";
115222
115223
115224var KEYWORDS = ['multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', 'minLength', 'pattern', 'additionalItems', 'maxItems', 'minItems', 'uniqueItems', 'maxProperties', 'minProperties', 'required', 'additionalProperties', 'enum', 'format', 'const'];
115225
115226module.exports = function (metaSchema, keywordsJsonPointers) {
115227 for (var i = 0; i < keywordsJsonPointers.length; i++) {
115228 metaSchema = JSON.parse(JSON.stringify(metaSchema));
115229 var segments = keywordsJsonPointers[i].split('/');
115230 var keywords = metaSchema;
115231 var j;
115232
115233 for (j = 1; j < segments.length; j++) keywords = keywords[segments[j]];
115234
115235 for (j = 0; j < KEYWORDS.length; j++) {
115236 var key = KEYWORDS[j];
115237 var schema = keywords[key];
115238
115239 if (schema) {
115240 keywords[key] = {
115241 anyOf: [schema, {
115242 $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#'
115243 }]
115244 };
115245 }
115246 }
115247 }
115248
115249 return metaSchema;
115250};
115251
115252/***/ }),
6a5a0f88 115253/* 769 */
eb39fafa
DC
115254/***/ (function(module, exports, __webpack_require__) {
115255
115256"use strict";
115257
115258
6a5a0f88 115259var MissingRefError = __webpack_require__(738).MissingRef;
eb39fafa
DC
115260
115261module.exports = compileAsync;
115262/**
115263 * Creates validating function for passed schema with asynchronous loading of missing schemas.
115264 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
115265 * @this Ajv
115266 * @param {Object} schema schema object
115267 * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
115268 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
115269 * @return {Promise} promise that resolves with a validating function.
115270 */
115271
115272function compileAsync(schema, meta, callback) {
115273 /* eslint no-shadow: 0 */
115274
115275 /* global Promise */
115276
115277 /* jshint validthis: true */
115278 var self = this;
115279 if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function');
115280
115281 if (typeof meta == 'function') {
115282 callback = meta;
115283 meta = undefined;
115284 }
115285
115286 var p = loadMetaSchemaOf(schema).then(function () {
115287 var schemaObj = self._addSchema(schema, undefined, meta);
115288
115289 return schemaObj.validate || _compileAsync(schemaObj);
115290 });
115291
115292 if (callback) {
115293 p.then(function (v) {
115294 callback(null, v);
115295 }, callback);
115296 }
115297
115298 return p;
115299
115300 function loadMetaSchemaOf(sch) {
115301 var $schema = sch.$schema;
115302 return $schema && !self.getSchema($schema) ? compileAsync.call(self, {
115303 $ref: $schema
115304 }, true) : Promise.resolve();
115305 }
115306
115307 function _compileAsync(schemaObj) {
115308 try {
115309 return self._compile(schemaObj);
115310 } catch (e) {
115311 if (e instanceof MissingRefError) return loadMissingSchema(e);
115312 throw e;
115313 }
115314
115315 function loadMissingSchema(e) {
115316 var ref = e.missingSchema;
115317 if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
115318 var schemaPromise = self._loadingSchemas[ref];
115319
115320 if (!schemaPromise) {
115321 schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
115322 schemaPromise.then(removePromise, removePromise);
115323 }
115324
115325 return schemaPromise.then(function (sch) {
115326 if (!added(ref)) {
115327 return loadMetaSchemaOf(sch).then(function () {
115328 if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
115329 });
115330 }
115331 }).then(function () {
115332 return _compileAsync(schemaObj);
115333 });
115334
115335 function removePromise() {
115336 delete self._loadingSchemas[ref];
115337 }
115338
115339 function added(ref) {
115340 return self._refs[ref] || self._schemas[ref];
115341 }
115342 }
115343 }
115344}
115345
115346/***/ }),
6a5a0f88 115347/* 770 */
eb39fafa
DC
115348/***/ (function(module, exports, __webpack_require__) {
115349
115350"use strict";
115351
115352
115353var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
115354
6a5a0f88 115355var customRuleCode = __webpack_require__(771);
eb39fafa 115356
6a5a0f88 115357var definitionSchema = __webpack_require__(772);
eb39fafa
DC
115358
115359module.exports = {
115360 add: addKeyword,
115361 get: getKeyword,
115362 remove: removeKeyword,
115363 validate: validateKeyword
115364};
115365/**
115366 * Define custom keyword
115367 * @this Ajv
115368 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
115369 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
115370 * @return {Ajv} this for method chaining
115371 */
115372
115373function addKeyword(keyword, definition) {
115374 /* jshint validthis: true */
115375
115376 /* eslint no-shadow: 0 */
115377 var RULES = this.RULES;
115378 if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined');
115379 if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier');
115380
115381 if (definition) {
115382 this.validateKeyword(definition, true);
115383 var dataType = definition.type;
115384
115385 if (Array.isArray(dataType)) {
115386 for (var i = 0; i < dataType.length; i++) _addRule(keyword, dataType[i], definition);
115387 } else {
115388 _addRule(keyword, dataType, definition);
115389 }
115390
115391 var metaSchema = definition.metaSchema;
115392
115393 if (metaSchema) {
115394 if (definition.$data && this._opts.$data) {
115395 metaSchema = {
115396 anyOf: [metaSchema, {
115397 '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#'
115398 }]
115399 };
115400 }
115401
115402 definition.validateSchema = this.compile(metaSchema, true);
115403 }
115404 }
115405
115406 RULES.keywords[keyword] = RULES.all[keyword] = true;
115407
115408 function _addRule(keyword, dataType, definition) {
115409 var ruleGroup;
115410
115411 for (var i = 0; i < RULES.length; i++) {
115412 var rg = RULES[i];
115413
115414 if (rg.type == dataType) {
115415 ruleGroup = rg;
115416 break;
115417 }
115418 }
115419
115420 if (!ruleGroup) {
115421 ruleGroup = {
115422 type: dataType,
115423 rules: []
115424 };
115425 RULES.push(ruleGroup);
115426 }
115427
115428 var rule = {
115429 keyword: keyword,
115430 definition: definition,
115431 custom: true,
115432 code: customRuleCode,
115433 implements: definition.implements
115434 };
115435 ruleGroup.rules.push(rule);
115436 RULES.custom[keyword] = rule;
115437 }
115438
115439 return this;
115440}
115441/**
115442 * Get keyword
115443 * @this Ajv
115444 * @param {String} keyword pre-defined or custom keyword.
115445 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
115446 */
115447
115448
115449function getKeyword(keyword) {
115450 /* jshint validthis: true */
115451 var rule = this.RULES.custom[keyword];
115452 return rule ? rule.definition : this.RULES.keywords[keyword] || false;
115453}
115454/**
115455 * Remove keyword
115456 * @this Ajv
115457 * @param {String} keyword pre-defined or custom keyword.
115458 * @return {Ajv} this for method chaining
115459 */
115460
115461
115462function removeKeyword(keyword) {
115463 /* jshint validthis: true */
115464 var RULES = this.RULES;
115465 delete RULES.keywords[keyword];
115466 delete RULES.all[keyword];
115467 delete RULES.custom[keyword];
115468
115469 for (var i = 0; i < RULES.length; i++) {
115470 var rules = RULES[i].rules;
115471
115472 for (var j = 0; j < rules.length; j++) {
115473 if (rules[j].keyword == keyword) {
115474 rules.splice(j, 1);
115475 break;
115476 }
115477 }
115478 }
115479
115480 return this;
115481}
115482/**
115483 * Validate keyword definition
115484 * @this Ajv
115485 * @param {Object} definition keyword definition object.
115486 * @param {Boolean} throwError true to throw exception if definition is invalid
115487 * @return {boolean} validation result
115488 */
115489
115490
115491function validateKeyword(definition, throwError) {
115492 validateKeyword.errors = null;
115493 var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true);
115494 if (v(definition)) return true;
115495 validateKeyword.errors = v.errors;
115496 if (throwError) throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));else return false;
115497}
115498
115499/***/ }),
6a5a0f88 115500/* 771 */
eb39fafa
DC
115501/***/ (function(module, exports, __webpack_require__) {
115502
115503"use strict";
115504
115505
115506module.exports = function generate_custom(it, $keyword, $ruleType) {
115507 var out = ' ';
115508 var $lvl = it.level;
115509 var $dataLvl = it.dataLevel;
115510 var $schema = it.schema[$keyword];
115511 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
115512 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
115513 var $breakOnError = !it.opts.allErrors;
115514 var $errorKeyword;
115515 var $data = 'data' + ($dataLvl || '');
115516 var $valid = 'valid' + $lvl;
115517 var $errs = 'errs__' + $lvl;
115518 var $isData = it.opts.$data && $schema && $schema.$data,
115519 $schemaValue;
115520
115521 if ($isData) {
115522 out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
115523 $schemaValue = 'schema' + $lvl;
115524 } else {
115525 $schemaValue = $schema;
115526 }
115527
115528 var $rule = this,
115529 $definition = 'definition' + $lvl,
115530 $rDef = $rule.definition,
115531 $closingBraces = '';
115532 var $compile, $inline, $macro, $ruleValidate, $validateCode;
115533
115534 if ($isData && $rDef.$data) {
115535 $validateCode = 'keywordValidate' + $lvl;
115536 var $validateSchema = $rDef.validateSchema;
115537 out += ' var ' + $definition + ' = RULES.custom[\'' + $keyword + '\'].definition; var ' + $validateCode + ' = ' + $definition + '.validate;';
115538 } else {
115539 $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
115540 if (!$ruleValidate) return;
115541 $schemaValue = 'validate.schema' + $schemaPath;
115542 $validateCode = $ruleValidate.code;
115543 $compile = $rDef.compile;
115544 $inline = $rDef.inline;
115545 $macro = $rDef.macro;
115546 }
115547
115548 var $ruleErrs = $validateCode + '.errors',
115549 $i = 'i' + $lvl,
115550 $ruleErr = 'ruleErr' + $lvl,
115551 $asyncKeyword = $rDef.async;
115552 if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
115553
115554 if (!($inline || $macro)) {
115555 out += '' + $ruleErrs + ' = null;';
115556 }
115557
115558 out += 'var ' + $errs + ' = errors;var ' + $valid + ';';
115559
115560 if ($isData && $rDef.$data) {
115561 $closingBraces += '}';
115562 out += ' if (' + $schemaValue + ' === undefined) { ' + $valid + ' = true; } else { ';
115563
115564 if ($validateSchema) {
115565 $closingBraces += '}';
115566 out += ' ' + $valid + ' = ' + $definition + '.validateSchema(' + $schemaValue + '); if (' + $valid + ') { ';
115567 }
115568 }
115569
115570 if ($inline) {
115571 if ($rDef.statements) {
115572 out += ' ' + $ruleValidate.validate + ' ';
115573 } else {
115574 out += ' ' + $valid + ' = ' + $ruleValidate.validate + '; ';
115575 }
115576 } else if ($macro) {
115577 var $it = it.util.copy(it);
115578 var $closingBraces = '';
115579 $it.level++;
115580 var $nextValid = 'valid' + $it.level;
115581 $it.schema = $ruleValidate.validate;
115582 $it.schemaPath = '';
115583 var $wasComposite = it.compositeRule;
115584 it.compositeRule = $it.compositeRule = true;
115585 var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
115586 it.compositeRule = $it.compositeRule = $wasComposite;
115587 out += ' ' + $code;
115588 } else {
115589 var $$outStack = $$outStack || [];
115590 $$outStack.push(out);
115591 out = '';
115592 out += ' ' + $validateCode + '.call( ';
115593
115594 if (it.opts.passContext) {
115595 out += 'this';
115596 } else {
115597 out += 'self';
115598 }
115599
115600 if ($compile || $rDef.schema === false) {
115601 out += ' , ' + $data + ' ';
115602 } else {
115603 out += ' , ' + $schemaValue + ' , ' + $data + ' , validate.schema' + it.schemaPath + ' ';
115604 }
115605
115606 out += ' , (dataPath || \'\')';
115607
115608 if (it.errorPath != '""') {
115609 out += ' + ' + it.errorPath;
115610 }
115611
115612 var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData',
115613 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
115614 out += ' , ' + $parentData + ' , ' + $parentDataProperty + ' , rootData ) ';
115615 var def_callRuleValidate = out;
115616 out = $$outStack.pop();
115617
115618 if ($rDef.errors === false) {
115619 out += ' ' + $valid + ' = ';
115620
115621 if ($asyncKeyword) {
115622 out += 'await ';
115623 }
115624
115625 out += '' + def_callRuleValidate + '; ';
115626 } else {
115627 if ($asyncKeyword) {
115628 $ruleErrs = 'customErrors' + $lvl;
115629 out += ' var ' + $ruleErrs + ' = null; try { ' + $valid + ' = await ' + def_callRuleValidate + '; } catch (e) { ' + $valid + ' = false; if (e instanceof ValidationError) ' + $ruleErrs + ' = e.errors; else throw e; } ';
115630 } else {
115631 out += ' ' + $ruleErrs + ' = null; ' + $valid + ' = ' + def_callRuleValidate + '; ';
115632 }
115633 }
115634 }
115635
115636 if ($rDef.modifying) {
115637 out += ' if (' + $parentData + ') ' + $data + ' = ' + $parentData + '[' + $parentDataProperty + '];';
115638 }
115639
115640 out += '' + $closingBraces;
115641
115642 if ($rDef.valid) {
115643 if ($breakOnError) {
115644 out += ' if (true) { ';
115645 }
115646 } else {
115647 out += ' if ( ';
115648
115649 if ($rDef.valid === undefined) {
115650 out += ' !';
115651
115652 if ($macro) {
115653 out += '' + $nextValid;
115654 } else {
115655 out += '' + $valid;
115656 }
115657 } else {
115658 out += ' ' + !$rDef.valid + ' ';
115659 }
115660
115661 out += ') { ';
115662 $errorKeyword = $rule.keyword;
115663 var $$outStack = $$outStack || [];
115664 $$outStack.push(out);
115665 out = '';
115666 var $$outStack = $$outStack || [];
115667 $$outStack.push(out);
115668 out = '';
115669 /* istanbul ignore else */
115670
115671 if (it.createErrors !== false) {
115672 out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { keyword: \'' + $rule.keyword + '\' } ';
115673
115674 if (it.opts.messages !== false) {
115675 out += ' , message: \'should pass "' + $rule.keyword + '" keyword validation\' ';
115676 }
115677
115678 if (it.opts.verbose) {
115679 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
115680 }
115681
115682 out += ' } ';
115683 } else {
115684 out += ' {} ';
115685 }
115686
115687 var __err = out;
115688 out = $$outStack.pop();
115689
115690 if (!it.compositeRule && $breakOnError) {
115691 /* istanbul ignore if */
115692 if (it.async) {
115693 out += ' throw new ValidationError([' + __err + ']); ';
115694 } else {
115695 out += ' validate.errors = [' + __err + ']; return false; ';
115696 }
115697 } else {
115698 out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
115699 }
115700
115701 var def_customError = out;
115702 out = $$outStack.pop();
115703
115704 if ($inline) {
115705 if ($rDef.errors) {
115706 if ($rDef.errors != 'full') {
115707 out += ' for (var ' + $i + '=' + $errs + '; ' + $i + '<errors; ' + $i + '++) { var ' + $ruleErr + ' = vErrors[' + $i + ']; if (' + $ruleErr + '.dataPath === undefined) ' + $ruleErr + '.dataPath = (dataPath || \'\') + ' + it.errorPath + '; if (' + $ruleErr + '.schemaPath === undefined) { ' + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
115708
115709 if (it.opts.verbose) {
115710 out += ' ' + $ruleErr + '.schema = ' + $schemaValue + '; ' + $ruleErr + '.data = ' + $data + '; ';
115711 }
115712
115713 out += ' } ';
115714 }
115715 } else {
115716 if ($rDef.errors === false) {
115717 out += ' ' + def_customError + ' ';
115718 } else {
115719 out += ' if (' + $errs + ' == errors) { ' + def_customError + ' } else { for (var ' + $i + '=' + $errs + '; ' + $i + '<errors; ' + $i + '++) { var ' + $ruleErr + ' = vErrors[' + $i + ']; if (' + $ruleErr + '.dataPath === undefined) ' + $ruleErr + '.dataPath = (dataPath || \'\') + ' + it.errorPath + '; if (' + $ruleErr + '.schemaPath === undefined) { ' + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
115720
115721 if (it.opts.verbose) {
115722 out += ' ' + $ruleErr + '.schema = ' + $schemaValue + '; ' + $ruleErr + '.data = ' + $data + '; ';
115723 }
115724
115725 out += ' } } ';
115726 }
115727 }
115728 } else if ($macro) {
115729 out += ' var err = ';
115730 /* istanbul ignore else */
115731
115732 if (it.createErrors !== false) {
115733 out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { keyword: \'' + $rule.keyword + '\' } ';
115734
115735 if (it.opts.messages !== false) {
115736 out += ' , message: \'should pass "' + $rule.keyword + '" keyword validation\' ';
115737 }
115738
115739 if (it.opts.verbose) {
115740 out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
115741 }
115742
115743 out += ' } ';
115744 } else {
115745 out += ' {} ';
115746 }
115747
115748 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
115749
115750 if (!it.compositeRule && $breakOnError) {
115751 /* istanbul ignore if */
115752 if (it.async) {
115753 out += ' throw new ValidationError(vErrors); ';
115754 } else {
115755 out += ' validate.errors = vErrors; return false; ';
115756 }
115757 }
115758 } else {
115759 if ($rDef.errors === false) {
115760 out += ' ' + def_customError + ' ';
115761 } else {
115762 out += ' if (Array.isArray(' + $ruleErrs + ')) { if (vErrors === null) vErrors = ' + $ruleErrs + '; else vErrors = vErrors.concat(' + $ruleErrs + '); errors = vErrors.length; for (var ' + $i + '=' + $errs + '; ' + $i + '<errors; ' + $i + '++) { var ' + $ruleErr + ' = vErrors[' + $i + ']; if (' + $ruleErr + '.dataPath === undefined) ' + $ruleErr + '.dataPath = (dataPath || \'\') + ' + it.errorPath + '; ' + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; ';
115763
115764 if (it.opts.verbose) {
115765 out += ' ' + $ruleErr + '.schema = ' + $schemaValue + '; ' + $ruleErr + '.data = ' + $data + '; ';
115766 }
115767
115768 out += ' } } else { ' + def_customError + ' } ';
115769 }
115770 }
115771
115772 out += ' } ';
115773
115774 if ($breakOnError) {
115775 out += ' else { ';
115776 }
115777 }
115778
115779 return out;
115780};
115781
115782/***/ }),
6a5a0f88 115783/* 772 */
eb39fafa
DC
115784/***/ (function(module, exports, __webpack_require__) {
115785
115786"use strict";
115787
115788
6a5a0f88 115789var metaSchema = __webpack_require__(773);
eb39fafa
DC
115790
115791module.exports = {
115792 $id: 'https://github.com/epoberezkin/ajv/blob/master/lib/definition_schema.js',
115793 definitions: {
115794 simpleTypes: metaSchema.definitions.simpleTypes
115795 },
115796 type: 'object',
115797 dependencies: {
115798 schema: ['validate'],
115799 $data: ['validate'],
115800 statements: ['inline'],
115801 valid: {
115802 not: {
115803 required: ['macro']
115804 }
115805 }
115806 },
115807 properties: {
115808 type: metaSchema.properties.type,
115809 schema: {
115810 type: 'boolean'
115811 },
115812 statements: {
115813 type: 'boolean'
115814 },
115815 dependencies: {
115816 type: 'array',
115817 items: {
115818 type: 'string'
115819 }
115820 },
115821 metaSchema: {
115822 type: 'object'
115823 },
115824 modifying: {
115825 type: 'boolean'
115826 },
115827 valid: {
115828 type: 'boolean'
115829 },
115830 $data: {
115831 type: 'boolean'
115832 },
115833 async: {
115834 type: 'boolean'
115835 },
115836 errors: {
115837 anyOf: [{
115838 type: 'boolean'
115839 }, {
115840 const: 'full'
115841 }]
115842 }
115843 }
115844};
115845
115846/***/ }),
6a5a0f88 115847/* 773 */
eb39fafa
DC
115848/***/ (function(module) {
115849
115850module.exports = JSON.parse("{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"$id\":\"http://json-schema.org/draft-07/schema#\",\"title\":\"Core schema meta-schema\",\"definitions\":{\"schemaArray\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"$ref\":\"#\"}},\"nonNegativeInteger\":{\"type\":\"integer\",\"minimum\":0},\"nonNegativeIntegerDefault0\":{\"allOf\":[{\"$ref\":\"#/definitions/nonNegativeInteger\"},{\"default\":0}]},\"simpleTypes\":{\"enum\":[\"array\",\"boolean\",\"integer\",\"null\",\"number\",\"object\",\"string\"]},\"stringArray\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"uniqueItems\":true,\"default\":[]}},\"type\":[\"object\",\"boolean\"],\"properties\":{\"$id\":{\"type\":\"string\",\"format\":\"uri-reference\"},\"$schema\":{\"type\":\"string\",\"format\":\"uri\"},\"$ref\":{\"type\":\"string\",\"format\":\"uri-reference\"},\"$comment\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"default\":true,\"readOnly\":{\"type\":\"boolean\",\"default\":false},\"examples\":{\"type\":\"array\",\"items\":true},\"multipleOf\":{\"type\":\"number\",\"exclusiveMinimum\":0},\"maximum\":{\"type\":\"number\"},\"exclusiveMaximum\":{\"type\":\"number\"},\"minimum\":{\"type\":\"number\"},\"exclusiveMinimum\":{\"type\":\"number\"},\"maxLength\":{\"$ref\":\"#/definitions/nonNegativeInteger\"},\"minLength\":{\"$ref\":\"#/definitions/nonNegativeIntegerDefault0\"},\"pattern\":{\"type\":\"string\",\"format\":\"regex\"},\"additionalItems\":{\"$ref\":\"#\"},\"items\":{\"anyOf\":[{\"$ref\":\"#\"},{\"$ref\":\"#/definitions/schemaArray\"}],\"default\":true},\"maxItems\":{\"$ref\":\"#/definitions/nonNegativeInteger\"},\"minItems\":{\"$ref\":\"#/definitions/nonNegativeIntegerDefault0\"},\"uniqueItems\":{\"type\":\"boolean\",\"default\":false},\"contains\":{\"$ref\":\"#\"},\"maxProperties\":{\"$ref\":\"#/definitions/nonNegativeInteger\"},\"minProperties\":{\"$ref\":\"#/definitions/nonNegativeIntegerDefault0\"},\"required\":{\"$ref\":\"#/definitions/stringArray\"},\"additionalProperties\":{\"$ref\":\"#\"},\"definitions\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"properties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"patternProperties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"propertyNames\":{\"format\":\"regex\"},\"default\":{}},\"dependencies\":{\"type\":\"object\",\"additionalProperties\":{\"anyOf\":[{\"$ref\":\"#\"},{\"$ref\":\"#/definitions/stringArray\"}]}},\"propertyNames\":{\"$ref\":\"#\"},\"const\":true,\"enum\":{\"type\":\"array\",\"items\":true,\"minItems\":1,\"uniqueItems\":true},\"type\":{\"anyOf\":[{\"$ref\":\"#/definitions/simpleTypes\"},{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/simpleTypes\"},\"minItems\":1,\"uniqueItems\":true}]},\"format\":{\"type\":\"string\"},\"contentMediaType\":{\"type\":\"string\"},\"contentEncoding\":{\"type\":\"string\"},\"if\":{\"$ref\":\"#\"},\"then\":{\"$ref\":\"#\"},\"else\":{\"$ref\":\"#\"},\"allOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"anyOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"oneOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"not\":{\"$ref\":\"#\"}},\"default\":true}");
115851
115852/***/ }),
6a5a0f88 115853/* 774 */
eb39fafa
DC
115854/***/ (function(module) {
115855
115856module.exports = JSON.parse("{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"$id\":\"https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#\",\"description\":\"Meta-schema for $data reference (JSON Schema extension proposal)\",\"type\":\"object\",\"required\":[\"$data\"],\"properties\":{\"$data\":{\"type\":\"string\",\"anyOf\":[{\"format\":\"relative-json-pointer\"},{\"format\":\"json-pointer\"}]}},\"additionalProperties\":false}");
115857
115858/***/ }),
6a5a0f88 115859/* 775 */
eb39fafa
DC
115860/***/ (function(module) {
115861
115862module.exports = JSON.parse("{\"id\":\"http://json-schema.org/draft-04/schema#\",\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"description\":\"Core schema meta-schema\",\"definitions\":{\"schemaArray\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"$ref\":\"#\"}},\"positiveInteger\":{\"type\":\"integer\",\"minimum\":0},\"positiveIntegerDefault0\":{\"allOf\":[{\"$ref\":\"#/definitions/positiveInteger\"},{\"default\":0}]},\"simpleTypes\":{\"enum\":[\"array\",\"boolean\",\"integer\",\"null\",\"number\",\"object\",\"string\"]},\"stringArray\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"minItems\":1,\"uniqueItems\":true}},\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"$schema\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"default\":{},\"multipleOf\":{\"type\":\"number\",\"minimum\":0,\"exclusiveMinimum\":true},\"maximum\":{\"type\":\"number\"},\"exclusiveMaximum\":{\"type\":\"boolean\",\"default\":false},\"minimum\":{\"type\":\"number\"},\"exclusiveMinimum\":{\"type\":\"boolean\",\"default\":false},\"maxLength\":{\"$ref\":\"#/definitions/positiveInteger\"},\"minLength\":{\"$ref\":\"#/definitions/positiveIntegerDefault0\"},\"pattern\":{\"type\":\"string\",\"format\":\"regex\"},\"additionalItems\":{\"anyOf\":[{\"type\":\"boolean\"},{\"$ref\":\"#\"}],\"default\":{}},\"items\":{\"anyOf\":[{\"$ref\":\"#\"},{\"$ref\":\"#/definitions/schemaArray\"}],\"default\":{}},\"maxItems\":{\"$ref\":\"#/definitions/positiveInteger\"},\"minItems\":{\"$ref\":\"#/definitions/positiveIntegerDefault0\"},\"uniqueItems\":{\"type\":\"boolean\",\"default\":false},\"maxProperties\":{\"$ref\":\"#/definitions/positiveInteger\"},\"minProperties\":{\"$ref\":\"#/definitions/positiveIntegerDefault0\"},\"required\":{\"$ref\":\"#/definitions/stringArray\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"boolean\"},{\"$ref\":\"#\"}],\"default\":{}},\"definitions\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"properties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"patternProperties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#\"},\"default\":{}},\"dependencies\":{\"type\":\"object\",\"additionalProperties\":{\"anyOf\":[{\"$ref\":\"#\"},{\"$ref\":\"#/definitions/stringArray\"}]}},\"enum\":{\"type\":\"array\",\"minItems\":1,\"uniqueItems\":true},\"type\":{\"anyOf\":[{\"$ref\":\"#/definitions/simpleTypes\"},{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/simpleTypes\"},\"minItems\":1,\"uniqueItems\":true}]},\"format\":{\"type\":\"string\"},\"allOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"anyOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"oneOf\":{\"$ref\":\"#/definitions/schemaArray\"},\"not\":{\"$ref\":\"#\"}},\"dependencies\":{\"exclusiveMaximum\":[\"maximum\"],\"exclusiveMinimum\":[\"minimum\"]},\"default\":{}}");
115863
115864/***/ }),
6a5a0f88 115865/* 776 */
eb39fafa
DC
115866/***/ (function(module, exports, __webpack_require__) {
115867
115868"use strict";
115869
115870
115871module.exports = {
6a5a0f88 115872 SourceCode: __webpack_require__(777)
eb39fafa
DC
115873};
115874
115875/***/ }),
6a5a0f88 115876/* 777 */
eb39fafa
DC
115877/***/ (function(module, exports, __webpack_require__) {
115878
115879"use strict";
115880/**
115881 * @fileoverview Abstraction of JavaScript source code.
115882 * @author Nicholas C. Zakas
115883 */
115884 //------------------------------------------------------------------------------
115885// Requirements
115886//------------------------------------------------------------------------------
115887
115888const {
115889 isCommentToken
115890} = __webpack_require__(549),
6a5a0f88 115891 TokenStore = __webpack_require__(778),
eb39fafa 115892 astUtils = __webpack_require__(409),
6a5a0f88 115893 Traverser = __webpack_require__(640),
eb39fafa
DC
115894 lodash = __webpack_require__(403); //------------------------------------------------------------------------------
115895// Private
115896//------------------------------------------------------------------------------
115897
115898/**
115899 * Validates that the given AST has the required information.
115900 * @param {ASTNode} ast The Program node of the AST to check.
115901 * @throws {Error} If the AST doesn't contain the correct information.
115902 * @returns {void}
115903 * @private
115904 */
115905
115906
115907function validate(ast) {
115908 if (!ast.tokens) {
115909 throw new Error("AST is missing the tokens array.");
115910 }
115911
115912 if (!ast.comments) {
115913 throw new Error("AST is missing the comments array.");
115914 }
115915
115916 if (!ast.loc) {
115917 throw new Error("AST is missing location information.");
115918 }
115919
115920 if (!ast.range) {
115921 throw new Error("AST is missing range information");
115922 }
115923}
115924/**
115925 * Check to see if its a ES6 export declaration.
115926 * @param {ASTNode} astNode An AST node.
115927 * @returns {boolean} whether the given node represents an export declaration.
115928 * @private
115929 */
115930
115931
115932function looksLikeExport(astNode) {
115933 return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
115934}
115935/**
115936 * Merges two sorted lists into a larger sorted list in O(n) time.
115937 * @param {Token[]} tokens The list of tokens.
115938 * @param {Token[]} comments The list of comments.
115939 * @returns {Token[]} A sorted list of tokens and comments.
115940 * @private
115941 */
115942
115943
115944function sortedMerge(tokens, comments) {
115945 const result = [];
115946 let tokenIndex = 0;
115947 let commentIndex = 0;
115948
115949 while (tokenIndex < tokens.length || commentIndex < comments.length) {
115950 if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) {
115951 result.push(tokens[tokenIndex++]);
115952 } else {
115953 result.push(comments[commentIndex++]);
115954 }
115955 }
115956
115957 return result;
115958}
115959/**
115960 * Determines if two nodes or tokens overlap.
115961 * @param {ASTNode|Token} first The first node or token to check.
115962 * @param {ASTNode|Token} second The second node or token to check.
115963 * @returns {boolean} True if the two nodes or tokens overlap.
115964 * @private
115965 */
115966
115967
115968function nodesOrTokensOverlap(first, second) {
115969 return first.range[0] <= second.range[0] && first.range[1] >= second.range[0] || second.range[0] <= first.range[0] && second.range[1] >= first.range[0];
115970}
115971/**
115972 * Determines if two nodes or tokens have at least one whitespace character
115973 * between them. Order does not matter. Returns false if the given nodes or
115974 * tokens overlap.
115975 * @param {SourceCode} sourceCode The source code object.
115976 * @param {ASTNode|Token} first The first node or token to check between.
115977 * @param {ASTNode|Token} second The second node or token to check between.
115978 * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility.
115979 * @returns {boolean} True if there is a whitespace character between
115980 * any of the tokens found between the two given nodes or tokens.
115981 * @public
115982 */
115983
115984
115985function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) {
115986 if (nodesOrTokensOverlap(first, second)) {
115987 return false;
115988 }
115989
115990 const [startingNodeOrToken, endingNodeOrToken] = first.range[1] <= second.range[0] ? [first, second] : [second, first];
115991 const firstToken = sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken;
115992 const finalToken = sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken;
115993 let currentToken = firstToken;
115994
115995 while (currentToken !== finalToken) {
115996 const nextToken = sourceCode.getTokenAfter(currentToken, {
115997 includeComments: true
115998 });
115999
116000 if (currentToken.range[1] !== nextToken.range[0] ||
116001 /*
116002 * For backward compatibility, check spaces in JSXText.
116003 * https://github.com/eslint/eslint/issues/12614
116004 */
116005 checkInsideOfJSXText && nextToken !== finalToken && nextToken.type === "JSXText" && /\s/u.test(nextToken.value)) {
116006 return true;
116007 }
116008
116009 currentToken = nextToken;
116010 }
116011
116012 return false;
116013} //------------------------------------------------------------------------------
116014// Public Interface
116015//------------------------------------------------------------------------------
116016
116017
116018class SourceCode extends TokenStore {
116019 /**
116020 * Represents parsed source code.
116021 * @param {string|Object} textOrConfig The source code text or config object.
116022 * @param {string} textOrConfig.text The source code text.
116023 * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
116024 * @param {Object|null} textOrConfig.parserServices The parser services.
116025 * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code.
116026 * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST.
116027 * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
116028 */
116029 constructor(textOrConfig, astIfNoConfig) {
116030 let text, ast, parserServices, scopeManager, visitorKeys; // Process overloading.
116031
116032 if (typeof textOrConfig === "string") {
116033 text = textOrConfig;
116034 ast = astIfNoConfig;
116035 } else if (typeof textOrConfig === "object" && textOrConfig !== null) {
116036 text = textOrConfig.text;
116037 ast = textOrConfig.ast;
116038 parserServices = textOrConfig.parserServices;
116039 scopeManager = textOrConfig.scopeManager;
116040 visitorKeys = textOrConfig.visitorKeys;
116041 }
116042
116043 validate(ast);
116044 super(ast.tokens, ast.comments);
116045 /**
116046 * The flag to indicate that the source code has Unicode BOM.
116047 * @type boolean
116048 */
116049
116050 this.hasBOM = text.charCodeAt(0) === 0xFEFF;
116051 /**
116052 * The original text source code.
116053 * BOM was stripped from this text.
116054 * @type string
116055 */
116056
116057 this.text = this.hasBOM ? text.slice(1) : text;
116058 /**
116059 * The parsed AST for the source code.
116060 * @type ASTNode
116061 */
116062
116063 this.ast = ast;
116064 /**
116065 * The parser services of this source code.
116066 * @type {Object}
116067 */
116068
116069 this.parserServices = parserServices || {};
116070 /**
116071 * The scope of this source code.
116072 * @type {ScopeManager|null}
116073 */
116074
116075 this.scopeManager = scopeManager || null;
116076 /**
116077 * The visitor keys to traverse AST.
116078 * @type {Object}
116079 */
116080
116081 this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; // Check the source text for the presence of a shebang since it is parsed as a standard line comment.
116082
116083 const shebangMatched = this.text.match(astUtils.shebangPattern);
116084 const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1];
116085
116086 if (hasShebang) {
116087 ast.comments[0].type = "Shebang";
116088 }
116089
116090 this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
116091 /**
116092 * The source code split into lines according to ECMA-262 specification.
116093 * This is done to avoid each rule needing to do so separately.
116094 * @type string[]
116095 */
116096
116097 this.lines = [];
116098 this.lineStartIndices = [0];
116099 const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
116100 let match;
116101 /*
116102 * Previously, this was implemented using a regex that
116103 * matched a sequence of non-linebreak characters followed by a
116104 * linebreak, then adding the lengths of the matches. However,
116105 * this caused a catastrophic backtracking issue when the end
116106 * of a file contained a large number of non-newline characters.
116107 * To avoid this, the current implementation just matches newlines
116108 * and uses match.index to get the correct line start indices.
116109 */
116110
116111 while (match = lineEndingPattern.exec(this.text)) {
116112 this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index));
116113 this.lineStartIndices.push(match.index + match[0].length);
116114 }
116115
116116 this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1])); // Cache for comments found using getComments().
116117
116118 this._commentCache = new WeakMap(); // don't allow modification of this object
116119
116120 Object.freeze(this);
116121 Object.freeze(this.lines);
116122 }
116123 /**
116124 * Split the source code into multiple lines based on the line delimiters.
116125 * @param {string} text Source code as a string.
116126 * @returns {string[]} Array of source code lines.
116127 * @public
116128 */
116129
116130
116131 static splitLines(text) {
116132 return text.split(astUtils.createGlobalLinebreakMatcher());
116133 }
116134 /**
116135 * Gets the source code for the given node.
116136 * @param {ASTNode} [node] The AST node to get the text for.
116137 * @param {int} [beforeCount] The number of characters before the node to retrieve.
116138 * @param {int} [afterCount] The number of characters after the node to retrieve.
116139 * @returns {string} The text representing the AST node.
116140 * @public
116141 */
116142
116143
116144 getText(node, beforeCount, afterCount) {
116145 if (node) {
116146 return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0), node.range[1] + (afterCount || 0));
116147 }
116148
116149 return this.text;
116150 }
116151 /**
116152 * Gets the entire source text split into an array of lines.
116153 * @returns {Array} The source text as an array of lines.
116154 * @public
116155 */
116156
116157
116158 getLines() {
116159 return this.lines;
116160 }
116161 /**
116162 * Retrieves an array containing all comments in the source code.
116163 * @returns {ASTNode[]} An array of comment nodes.
116164 * @public
116165 */
116166
116167
116168 getAllComments() {
116169 return this.ast.comments;
116170 }
116171 /**
116172 * Gets all comments for the given node.
116173 * @param {ASTNode} node The AST node to get the comments for.
116174 * @returns {Object} An object containing a leading and trailing array
116175 * of comments indexed by their position.
116176 * @public
6a5a0f88 116177 * @deprecated replaced by getCommentsBefore(), getCommentsAfter(), and getCommentsInside().
eb39fafa
DC
116178 */
116179
116180
116181 getComments(node) {
116182 if (this._commentCache.has(node)) {
116183 return this._commentCache.get(node);
116184 }
116185
116186 const comments = {
116187 leading: [],
116188 trailing: []
116189 };
116190 /*
116191 * Return all comments as leading comments of the Program node when
116192 * there is no executable code.
116193 */
116194
116195 if (node.type === "Program") {
116196 if (node.body.length === 0) {
116197 comments.leading = node.comments;
116198 }
116199 } else {
116200 /*
116201 * Return comments as trailing comments of nodes that only contain
116202 * comments (to mimic the comment attachment behavior present in Espree).
116203 */
116204 if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 || node.type === "ObjectExpression" && node.properties.length === 0 || node.type === "ArrayExpression" && node.elements.length === 0 || node.type === "SwitchStatement" && node.cases.length === 0) {
116205 comments.trailing = this.getTokens(node, {
116206 includeComments: true,
116207 filter: isCommentToken
116208 });
116209 }
116210 /*
116211 * Iterate over tokens before and after node and collect comment tokens.
116212 * Do not include comments that exist outside of the parent node
116213 * to avoid duplication.
116214 */
116215
116216
116217 let currentToken = this.getTokenBefore(node, {
116218 includeComments: true
116219 });
116220
116221 while (currentToken && isCommentToken(currentToken)) {
116222 if (node.parent && currentToken.start < node.parent.start) {
116223 break;
116224 }
116225
116226 comments.leading.push(currentToken);
116227 currentToken = this.getTokenBefore(currentToken, {
116228 includeComments: true
116229 });
116230 }
116231
116232 comments.leading.reverse();
116233 currentToken = this.getTokenAfter(node, {
116234 includeComments: true
116235 });
116236
116237 while (currentToken && isCommentToken(currentToken)) {
116238 if (node.parent && currentToken.end > node.parent.end) {
116239 break;
116240 }
116241
116242 comments.trailing.push(currentToken);
116243 currentToken = this.getTokenAfter(currentToken, {
116244 includeComments: true
116245 });
116246 }
116247 }
116248
116249 this._commentCache.set(node, comments);
116250
116251 return comments;
116252 }
116253 /**
116254 * Retrieves the JSDoc comment for a given node.
116255 * @param {ASTNode} node The AST node to get the comment for.
116256 * @returns {Token|null} The Block comment token containing the JSDoc comment
116257 * for the given node or null if not found.
116258 * @public
116259 * @deprecated
116260 */
116261
116262
116263 getJSDocComment(node) {
116264 /**
116265 * Checks for the presence of a JSDoc comment for the given node and returns it.
116266 * @param {ASTNode} astNode The AST node to get the comment for.
116267 * @returns {Token|null} The Block comment token containing the JSDoc comment
116268 * for the given node or null if not found.
116269 * @private
116270 */
116271 const findJSDocComment = astNode => {
116272 const tokenBefore = this.getTokenBefore(astNode, {
116273 includeComments: true
116274 });
116275
116276 if (tokenBefore && isCommentToken(tokenBefore) && tokenBefore.type === "Block" && tokenBefore.value.charAt(0) === "*" && astNode.loc.start.line - tokenBefore.loc.end.line <= 1) {
116277 return tokenBefore;
116278 }
116279
116280 return null;
116281 };
116282
116283 let parent = node.parent;
116284
116285 switch (node.type) {
116286 case "ClassDeclaration":
116287 case "FunctionDeclaration":
116288 return findJSDocComment(looksLikeExport(parent) ? parent : node);
116289
116290 case "ClassExpression":
116291 return findJSDocComment(parent.parent);
116292
116293 case "ArrowFunctionExpression":
116294 case "FunctionExpression":
116295 if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
116296 while (!this.getCommentsBefore(parent).length && !/Function/u.test(parent.type) && parent.type !== "MethodDefinition" && parent.type !== "Property") {
116297 parent = parent.parent;
116298
116299 if (!parent) {
116300 break;
116301 }
116302 }
116303
116304 if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") {
116305 return findJSDocComment(parent);
116306 }
116307 }
116308
116309 return findJSDocComment(node);
116310 // falls through
116311
116312 default:
116313 return null;
116314 }
116315 }
116316 /**
116317 * Gets the deepest node containing a range index.
116318 * @param {int} index Range index of the desired node.
116319 * @returns {ASTNode} The node if found or null if not found.
116320 * @public
116321 */
116322
116323
116324 getNodeByRangeIndex(index) {
116325 let result = null;
116326 Traverser.traverse(this.ast, {
116327 visitorKeys: this.visitorKeys,
116328
116329 enter(node) {
116330 if (node.range[0] <= index && index < node.range[1]) {
116331 result = node;
116332 } else {
116333 this.skip();
116334 }
116335 },
116336
116337 leave(node) {
116338 if (node === result) {
116339 this.break();
116340 }
116341 }
116342
116343 });
116344 return result;
116345 }
116346 /**
116347 * Determines if two nodes or tokens have at least one whitespace character
116348 * between them. Order does not matter. Returns false if the given nodes or
116349 * tokens overlap.
116350 * @param {ASTNode|Token} first The first node or token to check between.
116351 * @param {ASTNode|Token} second The second node or token to check between.
116352 * @returns {boolean} True if there is a whitespace character between
116353 * any of the tokens found between the two given nodes or tokens.
116354 * @public
116355 */
116356
116357
116358 isSpaceBetween(first, second) {
116359 return isSpaceBetween(this, first, second, false);
116360 }
116361 /**
116362 * Determines if two nodes or tokens have at least one whitespace character
116363 * between them. Order does not matter. Returns false if the given nodes or
116364 * tokens overlap.
116365 * For backward compatibility, this method returns true if there are
116366 * `JSXText` tokens that contain whitespaces between the two.
116367 * @param {ASTNode|Token} first The first node or token to check between.
116368 * @param {ASTNode|Token} second The second node or token to check between.
116369 * @returns {boolean} True if there is a whitespace character between
116370 * any of the tokens found between the two given nodes or tokens.
116371 * @deprecated in favor of isSpaceBetween().
116372 * @public
116373 */
116374
116375
116376 isSpaceBetweenTokens(first, second) {
116377 return isSpaceBetween(this, first, second, true);
116378 }
116379 /**
116380 * Converts a source text index into a (line, column) pair.
116381 * @param {number} index The index of a character in a file
116382 * @returns {Object} A {line, column} location object with a 0-indexed column
116383 * @public
116384 */
116385
116386
116387 getLocFromIndex(index) {
116388 if (typeof index !== "number") {
116389 throw new TypeError("Expected `index` to be a number.");
116390 }
116391
116392 if (index < 0 || index > this.text.length) {
116393 throw new RangeError("Index out of range (requested index ".concat(index, ", but source text has length ").concat(this.text.length, ")."));
116394 }
116395 /*
116396 * For an argument of this.text.length, return the location one "spot" past the last character
116397 * of the file. If the last character is a linebreak, the location will be column 0 of the next
116398 * line; otherwise, the location will be in the next column on the same line.
116399 *
116400 * See getIndexFromLoc for the motivation for this special case.
116401 */
116402
116403
116404 if (index === this.text.length) {
116405 return {
116406 line: this.lines.length,
116407 column: this.lines[this.lines.length - 1].length
116408 };
116409 }
116410 /*
116411 * To figure out which line rangeIndex is on, determine the last index at which rangeIndex could
116412 * be inserted into lineIndices to keep the list sorted.
116413 */
116414
116415
116416 const lineNumber = lodash.sortedLastIndex(this.lineStartIndices, index);
116417 return {
116418 line: lineNumber,
116419 column: index - this.lineStartIndices[lineNumber - 1]
116420 };
116421 }
116422 /**
116423 * Converts a (line, column) pair into a range index.
116424 * @param {Object} loc A line/column location
116425 * @param {number} loc.line The line number of the location (1-indexed)
116426 * @param {number} loc.column The column number of the location (0-indexed)
116427 * @returns {number} The range index of the location in the file.
116428 * @public
116429 */
116430
116431
116432 getIndexFromLoc(loc) {
116433 if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") {
116434 throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties.");
116435 }
116436
116437 if (loc.line <= 0) {
116438 throw new RangeError("Line number out of range (line ".concat(loc.line, " requested). Line numbers should be 1-based."));
116439 }
116440
116441 if (loc.line > this.lineStartIndices.length) {
116442 throw new RangeError("Line number out of range (line ".concat(loc.line, " requested, but only ").concat(this.lineStartIndices.length, " lines present)."));
116443 }
116444
116445 const lineStartIndex = this.lineStartIndices[loc.line - 1];
116446 const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line];
116447 const positionIndex = lineStartIndex + loc.column;
116448 /*
116449 * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of
116450 * the given line, provided that the line number is valid element of this.lines. Since the
116451 * last element of this.lines is an empty string for files with trailing newlines, add a
116452 * special case where getting the index for the first location after the end of the file
116453 * will return the length of the file, rather than throwing an error. This allows rules to
116454 * use getIndexFromLoc consistently without worrying about edge cases at the end of a file.
116455 */
116456
116457 if (loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex || loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex) {
116458 throw new RangeError("Column number out of range (column ".concat(loc.column, " requested, but the length of line ").concat(loc.line, " is ").concat(lineEndIndex - lineStartIndex, ")."));
116459 }
116460
116461 return positionIndex;
116462 }
116463
116464}
116465
116466module.exports = SourceCode;
116467
116468/***/ }),
6a5a0f88 116469/* 778 */
eb39fafa
DC
116470/***/ (function(module, exports, __webpack_require__) {
116471
116472"use strict";
116473/**
116474 * @fileoverview Object to handle access and retrieval of tokens.
116475 * @author Brandon Mills
116476 */
116477 //------------------------------------------------------------------------------
116478// Requirements
116479//------------------------------------------------------------------------------
116480
116481const assert = __webpack_require__(379);
116482
116483const {
116484 isCommentToken
116485} = __webpack_require__(549);
116486
6a5a0f88 116487const cursors = __webpack_require__(779);
eb39fafa 116488
6a5a0f88 116489const ForwardTokenCursor = __webpack_require__(787);
eb39fafa 116490
6a5a0f88 116491const PaddedTokenCursor = __webpack_require__(790);
eb39fafa 116492
6a5a0f88 116493const utils = __webpack_require__(782); //------------------------------------------------------------------------------
eb39fafa
DC
116494// Helpers
116495//------------------------------------------------------------------------------
116496
116497
116498const TOKENS = Symbol("tokens");
116499const COMMENTS = Symbol("comments");
116500const INDEX_MAP = Symbol("indexMap");
116501/**
116502 * Creates the map from locations to indices in `tokens`.
116503 *
116504 * The first/last location of tokens is mapped to the index of the token.
116505 * The first/last location of comments is mapped to the index of the next token of each comment.
116506 * @param {Token[]} tokens The array of tokens.
116507 * @param {Comment[]} comments The array of comments.
116508 * @returns {Object} The map from locations to indices in `tokens`.
116509 * @private
116510 */
116511
116512function createIndexMap(tokens, comments) {
116513 const map = Object.create(null);
116514 let tokenIndex = 0;
116515 let commentIndex = 0;
116516 let nextStart = 0;
116517 let range = null;
116518
116519 while (tokenIndex < tokens.length || commentIndex < comments.length) {
116520 nextStart = commentIndex < comments.length ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER;
116521
116522 while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) {
116523 map[range[0]] = tokenIndex;
116524 map[range[1] - 1] = tokenIndex;
116525 tokenIndex += 1;
116526 }
116527
116528 nextStart = tokenIndex < tokens.length ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER;
116529
116530 while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) {
116531 map[range[0]] = tokenIndex;
116532 map[range[1] - 1] = tokenIndex;
116533 commentIndex += 1;
116534 }
116535 }
116536
116537 return map;
116538}
116539/**
116540 * Creates the cursor iterates tokens with options.
116541 * @param {CursorFactory} factory The cursor factory to initialize cursor.
116542 * @param {Token[]} tokens The array of tokens.
116543 * @param {Comment[]} comments The array of comments.
116544 * @param {Object} indexMap The map from locations to indices in `tokens`.
116545 * @param {number} startLoc The start location of the iteration range.
116546 * @param {number} endLoc The end location of the iteration range.
116547 * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`.
116548 * @param {boolean} [opts.includeComments=false] The flag to iterate comments as well.
116549 * @param {Function|null} [opts.filter=null] The predicate function to choose tokens.
116550 * @param {number} [opts.skip=0] The count of tokens the cursor skips.
116551 * @returns {Cursor} The created cursor.
116552 * @private
116553 */
116554
116555
116556function createCursorWithSkip(factory, tokens, comments, indexMap, startLoc, endLoc, opts) {
116557 let includeComments = false;
116558 let skip = 0;
116559 let filter = null;
116560
116561 if (typeof opts === "number") {
116562 skip = opts | 0;
116563 } else if (typeof opts === "function") {
116564 filter = opts;
116565 } else if (opts) {
116566 includeComments = !!opts.includeComments;
116567 skip = opts.skip | 0;
116568 filter = opts.filter || null;
116569 }
116570
116571 assert(skip >= 0, "options.skip should be zero or a positive integer.");
116572 assert(!filter || typeof filter === "function", "options.filter should be a function.");
116573 return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, -1);
116574}
116575/**
116576 * Creates the cursor iterates tokens with options.
116577 * @param {CursorFactory} factory The cursor factory to initialize cursor.
116578 * @param {Token[]} tokens The array of tokens.
116579 * @param {Comment[]} comments The array of comments.
116580 * @param {Object} indexMap The map from locations to indices in `tokens`.
116581 * @param {number} startLoc The start location of the iteration range.
116582 * @param {number} endLoc The end location of the iteration range.
116583 * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`.
116584 * @param {boolean} [opts.includeComments] The flag to iterate comments as well.
116585 * @param {Function|null} [opts.filter=null] The predicate function to choose tokens.
116586 * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
116587 * @returns {Cursor} The created cursor.
116588 * @private
116589 */
116590
116591
116592function createCursorWithCount(factory, tokens, comments, indexMap, startLoc, endLoc, opts) {
116593 let includeComments = false;
116594 let count = 0;
116595 let countExists = false;
116596 let filter = null;
116597
116598 if (typeof opts === "number") {
116599 count = opts | 0;
116600 countExists = true;
116601 } else if (typeof opts === "function") {
116602 filter = opts;
116603 } else if (opts) {
116604 includeComments = !!opts.includeComments;
116605 count = opts.count | 0;
116606 countExists = typeof opts.count === "number";
116607 filter = opts.filter || null;
116608 }
116609
116610 assert(count >= 0, "options.count should be zero or a positive integer.");
116611 assert(!filter || typeof filter === "function", "options.filter should be a function.");
116612 return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, 0, countExists ? count : -1);
116613}
116614/**
116615 * Creates the cursor iterates tokens with options.
116616 * This is overload function of the below.
116617 * @param {Token[]} tokens The array of tokens.
116618 * @param {Comment[]} comments The array of comments.
116619 * @param {Object} indexMap The map from locations to indices in `tokens`.
116620 * @param {number} startLoc The start location of the iteration range.
116621 * @param {number} endLoc The end location of the iteration range.
116622 * @param {Function|Object} opts The option object. If this is a function then it's `opts.filter`.
116623 * @param {boolean} [opts.includeComments] The flag to iterate comments as well.
116624 * @param {Function|null} [opts.filter=null] The predicate function to choose tokens.
116625 * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
116626 * @returns {Cursor} The created cursor.
116627 * @private
116628 */
116629
116630/**
116631 * Creates the cursor iterates tokens with options.
116632 * @param {Token[]} tokens The array of tokens.
116633 * @param {Comment[]} comments The array of comments.
116634 * @param {Object} indexMap The map from locations to indices in `tokens`.
116635 * @param {number} startLoc The start location of the iteration range.
116636 * @param {number} endLoc The end location of the iteration range.
116637 * @param {number} [beforeCount=0] The number of tokens before the node to retrieve.
116638 * @param {boolean} [afterCount=0] The number of tokens after the node to retrieve.
116639 * @returns {Cursor} The created cursor.
116640 * @private
116641 */
116642
116643
116644function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) {
116645 if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") {
116646 return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc);
116647 }
116648
116649 if (typeof beforeCount === "number" || typeof beforeCount === "undefined") {
116650 return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount | 0, afterCount | 0);
116651 }
116652
116653 return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount);
116654}
116655/**
116656 * Gets comment tokens that are adjacent to the current cursor position.
116657 * @param {Cursor} cursor A cursor instance.
116658 * @returns {Array} An array of comment tokens adjacent to the current cursor position.
116659 * @private
116660 */
116661
116662
116663function getAdjacentCommentTokensFromCursor(cursor) {
116664 const tokens = [];
116665 let currentToken = cursor.getOneToken();
116666
116667 while (currentToken && isCommentToken(currentToken)) {
116668 tokens.push(currentToken);
116669 currentToken = cursor.getOneToken();
116670 }
116671
116672 return tokens;
116673} //------------------------------------------------------------------------------
116674// Exports
116675//------------------------------------------------------------------------------
116676
116677/**
116678 * The token store.
116679 *
116680 * This class provides methods to get tokens by locations as fast as possible.
116681 * The methods are a part of public API, so we should be careful if it changes this class.
116682 *
116683 * People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens.
116684 * Also people can get a mix of tokens and comments in O(log k), the k is the number of comments.
116685 * Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost.
116686 * This uses binary-searching instead for comments.
116687 */
116688
116689
116690module.exports = class TokenStore {
116691 /**
116692 * Initializes this token store.
116693 * @param {Token[]} tokens The array of tokens.
116694 * @param {Comment[]} comments The array of comments.
116695 */
116696 constructor(tokens, comments) {
116697 this[TOKENS] = tokens;
116698 this[COMMENTS] = comments;
116699 this[INDEX_MAP] = createIndexMap(tokens, comments);
116700 } //--------------------------------------------------------------------------
116701 // Gets single token.
116702 //--------------------------------------------------------------------------
116703
116704 /**
116705 * Gets the token starting at the specified index.
116706 * @param {number} offset Index of the start of the token's range.
116707 * @param {Object} [options=0] The option object.
116708 * @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
116709 * @returns {Token|null} The token starting at index, or null if no such token.
116710 */
116711
116712
116713 getTokenByRangeStart(offset, options) {
116714 const includeComments = options && options.includeComments;
116715 const token = cursors.forward.createBaseCursor(this[TOKENS], this[COMMENTS], this[INDEX_MAP], offset, -1, includeComments).getOneToken();
116716
116717 if (token && token.range[0] === offset) {
116718 return token;
116719 }
116720
116721 return null;
116722 }
116723 /**
116724 * Gets the first token of the given node.
116725 * @param {ASTNode} node The AST node.
116726 * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`.
116727 * @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
116728 * @param {Function|null} [options.filter=null] The predicate function to choose tokens.
116729 * @param {number} [options.skip=0] The count of tokens the cursor skips.
116730 * @returns {Token|null} An object representing the token.
116731 */
116732
116733
116734 getFirstToken(node, options) {
116735 return createCursorWithSkip(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[0], node.range[1], options).getOneToken();
116736 }
116737 /**
116738 * Gets the last token of the given node.
116739 * @param {ASTNode} node The AST node.
116740 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
116741 * @returns {Token|null} An object representing the token.
116742 */
116743
116744
116745 getLastToken(node, options) {
116746 return createCursorWithSkip(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[0], node.range[1], options).getOneToken();
116747 }
116748 /**
116749 * Gets the token that precedes a given node or token.
116750 * @param {ASTNode|Token|Comment} node The AST node or token.
116751 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
116752 * @returns {Token|null} An object representing the token.
116753 */
116754
116755
116756 getTokenBefore(node, options) {
116757 return createCursorWithSkip(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], -1, node.range[0], options).getOneToken();
116758 }
116759 /**
116760 * Gets the token that follows a given node or token.
116761 * @param {ASTNode|Token|Comment} node The AST node or token.
116762 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
116763 * @returns {Token|null} An object representing the token.
116764 */
116765
116766
116767 getTokenAfter(node, options) {
116768 return createCursorWithSkip(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[1], -1, options).getOneToken();
116769 }
116770 /**
116771 * Gets the first token between two non-overlapping nodes.
116772 * @param {ASTNode|Token|Comment} left Node before the desired token range.
116773 * @param {ASTNode|Token|Comment} right Node after the desired token range.
116774 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
116775 * @returns {Token|null} An object representing the token.
116776 */
116777
116778
116779 getFirstTokenBetween(left, right, options) {
116780 return createCursorWithSkip(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], left.range[1], right.range[0], options).getOneToken();
116781 }
116782 /**
116783 * Gets the last token between two non-overlapping nodes.
116784 * @param {ASTNode|Token|Comment} left Node before the desired token range.
116785 * @param {ASTNode|Token|Comment} right Node after the desired token range.
116786 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
116787 * @returns {Token|null} An object representing the token.
116788 */
116789
116790
116791 getLastTokenBetween(left, right, options) {
116792 return createCursorWithSkip(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], left.range[1], right.range[0], options).getOneToken();
116793 }
116794 /**
116795 * Gets the token that precedes a given node or token in the token stream.
116796 * This is defined for backward compatibility. Use `includeComments` option instead.
116797 * TODO: We have a plan to remove this in a future major version.
116798 * @param {ASTNode|Token|Comment} node The AST node or token.
116799 * @param {number} [skip=0] A number of tokens to skip.
116800 * @returns {Token|null} An object representing the token.
116801 * @deprecated
116802 */
116803
116804
116805 getTokenOrCommentBefore(node, skip) {
116806 return this.getTokenBefore(node, {
116807 includeComments: true,
116808 skip
116809 });
116810 }
116811 /**
116812 * Gets the token that follows a given node or token in the token stream.
116813 * This is defined for backward compatibility. Use `includeComments` option instead.
116814 * TODO: We have a plan to remove this in a future major version.
116815 * @param {ASTNode|Token|Comment} node The AST node or token.
116816 * @param {number} [skip=0] A number of tokens to skip.
116817 * @returns {Token|null} An object representing the token.
116818 * @deprecated
116819 */
116820
116821
116822 getTokenOrCommentAfter(node, skip) {
116823 return this.getTokenAfter(node, {
116824 includeComments: true,
116825 skip
116826 });
116827 } //--------------------------------------------------------------------------
116828 // Gets multiple tokens.
116829 //--------------------------------------------------------------------------
116830
116831 /**
116832 * Gets the first `count` tokens of the given node.
116833 * @param {ASTNode} node The AST node.
116834 * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`.
116835 * @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
116836 * @param {Function|null} [options.filter=null] The predicate function to choose tokens.
116837 * @param {number} [options.count=0] The maximum count of tokens the cursor iterates.
116838 * @returns {Token[]} Tokens.
116839 */
116840
116841
116842 getFirstTokens(node, options) {
116843 return createCursorWithCount(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[0], node.range[1], options).getAllTokens();
116844 }
116845 /**
116846 * Gets the last `count` tokens of the given node.
116847 * @param {ASTNode} node The AST node.
116848 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
116849 * @returns {Token[]} Tokens.
116850 */
116851
116852
116853 getLastTokens(node, options) {
116854 return createCursorWithCount(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[0], node.range[1], options).getAllTokens().reverse();
116855 }
116856 /**
116857 * Gets the `count` tokens that precedes a given node or token.
116858 * @param {ASTNode|Token|Comment} node The AST node or token.
116859 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
116860 * @returns {Token[]} Tokens.
116861 */
116862
116863
116864 getTokensBefore(node, options) {
116865 return createCursorWithCount(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], -1, node.range[0], options).getAllTokens().reverse();
116866 }
116867 /**
116868 * Gets the `count` tokens that follows a given node or token.
116869 * @param {ASTNode|Token|Comment} node The AST node or token.
116870 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
116871 * @returns {Token[]} Tokens.
116872 */
116873
116874
116875 getTokensAfter(node, options) {
116876 return createCursorWithCount(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[1], -1, options).getAllTokens();
116877 }
116878 /**
116879 * Gets the first `count` tokens between two non-overlapping nodes.
116880 * @param {ASTNode|Token|Comment} left Node before the desired token range.
116881 * @param {ASTNode|Token|Comment} right Node after the desired token range.
116882 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
116883 * @returns {Token[]} Tokens between left and right.
116884 */
116885
116886
116887 getFirstTokensBetween(left, right, options) {
116888 return createCursorWithCount(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], left.range[1], right.range[0], options).getAllTokens();
116889 }
116890 /**
116891 * Gets the last `count` tokens between two non-overlapping nodes.
116892 * @param {ASTNode|Token|Comment} left Node before the desired token range.
116893 * @param {ASTNode|Token|Comment} right Node after the desired token range.
116894 * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
116895 * @returns {Token[]} Tokens between left and right.
116896 */
116897
116898
116899 getLastTokensBetween(left, right, options) {
116900 return createCursorWithCount(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], left.range[1], right.range[0], options).getAllTokens().reverse();
116901 }
116902 /**
116903 * Gets all tokens that are related to the given node.
116904 * @param {ASTNode} node The AST node.
116905 * @param {Function|Object} options The option object. If this is a function then it's `options.filter`.
116906 * @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
116907 * @param {Function|null} [options.filter=null] The predicate function to choose tokens.
116908 * @param {number} [options.count=0] The maximum count of tokens the cursor iterates.
116909 * @returns {Token[]} Array of objects representing tokens.
116910 */
116911
116912 /**
116913 * Gets all tokens that are related to the given node.
116914 * @param {ASTNode} node The AST node.
116915 * @param {int} [beforeCount=0] The number of tokens before the node to retrieve.
116916 * @param {int} [afterCount=0] The number of tokens after the node to retrieve.
116917 * @returns {Token[]} Array of objects representing tokens.
116918 */
116919
116920
116921 getTokens(node, beforeCount, afterCount) {
116922 return createCursorWithPadding(this[TOKENS], this[COMMENTS], this[INDEX_MAP], node.range[0], node.range[1], beforeCount, afterCount).getAllTokens();
116923 }
116924 /**
116925 * Gets all of the tokens between two non-overlapping nodes.
116926 * @param {ASTNode|Token|Comment} left Node before the desired token range.
116927 * @param {ASTNode|Token|Comment} right Node after the desired token range.
116928 * @param {Function|Object} options The option object. If this is a function then it's `options.filter`.
116929 * @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
116930 * @param {Function|null} [options.filter=null] The predicate function to choose tokens.
116931 * @param {number} [options.count=0] The maximum count of tokens the cursor iterates.
116932 * @returns {Token[]} Tokens between left and right.
116933 */
116934
116935 /**
116936 * Gets all of the tokens between two non-overlapping nodes.
116937 * @param {ASTNode|Token|Comment} left Node before the desired token range.
116938 * @param {ASTNode|Token|Comment} right Node after the desired token range.
116939 * @param {int} [padding=0] Number of extra tokens on either side of center.
116940 * @returns {Token[]} Tokens between left and right.
116941 */
116942
116943
116944 getTokensBetween(left, right, padding) {
116945 return createCursorWithPadding(this[TOKENS], this[COMMENTS], this[INDEX_MAP], left.range[1], right.range[0], padding, padding).getAllTokens();
116946 } //--------------------------------------------------------------------------
116947 // Others.
116948 //--------------------------------------------------------------------------
116949
116950 /**
116951 * Checks whether any comments exist or not between the given 2 nodes.
116952 * @param {ASTNode} left The node to check.
116953 * @param {ASTNode} right The node to check.
116954 * @returns {boolean} `true` if one or more comments exist.
116955 */
116956
116957
116958 commentsExistBetween(left, right) {
116959 const index = utils.search(this[COMMENTS], left.range[1]);
116960 return index < this[COMMENTS].length && this[COMMENTS][index].range[1] <= right.range[0];
116961 }
116962 /**
116963 * Gets all comment tokens directly before the given node or token.
116964 * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens.
116965 * @returns {Array} An array of comments in occurrence order.
116966 */
116967
116968
116969 getCommentsBefore(nodeOrToken) {
116970 const cursor = createCursorWithCount(cursors.backward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], -1, nodeOrToken.range[0], {
116971 includeComments: true
116972 });
116973 return getAdjacentCommentTokensFromCursor(cursor).reverse();
116974 }
116975 /**
116976 * Gets all comment tokens directly after the given node or token.
116977 * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens.
116978 * @returns {Array} An array of comments in occurrence order.
116979 */
116980
116981
116982 getCommentsAfter(nodeOrToken) {
116983 const cursor = createCursorWithCount(cursors.forward, this[TOKENS], this[COMMENTS], this[INDEX_MAP], nodeOrToken.range[1], -1, {
116984 includeComments: true
116985 });
116986 return getAdjacentCommentTokensFromCursor(cursor);
116987 }
116988 /**
116989 * Gets all comment tokens inside the given node.
116990 * @param {ASTNode} node The AST node to get the comments for.
116991 * @returns {Array} An array of comments in occurrence order.
116992 */
116993
116994
116995 getCommentsInside(node) {
116996 return this.getTokens(node, {
116997 includeComments: true,
116998 filter: isCommentToken
116999 });
117000 }
117001
117002};
117003
117004/***/ }),
6a5a0f88 117005/* 779 */
eb39fafa
DC
117006/***/ (function(module, exports, __webpack_require__) {
117007
117008"use strict";
117009/**
117010 * @fileoverview Define 2 token factories; forward and backward.
117011 * @author Toru Nagashima
117012 */
117013 //------------------------------------------------------------------------------
117014// Requirements
117015//------------------------------------------------------------------------------
117016
6a5a0f88 117017const BackwardTokenCommentCursor = __webpack_require__(780);
eb39fafa 117018
6a5a0f88 117019const BackwardTokenCursor = __webpack_require__(783);
eb39fafa 117020
6a5a0f88 117021const FilterCursor = __webpack_require__(784);
eb39fafa 117022
6a5a0f88 117023const ForwardTokenCommentCursor = __webpack_require__(786);
eb39fafa 117024
6a5a0f88 117025const ForwardTokenCursor = __webpack_require__(787);
eb39fafa 117026
6a5a0f88 117027const LimitCursor = __webpack_require__(788);
eb39fafa 117028
6a5a0f88 117029const SkipCursor = __webpack_require__(789); //------------------------------------------------------------------------------
eb39fafa
DC
117030// Helpers
117031//------------------------------------------------------------------------------
117032
117033/**
117034 * The cursor factory.
117035 * @private
117036 */
117037
117038
117039class CursorFactory {
117040 /**
117041 * Initializes this cursor.
117042 * @param {Function} TokenCursor The class of the cursor which iterates tokens only.
117043 * @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments.
117044 */
117045 constructor(TokenCursor, TokenCommentCursor) {
117046 this.TokenCursor = TokenCursor;
117047 this.TokenCommentCursor = TokenCommentCursor;
117048 }
117049 /**
117050 * Creates a base cursor instance that can be decorated by createCursor.
117051 * @param {Token[]} tokens The array of tokens.
117052 * @param {Comment[]} comments The array of comments.
117053 * @param {Object} indexMap The map from locations to indices in `tokens`.
117054 * @param {number} startLoc The start location of the iteration range.
117055 * @param {number} endLoc The end location of the iteration range.
117056 * @param {boolean} includeComments The flag to iterate comments as well.
117057 * @returns {Cursor} The created base cursor.
117058 */
117059
117060
117061 createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments) {
117062 const Cursor = includeComments ? this.TokenCommentCursor : this.TokenCursor;
117063 return new Cursor(tokens, comments, indexMap, startLoc, endLoc);
117064 }
117065 /**
117066 * Creates a cursor that iterates tokens with normalized options.
117067 * @param {Token[]} tokens The array of tokens.
117068 * @param {Comment[]} comments The array of comments.
117069 * @param {Object} indexMap The map from locations to indices in `tokens`.
117070 * @param {number} startLoc The start location of the iteration range.
117071 * @param {number} endLoc The end location of the iteration range.
117072 * @param {boolean} includeComments The flag to iterate comments as well.
117073 * @param {Function|null} filter The predicate function to choose tokens.
117074 * @param {number} skip The count of tokens the cursor skips.
117075 * @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
117076 * @returns {Cursor} The created cursor.
117077 */
117078
117079
117080 createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, count) {
117081 let cursor = this.createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments);
117082
117083 if (filter) {
117084 cursor = new FilterCursor(cursor, filter);
117085 }
117086
117087 if (skip >= 1) {
117088 cursor = new SkipCursor(cursor, skip);
117089 }
117090
117091 if (count >= 0) {
117092 cursor = new LimitCursor(cursor, count);
117093 }
117094
117095 return cursor;
117096 }
117097
117098} //------------------------------------------------------------------------------
117099// Exports
117100//------------------------------------------------------------------------------
117101
117102
117103exports.forward = new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor);
117104exports.backward = new CursorFactory(BackwardTokenCursor, BackwardTokenCommentCursor);
117105
117106/***/ }),
6a5a0f88 117107/* 780 */
eb39fafa
DC
117108/***/ (function(module, exports, __webpack_require__) {
117109
117110"use strict";
117111/**
117112 * @fileoverview Define the cursor which iterates tokens and comments in reverse.
117113 * @author Toru Nagashima
117114 */
117115 //------------------------------------------------------------------------------
117116// Requirements
117117//------------------------------------------------------------------------------
117118
6a5a0f88 117119const Cursor = __webpack_require__(781);
eb39fafa 117120
6a5a0f88 117121const utils = __webpack_require__(782); //------------------------------------------------------------------------------
eb39fafa
DC
117122// Exports
117123//------------------------------------------------------------------------------
117124
117125/**
117126 * The cursor which iterates tokens and comments in reverse.
117127 */
117128
117129
117130module.exports = class BackwardTokenCommentCursor extends Cursor {
117131 /**
117132 * Initializes this cursor.
117133 * @param {Token[]} tokens The array of tokens.
117134 * @param {Comment[]} comments The array of comments.
117135 * @param {Object} indexMap The map from locations to indices in `tokens`.
117136 * @param {number} startLoc The start location of the iteration range.
117137 * @param {number} endLoc The end location of the iteration range.
117138 */
117139 constructor(tokens, comments, indexMap, startLoc, endLoc) {
117140 super();
117141 this.tokens = tokens;
117142 this.comments = comments;
117143 this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc);
117144 this.commentIndex = utils.search(comments, endLoc) - 1;
117145 this.border = startLoc;
117146 }
117147 /** @inheritdoc */
117148
117149
117150 moveNext() {
117151 const token = this.tokenIndex >= 0 ? this.tokens[this.tokenIndex] : null;
117152 const comment = this.commentIndex >= 0 ? this.comments[this.commentIndex] : null;
117153
117154 if (token && (!comment || token.range[1] > comment.range[1])) {
117155 this.current = token;
117156 this.tokenIndex -= 1;
117157 } else if (comment) {
117158 this.current = comment;
117159 this.commentIndex -= 1;
117160 } else {
117161 this.current = null;
117162 }
117163
117164 return Boolean(this.current) && (this.border === -1 || this.current.range[0] >= this.border);
117165 }
117166
117167};
117168
117169/***/ }),
6a5a0f88 117170/* 781 */
eb39fafa
DC
117171/***/ (function(module, exports, __webpack_require__) {
117172
117173"use strict";
117174/**
117175 * @fileoverview Define the abstract class about cursors which iterate tokens.
117176 * @author Toru Nagashima
117177 */
117178 //------------------------------------------------------------------------------
117179// Exports
117180//------------------------------------------------------------------------------
117181
117182/**
117183 * The abstract class about cursors which iterate tokens.
117184 *
117185 * This class has 2 abstract methods.
117186 *
117187 * - `current: Token | Comment | null` ... The current token.
117188 * - `moveNext(): boolean` ... Moves this cursor to the next token. If the next token didn't exist, it returns `false`.
117189 *
117190 * This is similar to ES2015 Iterators.
117191 * However, Iterators were slow (at 2017-01), so I created this class as similar to C# IEnumerable.
117192 *
117193 * There are the following known sub classes.
117194 *
117195 * - ForwardTokenCursor .......... The cursor which iterates tokens only.
117196 * - BackwardTokenCursor ......... The cursor which iterates tokens only in reverse.
117197 * - ForwardTokenCommentCursor ... The cursor which iterates tokens and comments.
117198 * - BackwardTokenCommentCursor .. The cursor which iterates tokens and comments in reverse.
117199 * - DecorativeCursor
117200 * - FilterCursor ............ The cursor which ignores the specified tokens.
117201 * - SkipCursor .............. The cursor which ignores the first few tokens.
117202 * - LimitCursor ............. The cursor which limits the count of tokens.
117203 *
117204 */
117205
117206module.exports = class Cursor {
117207 /**
117208 * Initializes this cursor.
117209 */
117210 constructor() {
117211 this.current = null;
117212 }
117213 /**
117214 * Gets the first token.
117215 * This consumes this cursor.
117216 * @returns {Token|Comment} The first token or null.
117217 */
117218
117219
117220 getOneToken() {
117221 return this.moveNext() ? this.current : null;
117222 }
117223 /**
117224 * Gets the first tokens.
117225 * This consumes this cursor.
117226 * @returns {(Token|Comment)[]} All tokens.
117227 */
117228
117229
117230 getAllTokens() {
117231 const tokens = [];
117232
117233 while (this.moveNext()) {
117234 tokens.push(this.current);
117235 }
117236
117237 return tokens;
117238 }
117239 /**
117240 * Moves this cursor to the next token.
117241 * @returns {boolean} `true` if the next token exists.
117242 * @abstract
117243 */
117244
117245 /* istanbul ignore next */
117246
117247
117248 moveNext() {
117249 // eslint-disable-line class-methods-use-this
117250 throw new Error("Not implemented.");
117251 }
117252
117253};
117254
117255/***/ }),
6a5a0f88 117256/* 782 */
eb39fafa
DC
117257/***/ (function(module, exports, __webpack_require__) {
117258
117259"use strict";
117260/**
117261 * @fileoverview Define utility functions for token store.
117262 * @author Toru Nagashima
117263 */
117264 //------------------------------------------------------------------------------
117265// Requirements
117266//------------------------------------------------------------------------------
117267
117268const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
117269// Helpers
117270//------------------------------------------------------------------------------
117271
117272/**
117273 * Gets `token.range[0]` from the given token.
117274 * @param {Node|Token|Comment} token The token to get.
117275 * @returns {number} The start location.
117276 * @private
117277 */
117278
117279
117280function getStartLocation(token) {
117281 return token.range[0];
117282} //------------------------------------------------------------------------------
117283// Exports
117284//------------------------------------------------------------------------------
117285
117286/**
117287 * Binary-searches the index of the first token which is after the given location.
117288 * If it was not found, this returns `tokens.length`.
117289 * @param {(Token|Comment)[]} tokens It searches the token in this list.
117290 * @param {number} location The location to search.
117291 * @returns {number} The found index or `tokens.length`.
117292 */
117293
117294
117295exports.search = function search(tokens, location) {
117296 return lodash.sortedIndexBy(tokens, {
117297 range: [location]
117298 }, getStartLocation);
117299};
117300/**
117301 * Gets the index of the `startLoc` in `tokens`.
117302 * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well.
117303 * @param {(Token|Comment)[]} tokens The tokens to find an index.
117304 * @param {Object} indexMap The map from locations to indices.
117305 * @param {number} startLoc The location to get an index.
117306 * @returns {number} The index.
117307 */
117308
117309
117310exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) {
117311 if (startLoc in indexMap) {
117312 return indexMap[startLoc];
117313 }
117314
117315 if (startLoc - 1 in indexMap) {
117316 const index = indexMap[startLoc - 1];
117317 const token = index >= 0 && index < tokens.length ? tokens[index] : null;
117318 /*
117319 * For the map of "comment's location -> token's index", it points the next token of a comment.
117320 * In that case, +1 is unnecessary.
117321 */
117322
117323 if (token && token.range[0] >= startLoc) {
117324 return index;
117325 }
117326
117327 return index + 1;
117328 }
117329
117330 return 0;
117331};
117332/**
117333 * Gets the index of the `endLoc` in `tokens`.
117334 * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well.
117335 * @param {(Token|Comment)[]} tokens The tokens to find an index.
117336 * @param {Object} indexMap The map from locations to indices.
117337 * @param {number} endLoc The location to get an index.
117338 * @returns {number} The index.
117339 */
117340
117341
117342exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) {
117343 if (endLoc in indexMap) {
117344 return indexMap[endLoc] - 1;
117345 }
117346
117347 if (endLoc - 1 in indexMap) {
117348 const index = indexMap[endLoc - 1];
117349 const token = index >= 0 && index < tokens.length ? tokens[index] : null;
117350 /*
117351 * For the map of "comment's location -> token's index", it points the next token of a comment.
117352 * In that case, -1 is necessary.
117353 */
117354
117355 if (token && token.range[1] > endLoc) {
117356 return index - 1;
117357 }
117358
117359 return index;
117360 }
117361
117362 return tokens.length - 1;
117363};
117364
117365/***/ }),
6a5a0f88 117366/* 783 */
eb39fafa
DC
117367/***/ (function(module, exports, __webpack_require__) {
117368
117369"use strict";
117370/**
117371 * @fileoverview Define the cursor which iterates tokens only in reverse.
117372 * @author Toru Nagashima
117373 */
117374 //------------------------------------------------------------------------------
117375// Requirements
117376//------------------------------------------------------------------------------
117377
6a5a0f88 117378const Cursor = __webpack_require__(781);
eb39fafa 117379
6a5a0f88 117380const utils = __webpack_require__(782); //------------------------------------------------------------------------------
eb39fafa
DC
117381// Exports
117382//------------------------------------------------------------------------------
117383
117384/**
117385 * The cursor which iterates tokens only in reverse.
117386 */
117387
117388
117389module.exports = class BackwardTokenCursor extends Cursor {
117390 /**
117391 * Initializes this cursor.
117392 * @param {Token[]} tokens The array of tokens.
117393 * @param {Comment[]} comments The array of comments.
117394 * @param {Object} indexMap The map from locations to indices in `tokens`.
117395 * @param {number} startLoc The start location of the iteration range.
117396 * @param {number} endLoc The end location of the iteration range.
117397 */
117398 constructor(tokens, comments, indexMap, startLoc, endLoc) {
117399 super();
117400 this.tokens = tokens;
117401 this.index = utils.getLastIndex(tokens, indexMap, endLoc);
117402 this.indexEnd = utils.getFirstIndex(tokens, indexMap, startLoc);
117403 }
117404 /** @inheritdoc */
117405
117406
117407 moveNext() {
117408 if (this.index >= this.indexEnd) {
117409 this.current = this.tokens[this.index];
117410 this.index -= 1;
117411 return true;
117412 }
117413
117414 return false;
117415 }
117416 /*
117417 *
117418 * Shorthand for performance.
117419 *
117420 */
117421
117422 /** @inheritdoc */
117423
117424
117425 getOneToken() {
117426 return this.index >= this.indexEnd ? this.tokens[this.index] : null;
117427 }
117428
117429};
117430
117431/***/ }),
6a5a0f88 117432/* 784 */
eb39fafa
DC
117433/***/ (function(module, exports, __webpack_require__) {
117434
117435"use strict";
117436/**
117437 * @fileoverview Define the cursor which ignores specified tokens.
117438 * @author Toru Nagashima
117439 */
117440 //------------------------------------------------------------------------------
117441// Requirements
117442//------------------------------------------------------------------------------
117443
6a5a0f88 117444const DecorativeCursor = __webpack_require__(785); //------------------------------------------------------------------------------
eb39fafa
DC
117445// Exports
117446//------------------------------------------------------------------------------
117447
117448/**
117449 * The decorative cursor which ignores specified tokens.
117450 */
117451
117452
117453module.exports = class FilterCursor extends DecorativeCursor {
117454 /**
117455 * Initializes this cursor.
117456 * @param {Cursor} cursor The cursor to be decorated.
117457 * @param {Function} predicate The predicate function to decide tokens this cursor iterates.
117458 */
117459 constructor(cursor, predicate) {
117460 super(cursor);
117461 this.predicate = predicate;
117462 }
117463 /** @inheritdoc */
117464
117465
117466 moveNext() {
117467 const predicate = this.predicate;
117468
117469 while (super.moveNext()) {
117470 if (predicate(this.current)) {
117471 return true;
117472 }
117473 }
117474
117475 return false;
117476 }
117477
117478};
117479
117480/***/ }),
6a5a0f88 117481/* 785 */
eb39fafa
DC
117482/***/ (function(module, exports, __webpack_require__) {
117483
117484"use strict";
117485/**
117486 * @fileoverview Define the abstract class about cursors which manipulate another cursor.
117487 * @author Toru Nagashima
117488 */
117489 //------------------------------------------------------------------------------
117490// Requirements
117491//------------------------------------------------------------------------------
117492
6a5a0f88 117493const Cursor = __webpack_require__(781); //------------------------------------------------------------------------------
eb39fafa
DC
117494// Exports
117495//------------------------------------------------------------------------------
117496
117497/**
117498 * The abstract class about cursors which manipulate another cursor.
117499 */
117500
117501
117502module.exports = class DecorativeCursor extends Cursor {
117503 /**
117504 * Initializes this cursor.
117505 * @param {Cursor} cursor The cursor to be decorated.
117506 */
117507 constructor(cursor) {
117508 super();
117509 this.cursor = cursor;
117510 }
117511 /** @inheritdoc */
117512
117513
117514 moveNext() {
117515 const retv = this.cursor.moveNext();
117516 this.current = this.cursor.current;
117517 return retv;
117518 }
117519
117520};
117521
117522/***/ }),
6a5a0f88 117523/* 786 */
eb39fafa
DC
117524/***/ (function(module, exports, __webpack_require__) {
117525
117526"use strict";
117527/**
117528 * @fileoverview Define the cursor which iterates tokens and comments.
117529 * @author Toru Nagashima
117530 */
117531 //------------------------------------------------------------------------------
117532// Requirements
117533//------------------------------------------------------------------------------
117534
6a5a0f88 117535const Cursor = __webpack_require__(781);
eb39fafa 117536
6a5a0f88 117537const utils = __webpack_require__(782); //------------------------------------------------------------------------------
eb39fafa
DC
117538// Exports
117539//------------------------------------------------------------------------------
117540
117541/**
117542 * The cursor which iterates tokens and comments.
117543 */
117544
117545
117546module.exports = class ForwardTokenCommentCursor extends Cursor {
117547 /**
117548 * Initializes this cursor.
117549 * @param {Token[]} tokens The array of tokens.
117550 * @param {Comment[]} comments The array of comments.
117551 * @param {Object} indexMap The map from locations to indices in `tokens`.
117552 * @param {number} startLoc The start location of the iteration range.
117553 * @param {number} endLoc The end location of the iteration range.
117554 */
117555 constructor(tokens, comments, indexMap, startLoc, endLoc) {
117556 super();
117557 this.tokens = tokens;
117558 this.comments = comments;
117559 this.tokenIndex = utils.getFirstIndex(tokens, indexMap, startLoc);
117560 this.commentIndex = utils.search(comments, startLoc);
117561 this.border = endLoc;
117562 }
117563 /** @inheritdoc */
117564
117565
117566 moveNext() {
117567 const token = this.tokenIndex < this.tokens.length ? this.tokens[this.tokenIndex] : null;
117568 const comment = this.commentIndex < this.comments.length ? this.comments[this.commentIndex] : null;
117569
117570 if (token && (!comment || token.range[0] < comment.range[0])) {
117571 this.current = token;
117572 this.tokenIndex += 1;
117573 } else if (comment) {
117574 this.current = comment;
117575 this.commentIndex += 1;
117576 } else {
117577 this.current = null;
117578 }
117579
117580 return Boolean(this.current) && (this.border === -1 || this.current.range[1] <= this.border);
117581 }
117582
117583};
117584
117585/***/ }),
6a5a0f88 117586/* 787 */
eb39fafa
DC
117587/***/ (function(module, exports, __webpack_require__) {
117588
117589"use strict";
117590/**
117591 * @fileoverview Define the cursor which iterates tokens only.
117592 * @author Toru Nagashima
117593 */
117594 //------------------------------------------------------------------------------
117595// Requirements
117596//------------------------------------------------------------------------------
117597
6a5a0f88 117598const Cursor = __webpack_require__(781);
eb39fafa 117599
6a5a0f88 117600const utils = __webpack_require__(782); //------------------------------------------------------------------------------
eb39fafa
DC
117601// Exports
117602//------------------------------------------------------------------------------
117603
117604/**
117605 * The cursor which iterates tokens only.
117606 */
117607
117608
117609module.exports = class ForwardTokenCursor extends Cursor {
117610 /**
117611 * Initializes this cursor.
117612 * @param {Token[]} tokens The array of tokens.
117613 * @param {Comment[]} comments The array of comments.
117614 * @param {Object} indexMap The map from locations to indices in `tokens`.
117615 * @param {number} startLoc The start location of the iteration range.
117616 * @param {number} endLoc The end location of the iteration range.
117617 */
117618 constructor(tokens, comments, indexMap, startLoc, endLoc) {
117619 super();
117620 this.tokens = tokens;
117621 this.index = utils.getFirstIndex(tokens, indexMap, startLoc);
117622 this.indexEnd = utils.getLastIndex(tokens, indexMap, endLoc);
117623 }
117624 /** @inheritdoc */
117625
117626
117627 moveNext() {
117628 if (this.index <= this.indexEnd) {
117629 this.current = this.tokens[this.index];
117630 this.index += 1;
117631 return true;
117632 }
117633
117634 return false;
117635 }
117636 /*
117637 *
117638 * Shorthand for performance.
117639 *
117640 */
117641
117642 /** @inheritdoc */
117643
117644
117645 getOneToken() {
117646 return this.index <= this.indexEnd ? this.tokens[this.index] : null;
117647 }
117648 /** @inheritdoc */
117649
117650
117651 getAllTokens() {
117652 return this.tokens.slice(this.index, this.indexEnd + 1);
117653 }
117654
117655};
117656
117657/***/ }),
6a5a0f88 117658/* 788 */
eb39fafa
DC
117659/***/ (function(module, exports, __webpack_require__) {
117660
117661"use strict";
117662/**
117663 * @fileoverview Define the cursor which limits the number of tokens.
117664 * @author Toru Nagashima
117665 */
117666 //------------------------------------------------------------------------------
117667// Requirements
117668//------------------------------------------------------------------------------
117669
6a5a0f88 117670const DecorativeCursor = __webpack_require__(785); //------------------------------------------------------------------------------
eb39fafa
DC
117671// Exports
117672//------------------------------------------------------------------------------
117673
117674/**
117675 * The decorative cursor which limits the number of tokens.
117676 */
117677
117678
117679module.exports = class LimitCursor extends DecorativeCursor {
117680 /**
117681 * Initializes this cursor.
117682 * @param {Cursor} cursor The cursor to be decorated.
117683 * @param {number} count The count of tokens this cursor iterates.
117684 */
117685 constructor(cursor, count) {
117686 super(cursor);
117687 this.count = count;
117688 }
117689 /** @inheritdoc */
117690
117691
117692 moveNext() {
117693 if (this.count > 0) {
117694 this.count -= 1;
117695 return super.moveNext();
117696 }
117697
117698 return false;
117699 }
117700
117701};
117702
117703/***/ }),
6a5a0f88 117704/* 789 */
eb39fafa
DC
117705/***/ (function(module, exports, __webpack_require__) {
117706
117707"use strict";
117708/**
117709 * @fileoverview Define the cursor which ignores the first few tokens.
117710 * @author Toru Nagashima
117711 */
117712 //------------------------------------------------------------------------------
117713// Requirements
117714//------------------------------------------------------------------------------
117715
6a5a0f88 117716const DecorativeCursor = __webpack_require__(785); //------------------------------------------------------------------------------
eb39fafa
DC
117717// Exports
117718//------------------------------------------------------------------------------
117719
117720/**
117721 * The decorative cursor which ignores the first few tokens.
117722 */
117723
117724
117725module.exports = class SkipCursor extends DecorativeCursor {
117726 /**
117727 * Initializes this cursor.
117728 * @param {Cursor} cursor The cursor to be decorated.
117729 * @param {number} count The count of tokens this cursor skips.
117730 */
117731 constructor(cursor, count) {
117732 super(cursor);
117733 this.count = count;
117734 }
117735 /** @inheritdoc */
117736
117737
117738 moveNext() {
117739 while (this.count > 0) {
117740 this.count -= 1;
117741
117742 if (!super.moveNext()) {
117743 return false;
117744 }
117745 }
117746
117747 return super.moveNext();
117748 }
117749
117750};
117751
117752/***/ }),
6a5a0f88 117753/* 790 */
eb39fafa
DC
117754/***/ (function(module, exports, __webpack_require__) {
117755
117756"use strict";
117757/**
117758 * @fileoverview Define the cursor which iterates tokens only, with inflated range.
117759 * @author Toru Nagashima
117760 */
117761 //------------------------------------------------------------------------------
117762// Requirements
117763//------------------------------------------------------------------------------
117764
6a5a0f88 117765const ForwardTokenCursor = __webpack_require__(787); //------------------------------------------------------------------------------
eb39fafa
DC
117766// Exports
117767//------------------------------------------------------------------------------
117768
117769/**
117770 * The cursor which iterates tokens only, with inflated range.
117771 * This is for the backward compatibility of padding options.
117772 */
117773
117774
117775module.exports = class PaddedTokenCursor extends ForwardTokenCursor {
117776 /**
117777 * Initializes this cursor.
117778 * @param {Token[]} tokens The array of tokens.
117779 * @param {Comment[]} comments The array of comments.
117780 * @param {Object} indexMap The map from locations to indices in `tokens`.
117781 * @param {number} startLoc The start location of the iteration range.
117782 * @param {number} endLoc The end location of the iteration range.
117783 * @param {number} beforeCount The number of tokens this cursor iterates before start.
117784 * @param {number} afterCount The number of tokens this cursor iterates after end.
117785 */
117786 constructor(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) {
117787 super(tokens, comments, indexMap, startLoc, endLoc);
117788 this.index = Math.max(0, this.index - beforeCount);
117789 this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount);
117790 }
117791
117792};
117793
117794/***/ }),
6a5a0f88 117795/* 791 */
eb39fafa
DC
117796/***/ (function(module, exports, __webpack_require__) {
117797
117798"use strict";
117799/**
117800 * @fileoverview A class of the code path analyzer.
117801 * @author Toru Nagashima
117802 */
117803 //------------------------------------------------------------------------------
117804// Requirements
117805//------------------------------------------------------------------------------
117806
117807const assert = __webpack_require__(379),
117808 {
117809 breakableTypePattern
117810} = __webpack_require__(409),
6a5a0f88
TL
117811 CodePath = __webpack_require__(792),
117812 CodePathSegment = __webpack_require__(794),
117813 IdGenerator = __webpack_require__(797),
117814 debug = __webpack_require__(795); //------------------------------------------------------------------------------
eb39fafa
DC
117815// Helpers
117816//------------------------------------------------------------------------------
117817
117818/**
117819 * Checks whether or not a given node is a `case` node (not `default` node).
117820 * @param {ASTNode} node A `SwitchCase` node to check.
117821 * @returns {boolean} `true` if the node is a `case` node (not `default` node).
117822 */
117823
117824
117825function isCaseNode(node) {
117826 return Boolean(node.test);
117827}
117828/**
117829 * Checks whether the given logical operator is taken into account for the code
117830 * path analysis.
117831 * @param {string} operator The operator found in the LogicalExpression node
117832 * @returns {boolean} `true` if the operator is "&&" or "||"
117833 */
117834
117835
117836function isHandledLogicalOperator(operator) {
117837 return operator === "&&" || operator === "||";
117838}
117839/**
117840 * Gets the label if the parent node of a given node is a LabeledStatement.
117841 * @param {ASTNode} node A node to get.
117842 * @returns {string|null} The label or `null`.
117843 */
117844
117845
117846function getLabel(node) {
117847 if (node.parent.type === "LabeledStatement") {
117848 return node.parent.label.name;
117849 }
117850
117851 return null;
117852}
117853/**
117854 * Checks whether or not a given logical expression node goes different path
117855 * between the `true` case and the `false` case.
117856 * @param {ASTNode} node A node to check.
117857 * @returns {boolean} `true` if the node is a test of a choice statement.
117858 */
117859
117860
117861function isForkingByTrueOrFalse(node) {
117862 const parent = node.parent;
117863
117864 switch (parent.type) {
117865 case "ConditionalExpression":
117866 case "IfStatement":
117867 case "WhileStatement":
117868 case "DoWhileStatement":
117869 case "ForStatement":
117870 return parent.test === node;
117871
117872 case "LogicalExpression":
117873 return isHandledLogicalOperator(parent.operator);
117874
117875 default:
117876 return false;
117877 }
117878}
117879/**
117880 * Gets the boolean value of a given literal node.
117881 *
117882 * This is used to detect infinity loops (e.g. `while (true) {}`).
117883 * Statements preceded by an infinity loop are unreachable if the loop didn't
117884 * have any `break` statement.
117885 * @param {ASTNode} node A node to get.
117886 * @returns {boolean|undefined} a boolean value if the node is a Literal node,
117887 * otherwise `undefined`.
117888 */
117889
117890
117891function getBooleanValueIfSimpleConstant(node) {
117892 if (node.type === "Literal") {
117893 return Boolean(node.value);
117894 }
117895
117896 return void 0;
117897}
117898/**
117899 * Checks that a given identifier node is a reference or not.
117900 *
117901 * This is used to detect the first throwable node in a `try` block.
117902 * @param {ASTNode} node An Identifier node to check.
117903 * @returns {boolean} `true` if the node is a reference.
117904 */
117905
117906
117907function isIdentifierReference(node) {
117908 const parent = node.parent;
117909
117910 switch (parent.type) {
117911 case "LabeledStatement":
117912 case "BreakStatement":
117913 case "ContinueStatement":
117914 case "ArrayPattern":
117915 case "RestElement":
117916 case "ImportSpecifier":
117917 case "ImportDefaultSpecifier":
117918 case "ImportNamespaceSpecifier":
117919 case "CatchClause":
117920 return false;
117921
117922 case "FunctionDeclaration":
117923 case "FunctionExpression":
117924 case "ArrowFunctionExpression":
117925 case "ClassDeclaration":
117926 case "ClassExpression":
117927 case "VariableDeclarator":
117928 return parent.id !== node;
117929
117930 case "Property":
117931 case "MethodDefinition":
117932 return parent.key !== node || parent.computed || parent.shorthand;
117933
117934 case "AssignmentPattern":
117935 return parent.key !== node;
117936
117937 default:
117938 return true;
117939 }
117940}
117941/**
117942 * Updates the current segment with the head segment.
117943 * This is similar to local branches and tracking branches of git.
117944 *
117945 * To separate the current and the head is in order to not make useless segments.
117946 *
117947 * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd"
117948 * events are fired.
117949 * @param {CodePathAnalyzer} analyzer The instance.
117950 * @param {ASTNode} node The current AST node.
117951 * @returns {void}
117952 */
117953
117954
117955function forwardCurrentToHead(analyzer, node) {
117956 const codePath = analyzer.codePath;
117957 const state = CodePath.getState(codePath);
117958 const currentSegments = state.currentSegments;
117959 const headSegments = state.headSegments;
117960 const end = Math.max(currentSegments.length, headSegments.length);
117961 let i, currentSegment, headSegment; // Fires leaving events.
117962
117963 for (i = 0; i < end; ++i) {
117964 currentSegment = currentSegments[i];
117965 headSegment = headSegments[i];
117966
117967 if (currentSegment !== headSegment && currentSegment) {
117968 debug.dump("onCodePathSegmentEnd ".concat(currentSegment.id));
117969
117970 if (currentSegment.reachable) {
117971 analyzer.emitter.emit("onCodePathSegmentEnd", currentSegment, node);
117972 }
117973 }
117974 } // Update state.
117975
117976
117977 state.currentSegments = headSegments; // Fires entering events.
117978
117979 for (i = 0; i < end; ++i) {
117980 currentSegment = currentSegments[i];
117981 headSegment = headSegments[i];
117982
117983 if (currentSegment !== headSegment && headSegment) {
117984 debug.dump("onCodePathSegmentStart ".concat(headSegment.id));
117985 CodePathSegment.markUsed(headSegment);
117986
117987 if (headSegment.reachable) {
117988 analyzer.emitter.emit("onCodePathSegmentStart", headSegment, node);
117989 }
117990 }
117991 }
117992}
117993/**
117994 * Updates the current segment with empty.
117995 * This is called at the last of functions or the program.
117996 * @param {CodePathAnalyzer} analyzer The instance.
117997 * @param {ASTNode} node The current AST node.
117998 * @returns {void}
117999 */
118000
118001
118002function leaveFromCurrentSegment(analyzer, node) {
118003 const state = CodePath.getState(analyzer.codePath);
118004 const currentSegments = state.currentSegments;
118005
118006 for (let i = 0; i < currentSegments.length; ++i) {
118007 const currentSegment = currentSegments[i];
118008 debug.dump("onCodePathSegmentEnd ".concat(currentSegment.id));
118009
118010 if (currentSegment.reachable) {
118011 analyzer.emitter.emit("onCodePathSegmentEnd", currentSegment, node);
118012 }
118013 }
118014
118015 state.currentSegments = [];
118016}
118017/**
118018 * Updates the code path due to the position of a given node in the parent node
118019 * thereof.
118020 *
118021 * For example, if the node is `parent.consequent`, this creates a fork from the
118022 * current path.
118023 * @param {CodePathAnalyzer} analyzer The instance.
118024 * @param {ASTNode} node The current AST node.
118025 * @returns {void}
118026 */
118027
118028
118029function preprocess(analyzer, node) {
118030 const codePath = analyzer.codePath;
118031 const state = CodePath.getState(codePath);
118032 const parent = node.parent;
118033
118034 switch (parent.type) {
118035 case "LogicalExpression":
118036 if (parent.right === node && isHandledLogicalOperator(parent.operator)) {
118037 state.makeLogicalRight();
118038 }
118039
118040 break;
118041
118042 case "ConditionalExpression":
118043 case "IfStatement":
118044 /*
118045 * Fork if this node is at `consequent`/`alternate`.
118046 * `popForkContext()` exists at `IfStatement:exit` and
118047 * `ConditionalExpression:exit`.
118048 */
118049 if (parent.consequent === node) {
118050 state.makeIfConsequent();
118051 } else if (parent.alternate === node) {
118052 state.makeIfAlternate();
118053 }
118054
118055 break;
118056
118057 case "SwitchCase":
118058 if (parent.consequent[0] === node) {
118059 state.makeSwitchCaseBody(false, !parent.test);
118060 }
118061
118062 break;
118063
118064 case "TryStatement":
118065 if (parent.handler === node) {
118066 state.makeCatchBlock();
118067 } else if (parent.finalizer === node) {
118068 state.makeFinallyBlock();
118069 }
118070
118071 break;
118072
118073 case "WhileStatement":
118074 if (parent.test === node) {
118075 state.makeWhileTest(getBooleanValueIfSimpleConstant(node));
118076 } else {
118077 assert(parent.body === node);
118078 state.makeWhileBody();
118079 }
118080
118081 break;
118082
118083 case "DoWhileStatement":
118084 if (parent.body === node) {
118085 state.makeDoWhileBody();
118086 } else {
118087 assert(parent.test === node);
118088 state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node));
118089 }
118090
118091 break;
118092
118093 case "ForStatement":
118094 if (parent.test === node) {
118095 state.makeForTest(getBooleanValueIfSimpleConstant(node));
118096 } else if (parent.update === node) {
118097 state.makeForUpdate();
118098 } else if (parent.body === node) {
118099 state.makeForBody();
118100 }
118101
118102 break;
118103
118104 case "ForInStatement":
118105 case "ForOfStatement":
118106 if (parent.left === node) {
118107 state.makeForInOfLeft();
118108 } else if (parent.right === node) {
118109 state.makeForInOfRight();
118110 } else {
118111 assert(parent.body === node);
118112 state.makeForInOfBody();
118113 }
118114
118115 break;
118116
118117 case "AssignmentPattern":
118118 /*
118119 * Fork if this node is at `right`.
118120 * `left` is executed always, so it uses the current path.
118121 * `popForkContext()` exists at `AssignmentPattern:exit`.
118122 */
118123 if (parent.right === node) {
118124 state.pushForkContext();
118125 state.forkBypassPath();
118126 state.forkPath();
118127 }
118128
118129 break;
118130
118131 default:
118132 break;
118133 }
118134}
118135/**
118136 * Updates the code path due to the type of a given node in entering.
118137 * @param {CodePathAnalyzer} analyzer The instance.
118138 * @param {ASTNode} node The current AST node.
118139 * @returns {void}
118140 */
118141
118142
118143function processCodePathToEnter(analyzer, node) {
118144 let codePath = analyzer.codePath;
118145 let state = codePath && CodePath.getState(codePath);
118146 const parent = node.parent;
118147
118148 switch (node.type) {
118149 case "Program":
118150 case "FunctionDeclaration":
118151 case "FunctionExpression":
118152 case "ArrowFunctionExpression":
118153 if (codePath) {
118154 // Emits onCodePathSegmentStart events if updated.
118155 forwardCurrentToHead(analyzer, node);
118156 debug.dumpState(node, state, false);
118157 } // Create the code path of this scope.
118158
118159
118160 codePath = analyzer.codePath = new CodePath(analyzer.idGenerator.next(), codePath, analyzer.onLooped);
118161 state = CodePath.getState(codePath); // Emits onCodePathStart events.
118162
118163 debug.dump("onCodePathStart ".concat(codePath.id));
118164 analyzer.emitter.emit("onCodePathStart", codePath, node);
118165 break;
118166
118167 case "LogicalExpression":
118168 if (isHandledLogicalOperator(node.operator)) {
118169 state.pushChoiceContext(node.operator, isForkingByTrueOrFalse(node));
118170 }
118171
118172 break;
118173
118174 case "ConditionalExpression":
118175 case "IfStatement":
118176 state.pushChoiceContext("test", false);
118177 break;
118178
118179 case "SwitchStatement":
118180 state.pushSwitchContext(node.cases.some(isCaseNode), getLabel(node));
118181 break;
118182
118183 case "TryStatement":
118184 state.pushTryContext(Boolean(node.finalizer));
118185 break;
118186
118187 case "SwitchCase":
118188 /*
118189 * Fork if this node is after the 2st node in `cases`.
118190 * It's similar to `else` blocks.
118191 * The next `test` node is processed in this path.
118192 */
118193 if (parent.discriminant !== node && parent.cases[0] !== node) {
118194 state.forkPath();
118195 }
118196
118197 break;
118198
118199 case "WhileStatement":
118200 case "DoWhileStatement":
118201 case "ForStatement":
118202 case "ForInStatement":
118203 case "ForOfStatement":
118204 state.pushLoopContext(node.type, getLabel(node));
118205 break;
118206
118207 case "LabeledStatement":
118208 if (!breakableTypePattern.test(node.body.type)) {
118209 state.pushBreakContext(false, node.label.name);
118210 }
118211
118212 break;
118213
118214 default:
118215 break;
118216 } // Emits onCodePathSegmentStart events if updated.
118217
118218
118219 forwardCurrentToHead(analyzer, node);
118220 debug.dumpState(node, state, false);
118221}
118222/**
118223 * Updates the code path due to the type of a given node in leaving.
118224 * @param {CodePathAnalyzer} analyzer The instance.
118225 * @param {ASTNode} node The current AST node.
118226 * @returns {void}
118227 */
118228
118229
118230function processCodePathToExit(analyzer, node) {
118231 const codePath = analyzer.codePath;
118232 const state = CodePath.getState(codePath);
118233 let dontForward = false;
118234
118235 switch (node.type) {
118236 case "IfStatement":
118237 case "ConditionalExpression":
118238 state.popChoiceContext();
118239 break;
118240
118241 case "LogicalExpression":
118242 if (isHandledLogicalOperator(node.operator)) {
118243 state.popChoiceContext();
118244 }
118245
118246 break;
118247
118248 case "SwitchStatement":
118249 state.popSwitchContext();
118250 break;
118251
118252 case "SwitchCase":
118253 /*
118254 * This is the same as the process at the 1st `consequent` node in
118255 * `preprocess` function.
118256 * Must do if this `consequent` is empty.
118257 */
118258 if (node.consequent.length === 0) {
118259 state.makeSwitchCaseBody(true, !node.test);
118260 }
118261
118262 if (state.forkContext.reachable) {
118263 dontForward = true;
118264 }
118265
118266 break;
118267
118268 case "TryStatement":
118269 state.popTryContext();
118270 break;
118271
118272 case "BreakStatement":
118273 forwardCurrentToHead(analyzer, node);
118274 state.makeBreak(node.label && node.label.name);
118275 dontForward = true;
118276 break;
118277
118278 case "ContinueStatement":
118279 forwardCurrentToHead(analyzer, node);
118280 state.makeContinue(node.label && node.label.name);
118281 dontForward = true;
118282 break;
118283
118284 case "ReturnStatement":
118285 forwardCurrentToHead(analyzer, node);
118286 state.makeReturn();
118287 dontForward = true;
118288 break;
118289
118290 case "ThrowStatement":
118291 forwardCurrentToHead(analyzer, node);
118292 state.makeThrow();
118293 dontForward = true;
118294 break;
118295
118296 case "Identifier":
118297 if (isIdentifierReference(node)) {
118298 state.makeFirstThrowablePathInTryBlock();
118299 dontForward = true;
118300 }
118301
118302 break;
118303
118304 case "CallExpression":
118305 case "ImportExpression":
118306 case "MemberExpression":
118307 case "NewExpression":
118308 case "YieldExpression":
118309 state.makeFirstThrowablePathInTryBlock();
118310 break;
118311
118312 case "WhileStatement":
118313 case "DoWhileStatement":
118314 case "ForStatement":
118315 case "ForInStatement":
118316 case "ForOfStatement":
118317 state.popLoopContext();
118318 break;
118319
118320 case "AssignmentPattern":
118321 state.popForkContext();
118322 break;
118323
118324 case "LabeledStatement":
118325 if (!breakableTypePattern.test(node.body.type)) {
118326 state.popBreakContext();
118327 }
118328
118329 break;
118330
118331 default:
118332 break;
118333 } // Emits onCodePathSegmentStart events if updated.
118334
118335
118336 if (!dontForward) {
118337 forwardCurrentToHead(analyzer, node);
118338 }
118339
118340 debug.dumpState(node, state, true);
118341}
118342/**
118343 * Updates the code path to finalize the current code path.
118344 * @param {CodePathAnalyzer} analyzer The instance.
118345 * @param {ASTNode} node The current AST node.
118346 * @returns {void}
118347 */
118348
118349
118350function postprocess(analyzer, node) {
118351 switch (node.type) {
118352 case "Program":
118353 case "FunctionDeclaration":
118354 case "FunctionExpression":
118355 case "ArrowFunctionExpression":
118356 {
118357 let codePath = analyzer.codePath; // Mark the current path as the final node.
118358
118359 CodePath.getState(codePath).makeFinal(); // Emits onCodePathSegmentEnd event of the current segments.
118360
118361 leaveFromCurrentSegment(analyzer, node); // Emits onCodePathEnd event of this code path.
118362
118363 debug.dump("onCodePathEnd ".concat(codePath.id));
118364 analyzer.emitter.emit("onCodePathEnd", codePath, node);
118365 debug.dumpDot(codePath);
118366 codePath = analyzer.codePath = analyzer.codePath.upper;
118367
118368 if (codePath) {
118369 debug.dumpState(node, CodePath.getState(codePath), true);
118370 }
118371
118372 break;
118373 }
118374
118375 default:
118376 break;
118377 }
118378} //------------------------------------------------------------------------------
118379// Public Interface
118380//------------------------------------------------------------------------------
118381
118382/**
118383 * The class to analyze code paths.
118384 * This class implements the EventGenerator interface.
118385 */
118386
118387
118388class CodePathAnalyzer {
118389 // eslint-disable-next-line jsdoc/require-description
118390
118391 /**
118392 * @param {EventGenerator} eventGenerator An event generator to wrap.
118393 */
118394 constructor(eventGenerator) {
118395 this.original = eventGenerator;
118396 this.emitter = eventGenerator.emitter;
118397 this.codePath = null;
118398 this.idGenerator = new IdGenerator("s");
118399 this.currentNode = null;
118400 this.onLooped = this.onLooped.bind(this);
118401 }
118402 /**
118403 * Does the process to enter a given AST node.
118404 * This updates state of analysis and calls `enterNode` of the wrapped.
118405 * @param {ASTNode} node A node which is entering.
118406 * @returns {void}
118407 */
118408
118409
118410 enterNode(node) {
118411 this.currentNode = node; // Updates the code path due to node's position in its parent node.
118412
118413 if (node.parent) {
118414 preprocess(this, node);
118415 }
118416 /*
118417 * Updates the code path.
118418 * And emits onCodePathStart/onCodePathSegmentStart events.
118419 */
118420
118421
118422 processCodePathToEnter(this, node); // Emits node events.
118423
118424 this.original.enterNode(node);
118425 this.currentNode = null;
118426 }
118427 /**
118428 * Does the process to leave a given AST node.
118429 * This updates state of analysis and calls `leaveNode` of the wrapped.
118430 * @param {ASTNode} node A node which is leaving.
118431 * @returns {void}
118432 */
118433
118434
118435 leaveNode(node) {
118436 this.currentNode = node;
118437 /*
118438 * Updates the code path.
118439 * And emits onCodePathStart/onCodePathSegmentStart events.
118440 */
118441
118442 processCodePathToExit(this, node); // Emits node events.
118443
118444 this.original.leaveNode(node); // Emits the last onCodePathStart/onCodePathSegmentStart events.
118445
118446 postprocess(this, node);
118447 this.currentNode = null;
118448 }
118449 /**
118450 * This is called on a code path looped.
118451 * Then this raises a looped event.
118452 * @param {CodePathSegment} fromSegment A segment of prev.
118453 * @param {CodePathSegment} toSegment A segment of next.
118454 * @returns {void}
118455 */
118456
118457
118458 onLooped(fromSegment, toSegment) {
118459 if (fromSegment.reachable && toSegment.reachable) {
118460 debug.dump("onCodePathSegmentLoop ".concat(fromSegment.id, " -> ").concat(toSegment.id));
118461 this.emitter.emit("onCodePathSegmentLoop", fromSegment, toSegment, this.currentNode);
118462 }
118463 }
118464
118465}
118466
118467module.exports = CodePathAnalyzer;
118468
118469/***/ }),
6a5a0f88 118470/* 792 */
eb39fafa
DC
118471/***/ (function(module, exports, __webpack_require__) {
118472
118473"use strict";
118474/**
118475 * @fileoverview A class of the code path.
118476 * @author Toru Nagashima
118477 */
118478 //------------------------------------------------------------------------------
118479// Requirements
118480//------------------------------------------------------------------------------
118481
6a5a0f88 118482const CodePathState = __webpack_require__(793);
eb39fafa 118483
6a5a0f88 118484const IdGenerator = __webpack_require__(797); //------------------------------------------------------------------------------
eb39fafa
DC
118485// Public Interface
118486//------------------------------------------------------------------------------
118487
118488/**
118489 * A code path.
118490 */
118491
118492
118493class CodePath {
118494 // eslint-disable-next-line jsdoc/require-description
118495
118496 /**
118497 * @param {string} id An identifier.
118498 * @param {CodePath|null} upper The code path of the upper function scope.
118499 * @param {Function} onLooped A callback function to notify looping.
118500 */
118501 constructor(id, upper, onLooped) {
118502 /**
118503 * The identifier of this code path.
118504 * Rules use it to store additional information of each rule.
118505 * @type {string}
118506 */
118507 this.id = id;
118508 /**
118509 * The code path of the upper function scope.
118510 * @type {CodePath|null}
118511 */
118512
118513 this.upper = upper;
118514 /**
118515 * The code paths of nested function scopes.
118516 * @type {CodePath[]}
118517 */
118518
118519 this.childCodePaths = []; // Initializes internal state.
118520
118521 Object.defineProperty(this, "internal", {
118522 value: new CodePathState(new IdGenerator("".concat(id, "_")), onLooped)
118523 }); // Adds this into `childCodePaths` of `upper`.
118524
118525 if (upper) {
118526 upper.childCodePaths.push(this);
118527 }
118528 }
118529 /**
118530 * Gets the state of a given code path.
118531 * @param {CodePath} codePath A code path to get.
118532 * @returns {CodePathState} The state of the code path.
118533 */
118534
118535
118536 static getState(codePath) {
118537 return codePath.internal;
118538 }
118539 /**
118540 * The initial code path segment.
118541 * @type {CodePathSegment}
118542 */
118543
118544
118545 get initialSegment() {
118546 return this.internal.initialSegment;
118547 }
118548 /**
118549 * Final code path segments.
118550 * This array is a mix of `returnedSegments` and `thrownSegments`.
118551 * @type {CodePathSegment[]}
118552 */
118553
118554
118555 get finalSegments() {
118556 return this.internal.finalSegments;
118557 }
118558 /**
118559 * Final code path segments which is with `return` statements.
118560 * This array contains the last path segment if it's reachable.
118561 * Since the reachable last path returns `undefined`.
118562 * @type {CodePathSegment[]}
118563 */
118564
118565
118566 get returnedSegments() {
118567 return this.internal.returnedForkContext;
118568 }
118569 /**
118570 * Final code path segments which is with `throw` statements.
118571 * @type {CodePathSegment[]}
118572 */
118573
118574
118575 get thrownSegments() {
118576 return this.internal.thrownForkContext;
118577 }
118578 /**
118579 * Current code path segments.
118580 * @type {CodePathSegment[]}
118581 */
118582
118583
118584 get currentSegments() {
118585 return this.internal.currentSegments;
118586 }
118587 /**
118588 * Traverses all segments in this code path.
118589 *
118590 * codePath.traverseSegments(function(segment, controller) {
118591 * // do something.
118592 * });
118593 *
118594 * This method enumerates segments in order from the head.
118595 *
118596 * The `controller` object has two methods.
118597 *
118598 * - `controller.skip()` - Skip the following segments in this branch.
118599 * - `controller.break()` - Skip all following segments.
118600 * @param {Object} [options] Omittable.
118601 * @param {CodePathSegment} [options.first] The first segment to traverse.
118602 * @param {CodePathSegment} [options.last] The last segment to traverse.
118603 * @param {Function} callback A callback function.
118604 * @returns {void}
118605 */
118606
118607
118608 traverseSegments(options, callback) {
118609 let resolvedOptions;
118610 let resolvedCallback;
118611
118612 if (typeof options === "function") {
118613 resolvedCallback = options;
118614 resolvedOptions = {};
118615 } else {
118616 resolvedOptions = options || {};
118617 resolvedCallback = callback;
118618 }
118619
118620 const startSegment = resolvedOptions.first || this.internal.initialSegment;
118621 const lastSegment = resolvedOptions.last;
118622 let item = null;
118623 let index = 0;
118624 let end = 0;
118625 let segment = null;
118626 const visited = Object.create(null);
118627 const stack = [[startSegment, 0]];
118628 let skippedSegment = null;
118629 let broken = false;
118630 const controller = {
118631 skip() {
118632 if (stack.length <= 1) {
118633 broken = true;
118634 } else {
118635 skippedSegment = stack[stack.length - 2][0];
118636 }
118637 },
118638
118639 break() {
118640 broken = true;
118641 }
118642
118643 };
118644 /**
118645 * Checks a given previous segment has been visited.
118646 * @param {CodePathSegment} prevSegment A previous segment to check.
118647 * @returns {boolean} `true` if the segment has been visited.
118648 */
118649
118650 function isVisited(prevSegment) {
118651 return visited[prevSegment.id] || segment.isLoopedPrevSegment(prevSegment);
118652 }
118653
118654 while (stack.length > 0) {
118655 item = stack[stack.length - 1];
118656 segment = item[0];
118657 index = item[1];
118658
118659 if (index === 0) {
118660 // Skip if this segment has been visited already.
118661 if (visited[segment.id]) {
118662 stack.pop();
118663 continue;
118664 } // Skip if all previous segments have not been visited.
118665
118666
118667 if (segment !== startSegment && segment.prevSegments.length > 0 && !segment.prevSegments.every(isVisited)) {
118668 stack.pop();
118669 continue;
118670 } // Reset the flag of skipping if all branches have been skipped.
118671
118672
118673 if (skippedSegment && segment.prevSegments.indexOf(skippedSegment) !== -1) {
118674 skippedSegment = null;
118675 }
118676
118677 visited[segment.id] = true; // Call the callback when the first time.
118678
118679 if (!skippedSegment) {
118680 resolvedCallback.call(this, segment, controller);
118681
118682 if (segment === lastSegment) {
118683 controller.skip();
118684 }
118685
118686 if (broken) {
118687 break;
118688 }
118689 }
118690 } // Update the stack.
118691
118692
118693 end = segment.nextSegments.length - 1;
118694
118695 if (index < end) {
118696 item[1] += 1;
118697 stack.push([segment.nextSegments[index], 0]);
118698 } else if (index === end) {
118699 item[0] = segment.nextSegments[index];
118700 item[1] = 0;
118701 } else {
118702 stack.pop();
118703 }
118704 }
118705 }
118706
118707}
118708
118709module.exports = CodePath;
118710
118711/***/ }),
6a5a0f88 118712/* 793 */
eb39fafa
DC
118713/***/ (function(module, exports, __webpack_require__) {
118714
118715"use strict";
118716/**
118717 * @fileoverview A class to manage state of generating a code path.
118718 * @author Toru Nagashima
118719 */
118720 //------------------------------------------------------------------------------
118721// Requirements
118722//------------------------------------------------------------------------------
118723
6a5a0f88
TL
118724const CodePathSegment = __webpack_require__(794),
118725 ForkContext = __webpack_require__(796); //------------------------------------------------------------------------------
eb39fafa
DC
118726// Helpers
118727//------------------------------------------------------------------------------
118728
118729/**
118730 * Adds given segments into the `dest` array.
118731 * If the `others` array does not includes the given segments, adds to the `all`
118732 * array as well.
118733 *
118734 * This adds only reachable and used segments.
118735 * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`).
118736 * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`).
118737 * @param {CodePathSegment[]} all The unified destination array (`finalSegments`).
118738 * @param {CodePathSegment[]} segments Segments to add.
118739 * @returns {void}
118740 */
118741
118742
118743function addToReturnedOrThrown(dest, others, all, segments) {
118744 for (let i = 0; i < segments.length; ++i) {
118745 const segment = segments[i];
118746 dest.push(segment);
118747
118748 if (others.indexOf(segment) === -1) {
118749 all.push(segment);
118750 }
118751 }
118752}
118753/**
118754 * Gets a loop-context for a `continue` statement.
118755 * @param {CodePathState} state A state to get.
118756 * @param {string} label The label of a `continue` statement.
118757 * @returns {LoopContext} A loop-context for a `continue` statement.
118758 */
118759
118760
118761function getContinueContext(state, label) {
118762 if (!label) {
118763 return state.loopContext;
118764 }
118765
118766 let context = state.loopContext;
118767
118768 while (context) {
118769 if (context.label === label) {
118770 return context;
118771 }
118772
118773 context = context.upper;
118774 }
118775 /* istanbul ignore next: foolproof (syntax error) */
118776
118777
118778 return null;
118779}
118780/**
118781 * Gets a context for a `break` statement.
118782 * @param {CodePathState} state A state to get.
118783 * @param {string} label The label of a `break` statement.
118784 * @returns {LoopContext|SwitchContext} A context for a `break` statement.
118785 */
118786
118787
118788function getBreakContext(state, label) {
118789 let context = state.breakContext;
118790
118791 while (context) {
118792 if (label ? context.label === label : context.breakable) {
118793 return context;
118794 }
118795
118796 context = context.upper;
118797 }
118798 /* istanbul ignore next: foolproof (syntax error) */
118799
118800
118801 return null;
118802}
118803/**
118804 * Gets a context for a `return` statement.
118805 * @param {CodePathState} state A state to get.
118806 * @returns {TryContext|CodePathState} A context for a `return` statement.
118807 */
118808
118809
118810function getReturnContext(state) {
118811 let context = state.tryContext;
118812
118813 while (context) {
118814 if (context.hasFinalizer && context.position !== "finally") {
118815 return context;
118816 }
118817
118818 context = context.upper;
118819 }
118820
118821 return state;
118822}
118823/**
118824 * Gets a context for a `throw` statement.
118825 * @param {CodePathState} state A state to get.
118826 * @returns {TryContext|CodePathState} A context for a `throw` statement.
118827 */
118828
118829
118830function getThrowContext(state) {
118831 let context = state.tryContext;
118832
118833 while (context) {
118834 if (context.position === "try" || context.hasFinalizer && context.position === "catch") {
118835 return context;
118836 }
118837
118838 context = context.upper;
118839 }
118840
118841 return state;
118842}
118843/**
118844 * Removes a given element from a given array.
118845 * @param {any[]} xs An array to remove the specific element.
118846 * @param {any} x An element to be removed.
118847 * @returns {void}
118848 */
118849
118850
118851function remove(xs, x) {
118852 xs.splice(xs.indexOf(x), 1);
118853}
118854/**
118855 * Disconnect given segments.
118856 *
118857 * This is used in a process for switch statements.
118858 * If there is the "default" chunk before other cases, the order is different
118859 * between node's and running's.
118860 * @param {CodePathSegment[]} prevSegments Forward segments to disconnect.
118861 * @param {CodePathSegment[]} nextSegments Backward segments to disconnect.
118862 * @returns {void}
118863 */
118864
118865
118866function removeConnection(prevSegments, nextSegments) {
118867 for (let i = 0; i < prevSegments.length; ++i) {
118868 const prevSegment = prevSegments[i];
118869 const nextSegment = nextSegments[i];
118870 remove(prevSegment.nextSegments, nextSegment);
118871 remove(prevSegment.allNextSegments, nextSegment);
118872 remove(nextSegment.prevSegments, prevSegment);
118873 remove(nextSegment.allPrevSegments, prevSegment);
118874 }
118875}
118876/**
118877 * Creates looping path.
118878 * @param {CodePathState} state The instance.
118879 * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source.
118880 * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination.
118881 * @returns {void}
118882 */
118883
118884
118885function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) {
118886 const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments);
118887 const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments);
118888 const end = Math.min(fromSegments.length, toSegments.length);
118889
118890 for (let i = 0; i < end; ++i) {
118891 const fromSegment = fromSegments[i];
118892 const toSegment = toSegments[i];
118893
118894 if (toSegment.reachable) {
118895 fromSegment.nextSegments.push(toSegment);
118896 }
118897
118898 if (fromSegment.reachable) {
118899 toSegment.prevSegments.push(fromSegment);
118900 }
118901
118902 fromSegment.allNextSegments.push(toSegment);
118903 toSegment.allPrevSegments.push(fromSegment);
118904
118905 if (toSegment.allPrevSegments.length >= 2) {
118906 CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment);
118907 }
118908
118909 state.notifyLooped(fromSegment, toSegment);
118910 }
118911}
118912/**
118913 * Finalizes segments of `test` chunk of a ForStatement.
118914 *
118915 * - Adds `false` paths to paths which are leaving from the loop.
118916 * - Sets `true` paths to paths which go to the body.
118917 * @param {LoopContext} context A loop context to modify.
118918 * @param {ChoiceContext} choiceContext A choice context of this loop.
118919 * @param {CodePathSegment[]} head The current head paths.
118920 * @returns {void}
118921 */
118922
118923
118924function finalizeTestSegmentsOfFor(context, choiceContext, head) {
118925 if (!choiceContext.processed) {
118926 choiceContext.trueForkContext.add(head);
118927 choiceContext.falseForkContext.add(head);
118928 }
118929
118930 if (context.test !== true) {
118931 context.brokenForkContext.addAll(choiceContext.falseForkContext);
118932 }
118933
118934 context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1);
118935} //------------------------------------------------------------------------------
118936// Public Interface
118937//------------------------------------------------------------------------------
118938
118939/**
118940 * A class which manages state to analyze code paths.
118941 */
118942
118943
118944class CodePathState {
118945 // eslint-disable-next-line jsdoc/require-description
118946
118947 /**
118948 * @param {IdGenerator} idGenerator An id generator to generate id for code
118949 * path segments.
118950 * @param {Function} onLooped A callback function to notify looping.
118951 */
118952 constructor(idGenerator, onLooped) {
118953 this.idGenerator = idGenerator;
118954 this.notifyLooped = onLooped;
118955 this.forkContext = ForkContext.newRoot(idGenerator);
118956 this.choiceContext = null;
118957 this.switchContext = null;
118958 this.tryContext = null;
118959 this.loopContext = null;
118960 this.breakContext = null;
118961 this.currentSegments = [];
118962 this.initialSegment = this.forkContext.head[0]; // returnedSegments and thrownSegments push elements into finalSegments also.
118963
118964 const final = this.finalSegments = [];
118965 const returned = this.returnedForkContext = [];
118966 const thrown = this.thrownForkContext = [];
118967 returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final);
118968 thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final);
118969 }
118970 /**
118971 * The head segments.
118972 * @type {CodePathSegment[]}
118973 */
118974
118975
118976 get headSegments() {
118977 return this.forkContext.head;
118978 }
118979 /**
118980 * The parent forking context.
118981 * This is used for the root of new forks.
118982 * @type {ForkContext}
118983 */
118984
118985
118986 get parentForkContext() {
118987 const current = this.forkContext;
118988 return current && current.upper;
118989 }
118990 /**
118991 * Creates and stacks new forking context.
118992 * @param {boolean} forkLeavingPath A flag which shows being in a
118993 * "finally" block.
118994 * @returns {ForkContext} The created context.
118995 */
118996
118997
118998 pushForkContext(forkLeavingPath) {
118999 this.forkContext = ForkContext.newEmpty(this.forkContext, forkLeavingPath);
119000 return this.forkContext;
119001 }
119002 /**
119003 * Pops and merges the last forking context.
119004 * @returns {ForkContext} The last context.
119005 */
119006
119007
119008 popForkContext() {
119009 const lastContext = this.forkContext;
119010 this.forkContext = lastContext.upper;
119011 this.forkContext.replaceHead(lastContext.makeNext(0, -1));
119012 return lastContext;
119013 }
119014 /**
119015 * Creates a new path.
119016 * @returns {void}
119017 */
119018
119019
119020 forkPath() {
119021 this.forkContext.add(this.parentForkContext.makeNext(-1, -1));
119022 }
119023 /**
119024 * Creates a bypass path.
119025 * This is used for such as IfStatement which does not have "else" chunk.
119026 * @returns {void}
119027 */
119028
119029
119030 forkBypassPath() {
119031 this.forkContext.add(this.parentForkContext.head);
119032 } //--------------------------------------------------------------------------
119033 // ConditionalExpression, LogicalExpression, IfStatement
119034 //--------------------------------------------------------------------------
119035
119036 /**
119037 * Creates a context for ConditionalExpression, LogicalExpression,
119038 * IfStatement, WhileStatement, DoWhileStatement, or ForStatement.
119039 *
119040 * LogicalExpressions have cases that it goes different paths between the
119041 * `true` case and the `false` case.
119042 *
119043 * For Example:
119044 *
119045 * if (a || b) {
119046 * foo();
119047 * } else {
119048 * bar();
119049 * }
119050 *
119051 * In this case, `b` is evaluated always in the code path of the `else`
119052 * block, but it's not so in the code path of the `if` block.
119053 * So there are 3 paths.
119054 *
119055 * a -> foo();
119056 * a -> b -> foo();
119057 * a -> b -> bar();
119058 * @param {string} kind A kind string.
119059 * If the new context is LogicalExpression's, this is `"&&"` or `"||"`.
119060 * If it's IfStatement's or ConditionalExpression's, this is `"test"`.
119061 * Otherwise, this is `"loop"`.
119062 * @param {boolean} isForkingAsResult A flag that shows that goes different
119063 * paths between `true` and `false`.
119064 * @returns {void}
119065 */
119066
119067
119068 pushChoiceContext(kind, isForkingAsResult) {
119069 this.choiceContext = {
119070 upper: this.choiceContext,
119071 kind,
119072 isForkingAsResult,
119073 trueForkContext: ForkContext.newEmpty(this.forkContext),
119074 falseForkContext: ForkContext.newEmpty(this.forkContext),
119075 processed: false
119076 };
119077 }
119078 /**
119079 * Pops the last choice context and finalizes it.
119080 * @returns {ChoiceContext} The popped context.
119081 */
119082
119083
119084 popChoiceContext() {
119085 const context = this.choiceContext;
119086 this.choiceContext = context.upper;
119087 const forkContext = this.forkContext;
119088 const headSegments = forkContext.head;
119089
119090 switch (context.kind) {
119091 case "&&":
119092 case "||":
119093 /*
119094 * If any result were not transferred from child contexts,
119095 * this sets the head segments to both cases.
119096 * The head segments are the path of the right-hand operand.
119097 */
119098 if (!context.processed) {
119099 context.trueForkContext.add(headSegments);
119100 context.falseForkContext.add(headSegments);
119101 }
119102 /*
119103 * Transfers results to upper context if this context is in
119104 * test chunk.
119105 */
119106
119107
119108 if (context.isForkingAsResult) {
119109 const parentContext = this.choiceContext;
119110 parentContext.trueForkContext.addAll(context.trueForkContext);
119111 parentContext.falseForkContext.addAll(context.falseForkContext);
119112 parentContext.processed = true;
119113 return context;
119114 }
119115
119116 break;
119117
119118 case "test":
119119 if (!context.processed) {
119120 /*
119121 * The head segments are the path of the `if` block here.
119122 * Updates the `true` path with the end of the `if` block.
119123 */
119124 context.trueForkContext.clear();
119125 context.trueForkContext.add(headSegments);
119126 } else {
119127 /*
119128 * The head segments are the path of the `else` block here.
119129 * Updates the `false` path with the end of the `else`
119130 * block.
119131 */
119132 context.falseForkContext.clear();
119133 context.falseForkContext.add(headSegments);
119134 }
119135
119136 break;
119137
119138 case "loop":
119139 /*
119140 * Loops are addressed in popLoopContext().
119141 * This is called from popLoopContext().
119142 */
119143 return context;
119144
119145 /* istanbul ignore next */
119146
119147 default:
119148 throw new Error("unreachable");
119149 } // Merges all paths.
119150
119151
119152 const prevForkContext = context.trueForkContext;
119153 prevForkContext.addAll(context.falseForkContext);
119154 forkContext.replaceHead(prevForkContext.makeNext(0, -1));
119155 return context;
119156 }
119157 /**
119158 * Makes a code path segment of the right-hand operand of a logical
119159 * expression.
119160 * @returns {void}
119161 */
119162
119163
119164 makeLogicalRight() {
119165 const context = this.choiceContext;
119166 const forkContext = this.forkContext;
119167
119168 if (context.processed) {
119169 /*
119170 * This got segments already from the child choice context.
119171 * Creates the next path from own true/false fork context.
119172 */
119173 const prevForkContext = context.kind === "&&" ? context.trueForkContext
119174 /* kind === "||" */
119175 : context.falseForkContext;
119176 forkContext.replaceHead(prevForkContext.makeNext(0, -1));
119177 prevForkContext.clear();
119178 context.processed = false;
119179 } else {
119180 /*
119181 * This did not get segments from the child choice context.
119182 * So addresses the head segments.
119183 * The head segments are the path of the left-hand operand.
119184 */
119185 if (context.kind === "&&") {
119186 // The path does short-circuit if false.
119187 context.falseForkContext.add(forkContext.head);
119188 } else {
119189 // The path does short-circuit if true.
119190 context.trueForkContext.add(forkContext.head);
119191 }
119192
119193 forkContext.replaceHead(forkContext.makeNext(-1, -1));
119194 }
119195 }
119196 /**
119197 * Makes a code path segment of the `if` block.
119198 * @returns {void}
119199 */
119200
119201
119202 makeIfConsequent() {
119203 const context = this.choiceContext;
119204 const forkContext = this.forkContext;
119205 /*
119206 * If any result were not transferred from child contexts,
119207 * this sets the head segments to both cases.
119208 * The head segments are the path of the test expression.
119209 */
119210
119211 if (!context.processed) {
119212 context.trueForkContext.add(forkContext.head);
119213 context.falseForkContext.add(forkContext.head);
119214 }
119215
119216 context.processed = false; // Creates new path from the `true` case.
119217
119218 forkContext.replaceHead(context.trueForkContext.makeNext(0, -1));
119219 }
119220 /**
119221 * Makes a code path segment of the `else` block.
119222 * @returns {void}
119223 */
119224
119225
119226 makeIfAlternate() {
119227 const context = this.choiceContext;
119228 const forkContext = this.forkContext;
119229 /*
119230 * The head segments are the path of the `if` block.
119231 * Updates the `true` path with the end of the `if` block.
119232 */
119233
119234 context.trueForkContext.clear();
119235 context.trueForkContext.add(forkContext.head);
119236 context.processed = true; // Creates new path from the `false` case.
119237
119238 forkContext.replaceHead(context.falseForkContext.makeNext(0, -1));
119239 } //--------------------------------------------------------------------------
119240 // SwitchStatement
119241 //--------------------------------------------------------------------------
119242
119243 /**
119244 * Creates a context object of SwitchStatement and stacks it.
119245 * @param {boolean} hasCase `true` if the switch statement has one or more
119246 * case parts.
119247 * @param {string|null} label The label text.
119248 * @returns {void}
119249 */
119250
119251
119252 pushSwitchContext(hasCase, label) {
119253 this.switchContext = {
119254 upper: this.switchContext,
119255 hasCase,
119256 defaultSegments: null,
119257 defaultBodySegments: null,
119258 foundDefault: false,
119259 lastIsDefault: false,
119260 countForks: 0
119261 };
119262 this.pushBreakContext(true, label);
119263 }
119264 /**
119265 * Pops the last context of SwitchStatement and finalizes it.
119266 *
119267 * - Disposes all forking stack for `case` and `default`.
119268 * - Creates the next code path segment from `context.brokenForkContext`.
119269 * - If the last `SwitchCase` node is not a `default` part, creates a path
119270 * to the `default` body.
119271 * @returns {void}
119272 */
119273
119274
119275 popSwitchContext() {
119276 const context = this.switchContext;
119277 this.switchContext = context.upper;
119278 const forkContext = this.forkContext;
119279 const brokenForkContext = this.popBreakContext().brokenForkContext;
119280
119281 if (context.countForks === 0) {
119282 /*
119283 * When there is only one `default` chunk and there is one or more
119284 * `break` statements, even if forks are nothing, it needs to merge
119285 * those.
119286 */
119287 if (!brokenForkContext.empty) {
119288 brokenForkContext.add(forkContext.makeNext(-1, -1));
119289 forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
119290 }
119291
119292 return;
119293 }
119294
119295 const lastSegments = forkContext.head;
119296 this.forkBypassPath();
119297 const lastCaseSegments = forkContext.head;
119298 /*
119299 * `brokenForkContext` is used to make the next segment.
119300 * It must add the last segment into `brokenForkContext`.
119301 */
119302
119303 brokenForkContext.add(lastSegments);
119304 /*
119305 * A path which is failed in all case test should be connected to path
119306 * of `default` chunk.
119307 */
119308
119309 if (!context.lastIsDefault) {
119310 if (context.defaultBodySegments) {
119311 /*
119312 * Remove a link from `default` label to its chunk.
119313 * It's false route.
119314 */
119315 removeConnection(context.defaultSegments, context.defaultBodySegments);
119316 makeLooped(this, lastCaseSegments, context.defaultBodySegments);
119317 } else {
119318 /*
119319 * It handles the last case body as broken if `default` chunk
119320 * does not exist.
119321 */
119322 brokenForkContext.add(lastCaseSegments);
119323 }
119324 } // Pops the segment context stack until the entry segment.
119325
119326
119327 for (let i = 0; i < context.countForks; ++i) {
119328 this.forkContext = this.forkContext.upper;
119329 }
119330 /*
119331 * Creates a path from all brokenForkContext paths.
119332 * This is a path after switch statement.
119333 */
119334
119335
119336 this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
119337 }
119338 /**
119339 * Makes a code path segment for a `SwitchCase` node.
119340 * @param {boolean} isEmpty `true` if the body is empty.
119341 * @param {boolean} isDefault `true` if the body is the default case.
119342 * @returns {void}
119343 */
119344
119345
119346 makeSwitchCaseBody(isEmpty, isDefault) {
119347 const context = this.switchContext;
119348
119349 if (!context.hasCase) {
119350 return;
119351 }
119352 /*
119353 * Merge forks.
119354 * The parent fork context has two segments.
119355 * Those are from the current case and the body of the previous case.
119356 */
119357
119358
119359 const parentForkContext = this.forkContext;
119360 const forkContext = this.pushForkContext();
119361 forkContext.add(parentForkContext.makeNext(0, -1));
119362 /*
119363 * Save `default` chunk info.
119364 * If the `default` label is not at the last, we must make a path from
119365 * the last `case` to the `default` chunk.
119366 */
119367
119368 if (isDefault) {
119369 context.defaultSegments = parentForkContext.head;
119370
119371 if (isEmpty) {
119372 context.foundDefault = true;
119373 } else {
119374 context.defaultBodySegments = forkContext.head;
119375 }
119376 } else {
119377 if (!isEmpty && context.foundDefault) {
119378 context.foundDefault = false;
119379 context.defaultBodySegments = forkContext.head;
119380 }
119381 }
119382
119383 context.lastIsDefault = isDefault;
119384 context.countForks += 1;
119385 } //--------------------------------------------------------------------------
119386 // TryStatement
119387 //--------------------------------------------------------------------------
119388
119389 /**
119390 * Creates a context object of TryStatement and stacks it.
119391 * @param {boolean} hasFinalizer `true` if the try statement has a
119392 * `finally` block.
119393 * @returns {void}
119394 */
119395
119396
119397 pushTryContext(hasFinalizer) {
119398 this.tryContext = {
119399 upper: this.tryContext,
119400 position: "try",
119401 hasFinalizer,
119402 returnedForkContext: hasFinalizer ? ForkContext.newEmpty(this.forkContext) : null,
119403 thrownForkContext: ForkContext.newEmpty(this.forkContext),
119404 lastOfTryIsReachable: false,
119405 lastOfCatchIsReachable: false
119406 };
119407 }
119408 /**
119409 * Pops the last context of TryStatement and finalizes it.
119410 * @returns {void}
119411 */
119412
119413
119414 popTryContext() {
119415 const context = this.tryContext;
119416 this.tryContext = context.upper;
119417
119418 if (context.position === "catch") {
119419 // Merges two paths from the `try` block and `catch` block merely.
119420 this.popForkContext();
119421 return;
119422 }
119423 /*
119424 * The following process is executed only when there is the `finally`
119425 * block.
119426 */
119427
119428
119429 const returned = context.returnedForkContext;
119430 const thrown = context.thrownForkContext;
119431
119432 if (returned.empty && thrown.empty) {
119433 return;
119434 } // Separate head to normal paths and leaving paths.
119435
119436
119437 const headSegments = this.forkContext.head;
119438 this.forkContext = this.forkContext.upper;
119439 const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0);
119440 const leavingSegments = headSegments.slice(headSegments.length / 2 | 0); // Forwards the leaving path to upper contexts.
119441
119442 if (!returned.empty) {
119443 getReturnContext(this).returnedForkContext.add(leavingSegments);
119444 }
119445
119446 if (!thrown.empty) {
119447 getThrowContext(this).thrownForkContext.add(leavingSegments);
119448 } // Sets the normal path as the next.
119449
119450
119451 this.forkContext.replaceHead(normalSegments);
119452 /*
119453 * If both paths of the `try` block and the `catch` block are
119454 * unreachable, the next path becomes unreachable as well.
119455 */
119456
119457 if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) {
119458 this.forkContext.makeUnreachable();
119459 }
119460 }
119461 /**
119462 * Makes a code path segment for a `catch` block.
119463 * @returns {void}
119464 */
119465
119466
119467 makeCatchBlock() {
119468 const context = this.tryContext;
119469 const forkContext = this.forkContext;
119470 const thrown = context.thrownForkContext; // Update state.
119471
119472 context.position = "catch";
119473 context.thrownForkContext = ForkContext.newEmpty(forkContext);
119474 context.lastOfTryIsReachable = forkContext.reachable; // Merge thrown paths.
119475
119476 thrown.add(forkContext.head);
119477 const thrownSegments = thrown.makeNext(0, -1); // Fork to a bypass and the merged thrown path.
119478
119479 this.pushForkContext();
119480 this.forkBypassPath();
119481 this.forkContext.add(thrownSegments);
119482 }
119483 /**
119484 * Makes a code path segment for a `finally` block.
119485 *
119486 * In the `finally` block, parallel paths are created. The parallel paths
119487 * are used as leaving-paths. The leaving-paths are paths from `return`
119488 * statements and `throw` statements in a `try` block or a `catch` block.
119489 * @returns {void}
119490 */
119491
119492
119493 makeFinallyBlock() {
119494 const context = this.tryContext;
119495 let forkContext = this.forkContext;
119496 const returned = context.returnedForkContext;
119497 const thrown = context.thrownForkContext;
119498 const headOfLeavingSegments = forkContext.head; // Update state.
119499
119500 if (context.position === "catch") {
119501 // Merges two paths from the `try` block and `catch` block.
119502 this.popForkContext();
119503 forkContext = this.forkContext;
119504 context.lastOfCatchIsReachable = forkContext.reachable;
119505 } else {
119506 context.lastOfTryIsReachable = forkContext.reachable;
119507 }
119508
119509 context.position = "finally";
119510
119511 if (returned.empty && thrown.empty) {
119512 // This path does not leave.
119513 return;
119514 }
119515 /*
119516 * Create a parallel segment from merging returned and thrown.
119517 * This segment will leave at the end of this finally block.
119518 */
119519
119520
119521 const segments = forkContext.makeNext(-1, -1);
119522
119523 for (let i = 0; i < forkContext.count; ++i) {
119524 const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]];
119525
119526 for (let j = 0; j < returned.segmentsList.length; ++j) {
119527 prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]);
119528 }
119529
119530 for (let j = 0; j < thrown.segmentsList.length; ++j) {
119531 prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]);
119532 }
119533
119534 segments.push(CodePathSegment.newNext(this.idGenerator.next(), prevSegsOfLeavingSegment));
119535 }
119536
119537 this.pushForkContext(true);
119538 this.forkContext.add(segments);
119539 }
119540 /**
119541 * Makes a code path segment from the first throwable node to the `catch`
119542 * block or the `finally` block.
119543 * @returns {void}
119544 */
119545
119546
119547 makeFirstThrowablePathInTryBlock() {
119548 const forkContext = this.forkContext;
119549
119550 if (!forkContext.reachable) {
119551 return;
119552 }
119553
119554 const context = getThrowContext(this);
119555
119556 if (context === this || context.position !== "try" || !context.thrownForkContext.empty) {
119557 return;
119558 }
119559
119560 context.thrownForkContext.add(forkContext.head);
119561 forkContext.replaceHead(forkContext.makeNext(-1, -1));
119562 } //--------------------------------------------------------------------------
119563 // Loop Statements
119564 //--------------------------------------------------------------------------
119565
119566 /**
119567 * Creates a context object of a loop statement and stacks it.
119568 * @param {string} type The type of the node which was triggered. One of
119569 * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`,
119570 * and `ForStatement`.
119571 * @param {string|null} label A label of the node which was triggered.
119572 * @returns {void}
119573 */
119574
119575
119576 pushLoopContext(type, label) {
119577 const forkContext = this.forkContext;
119578 const breakContext = this.pushBreakContext(true, label);
119579
119580 switch (type) {
119581 case "WhileStatement":
119582 this.pushChoiceContext("loop", false);
119583 this.loopContext = {
119584 upper: this.loopContext,
119585 type,
119586 label,
119587 test: void 0,
119588 continueDestSegments: null,
119589 brokenForkContext: breakContext.brokenForkContext
119590 };
119591 break;
119592
119593 case "DoWhileStatement":
119594 this.pushChoiceContext("loop", false);
119595 this.loopContext = {
119596 upper: this.loopContext,
119597 type,
119598 label,
119599 test: void 0,
119600 entrySegments: null,
119601 continueForkContext: ForkContext.newEmpty(forkContext),
119602 brokenForkContext: breakContext.brokenForkContext
119603 };
119604 break;
119605
119606 case "ForStatement":
119607 this.pushChoiceContext("loop", false);
119608 this.loopContext = {
119609 upper: this.loopContext,
119610 type,
119611 label,
119612 test: void 0,
119613 endOfInitSegments: null,
119614 testSegments: null,
119615 endOfTestSegments: null,
119616 updateSegments: null,
119617 endOfUpdateSegments: null,
119618 continueDestSegments: null,
119619 brokenForkContext: breakContext.brokenForkContext
119620 };
119621 break;
119622
119623 case "ForInStatement":
119624 case "ForOfStatement":
119625 this.loopContext = {
119626 upper: this.loopContext,
119627 type,
119628 label,
119629 prevSegments: null,
119630 leftSegments: null,
119631 endOfLeftSegments: null,
119632 continueDestSegments: null,
119633 brokenForkContext: breakContext.brokenForkContext
119634 };
119635 break;
119636
119637 /* istanbul ignore next */
119638
119639 default:
119640 throw new Error("unknown type: \"".concat(type, "\""));
119641 }
119642 }
119643 /**
119644 * Pops the last context of a loop statement and finalizes it.
119645 * @returns {void}
119646 */
119647
119648
119649 popLoopContext() {
119650 const context = this.loopContext;
119651 this.loopContext = context.upper;
119652 const forkContext = this.forkContext;
119653 const brokenForkContext = this.popBreakContext().brokenForkContext; // Creates a looped path.
119654
119655 switch (context.type) {
119656 case "WhileStatement":
119657 case "ForStatement":
119658 this.popChoiceContext();
119659 makeLooped(this, forkContext.head, context.continueDestSegments);
119660 break;
119661
119662 case "DoWhileStatement":
119663 {
119664 const choiceContext = this.popChoiceContext();
119665
119666 if (!choiceContext.processed) {
119667 choiceContext.trueForkContext.add(forkContext.head);
119668 choiceContext.falseForkContext.add(forkContext.head);
119669 }
119670
119671 if (context.test !== true) {
119672 brokenForkContext.addAll(choiceContext.falseForkContext);
119673 } // `true` paths go to looping.
119674
119675
119676 const segmentsList = choiceContext.trueForkContext.segmentsList;
119677
119678 for (let i = 0; i < segmentsList.length; ++i) {
119679 makeLooped(this, segmentsList[i], context.entrySegments);
119680 }
119681
119682 break;
119683 }
119684
119685 case "ForInStatement":
119686 case "ForOfStatement":
119687 brokenForkContext.add(forkContext.head);
119688 makeLooped(this, forkContext.head, context.leftSegments);
119689 break;
119690
119691 /* istanbul ignore next */
119692
119693 default:
119694 throw new Error("unreachable");
119695 } // Go next.
119696
119697
119698 if (brokenForkContext.empty) {
119699 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
119700 } else {
119701 forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
119702 }
119703 }
119704 /**
119705 * Makes a code path segment for the test part of a WhileStatement.
119706 * @param {boolean|undefined} test The test value (only when constant).
119707 * @returns {void}
119708 */
119709
119710
119711 makeWhileTest(test) {
119712 const context = this.loopContext;
119713 const forkContext = this.forkContext;
119714 const testSegments = forkContext.makeNext(0, -1); // Update state.
119715
119716 context.test = test;
119717 context.continueDestSegments = testSegments;
119718 forkContext.replaceHead(testSegments);
119719 }
119720 /**
119721 * Makes a code path segment for the body part of a WhileStatement.
119722 * @returns {void}
119723 */
119724
119725
119726 makeWhileBody() {
119727 const context = this.loopContext;
119728 const choiceContext = this.choiceContext;
119729 const forkContext = this.forkContext;
119730
119731 if (!choiceContext.processed) {
119732 choiceContext.trueForkContext.add(forkContext.head);
119733 choiceContext.falseForkContext.add(forkContext.head);
119734 } // Update state.
119735
119736
119737 if (context.test !== true) {
119738 context.brokenForkContext.addAll(choiceContext.falseForkContext);
119739 }
119740
119741 forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1));
119742 }
119743 /**
119744 * Makes a code path segment for the body part of a DoWhileStatement.
119745 * @returns {void}
119746 */
119747
119748
119749 makeDoWhileBody() {
119750 const context = this.loopContext;
119751 const forkContext = this.forkContext;
119752 const bodySegments = forkContext.makeNext(-1, -1); // Update state.
119753
119754 context.entrySegments = bodySegments;
119755 forkContext.replaceHead(bodySegments);
119756 }
119757 /**
119758 * Makes a code path segment for the test part of a DoWhileStatement.
119759 * @param {boolean|undefined} test The test value (only when constant).
119760 * @returns {void}
119761 */
119762
119763
119764 makeDoWhileTest(test) {
119765 const context = this.loopContext;
119766 const forkContext = this.forkContext;
119767 context.test = test; // Creates paths of `continue` statements.
119768
119769 if (!context.continueForkContext.empty) {
119770 context.continueForkContext.add(forkContext.head);
119771 const testSegments = context.continueForkContext.makeNext(0, -1);
119772 forkContext.replaceHead(testSegments);
119773 }
119774 }
119775 /**
119776 * Makes a code path segment for the test part of a ForStatement.
119777 * @param {boolean|undefined} test The test value (only when constant).
119778 * @returns {void}
119779 */
119780
119781
119782 makeForTest(test) {
119783 const context = this.loopContext;
119784 const forkContext = this.forkContext;
119785 const endOfInitSegments = forkContext.head;
119786 const testSegments = forkContext.makeNext(-1, -1); // Update state.
119787
119788 context.test = test;
119789 context.endOfInitSegments = endOfInitSegments;
119790 context.continueDestSegments = context.testSegments = testSegments;
119791 forkContext.replaceHead(testSegments);
119792 }
119793 /**
119794 * Makes a code path segment for the update part of a ForStatement.
119795 * @returns {void}
119796 */
119797
119798
119799 makeForUpdate() {
119800 const context = this.loopContext;
119801 const choiceContext = this.choiceContext;
119802 const forkContext = this.forkContext; // Make the next paths of the test.
119803
119804 if (context.testSegments) {
119805 finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head);
119806 } else {
119807 context.endOfInitSegments = forkContext.head;
119808 } // Update state.
119809
119810
119811 const updateSegments = forkContext.makeDisconnected(-1, -1);
119812 context.continueDestSegments = context.updateSegments = updateSegments;
119813 forkContext.replaceHead(updateSegments);
119814 }
119815 /**
119816 * Makes a code path segment for the body part of a ForStatement.
119817 * @returns {void}
119818 */
119819
119820
119821 makeForBody() {
119822 const context = this.loopContext;
119823 const choiceContext = this.choiceContext;
119824 const forkContext = this.forkContext; // Update state.
119825
119826 if (context.updateSegments) {
119827 context.endOfUpdateSegments = forkContext.head; // `update` -> `test`
119828
119829 if (context.testSegments) {
119830 makeLooped(this, context.endOfUpdateSegments, context.testSegments);
119831 }
119832 } else if (context.testSegments) {
119833 finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head);
119834 } else {
119835 context.endOfInitSegments = forkContext.head;
119836 }
119837
119838 let bodySegments = context.endOfTestSegments;
119839
119840 if (!bodySegments) {
119841 /*
119842 * If there is not the `test` part, the `body` path comes from the
119843 * `init` part and the `update` part.
119844 */
119845 const prevForkContext = ForkContext.newEmpty(forkContext);
119846 prevForkContext.add(context.endOfInitSegments);
119847
119848 if (context.endOfUpdateSegments) {
119849 prevForkContext.add(context.endOfUpdateSegments);
119850 }
119851
119852 bodySegments = prevForkContext.makeNext(0, -1);
119853 }
119854
119855 context.continueDestSegments = context.continueDestSegments || bodySegments;
119856 forkContext.replaceHead(bodySegments);
119857 }
119858 /**
119859 * Makes a code path segment for the left part of a ForInStatement and a
119860 * ForOfStatement.
119861 * @returns {void}
119862 */
119863
119864
119865 makeForInOfLeft() {
119866 const context = this.loopContext;
119867 const forkContext = this.forkContext;
119868 const leftSegments = forkContext.makeDisconnected(-1, -1); // Update state.
119869
119870 context.prevSegments = forkContext.head;
119871 context.leftSegments = context.continueDestSegments = leftSegments;
119872 forkContext.replaceHead(leftSegments);
119873 }
119874 /**
119875 * Makes a code path segment for the right part of a ForInStatement and a
119876 * ForOfStatement.
119877 * @returns {void}
119878 */
119879
119880
119881 makeForInOfRight() {
119882 const context = this.loopContext;
119883 const forkContext = this.forkContext;
119884 const temp = ForkContext.newEmpty(forkContext);
119885 temp.add(context.prevSegments);
119886 const rightSegments = temp.makeNext(-1, -1); // Update state.
119887
119888 context.endOfLeftSegments = forkContext.head;
119889 forkContext.replaceHead(rightSegments);
119890 }
119891 /**
119892 * Makes a code path segment for the body part of a ForInStatement and a
119893 * ForOfStatement.
119894 * @returns {void}
119895 */
119896
119897
119898 makeForInOfBody() {
119899 const context = this.loopContext;
119900 const forkContext = this.forkContext;
119901 const temp = ForkContext.newEmpty(forkContext);
119902 temp.add(context.endOfLeftSegments);
119903 const bodySegments = temp.makeNext(-1, -1); // Make a path: `right` -> `left`.
119904
119905 makeLooped(this, forkContext.head, context.leftSegments); // Update state.
119906
119907 context.brokenForkContext.add(forkContext.head);
119908 forkContext.replaceHead(bodySegments);
119909 } //--------------------------------------------------------------------------
119910 // Control Statements
119911 //--------------------------------------------------------------------------
119912
119913 /**
119914 * Creates new context for BreakStatement.
119915 * @param {boolean} breakable The flag to indicate it can break by
119916 * an unlabeled BreakStatement.
119917 * @param {string|null} label The label of this context.
119918 * @returns {Object} The new context.
119919 */
119920
119921
119922 pushBreakContext(breakable, label) {
119923 this.breakContext = {
119924 upper: this.breakContext,
119925 breakable,
119926 label,
119927 brokenForkContext: ForkContext.newEmpty(this.forkContext)
119928 };
119929 return this.breakContext;
119930 }
119931 /**
119932 * Removes the top item of the break context stack.
119933 * @returns {Object} The removed context.
119934 */
119935
119936
119937 popBreakContext() {
119938 const context = this.breakContext;
119939 const forkContext = this.forkContext;
119940 this.breakContext = context.upper; // Process this context here for other than switches and loops.
119941
119942 if (!context.breakable) {
119943 const brokenForkContext = context.brokenForkContext;
119944
119945 if (!brokenForkContext.empty) {
119946 brokenForkContext.add(forkContext.head);
119947 forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
119948 }
119949 }
119950
119951 return context;
119952 }
119953 /**
119954 * Makes a path for a `break` statement.
119955 *
119956 * It registers the head segment to a context of `break`.
119957 * It makes new unreachable segment, then it set the head with the segment.
119958 * @param {string} label A label of the break statement.
119959 * @returns {void}
119960 */
119961
119962
119963 makeBreak(label) {
119964 const forkContext = this.forkContext;
119965
119966 if (!forkContext.reachable) {
119967 return;
119968 }
119969
119970 const context = getBreakContext(this, label);
119971 /* istanbul ignore else: foolproof (syntax error) */
119972
119973 if (context) {
119974 context.brokenForkContext.add(forkContext.head);
119975 }
119976
119977 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
119978 }
119979 /**
119980 * Makes a path for a `continue` statement.
119981 *
119982 * It makes a looping path.
119983 * It makes new unreachable segment, then it set the head with the segment.
119984 * @param {string} label A label of the continue statement.
119985 * @returns {void}
119986 */
119987
119988
119989 makeContinue(label) {
119990 const forkContext = this.forkContext;
119991
119992 if (!forkContext.reachable) {
119993 return;
119994 }
119995
119996 const context = getContinueContext(this, label);
119997 /* istanbul ignore else: foolproof (syntax error) */
119998
119999 if (context) {
120000 if (context.continueDestSegments) {
120001 makeLooped(this, forkContext.head, context.continueDestSegments); // If the context is a for-in/of loop, this effects a break also.
120002
120003 if (context.type === "ForInStatement" || context.type === "ForOfStatement") {
120004 context.brokenForkContext.add(forkContext.head);
120005 }
120006 } else {
120007 context.continueForkContext.add(forkContext.head);
120008 }
120009 }
120010
120011 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
120012 }
120013 /**
120014 * Makes a path for a `return` statement.
120015 *
120016 * It registers the head segment to a context of `return`.
120017 * It makes new unreachable segment, then it set the head with the segment.
120018 * @returns {void}
120019 */
120020
120021
120022 makeReturn() {
120023 const forkContext = this.forkContext;
120024
120025 if (forkContext.reachable) {
120026 getReturnContext(this).returnedForkContext.add(forkContext.head);
120027 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
120028 }
120029 }
120030 /**
120031 * Makes a path for a `throw` statement.
120032 *
120033 * It registers the head segment to a context of `throw`.
120034 * It makes new unreachable segment, then it set the head with the segment.
120035 * @returns {void}
120036 */
120037
120038
120039 makeThrow() {
120040 const forkContext = this.forkContext;
120041
120042 if (forkContext.reachable) {
120043 getThrowContext(this).thrownForkContext.add(forkContext.head);
120044 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
120045 }
120046 }
120047 /**
120048 * Makes the final path.
120049 * @returns {void}
120050 */
120051
120052
120053 makeFinal() {
120054 const segments = this.currentSegments;
120055
120056 if (segments.length > 0 && segments[0].reachable) {
120057 this.returnedForkContext.add(segments);
120058 }
120059 }
120060
120061}
120062
120063module.exports = CodePathState;
120064
120065/***/ }),
6a5a0f88 120066/* 794 */
eb39fafa
DC
120067/***/ (function(module, exports, __webpack_require__) {
120068
120069"use strict";
120070/**
120071 * @fileoverview A class of the code path segment.
120072 * @author Toru Nagashima
120073 */
120074 //------------------------------------------------------------------------------
120075// Requirements
120076//------------------------------------------------------------------------------
120077
6a5a0f88 120078const debug = __webpack_require__(795); //------------------------------------------------------------------------------
eb39fafa
DC
120079// Helpers
120080//------------------------------------------------------------------------------
120081
120082/**
120083 * Checks whether or not a given segment is reachable.
120084 * @param {CodePathSegment} segment A segment to check.
120085 * @returns {boolean} `true` if the segment is reachable.
120086 */
120087
120088
120089function isReachable(segment) {
120090 return segment.reachable;
120091} //------------------------------------------------------------------------------
120092// Public Interface
120093//------------------------------------------------------------------------------
120094
120095/**
120096 * A code path segment.
120097 */
120098
120099
120100class CodePathSegment {
120101 // eslint-disable-next-line jsdoc/require-description
120102
120103 /**
120104 * @param {string} id An identifier.
120105 * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
120106 * This array includes unreachable segments.
120107 * @param {boolean} reachable A flag which shows this is reachable.
120108 */
120109 constructor(id, allPrevSegments, reachable) {
120110 /**
120111 * The identifier of this code path.
120112 * Rules use it to store additional information of each rule.
120113 * @type {string}
120114 */
120115 this.id = id;
120116 /**
120117 * An array of the next segments.
120118 * @type {CodePathSegment[]}
120119 */
120120
120121 this.nextSegments = [];
120122 /**
120123 * An array of the previous segments.
120124 * @type {CodePathSegment[]}
120125 */
120126
120127 this.prevSegments = allPrevSegments.filter(isReachable);
120128 /**
120129 * An array of the next segments.
120130 * This array includes unreachable segments.
120131 * @type {CodePathSegment[]}
120132 */
120133
120134 this.allNextSegments = [];
120135 /**
120136 * An array of the previous segments.
120137 * This array includes unreachable segments.
120138 * @type {CodePathSegment[]}
120139 */
120140
120141 this.allPrevSegments = allPrevSegments;
120142 /**
120143 * A flag which shows this is reachable.
120144 * @type {boolean}
120145 */
120146
120147 this.reachable = reachable; // Internal data.
120148
120149 Object.defineProperty(this, "internal", {
120150 value: {
120151 used: false,
120152 loopedPrevSegments: []
120153 }
120154 });
120155 /* istanbul ignore if */
120156
120157 if (debug.enabled) {
120158 this.internal.nodes = [];
120159 this.internal.exitNodes = [];
120160 }
120161 }
120162 /**
120163 * Checks a given previous segment is coming from the end of a loop.
120164 * @param {CodePathSegment} segment A previous segment to check.
120165 * @returns {boolean} `true` if the segment is coming from the end of a loop.
120166 */
120167
120168
120169 isLoopedPrevSegment(segment) {
120170 return this.internal.loopedPrevSegments.indexOf(segment) !== -1;
120171 }
120172 /**
120173 * Creates the root segment.
120174 * @param {string} id An identifier.
120175 * @returns {CodePathSegment} The created segment.
120176 */
120177
120178
120179 static newRoot(id) {
120180 return new CodePathSegment(id, [], true);
120181 }
120182 /**
120183 * Creates a segment that follows given segments.
120184 * @param {string} id An identifier.
120185 * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
120186 * @returns {CodePathSegment} The created segment.
120187 */
120188
120189
120190 static newNext(id, allPrevSegments) {
120191 return new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), allPrevSegments.some(isReachable));
120192 }
120193 /**
120194 * Creates an unreachable segment that follows given segments.
120195 * @param {string} id An identifier.
120196 * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
120197 * @returns {CodePathSegment} The created segment.
120198 */
120199
120200
120201 static newUnreachable(id, allPrevSegments) {
120202 const segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false);
120203 /*
120204 * In `if (a) return a; foo();` case, the unreachable segment preceded by
120205 * the return statement is not used but must not be remove.
120206 */
120207
120208 CodePathSegment.markUsed(segment);
120209 return segment;
120210 }
120211 /**
120212 * Creates a segment that follows given segments.
120213 * This factory method does not connect with `allPrevSegments`.
120214 * But this inherits `reachable` flag.
120215 * @param {string} id An identifier.
120216 * @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
120217 * @returns {CodePathSegment} The created segment.
120218 */
120219
120220
120221 static newDisconnected(id, allPrevSegments) {
120222 return new CodePathSegment(id, [], allPrevSegments.some(isReachable));
120223 }
120224 /**
120225 * Makes a given segment being used.
120226 *
120227 * And this function registers the segment into the previous segments as a next.
120228 * @param {CodePathSegment} segment A segment to mark.
120229 * @returns {void}
120230 */
120231
120232
120233 static markUsed(segment) {
120234 if (segment.internal.used) {
120235 return;
120236 }
120237
120238 segment.internal.used = true;
120239 let i;
120240
120241 if (segment.reachable) {
120242 for (i = 0; i < segment.allPrevSegments.length; ++i) {
120243 const prevSegment = segment.allPrevSegments[i];
120244 prevSegment.allNextSegments.push(segment);
120245 prevSegment.nextSegments.push(segment);
120246 }
120247 } else {
120248 for (i = 0; i < segment.allPrevSegments.length; ++i) {
120249 segment.allPrevSegments[i].allNextSegments.push(segment);
120250 }
120251 }
120252 }
120253 /**
120254 * Marks a previous segment as looped.
120255 * @param {CodePathSegment} segment A segment.
120256 * @param {CodePathSegment} prevSegment A previous segment to mark.
120257 * @returns {void}
120258 */
120259
120260
120261 static markPrevSegmentAsLooped(segment, prevSegment) {
120262 segment.internal.loopedPrevSegments.push(prevSegment);
120263 }
120264 /**
120265 * Replaces unused segments with the previous segments of each unused segment.
120266 * @param {CodePathSegment[]} segments An array of segments to replace.
120267 * @returns {CodePathSegment[]} The replaced array.
120268 */
120269
120270
120271 static flattenUnusedSegments(segments) {
120272 const done = Object.create(null);
120273 const retv = [];
120274
120275 for (let i = 0; i < segments.length; ++i) {
120276 const segment = segments[i]; // Ignores duplicated.
120277
120278 if (done[segment.id]) {
120279 continue;
120280 } // Use previous segments if unused.
120281
120282
120283 if (!segment.internal.used) {
120284 for (let j = 0; j < segment.allPrevSegments.length; ++j) {
120285 const prevSegment = segment.allPrevSegments[j];
120286
120287 if (!done[prevSegment.id]) {
120288 done[prevSegment.id] = true;
120289 retv.push(prevSegment);
120290 }
120291 }
120292 } else {
120293 done[segment.id] = true;
120294 retv.push(segment);
120295 }
120296 }
120297
120298 return retv;
120299 }
120300
120301}
120302
120303module.exports = CodePathSegment;
120304
120305/***/ }),
6a5a0f88 120306/* 795 */
eb39fafa
DC
120307/***/ (function(module, exports, __webpack_require__) {
120308
120309"use strict";
120310/**
120311 * @fileoverview Helpers to debug for code path analysis.
120312 * @author Toru Nagashima
120313 */
120314 //------------------------------------------------------------------------------
120315// Requirements
120316//------------------------------------------------------------------------------
120317
120318const debug = __webpack_require__(416)("eslint:code-path"); //------------------------------------------------------------------------------
120319// Helpers
120320//------------------------------------------------------------------------------
120321
120322/**
120323 * Gets id of a given segment.
120324 * @param {CodePathSegment} segment A segment to get.
120325 * @returns {string} Id of the segment.
120326 */
120327
120328/* istanbul ignore next */
120329
120330
120331function getId(segment) {
120332 // eslint-disable-line jsdoc/require-jsdoc
120333 return segment.id + (segment.reachable ? "" : "!");
120334} //------------------------------------------------------------------------------
120335// Public Interface
120336//------------------------------------------------------------------------------
120337
120338
120339module.exports = {
120340 /**
120341 * A flag that debug dumping is enabled or not.
120342 * @type {boolean}
120343 */
120344 enabled: debug.enabled,
120345
120346 /**
120347 * Dumps given objects.
120348 * @param {...any} args objects to dump.
120349 * @returns {void}
120350 */
120351 dump: debug,
120352
120353 /**
120354 * Dumps the current analyzing state.
120355 * @param {ASTNode} node A node to dump.
120356 * @param {CodePathState} state A state to dump.
120357 * @param {boolean} leaving A flag whether or not it's leaving
120358 * @returns {void}
120359 */
120360 dumpState: !debug.enabled ? debug :
120361 /* istanbul ignore next */
120362 function (node, state, leaving) {
120363 for (let i = 0; i < state.currentSegments.length; ++i) {
120364 const segInternal = state.currentSegments[i].internal;
120365
120366 if (leaving) {
120367 segInternal.exitNodes.push(node);
120368 } else {
120369 segInternal.nodes.push(node);
120370 }
120371 }
120372
120373 debug(["".concat(state.currentSegments.map(getId).join(","), ")"), "".concat(node.type).concat(leaving ? ":exit" : "")].join(" "));
120374 },
120375
120376 /**
120377 * Dumps a DOT code of a given code path.
120378 * The DOT code can be visualized with Graphvis.
120379 * @param {CodePath} codePath A code path to dump.
120380 * @returns {void}
120381 * @see http://www.graphviz.org
120382 * @see http://www.webgraphviz.com
120383 */
120384 dumpDot: !debug.enabled ? debug :
120385 /* istanbul ignore next */
120386 function (codePath) {
120387 let text = "\n" + "digraph {\n" + "node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" + "initial[label=\"\",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n";
120388
120389 if (codePath.returnedSegments.length > 0) {
120390 text += "final[label=\"\",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n";
120391 }
120392
120393 if (codePath.thrownSegments.length > 0) {
120394 text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize];\n";
120395 }
120396
120397 const traceMap = Object.create(null);
120398 const arrows = this.makeDotArrows(codePath, traceMap);
120399
120400 for (const id in traceMap) {
120401 // eslint-disable-line guard-for-in
120402 const segment = traceMap[id];
120403 text += "".concat(id, "[");
120404
120405 if (segment.reachable) {
120406 text += "label=\"";
120407 } else {
120408 text += "style=\"rounded,dashed,filled\",fillcolor=\"#FF9800\",label=\"<<unreachable>>\\n";
120409 }
120410
120411 if (segment.internal.nodes.length > 0 || segment.internal.exitNodes.length > 0) {
120412 text += [].concat(segment.internal.nodes.map(node => {
120413 switch (node.type) {
120414 case "Identifier":
120415 return "".concat(node.type, " (").concat(node.name, ")");
120416
120417 case "Literal":
120418 return "".concat(node.type, " (").concat(node.value, ")");
120419
120420 default:
120421 return node.type;
120422 }
120423 }), segment.internal.exitNodes.map(node => {
120424 switch (node.type) {
120425 case "Identifier":
120426 return "".concat(node.type, ":exit (").concat(node.name, ")");
120427
120428 case "Literal":
120429 return "".concat(node.type, ":exit (").concat(node.value, ")");
120430
120431 default:
120432 return "".concat(node.type, ":exit");
120433 }
120434 })).join("\\n");
120435 } else {
120436 text += "????";
120437 }
120438
120439 text += "\"];\n";
120440 }
120441
120442 text += "".concat(arrows, "\n");
120443 text += "}";
120444 debug("DOT", text);
120445 },
120446
120447 /**
120448 * Makes a DOT code of a given code path.
120449 * The DOT code can be visualized with Graphvis.
120450 * @param {CodePath} codePath A code path to make DOT.
120451 * @param {Object} traceMap Optional. A map to check whether or not segments had been done.
120452 * @returns {string} A DOT code of the code path.
120453 */
120454 makeDotArrows(codePath, traceMap) {
120455 const stack = [[codePath.initialSegment, 0]];
120456 const done = traceMap || Object.create(null);
120457 let lastId = codePath.initialSegment.id;
120458 let text = "initial->".concat(codePath.initialSegment.id);
120459
120460 while (stack.length > 0) {
120461 const item = stack.pop();
120462 const segment = item[0];
120463 const index = item[1];
120464
120465 if (done[segment.id] && index === 0) {
120466 continue;
120467 }
120468
120469 done[segment.id] = segment;
120470 const nextSegment = segment.allNextSegments[index];
120471
120472 if (!nextSegment) {
120473 continue;
120474 }
120475
120476 if (lastId === segment.id) {
120477 text += "->".concat(nextSegment.id);
120478 } else {
120479 text += ";\n".concat(segment.id, "->").concat(nextSegment.id);
120480 }
120481
120482 lastId = nextSegment.id;
120483 stack.unshift([segment, 1 + index]);
120484 stack.push([nextSegment, 0]);
120485 }
120486
120487 codePath.returnedSegments.forEach(finalSegment => {
120488 if (lastId === finalSegment.id) {
120489 text += "->final";
120490 } else {
120491 text += ";\n".concat(finalSegment.id, "->final");
120492 }
120493
120494 lastId = null;
120495 });
120496 codePath.thrownSegments.forEach(finalSegment => {
120497 if (lastId === finalSegment.id) {
120498 text += "->thrown";
120499 } else {
120500 text += ";\n".concat(finalSegment.id, "->thrown");
120501 }
120502
120503 lastId = null;
120504 });
120505 return "".concat(text, ";");
120506 }
120507
120508};
120509
120510/***/ }),
6a5a0f88 120511/* 796 */
eb39fafa
DC
120512/***/ (function(module, exports, __webpack_require__) {
120513
120514"use strict";
120515/**
120516 * @fileoverview A class to operate forking.
120517 *
120518 * This is state of forking.
120519 * This has a fork list and manages it.
120520 *
120521 * @author Toru Nagashima
120522 */
120523 //------------------------------------------------------------------------------
120524// Requirements
120525//------------------------------------------------------------------------------
120526
120527const assert = __webpack_require__(379),
6a5a0f88 120528 CodePathSegment = __webpack_require__(794); //------------------------------------------------------------------------------
eb39fafa
DC
120529// Helpers
120530//------------------------------------------------------------------------------
120531
120532/**
120533 * Gets whether or not a given segment is reachable.
120534 * @param {CodePathSegment} segment A segment to get.
120535 * @returns {boolean} `true` if the segment is reachable.
120536 */
120537
120538
120539function isReachable(segment) {
120540 return segment.reachable;
120541}
120542/**
120543 * Creates new segments from the specific range of `context.segmentsList`.
120544 *
120545 * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and
120546 * `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`.
120547 * This `h` is from `b`, `d`, and `f`.
120548 * @param {ForkContext} context An instance.
120549 * @param {number} begin The first index of the previous segments.
120550 * @param {number} end The last index of the previous segments.
120551 * @param {Function} create A factory function of new segments.
120552 * @returns {CodePathSegment[]} New segments.
120553 */
120554
120555
120556function makeSegments(context, begin, end, create) {
120557 const list = context.segmentsList;
120558 const normalizedBegin = begin >= 0 ? begin : list.length + begin;
120559 const normalizedEnd = end >= 0 ? end : list.length + end;
120560 const segments = [];
120561
120562 for (let i = 0; i < context.count; ++i) {
120563 const allPrevSegments = [];
120564
120565 for (let j = normalizedBegin; j <= normalizedEnd; ++j) {
120566 allPrevSegments.push(list[j][i]);
120567 }
120568
120569 segments.push(create(context.idGenerator.next(), allPrevSegments));
120570 }
120571
120572 return segments;
120573}
120574/**
120575 * `segments` becomes doubly in a `finally` block. Then if a code path exits by a
120576 * control statement (such as `break`, `continue`) from the `finally` block, the
120577 * destination's segments may be half of the source segments. In that case, this
120578 * merges segments.
120579 * @param {ForkContext} context An instance.
120580 * @param {CodePathSegment[]} segments Segments to merge.
120581 * @returns {CodePathSegment[]} The merged segments.
120582 */
120583
120584
120585function mergeExtraSegments(context, segments) {
120586 let currentSegments = segments;
120587
120588 while (currentSegments.length > context.count) {
120589 const merged = [];
120590
120591 for (let i = 0, length = currentSegments.length / 2 | 0; i < length; ++i) {
120592 merged.push(CodePathSegment.newNext(context.idGenerator.next(), [currentSegments[i], currentSegments[i + length]]));
120593 }
120594
120595 currentSegments = merged;
120596 }
120597
120598 return currentSegments;
120599} //------------------------------------------------------------------------------
120600// Public Interface
120601//------------------------------------------------------------------------------
120602
120603/**
120604 * A class to manage forking.
120605 */
120606
120607
120608class ForkContext {
120609 // eslint-disable-next-line jsdoc/require-description
120610
120611 /**
120612 * @param {IdGenerator} idGenerator An identifier generator for segments.
120613 * @param {ForkContext|null} upper An upper fork context.
120614 * @param {number} count A number of parallel segments.
120615 */
120616 constructor(idGenerator, upper, count) {
120617 this.idGenerator = idGenerator;
120618 this.upper = upper;
120619 this.count = count;
120620 this.segmentsList = [];
120621 }
120622 /**
120623 * The head segments.
120624 * @type {CodePathSegment[]}
120625 */
120626
120627
120628 get head() {
120629 const list = this.segmentsList;
120630 return list.length === 0 ? [] : list[list.length - 1];
120631 }
120632 /**
120633 * A flag which shows empty.
120634 * @type {boolean}
120635 */
120636
120637
120638 get empty() {
120639 return this.segmentsList.length === 0;
120640 }
120641 /**
120642 * A flag which shows reachable.
120643 * @type {boolean}
120644 */
120645
120646
120647 get reachable() {
120648 const segments = this.head;
120649 return segments.length > 0 && segments.some(isReachable);
120650 }
120651 /**
120652 * Creates new segments from this context.
120653 * @param {number} begin The first index of previous segments.
120654 * @param {number} end The last index of previous segments.
120655 * @returns {CodePathSegment[]} New segments.
120656 */
120657
120658
120659 makeNext(begin, end) {
120660 return makeSegments(this, begin, end, CodePathSegment.newNext);
120661 }
120662 /**
120663 * Creates new segments from this context.
120664 * The new segments is always unreachable.
120665 * @param {number} begin The first index of previous segments.
120666 * @param {number} end The last index of previous segments.
120667 * @returns {CodePathSegment[]} New segments.
120668 */
120669
120670
120671 makeUnreachable(begin, end) {
120672 return makeSegments(this, begin, end, CodePathSegment.newUnreachable);
120673 }
120674 /**
120675 * Creates new segments from this context.
120676 * The new segments don't have connections for previous segments.
120677 * But these inherit the reachable flag from this context.
120678 * @param {number} begin The first index of previous segments.
120679 * @param {number} end The last index of previous segments.
120680 * @returns {CodePathSegment[]} New segments.
120681 */
120682
120683
120684 makeDisconnected(begin, end) {
120685 return makeSegments(this, begin, end, CodePathSegment.newDisconnected);
120686 }
120687 /**
120688 * Adds segments into this context.
120689 * The added segments become the head.
120690 * @param {CodePathSegment[]} segments Segments to add.
120691 * @returns {void}
120692 */
120693
120694
120695 add(segments) {
120696 assert(segments.length >= this.count, "".concat(segments.length, " >= ").concat(this.count));
120697 this.segmentsList.push(mergeExtraSegments(this, segments));
120698 }
120699 /**
120700 * Replaces the head segments with given segments.
120701 * The current head segments are removed.
120702 * @param {CodePathSegment[]} segments Segments to add.
120703 * @returns {void}
120704 */
120705
120706
120707 replaceHead(segments) {
120708 assert(segments.length >= this.count, "".concat(segments.length, " >= ").concat(this.count));
120709 this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments));
120710 }
120711 /**
120712 * Adds all segments of a given fork context into this context.
120713 * @param {ForkContext} context A fork context to add.
120714 * @returns {void}
120715 */
120716
120717
120718 addAll(context) {
120719 assert(context.count === this.count);
120720 const source = context.segmentsList;
120721
120722 for (let i = 0; i < source.length; ++i) {
120723 this.segmentsList.push(source[i]);
120724 }
120725 }
120726 /**
120727 * Clears all segments in this context.
120728 * @returns {void}
120729 */
120730
120731
120732 clear() {
120733 this.segmentsList = [];
120734 }
120735 /**
120736 * Creates the root fork context.
120737 * @param {IdGenerator} idGenerator An identifier generator for segments.
120738 * @returns {ForkContext} New fork context.
120739 */
120740
120741
120742 static newRoot(idGenerator) {
120743 const context = new ForkContext(idGenerator, null, 1);
120744 context.add([CodePathSegment.newRoot(idGenerator.next())]);
120745 return context;
120746 }
120747 /**
120748 * Creates an empty fork context preceded by a given context.
120749 * @param {ForkContext} parentContext The parent fork context.
120750 * @param {boolean} forkLeavingPath A flag which shows inside of `finally` block.
120751 * @returns {ForkContext} New fork context.
120752 */
120753
120754
120755 static newEmpty(parentContext, forkLeavingPath) {
120756 return new ForkContext(parentContext.idGenerator, parentContext, (forkLeavingPath ? 2 : 1) * parentContext.count);
120757 }
120758
120759}
120760
120761module.exports = ForkContext;
120762
120763/***/ }),
6a5a0f88 120764/* 797 */
eb39fafa
DC
120765/***/ (function(module, exports, __webpack_require__) {
120766
120767"use strict";
120768/**
120769 * @fileoverview A class of identifiers generator for code path segments.
120770 *
120771 * Each rule uses the identifier of code path segments to store additional
120772 * information of the code path.
120773 *
120774 * @author Toru Nagashima
120775 */
120776 //------------------------------------------------------------------------------
120777// Public Interface
120778//------------------------------------------------------------------------------
120779
120780/**
120781 * A generator for unique ids.
120782 */
120783
120784class IdGenerator {
120785 // eslint-disable-next-line jsdoc/require-description
120786
120787 /**
120788 * @param {string} prefix Optional. A prefix of generated ids.
120789 */
120790 constructor(prefix) {
120791 this.prefix = String(prefix);
120792 this.n = 0;
120793 }
120794 /**
120795 * Generates id.
120796 * @returns {string} A generated id.
120797 */
120798
120799
120800 next() {
120801 this.n = 1 + this.n | 0;
120802 /* istanbul ignore if */
120803
120804 if (this.n < 0) {
120805 this.n = 1;
120806 }
120807
120808 return this.prefix + this.n;
120809 }
120810
120811}
120812
120813module.exports = IdGenerator;
120814
120815/***/ }),
6a5a0f88 120816/* 798 */
eb39fafa
DC
120817/***/ (function(module, exports, __webpack_require__) {
120818
120819"use strict";
120820/**
120821 * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments
120822 * @author Teddy Katz
120823 */
120824
120825
120826const lodash = __webpack_require__(403);
120827/**
120828 * Compares the locations of two objects in a source file
120829 * @param {{line: number, column: number}} itemA The first object
120830 * @param {{line: number, column: number}} itemB The second object
120831 * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if
120832 * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location.
120833 */
120834
120835
120836function compareLocations(itemA, itemB) {
120837 return itemA.line - itemB.line || itemA.column - itemB.column;
120838}
120839/**
120840 * This is the same as the exported function, except that it
120841 * doesn't handle disable-line and disable-next-line directives, and it always reports unused
120842 * disable directives.
120843 * @param {Object} options options for applying directives. This is the same as the options
120844 * for the exported function, except that `reportUnusedDisableDirectives` is not supported
120845 * (this function always reports unused disable directives).
120846 * @returns {{problems: Problem[], unusedDisableDirectives: Problem[]}} An object with a list
120847 * of filtered problems and unused eslint-disable directives
120848 */
120849
120850
120851function applyDirectives(options) {
120852 const problems = [];
120853 let nextDirectiveIndex = 0;
120854 let currentGlobalDisableDirective = null;
120855 const disabledRuleMap = new Map(); // enabledRules is only used when there is a current global disable directive.
120856
120857 const enabledRules = new Set();
120858 const usedDisableDirectives = new Set();
120859
120860 for (const problem of options.problems) {
120861 while (nextDirectiveIndex < options.directives.length && compareLocations(options.directives[nextDirectiveIndex], problem) <= 0) {
120862 const directive = options.directives[nextDirectiveIndex++];
120863
120864 switch (directive.type) {
120865 case "disable":
120866 if (directive.ruleId === null) {
120867 currentGlobalDisableDirective = directive;
120868 disabledRuleMap.clear();
120869 enabledRules.clear();
120870 } else if (currentGlobalDisableDirective) {
120871 enabledRules.delete(directive.ruleId);
120872 disabledRuleMap.set(directive.ruleId, directive);
120873 } else {
120874 disabledRuleMap.set(directive.ruleId, directive);
120875 }
120876
120877 break;
120878
120879 case "enable":
120880 if (directive.ruleId === null) {
120881 currentGlobalDisableDirective = null;
120882 disabledRuleMap.clear();
120883 } else if (currentGlobalDisableDirective) {
120884 enabledRules.add(directive.ruleId);
120885 disabledRuleMap.delete(directive.ruleId);
120886 } else {
120887 disabledRuleMap.delete(directive.ruleId);
120888 }
120889
120890 break;
120891 // no default
120892 }
120893 }
120894
120895 if (disabledRuleMap.has(problem.ruleId)) {
120896 usedDisableDirectives.add(disabledRuleMap.get(problem.ruleId));
120897 } else if (currentGlobalDisableDirective && !enabledRules.has(problem.ruleId)) {
120898 usedDisableDirectives.add(currentGlobalDisableDirective);
120899 } else {
120900 problems.push(problem);
120901 }
120902 }
120903
120904 const unusedDisableDirectives = options.directives.filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive)).map(directive => ({
120905 ruleId: null,
120906 message: directive.ruleId ? "Unused eslint-disable directive (no problems were reported from '".concat(directive.ruleId, "').") : "Unused eslint-disable directive (no problems were reported).",
120907 line: directive.unprocessedDirective.line,
120908 column: directive.unprocessedDirective.column,
120909 severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2,
120910 nodeType: null
120911 }));
120912 return {
120913 problems,
120914 unusedDisableDirectives
120915 };
120916}
120917/**
120918 * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list
120919 * of reported problems, determines which problems should be reported.
120920 * @param {Object} options Information about directives and problems
120921 * @param {{
120922 * type: ("disable"|"enable"|"disable-line"|"disable-next-line"),
120923 * ruleId: (string|null),
120924 * line: number,
120925 * column: number
120926 * }} options.directives Directive comments found in the file, with one-based columns.
120927 * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable
120928 * comment for two different rules is represented as two directives).
120929 * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems
120930 * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns.
120931 * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives
120932 * @returns {{ruleId: (string|null), line: number, column: number}[]}
120933 * A list of reported problems that were not disabled by the directive comments.
120934 */
120935
120936
120937module.exports = ({
120938 directives,
120939 problems,
120940 reportUnusedDisableDirectives = "off"
120941}) => {
120942 const blockDirectives = directives.filter(directive => directive.type === "disable" || directive.type === "enable").map(directive => Object.assign({}, directive, {
120943 unprocessedDirective: directive
120944 })).sort(compareLocations);
120945 const lineDirectives = lodash.flatMap(directives, directive => {
120946 switch (directive.type) {
120947 case "disable":
120948 case "enable":
120949 return [];
120950
120951 case "disable-line":
120952 return [{
120953 type: "disable",
120954 line: directive.line,
120955 column: 1,
120956 ruleId: directive.ruleId,
120957 unprocessedDirective: directive
120958 }, {
120959 type: "enable",
120960 line: directive.line + 1,
120961 column: 0,
120962 ruleId: directive.ruleId,
120963 unprocessedDirective: directive
120964 }];
120965
120966 case "disable-next-line":
120967 return [{
120968 type: "disable",
120969 line: directive.line + 1,
120970 column: 1,
120971 ruleId: directive.ruleId,
120972 unprocessedDirective: directive
120973 }, {
120974 type: "enable",
120975 line: directive.line + 2,
120976 column: 0,
120977 ruleId: directive.ruleId,
120978 unprocessedDirective: directive
120979 }];
120980
120981 default:
120982 throw new TypeError("Unrecognized directive type '".concat(directive.type, "'"));
120983 }
120984 }).sort(compareLocations);
120985 const blockDirectivesResult = applyDirectives({
120986 problems,
120987 directives: blockDirectives,
120988 reportUnusedDisableDirectives
120989 });
120990 const lineDirectivesResult = applyDirectives({
120991 problems: blockDirectivesResult.problems,
120992 directives: lineDirectives,
120993 reportUnusedDisableDirectives
120994 });
120995 return reportUnusedDisableDirectives !== "off" ? lineDirectivesResult.problems.concat(blockDirectivesResult.unusedDisableDirectives).concat(lineDirectivesResult.unusedDisableDirectives).sort(compareLocations) : lineDirectivesResult.problems;
120996};
120997
120998/***/ }),
6a5a0f88 120999/* 799 */
eb39fafa
DC
121000/***/ (function(module, exports, __webpack_require__) {
121001
121002"use strict";
121003/**
121004 * @fileoverview Config Comment Parser
121005 * @author Nicholas C. Zakas
121006 */
121007
121008/* eslint-disable class-methods-use-this*/
121009 //------------------------------------------------------------------------------
121010// Requirements
121011//------------------------------------------------------------------------------
121012
6a5a0f88 121013const levn = __webpack_require__(800),
eb39fafa
DC
121014 ConfigOps = __webpack_require__(410);
121015
121016const debug = __webpack_require__(416)("eslint:config-comment-parser"); //------------------------------------------------------------------------------
121017// Public Interface
121018//------------------------------------------------------------------------------
121019
121020/**
121021 * Object to parse ESLint configuration comments inside JavaScript files.
121022 * @name ConfigCommentParser
121023 */
121024
121025
121026module.exports = class ConfigCommentParser {
121027 /**
121028 * Parses a list of "name:string_value" or/and "name" options divided by comma or
121029 * whitespace. Used for "global" and "exported" comments.
121030 * @param {string} string The string to parse.
121031 * @param {Comment} comment The comment node which has the string.
121032 * @returns {Object} Result map object of names and string values, or null values if no value was provided
121033 */
121034 parseStringConfig(string, comment) {
121035 debug("Parsing String config");
121036 const items = {}; // Collapse whitespace around `:` and `,` to make parsing easier
121037
121038 const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1");
121039 trimmedString.split(/\s|,+/u).forEach(name => {
121040 if (!name) {
121041 return;
121042 } // value defaults to null (if not provided), e.g: "foo" => ["foo", null]
121043
121044
121045 const [key, value = null] = name.split(":");
121046 items[key] = {
121047 value,
121048 comment
121049 };
121050 });
121051 return items;
121052 }
121053 /**
121054 * Parses a JSON-like config.
121055 * @param {string} string The string to parse.
121056 * @param {Object} location Start line and column of comments for potential error message.
121057 * @returns {({success: true, config: Object}|{success: false, error: Problem})} Result map object
121058 */
121059
121060
121061 parseJsonConfig(string, location) {
121062 debug("Parsing JSON config");
121063 let items = {}; // Parses a JSON-like comment by the same way as parsing CLI option.
121064
121065 try {
121066 items = levn.parse("Object", string) || {}; // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`.
121067 // Also, commaless notations have invalid severity:
121068 // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"}
121069 // Should ignore that case as well.
121070
121071 if (ConfigOps.isEverySeverityValid(items)) {
121072 return {
121073 success: true,
121074 config: items
121075 };
121076 }
121077 } catch (ex) {
121078 debug("Levn parsing failed; falling back to manual parsing."); // ignore to parse the string by a fallback.
121079 }
121080 /*
121081 * Optionator cannot parse commaless notations.
121082 * But we are supporting that. So this is a fallback for that.
121083 */
121084
121085
121086 items = {};
121087 const normalizedString = string.replace(/([-a-zA-Z0-9/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,");
121088
121089 try {
121090 items = JSON.parse("{".concat(normalizedString, "}"));
121091 } catch (ex) {
121092 debug("Manual parsing failed.");
121093 return {
121094 success: false,
121095 error: {
121096 ruleId: null,
121097 fatal: true,
121098 severity: 2,
121099 message: "Failed to parse JSON from '".concat(normalizedString, "': ").concat(ex.message),
121100 line: location.start.line,
121101 column: location.start.column + 1
121102 }
121103 };
121104 }
121105
121106 return {
121107 success: true,
121108 config: items
121109 };
121110 }
121111 /**
121112 * Parses a config of values separated by comma.
121113 * @param {string} string The string to parse.
121114 * @returns {Object} Result map of values and true values
121115 */
121116
121117
121118 parseListConfig(string) {
121119 debug("Parsing list config");
121120 const items = {}; // Collapse whitespace around commas
121121
121122 string.replace(/\s*,\s*/gu, ",").split(/,+/u).forEach(name => {
121123 const trimmedName = name.trim();
121124
121125 if (trimmedName) {
121126 items[trimmedName] = true;
121127 }
121128 });
121129 return items;
121130 }
121131
121132};
121133
121134/***/ }),
6a5a0f88 121135/* 800 */
eb39fafa
DC
121136/***/ (function(module, exports, __webpack_require__) {
121137
56c4a2cb 121138// Generated by LiveScript 1.6.0
eb39fafa
DC
121139(function () {
121140 var parseString, cast, parseType, VERSION, parsedTypeParse, parse;
6a5a0f88
TL
121141 parseString = __webpack_require__(801);
121142 cast = __webpack_require__(808);
121143 parseType = __webpack_require__(809).parseType;
56c4a2cb 121144 VERSION = '0.4.1';
eb39fafa
DC
121145
121146 parsedTypeParse = function parsedTypeParse(parsedType, string, options) {
121147 options == null && (options = {});
121148 options.explicit == null && (options.explicit = false);
121149 options.customTypes == null && (options.customTypes = {});
121150 return cast(parseString(parsedType, string, options), parsedType, options);
121151 };
121152
121153 parse = function parse(type, string, options) {
121154 return parsedTypeParse(parseType(type), string, options);
121155 };
121156
121157 module.exports = {
121158 VERSION: VERSION,
121159 parse: parse,
121160 parsedTypeParse: parsedTypeParse
121161 };
121162}).call(this);
121163
121164/***/ }),
6a5a0f88 121165/* 801 */
eb39fafa
DC
121166/***/ (function(module, exports, __webpack_require__) {
121167
56c4a2cb 121168// Generated by LiveScript 1.6.0
eb39fafa
DC
121169(function () {
121170 var reject, special, tokenRegex;
6a5a0f88 121171 reject = __webpack_require__(802).reject;
eb39fafa
DC
121172
121173 function consumeOp(tokens, op) {
121174 if (tokens[0] === op) {
121175 return tokens.shift();
121176 } else {
121177 throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
121178 }
121179 }
121180
121181 function maybeConsumeOp(tokens, op) {
121182 if (tokens[0] === op) {
121183 return tokens.shift();
121184 }
121185 }
121186
121187 function consumeList(tokens, arg$, hasDelimiters) {
121188 var open, close, result, untilTest;
121189 open = arg$[0], close = arg$[1];
121190
121191 if (hasDelimiters) {
121192 consumeOp(tokens, open);
121193 }
121194
121195 result = [];
121196 untilTest = "," + (hasDelimiters ? close : '');
121197
121198 while (tokens.length && hasDelimiters && tokens[0] !== close) {
121199 result.push(consumeElement(tokens, untilTest));
121200 maybeConsumeOp(tokens, ',');
121201 }
121202
121203 if (hasDelimiters) {
121204 consumeOp(tokens, close);
121205 }
121206
121207 return result;
121208 }
121209
121210 function consumeArray(tokens, hasDelimiters) {
121211 return consumeList(tokens, ['[', ']'], hasDelimiters);
121212 }
121213
121214 function consumeTuple(tokens, hasDelimiters) {
121215 return consumeList(tokens, ['(', ')'], hasDelimiters);
121216 }
121217
121218 function consumeFields(tokens, hasDelimiters) {
121219 var result, untilTest, key;
121220
121221 if (hasDelimiters) {
121222 consumeOp(tokens, '{');
121223 }
121224
121225 result = {};
121226 untilTest = "," + (hasDelimiters ? '}' : '');
121227
121228 while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
121229 key = consumeValue(tokens, ':');
121230 consumeOp(tokens, ':');
121231 result[key] = consumeElement(tokens, untilTest);
121232 maybeConsumeOp(tokens, ',');
121233 }
121234
121235 if (hasDelimiters) {
121236 consumeOp(tokens, '}');
121237 }
121238
121239 return result;
121240 }
121241
121242 function consumeValue(tokens, untilTest) {
121243 var out;
121244 untilTest == null && (untilTest = '');
121245 out = '';
121246
121247 while (tokens.length && -1 === untilTest.indexOf(tokens[0])) {
121248 out += tokens.shift();
121249 }
121250
121251 return out;
121252 }
121253
121254 function consumeElement(tokens, untilTest) {
121255 switch (tokens[0]) {
121256 case '[':
121257 return consumeArray(tokens, true);
121258
121259 case '(':
121260 return consumeTuple(tokens, true);
121261
121262 case '{':
121263 return consumeFields(tokens, true);
121264
121265 default:
121266 return consumeValue(tokens, untilTest);
121267 }
121268 }
121269
121270 function consumeTopLevel(tokens, types, options) {
121271 var ref$, type, structure, origTokens, result, finalResult, x$, y$;
121272 ref$ = types[0], type = ref$.type, structure = ref$.structure;
121273 origTokens = tokens.concat();
121274
121275 if (!options.explicit && types.length === 1 && (!type && structure || type === 'Array' || type === 'Object')) {
121276 result = structure === 'array' || type === 'Array' ? consumeArray(tokens, tokens[0] === '[') : structure === 'tuple' ? consumeTuple(tokens, tokens[0] === '(') : consumeFields(tokens, tokens[0] === '{');
121277 finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array' ? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$) : (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
121278 } else {
121279 finalResult = consumeElement(tokens);
121280 }
121281
121282 return finalResult;
121283 }
121284
121285 special = /\[\]\(\)}{:,/.source;
121286 tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*');
121287
121288 module.exports = function (types, string, options) {
121289 var tokens, node;
121290 options == null && (options = {});
121291
121292 if (!options.explicit && types.length === 1 && types[0].type === 'String') {
56c4a2cb 121293 return string;
eb39fafa
DC
121294 }
121295
121296 tokens = reject(not$, string.split(tokenRegex));
121297 node = consumeTopLevel(tokens, types, options);
121298
121299 if (!node) {
121300 throw new Error("Error parsing '" + string + "'.");
121301 }
121302
121303 return node;
121304 };
121305
121306 function not$(x) {
121307 return !x;
121308 }
121309}).call(this);
121310
121311/***/ }),
6a5a0f88 121312/* 802 */
eb39fafa
DC
121313/***/ (function(module, exports, __webpack_require__) {
121314
56c4a2cb 121315// Generated by LiveScript 1.6.0
eb39fafa
DC
121316var Func,
121317 List,
121318 Obj,
121319 Str,
121320 Num,
121321 id,
121322 isType,
121323 replicate,
121324 prelude,
121325 toString$ = {}.toString;
6a5a0f88
TL
121326Func = __webpack_require__(803);
121327List = __webpack_require__(804);
121328Obj = __webpack_require__(805);
121329Str = __webpack_require__(806);
121330Num = __webpack_require__(807);
eb39fafa
DC
121331
121332id = function id(x) {
121333 return x;
121334};
121335
121336isType = curry$(function (type, x) {
121337 return toString$.call(x).slice(8, -1) === type;
121338});
121339replicate = curry$(function (n, x) {
121340 var i$,
121341 results$ = [];
121342
121343 for (i$ = 0; i$ < n; ++i$) {
121344 results$.push(x);
121345 }
121346
121347 return results$;
121348});
121349Str.empty = List.empty;
121350Str.slice = List.slice;
121351Str.take = List.take;
121352Str.drop = List.drop;
121353Str.splitAt = List.splitAt;
121354Str.takeWhile = List.takeWhile;
121355Str.dropWhile = List.dropWhile;
121356Str.span = List.span;
121357Str.breakStr = List.breakList;
121358prelude = {
121359 Func: Func,
121360 List: List,
121361 Obj: Obj,
121362 Str: Str,
121363 Num: Num,
121364 id: id,
121365 isType: isType,
121366 replicate: replicate
121367};
121368prelude.each = List.each;
121369prelude.map = List.map;
121370prelude.filter = List.filter;
121371prelude.compact = List.compact;
121372prelude.reject = List.reject;
121373prelude.partition = List.partition;
121374prelude.find = List.find;
121375prelude.head = List.head;
121376prelude.first = List.first;
121377prelude.tail = List.tail;
121378prelude.last = List.last;
121379prelude.initial = List.initial;
121380prelude.empty = List.empty;
121381prelude.reverse = List.reverse;
121382prelude.difference = List.difference;
121383prelude.intersection = List.intersection;
121384prelude.union = List.union;
121385prelude.countBy = List.countBy;
121386prelude.groupBy = List.groupBy;
121387prelude.fold = List.fold;
121388prelude.foldl = List.foldl;
121389prelude.fold1 = List.fold1;
121390prelude.foldl1 = List.foldl1;
121391prelude.foldr = List.foldr;
121392prelude.foldr1 = List.foldr1;
121393prelude.unfoldr = List.unfoldr;
121394prelude.andList = List.andList;
121395prelude.orList = List.orList;
121396prelude.any = List.any;
121397prelude.all = List.all;
121398prelude.unique = List.unique;
121399prelude.uniqueBy = List.uniqueBy;
121400prelude.sort = List.sort;
121401prelude.sortWith = List.sortWith;
121402prelude.sortBy = List.sortBy;
121403prelude.sum = List.sum;
121404prelude.product = List.product;
121405prelude.mean = List.mean;
121406prelude.average = List.average;
121407prelude.concat = List.concat;
121408prelude.concatMap = List.concatMap;
121409prelude.flatten = List.flatten;
121410prelude.maximum = List.maximum;
121411prelude.minimum = List.minimum;
121412prelude.maximumBy = List.maximumBy;
121413prelude.minimumBy = List.minimumBy;
121414prelude.scan = List.scan;
121415prelude.scanl = List.scanl;
121416prelude.scan1 = List.scan1;
121417prelude.scanl1 = List.scanl1;
121418prelude.scanr = List.scanr;
121419prelude.scanr1 = List.scanr1;
121420prelude.slice = List.slice;
121421prelude.take = List.take;
121422prelude.drop = List.drop;
121423prelude.splitAt = List.splitAt;
121424prelude.takeWhile = List.takeWhile;
121425prelude.dropWhile = List.dropWhile;
121426prelude.span = List.span;
121427prelude.breakList = List.breakList;
121428prelude.zip = List.zip;
121429prelude.zipWith = List.zipWith;
121430prelude.zipAll = List.zipAll;
121431prelude.zipAllWith = List.zipAllWith;
121432prelude.at = List.at;
121433prelude.elemIndex = List.elemIndex;
121434prelude.elemIndices = List.elemIndices;
121435prelude.findIndex = List.findIndex;
121436prelude.findIndices = List.findIndices;
121437prelude.apply = Func.apply;
121438prelude.curry = Func.curry;
121439prelude.flip = Func.flip;
121440prelude.fix = Func.fix;
121441prelude.over = Func.over;
121442prelude.split = Str.split;
121443prelude.join = Str.join;
121444prelude.lines = Str.lines;
121445prelude.unlines = Str.unlines;
121446prelude.words = Str.words;
121447prelude.unwords = Str.unwords;
121448prelude.chars = Str.chars;
121449prelude.unchars = Str.unchars;
121450prelude.repeat = Str.repeat;
121451prelude.capitalize = Str.capitalize;
121452prelude.camelize = Str.camelize;
121453prelude.dasherize = Str.dasherize;
121454prelude.values = Obj.values;
121455prelude.keys = Obj.keys;
121456prelude.pairsToObj = Obj.pairsToObj;
121457prelude.objToPairs = Obj.objToPairs;
121458prelude.listsToObj = Obj.listsToObj;
121459prelude.objToLists = Obj.objToLists;
121460prelude.max = Num.max;
121461prelude.min = Num.min;
121462prelude.negate = Num.negate;
121463prelude.abs = Num.abs;
121464prelude.signum = Num.signum;
121465prelude.quot = Num.quot;
121466prelude.rem = Num.rem;
121467prelude.div = Num.div;
121468prelude.mod = Num.mod;
121469prelude.recip = Num.recip;
121470prelude.pi = Num.pi;
121471prelude.tau = Num.tau;
121472prelude.exp = Num.exp;
121473prelude.sqrt = Num.sqrt;
121474prelude.ln = Num.ln;
121475prelude.pow = Num.pow;
121476prelude.sin = Num.sin;
121477prelude.tan = Num.tan;
121478prelude.cos = Num.cos;
121479prelude.acos = Num.acos;
121480prelude.asin = Num.asin;
121481prelude.atan = Num.atan;
121482prelude.atan2 = Num.atan2;
121483prelude.truncate = Num.truncate;
121484prelude.round = Num.round;
121485prelude.ceiling = Num.ceiling;
121486prelude.floor = Num.floor;
121487prelude.isItNaN = Num.isItNaN;
121488prelude.even = Num.even;
121489prelude.odd = Num.odd;
121490prelude.gcd = Num.gcd;
121491prelude.lcm = Num.lcm;
56c4a2cb 121492prelude.VERSION = '1.2.1';
eb39fafa
DC
121493module.exports = prelude;
121494
121495function curry$(f, bound) {
121496 var context,
121497 _curry = function _curry(args) {
121498 return f.length > 1 ? function () {
121499 var params = args ? args.concat() : [];
121500 context = bound ? context || this : this;
121501 return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params);
121502 } : f;
121503 };
121504
121505 return _curry();
121506}
121507
121508/***/ }),
6a5a0f88 121509/* 803 */
eb39fafa
DC
121510/***/ (function(module, exports) {
121511
56c4a2cb 121512// Generated by LiveScript 1.6.0
eb39fafa
DC
121513var apply,
121514 curry,
121515 flip,
121516 fix,
121517 over,
121518 memoize,
eb39fafa
DC
121519 toString$ = {}.toString;
121520apply = curry$(function (f, list) {
121521 return f.apply(null, list);
121522});
121523
121524curry = function curry(f) {
121525 return curry$(f);
121526};
121527
121528flip = curry$(function (f, x, y) {
121529 return f(y, x);
121530});
121531
121532fix = function fix(f) {
121533 return function (g) {
121534 return function () {
121535 return f(g(g)).apply(null, arguments);
121536 };
121537 }(function (g) {
121538 return function () {
121539 return f(g(g)).apply(null, arguments);
121540 };
121541 });
121542};
121543
121544over = curry$(function (f, g, x, y) {
121545 return f(g(x), g(y));
121546});
121547
121548memoize = function memoize(f) {
121549 var memo;
121550 memo = {};
121551 return function () {
56c4a2cb
DC
121552 var args, res$, i$, to$, key, arg;
121553 res$ = [];
121554
121555 for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) {
121556 res$.push(arguments[i$]);
121557 }
121558
121559 args = res$;
eb39fafa
DC
121560
121561 key = function () {
121562 var i$,
121563 ref$,
121564 len$,
121565 results$ = [];
121566
121567 for (i$ = 0, len$ = (ref$ = args).length; i$ < len$; ++i$) {
121568 arg = ref$[i$];
121569 results$.push(arg + toString$.call(arg).slice(8, -1));
121570 }
121571
121572 return results$;
121573 }().join('');
121574
121575 return memo[key] = key in memo ? memo[key] : f.apply(null, args);
121576 };
121577};
121578
121579module.exports = {
121580 curry: curry,
121581 flip: flip,
121582 fix: fix,
121583 apply: apply,
121584 over: over,
121585 memoize: memoize
121586};
121587
121588function curry$(f, bound) {
121589 var context,
121590 _curry = function _curry(args) {
121591 return f.length > 1 ? function () {
121592 var params = args ? args.concat() : [];
121593 context = bound ? context || this : this;
121594 return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params);
121595 } : f;
121596 };
121597
121598 return _curry();
121599}
121600
121601/***/ }),
6a5a0f88 121602/* 804 */
eb39fafa
DC
121603/***/ (function(module, exports) {
121604
56c4a2cb 121605// Generated by LiveScript 1.6.0
eb39fafa
DC
121606var each,
121607 map,
121608 compact,
121609 filter,
121610 reject,
56c4a2cb 121611 remove,
eb39fafa
DC
121612 partition,
121613 find,
121614 head,
121615 first,
121616 tail,
121617 last,
121618 initial,
121619 empty,
121620 reverse,
121621 unique,
121622 uniqueBy,
121623 fold,
121624 foldl,
121625 fold1,
121626 foldl1,
121627 foldr,
121628 foldr1,
121629 unfoldr,
121630 concat,
121631 concatMap,
121632 _flatten,
121633 difference,
121634 intersection,
121635 union,
121636 countBy,
121637 groupBy,
121638 andList,
121639 orList,
121640 any,
121641 all,
121642 sort,
121643 sortWith,
121644 sortBy,
121645 sum,
121646 product,
121647 mean,
121648 average,
121649 maximum,
121650 minimum,
121651 maximumBy,
121652 minimumBy,
121653 scan,
121654 scanl,
121655 scan1,
121656 scanl1,
121657 scanr,
121658 scanr1,
121659 slice,
121660 take,
121661 drop,
121662 splitAt,
121663 takeWhile,
121664 dropWhile,
121665 span,
121666 breakList,
121667 zip,
121668 zipWith,
121669 zipAll,
121670 zipAllWith,
121671 at,
121672 elemIndex,
121673 elemIndices,
121674 findIndex,
121675 findIndices,
56c4a2cb 121676 toString$ = {}.toString;
eb39fafa
DC
121677
121678each = curry$(function (f, xs) {
121679 var i$, len$, x;
121680
121681 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121682 x = xs[i$];
121683 f(x);
121684 }
121685
121686 return xs;
121687});
121688map = curry$(function (f, xs) {
121689 var i$,
121690 len$,
121691 x,
121692 results$ = [];
121693
121694 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121695 x = xs[i$];
121696 results$.push(f(x));
121697 }
121698
121699 return results$;
121700});
121701
121702compact = function compact(xs) {
121703 var i$,
121704 len$,
121705 x,
121706 results$ = [];
121707
121708 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121709 x = xs[i$];
121710
121711 if (x) {
121712 results$.push(x);
121713 }
121714 }
121715
121716 return results$;
121717};
121718
121719filter = curry$(function (f, xs) {
121720 var i$,
121721 len$,
121722 x,
121723 results$ = [];
121724
121725 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121726 x = xs[i$];
121727
121728 if (f(x)) {
121729 results$.push(x);
121730 }
121731 }
121732
121733 return results$;
121734});
121735reject = curry$(function (f, xs) {
121736 var i$,
121737 len$,
121738 x,
121739 results$ = [];
121740
121741 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121742 x = xs[i$];
121743
121744 if (!f(x)) {
121745 results$.push(x);
121746 }
121747 }
121748
121749 return results$;
121750});
56c4a2cb
DC
121751remove = curry$(function (el, xs) {
121752 var i, x$;
121753 i = elemIndex(el, xs);
121754 x$ = xs.slice();
121755
121756 if (i != null) {
121757 x$.splice(i, 1);
121758 }
121759
121760 return x$;
121761});
eb39fafa
DC
121762partition = curry$(function (f, xs) {
121763 var passed, failed, i$, len$, x;
121764 passed = [];
121765 failed = [];
121766
121767 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121768 x = xs[i$];
121769 (f(x) ? passed : failed).push(x);
121770 }
121771
121772 return [passed, failed];
121773});
121774find = curry$(function (f, xs) {
121775 var i$, len$, x;
121776
121777 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121778 x = xs[i$];
121779
121780 if (f(x)) {
121781 return x;
121782 }
121783 }
121784});
121785
121786head = first = function first(xs) {
121787 return xs[0];
121788};
121789
121790tail = function tail(xs) {
121791 if (!xs.length) {
121792 return;
121793 }
121794
121795 return xs.slice(1);
121796};
121797
121798last = function last(xs) {
121799 return xs[xs.length - 1];
121800};
121801
121802initial = function initial(xs) {
121803 if (!xs.length) {
121804 return;
121805 }
121806
121807 return xs.slice(0, -1);
121808};
121809
121810empty = function empty(xs) {
121811 return !xs.length;
121812};
121813
121814reverse = function reverse(xs) {
121815 return xs.concat().reverse();
121816};
121817
121818unique = function unique(xs) {
121819 var result, i$, len$, x;
121820 result = [];
121821
121822 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121823 x = xs[i$];
121824
121825 if (!in$(x, result)) {
121826 result.push(x);
121827 }
121828 }
121829
121830 return result;
121831};
121832
121833uniqueBy = curry$(function (f, xs) {
121834 var seen,
121835 i$,
121836 len$,
121837 x,
121838 val,
121839 results$ = [];
121840 seen = [];
121841
121842 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121843 x = xs[i$];
121844 val = f(x);
121845
121846 if (in$(val, seen)) {
121847 continue;
121848 }
121849
121850 seen.push(val);
121851 results$.push(x);
121852 }
121853
121854 return results$;
121855});
121856fold = foldl = curry$(function (f, memo, xs) {
121857 var i$, len$, x;
121858
121859 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121860 x = xs[i$];
121861 memo = f(memo, x);
121862 }
121863
121864 return memo;
121865});
121866fold1 = foldl1 = curry$(function (f, xs) {
121867 return fold(f, xs[0], xs.slice(1));
121868});
121869foldr = curry$(function (f, memo, xs) {
121870 var i$, x;
121871
121872 for (i$ = xs.length - 1; i$ >= 0; --i$) {
121873 x = xs[i$];
121874 memo = f(x, memo);
121875 }
121876
121877 return memo;
121878});
121879foldr1 = curry$(function (f, xs) {
121880 return foldr(f, xs[xs.length - 1], xs.slice(0, -1));
121881});
121882unfoldr = curry$(function (f, b) {
121883 var result, x, that;
121884 result = [];
121885 x = b;
121886
121887 while ((that = f(x)) != null) {
121888 result.push(that[0]);
121889 x = that[1];
121890 }
121891
121892 return result;
121893});
121894
121895concat = function concat(xss) {
121896 return [].concat.apply([], xss);
121897};
121898
121899concatMap = curry$(function (f, xs) {
121900 var x;
121901 return [].concat.apply([], function () {
121902 var i$,
121903 ref$,
121904 len$,
121905 results$ = [];
121906
121907 for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) {
121908 x = ref$[i$];
121909 results$.push(f(x));
121910 }
121911
121912 return results$;
121913 }());
121914});
121915
121916_flatten = function flatten(xs) {
121917 var x;
121918 return [].concat.apply([], function () {
121919 var i$,
121920 ref$,
121921 len$,
121922 results$ = [];
121923
121924 for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) {
121925 x = ref$[i$];
121926
121927 if (toString$.call(x).slice(8, -1) === 'Array') {
121928 results$.push(_flatten(x));
121929 } else {
121930 results$.push(x);
121931 }
121932 }
121933
121934 return results$;
121935 }());
121936};
121937
121938difference = function difference(xs) {
56c4a2cb
DC
121939 var yss, res$, i$, to$, results, len$, x, j$, len1$, ys;
121940 res$ = [];
121941
121942 for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) {
121943 res$.push(arguments[i$]);
121944 }
121945
121946 yss = res$;
eb39fafa
DC
121947 results = [];
121948
121949 outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121950 x = xs[i$];
121951
121952 for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) {
121953 ys = yss[j$];
121954
121955 if (in$(x, ys)) {
121956 continue outer;
121957 }
121958 }
121959
121960 results.push(x);
121961 }
121962
121963 return results;
121964};
121965
121966intersection = function intersection(xs) {
56c4a2cb
DC
121967 var yss, res$, i$, to$, results, len$, x, j$, len1$, ys;
121968 res$ = [];
121969
121970 for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) {
121971 res$.push(arguments[i$]);
121972 }
121973
121974 yss = res$;
eb39fafa
DC
121975 results = [];
121976
121977 outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
121978 x = xs[i$];
121979
121980 for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) {
121981 ys = yss[j$];
121982
121983 if (!in$(x, ys)) {
121984 continue outer;
121985 }
121986 }
121987
121988 results.push(x);
121989 }
121990
121991 return results;
121992};
121993
121994union = function union() {
56c4a2cb
DC
121995 var xss, res$, i$, to$, results, len$, xs, j$, len1$, x;
121996 res$ = [];
121997
121998 for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) {
121999 res$.push(arguments[i$]);
122000 }
122001
122002 xss = res$;
eb39fafa
DC
122003 results = [];
122004
122005 for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
122006 xs = xss[i$];
122007
122008 for (j$ = 0, len1$ = xs.length; j$ < len1$; ++j$) {
122009 x = xs[j$];
122010
122011 if (!in$(x, results)) {
122012 results.push(x);
122013 }
122014 }
122015 }
122016
122017 return results;
122018};
122019
122020countBy = curry$(function (f, xs) {
122021 var results, i$, len$, x, key;
122022 results = {};
122023
122024 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122025 x = xs[i$];
122026 key = f(x);
122027
122028 if (key in results) {
122029 results[key] += 1;
122030 } else {
122031 results[key] = 1;
122032 }
122033 }
122034
122035 return results;
122036});
122037groupBy = curry$(function (f, xs) {
122038 var results, i$, len$, x, key;
122039 results = {};
122040
122041 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122042 x = xs[i$];
122043 key = f(x);
122044
122045 if (key in results) {
122046 results[key].push(x);
122047 } else {
122048 results[key] = [x];
122049 }
122050 }
122051
122052 return results;
122053});
122054
122055andList = function andList(xs) {
122056 var i$, len$, x;
122057
122058 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122059 x = xs[i$];
122060
122061 if (!x) {
122062 return false;
122063 }
122064 }
122065
122066 return true;
122067};
122068
122069orList = function orList(xs) {
122070 var i$, len$, x;
122071
122072 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122073 x = xs[i$];
122074
122075 if (x) {
122076 return true;
122077 }
122078 }
122079
122080 return false;
122081};
122082
122083any = curry$(function (f, xs) {
122084 var i$, len$, x;
122085
122086 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122087 x = xs[i$];
122088
122089 if (f(x)) {
122090 return true;
122091 }
122092 }
122093
122094 return false;
122095});
122096all = curry$(function (f, xs) {
122097 var i$, len$, x;
122098
122099 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122100 x = xs[i$];
122101
122102 if (!f(x)) {
122103 return false;
122104 }
122105 }
122106
122107 return true;
122108});
122109
122110sort = function sort(xs) {
122111 return xs.concat().sort(function (x, y) {
122112 if (x > y) {
122113 return 1;
122114 } else if (x < y) {
122115 return -1;
122116 } else {
122117 return 0;
122118 }
122119 });
122120};
122121
122122sortWith = curry$(function (f, xs) {
122123 return xs.concat().sort(f);
122124});
122125sortBy = curry$(function (f, xs) {
122126 return xs.concat().sort(function (x, y) {
122127 if (f(x) > f(y)) {
122128 return 1;
122129 } else if (f(x) < f(y)) {
122130 return -1;
122131 } else {
122132 return 0;
122133 }
122134 });
122135});
122136
122137sum = function sum(xs) {
122138 var result, i$, len$, x;
122139 result = 0;
122140
122141 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122142 x = xs[i$];
122143 result += x;
122144 }
122145
122146 return result;
122147};
122148
122149product = function product(xs) {
122150 var result, i$, len$, x;
122151 result = 1;
122152
122153 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122154 x = xs[i$];
122155 result *= x;
122156 }
122157
122158 return result;
122159};
122160
122161mean = average = function average(xs) {
122162 var sum, i$, len$, x;
122163 sum = 0;
122164
122165 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122166 x = xs[i$];
122167 sum += x;
122168 }
122169
122170 return sum / xs.length;
122171};
122172
122173maximum = function maximum(xs) {
122174 var max, i$, ref$, len$, x;
122175 max = xs[0];
122176
122177 for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
122178 x = ref$[i$];
122179
122180 if (x > max) {
122181 max = x;
122182 }
122183 }
122184
122185 return max;
122186};
122187
122188minimum = function minimum(xs) {
122189 var min, i$, ref$, len$, x;
122190 min = xs[0];
122191
122192 for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
122193 x = ref$[i$];
122194
122195 if (x < min) {
122196 min = x;
122197 }
122198 }
122199
122200 return min;
122201};
122202
122203maximumBy = curry$(function (f, xs) {
122204 var max, i$, ref$, len$, x;
122205 max = xs[0];
122206
122207 for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
122208 x = ref$[i$];
122209
122210 if (f(x) > f(max)) {
122211 max = x;
122212 }
122213 }
122214
122215 return max;
122216});
122217minimumBy = curry$(function (f, xs) {
122218 var min, i$, ref$, len$, x;
122219 min = xs[0];
122220
122221 for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
122222 x = ref$[i$];
122223
122224 if (f(x) < f(min)) {
122225 min = x;
122226 }
122227 }
122228
122229 return min;
122230});
122231scan = scanl = curry$(function (f, memo, xs) {
122232 var last, x;
122233 last = memo;
122234 return [memo].concat(function () {
122235 var i$,
122236 ref$,
122237 len$,
122238 results$ = [];
122239
122240 for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) {
122241 x = ref$[i$];
122242 results$.push(last = f(last, x));
122243 }
122244
122245 return results$;
122246 }());
122247});
122248scan1 = scanl1 = curry$(function (f, xs) {
122249 if (!xs.length) {
122250 return;
122251 }
122252
122253 return scan(f, xs[0], xs.slice(1));
122254});
122255scanr = curry$(function (f, memo, xs) {
122256 xs = xs.concat().reverse();
122257 return scan(f, memo, xs).reverse();
122258});
122259scanr1 = curry$(function (f, xs) {
122260 if (!xs.length) {
122261 return;
122262 }
122263
122264 xs = xs.concat().reverse();
122265 return scan(f, xs[0], xs.slice(1)).reverse();
122266});
122267slice = curry$(function (x, y, xs) {
122268 return xs.slice(x, y);
122269});
122270take = curry$(function (n, xs) {
122271 if (n <= 0) {
122272 return xs.slice(0, 0);
122273 } else {
122274 return xs.slice(0, n);
122275 }
122276});
122277drop = curry$(function (n, xs) {
122278 if (n <= 0) {
122279 return xs;
122280 } else {
122281 return xs.slice(n);
122282 }
122283});
122284splitAt = curry$(function (n, xs) {
122285 return [take(n, xs), drop(n, xs)];
122286});
122287takeWhile = curry$(function (p, xs) {
122288 var len, i;
122289 len = xs.length;
122290
122291 if (!len) {
122292 return xs;
122293 }
122294
122295 i = 0;
122296
122297 while (i < len && p(xs[i])) {
122298 i += 1;
122299 }
122300
122301 return xs.slice(0, i);
122302});
122303dropWhile = curry$(function (p, xs) {
122304 var len, i;
122305 len = xs.length;
122306
122307 if (!len) {
122308 return xs;
122309 }
122310
122311 i = 0;
122312
122313 while (i < len && p(xs[i])) {
122314 i += 1;
122315 }
122316
122317 return xs.slice(i);
122318});
122319span = curry$(function (p, xs) {
122320 return [takeWhile(p, xs), dropWhile(p, xs)];
122321});
122322breakList = curry$(function (p, xs) {
122323 return span(compose$(p, not$), xs);
122324});
122325zip = curry$(function (xs, ys) {
122326 var result, len, i$, len$, i, x;
122327 result = [];
122328 len = ys.length;
122329
122330 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122331 i = i$;
122332 x = xs[i$];
122333
122334 if (i === len) {
122335 break;
122336 }
122337
122338 result.push([x, ys[i]]);
122339 }
122340
122341 return result;
122342});
122343zipWith = curry$(function (f, xs, ys) {
122344 var result, len, i$, len$, i, x;
122345 result = [];
122346 len = ys.length;
122347
122348 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122349 i = i$;
122350 x = xs[i$];
122351
122352 if (i === len) {
122353 break;
122354 }
122355
122356 result.push(f(x, ys[i]));
122357 }
122358
122359 return result;
122360});
122361
122362zipAll = function zipAll() {
122363 var xss,
56c4a2cb 122364 res$,
eb39fafa 122365 i$,
56c4a2cb
DC
122366 to$,
122367 minLength,
eb39fafa
DC
122368 len$,
122369 xs,
122370 ref$,
122371 i,
122372 lresult$,
122373 j$,
122374 results$ = [];
56c4a2cb
DC
122375 res$ = [];
122376
122377 for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) {
122378 res$.push(arguments[i$]);
122379 }
122380
122381 xss = res$;
eb39fafa
DC
122382 minLength = undefined;
122383
122384 for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
122385 xs = xss[i$];
122386 minLength <= (ref$ = xs.length) || (minLength = ref$);
122387 }
122388
122389 for (i$ = 0; i$ < minLength; ++i$) {
122390 i = i$;
122391 lresult$ = [];
122392
122393 for (j$ = 0, len$ = xss.length; j$ < len$; ++j$) {
122394 xs = xss[j$];
122395 lresult$.push(xs[i]);
122396 }
122397
122398 results$.push(lresult$);
122399 }
122400
122401 return results$;
122402};
122403
122404zipAllWith = function zipAllWith(f) {
122405 var xss,
56c4a2cb 122406 res$,
eb39fafa 122407 i$,
56c4a2cb
DC
122408 to$,
122409 minLength,
eb39fafa
DC
122410 len$,
122411 xs,
122412 ref$,
122413 i,
122414 results$ = [];
56c4a2cb
DC
122415 res$ = [];
122416
122417 for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) {
122418 res$.push(arguments[i$]);
122419 }
122420
122421 xss = res$;
eb39fafa
DC
122422 minLength = undefined;
122423
122424 for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
122425 xs = xss[i$];
122426 minLength <= (ref$ = xs.length) || (minLength = ref$);
122427 }
122428
122429 for (i$ = 0; i$ < minLength; ++i$) {
122430 i = i$;
122431 results$.push(f.apply(null, fn$()));
122432 }
122433
122434 return results$;
122435
122436 function fn$() {
122437 var i$,
122438 ref$,
122439 len$,
122440 results$ = [];
122441
122442 for (i$ = 0, len$ = (ref$ = xss).length; i$ < len$; ++i$) {
122443 xs = ref$[i$];
122444 results$.push(xs[i]);
122445 }
122446
122447 return results$;
122448 }
122449};
122450
122451at = curry$(function (n, xs) {
122452 if (n < 0) {
122453 return xs[xs.length + n];
122454 } else {
122455 return xs[n];
122456 }
122457});
122458elemIndex = curry$(function (el, xs) {
122459 var i$, len$, i, x;
122460
122461 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122462 i = i$;
122463 x = xs[i$];
122464
122465 if (x === el) {
122466 return i;
122467 }
122468 }
122469});
122470elemIndices = curry$(function (el, xs) {
122471 var i$,
122472 len$,
122473 i,
122474 x,
122475 results$ = [];
122476
122477 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122478 i = i$;
122479 x = xs[i$];
122480
122481 if (x === el) {
122482 results$.push(i);
122483 }
122484 }
122485
122486 return results$;
122487});
122488findIndex = curry$(function (f, xs) {
122489 var i$, len$, i, x;
122490
122491 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122492 i = i$;
122493 x = xs[i$];
122494
122495 if (f(x)) {
122496 return i;
122497 }
122498 }
122499});
122500findIndices = curry$(function (f, xs) {
122501 var i$,
122502 len$,
122503 i,
122504 x,
122505 results$ = [];
122506
122507 for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
122508 i = i$;
122509 x = xs[i$];
122510
122511 if (f(x)) {
122512 results$.push(i);
122513 }
122514 }
122515
122516 return results$;
122517});
122518module.exports = {
122519 each: each,
122520 map: map,
122521 filter: filter,
122522 compact: compact,
122523 reject: reject,
56c4a2cb 122524 remove: remove,
eb39fafa
DC
122525 partition: partition,
122526 find: find,
122527 head: head,
122528 first: first,
122529 tail: tail,
122530 last: last,
122531 initial: initial,
122532 empty: empty,
122533 reverse: reverse,
122534 difference: difference,
122535 intersection: intersection,
122536 union: union,
122537 countBy: countBy,
122538 groupBy: groupBy,
122539 fold: fold,
122540 fold1: fold1,
122541 foldl: foldl,
122542 foldl1: foldl1,
122543 foldr: foldr,
122544 foldr1: foldr1,
122545 unfoldr: unfoldr,
122546 andList: andList,
122547 orList: orList,
122548 any: any,
122549 all: all,
122550 unique: unique,
122551 uniqueBy: uniqueBy,
122552 sort: sort,
122553 sortWith: sortWith,
122554 sortBy: sortBy,
122555 sum: sum,
122556 product: product,
122557 mean: mean,
122558 average: average,
122559 concat: concat,
122560 concatMap: concatMap,
122561 flatten: _flatten,
122562 maximum: maximum,
122563 minimum: minimum,
122564 maximumBy: maximumBy,
122565 minimumBy: minimumBy,
122566 scan: scan,
122567 scan1: scan1,
122568 scanl: scanl,
122569 scanl1: scanl1,
122570 scanr: scanr,
122571 scanr1: scanr1,
122572 slice: slice,
122573 take: take,
122574 drop: drop,
122575 splitAt: splitAt,
122576 takeWhile: takeWhile,
122577 dropWhile: dropWhile,
122578 span: span,
122579 breakList: breakList,
122580 zip: zip,
122581 zipWith: zipWith,
122582 zipAll: zipAll,
122583 zipAllWith: zipAllWith,
122584 at: at,
122585 elemIndex: elemIndex,
122586 elemIndices: elemIndices,
122587 findIndex: findIndex,
122588 findIndices: findIndices
122589};
122590
122591function curry$(f, bound) {
122592 var context,
122593 _curry = function _curry(args) {
122594 return f.length > 1 ? function () {
122595 var params = args ? args.concat() : [];
122596 context = bound ? context || this : this;
122597 return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params);
122598 } : f;
122599 };
122600
122601 return _curry();
122602}
122603
122604function in$(x, xs) {
122605 var i = -1,
122606 l = xs.length >>> 0;
122607
122608 while (++i < l) if (x === xs[i]) return true;
122609
122610 return false;
122611}
122612
122613function compose$() {
122614 var functions = arguments;
122615 return function () {
122616 var i, result;
122617 result = functions[0].apply(this, arguments);
122618
122619 for (i = 1; i < functions.length; ++i) {
122620 result = functions[i](result);
122621 }
122622
122623 return result;
122624 };
122625}
122626
122627function not$(x) {
122628 return !x;
122629}
122630
122631/***/ }),
6a5a0f88 122632/* 805 */
eb39fafa
DC
122633/***/ (function(module, exports) {
122634
56c4a2cb 122635// Generated by LiveScript 1.6.0
eb39fafa
DC
122636var values, keys, pairsToObj, objToPairs, listsToObj, objToLists, empty, each, map, compact, filter, reject, partition, find;
122637
122638values = function values(object) {
122639 var i$,
122640 x,
122641 results$ = [];
122642
122643 for (i$ in object) {
122644 x = object[i$];
122645 results$.push(x);
122646 }
122647
122648 return results$;
122649};
122650
122651keys = function keys(object) {
122652 var x,
122653 results$ = [];
122654
122655 for (x in object) {
122656 results$.push(x);
122657 }
122658
122659 return results$;
122660};
122661
122662pairsToObj = function pairsToObj(object) {
122663 var i$,
122664 len$,
122665 x,
122666 resultObj$ = {};
122667
122668 for (i$ = 0, len$ = object.length; i$ < len$; ++i$) {
122669 x = object[i$];
122670 resultObj$[x[0]] = x[1];
122671 }
122672
122673 return resultObj$;
122674};
122675
122676objToPairs = function objToPairs(object) {
122677 var key,
122678 value,
122679 results$ = [];
122680
122681 for (key in object) {
122682 value = object[key];
122683 results$.push([key, value]);
122684 }
122685
122686 return results$;
122687};
122688
122689listsToObj = curry$(function (keys, values) {
122690 var i$,
122691 len$,
122692 i,
122693 key,
122694 resultObj$ = {};
122695
122696 for (i$ = 0, len$ = keys.length; i$ < len$; ++i$) {
122697 i = i$;
122698 key = keys[i$];
122699 resultObj$[key] = values[i];
122700 }
122701
122702 return resultObj$;
122703});
122704
122705objToLists = function objToLists(object) {
122706 var keys, values, key, value;
122707 keys = [];
122708 values = [];
122709
122710 for (key in object) {
122711 value = object[key];
122712 keys.push(key);
122713 values.push(value);
122714 }
122715
122716 return [keys, values];
122717};
122718
122719empty = function empty(object) {
122720 var x;
122721
122722 for (x in object) {
122723 return false;
122724 }
122725
122726 return true;
122727};
122728
122729each = curry$(function (f, object) {
122730 var i$, x;
122731
122732 for (i$ in object) {
122733 x = object[i$];
122734 f(x);
122735 }
122736
122737 return object;
122738});
122739map = curry$(function (f, object) {
122740 var k,
122741 x,
122742 resultObj$ = {};
122743
122744 for (k in object) {
122745 x = object[k];
122746 resultObj$[k] = f(x);
122747 }
122748
122749 return resultObj$;
122750});
122751
122752compact = function compact(object) {
122753 var k,
122754 x,
122755 resultObj$ = {};
122756
122757 for (k in object) {
122758 x = object[k];
122759
122760 if (x) {
122761 resultObj$[k] = x;
122762 }
122763 }
122764
122765 return resultObj$;
122766};
122767
122768filter = curry$(function (f, object) {
122769 var k,
122770 x,
122771 resultObj$ = {};
122772
122773 for (k in object) {
122774 x = object[k];
122775
122776 if (f(x)) {
122777 resultObj$[k] = x;
122778 }
122779 }
122780
122781 return resultObj$;
122782});
122783reject = curry$(function (f, object) {
122784 var k,
122785 x,
122786 resultObj$ = {};
122787
122788 for (k in object) {
122789 x = object[k];
122790
122791 if (!f(x)) {
122792 resultObj$[k] = x;
122793 }
122794 }
122795
122796 return resultObj$;
122797});
122798partition = curry$(function (f, object) {
122799 var passed, failed, k, x;
122800 passed = {};
122801 failed = {};
122802
122803 for (k in object) {
122804 x = object[k];
122805 (f(x) ? passed : failed)[k] = x;
122806 }
122807
122808 return [passed, failed];
122809});
122810find = curry$(function (f, object) {
122811 var i$, x;
122812
122813 for (i$ in object) {
122814 x = object[i$];
122815
122816 if (f(x)) {
122817 return x;
122818 }
122819 }
122820});
122821module.exports = {
122822 values: values,
122823 keys: keys,
122824 pairsToObj: pairsToObj,
122825 objToPairs: objToPairs,
122826 listsToObj: listsToObj,
122827 objToLists: objToLists,
122828 empty: empty,
122829 each: each,
122830 map: map,
122831 filter: filter,
122832 compact: compact,
122833 reject: reject,
122834 partition: partition,
122835 find: find
122836};
122837
122838function curry$(f, bound) {
122839 var context,
122840 _curry = function _curry(args) {
122841 return f.length > 1 ? function () {
122842 var params = args ? args.concat() : [];
122843 context = bound ? context || this : this;
122844 return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params);
122845 } : f;
122846 };
122847
122848 return _curry();
122849}
122850
122851/***/ }),
6a5a0f88 122852/* 806 */
eb39fafa
DC
122853/***/ (function(module, exports) {
122854
56c4a2cb 122855// Generated by LiveScript 1.6.0
eb39fafa
DC
122856var split, join, lines, unlines, words, unwords, chars, unchars, reverse, repeat, capitalize, camelize, dasherize;
122857split = curry$(function (sep, str) {
122858 return str.split(sep);
122859});
122860join = curry$(function (sep, xs) {
122861 return xs.join(sep);
122862});
122863
122864lines = function lines(str) {
122865 if (!str.length) {
122866 return [];
122867 }
122868
122869 return str.split('\n');
122870};
122871
122872unlines = function unlines(it) {
122873 return it.join('\n');
122874};
122875
122876words = function words(str) {
122877 if (!str.length) {
122878 return [];
122879 }
122880
122881 return str.split(/[ ]+/);
122882};
122883
122884unwords = function unwords(it) {
122885 return it.join(' ');
122886};
122887
122888chars = function chars(it) {
122889 return it.split('');
122890};
122891
122892unchars = function unchars(it) {
122893 return it.join('');
122894};
122895
122896reverse = function reverse(str) {
122897 return str.split('').reverse().join('');
122898};
122899
122900repeat = curry$(function (n, str) {
122901 var result, i$;
122902 result = '';
122903
122904 for (i$ = 0; i$ < n; ++i$) {
122905 result += str;
122906 }
122907
122908 return result;
122909});
122910
122911capitalize = function capitalize(str) {
122912 return str.charAt(0).toUpperCase() + str.slice(1);
122913};
122914
122915camelize = function camelize(it) {
122916 return it.replace(/[-_]+(.)?/g, function (arg$, c) {
122917 return (c != null ? c : '').toUpperCase();
122918 });
122919};
122920
122921dasherize = function dasherize(str) {
122922 return str.replace(/([^-A-Z])([A-Z]+)/g, function (arg$, lower, upper) {
122923 return lower + "-" + (upper.length > 1 ? upper : upper.toLowerCase());
122924 }).replace(/^([A-Z]+)/, function (arg$, upper) {
122925 if (upper.length > 1) {
122926 return upper + "-";
122927 } else {
122928 return upper.toLowerCase();
122929 }
122930 });
122931};
122932
122933module.exports = {
122934 split: split,
122935 join: join,
122936 lines: lines,
122937 unlines: unlines,
122938 words: words,
122939 unwords: unwords,
122940 chars: chars,
122941 unchars: unchars,
122942 reverse: reverse,
122943 repeat: repeat,
122944 capitalize: capitalize,
122945 camelize: camelize,
122946 dasherize: dasherize
122947};
122948
122949function curry$(f, bound) {
122950 var context,
122951 _curry = function _curry(args) {
122952 return f.length > 1 ? function () {
122953 var params = args ? args.concat() : [];
122954 context = bound ? context || this : this;
122955 return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params);
122956 } : f;
122957 };
122958
122959 return _curry();
122960}
122961
122962/***/ }),
6a5a0f88 122963/* 807 */
eb39fafa
DC
122964/***/ (function(module, exports) {
122965
56c4a2cb 122966// Generated by LiveScript 1.6.0
eb39fafa
DC
122967var max, min, negate, abs, signum, quot, rem, div, mod, recip, pi, tau, exp, sqrt, ln, pow, sin, tan, cos, asin, acos, atan, atan2, truncate, round, ceiling, floor, isItNaN, even, odd, gcd, lcm;
122968max = curry$(function (x$, y$) {
122969 return x$ > y$ ? x$ : y$;
122970});
122971min = curry$(function (x$, y$) {
122972 return x$ < y$ ? x$ : y$;
122973});
122974
122975negate = function negate(x) {
122976 return -x;
122977};
122978
122979abs = Math.abs;
122980
122981signum = function signum(x) {
122982 if (x < 0) {
122983 return -1;
122984 } else if (x > 0) {
122985 return 1;
122986 } else {
122987 return 0;
122988 }
122989};
122990
122991quot = curry$(function (x, y) {
122992 return ~~(x / y);
122993});
122994rem = curry$(function (x$, y$) {
122995 return x$ % y$;
122996});
122997div = curry$(function (x, y) {
122998 return Math.floor(x / y);
122999});
123000mod = curry$(function (x$, y$) {
123001 var ref$;
123002 return (x$ % (ref$ = y$) + ref$) % ref$;
123003});
123004
123005recip = function recip(it) {
123006 return 1 / it;
123007};
123008
123009pi = Math.PI;
123010tau = pi * 2;
123011exp = Math.exp;
123012sqrt = Math.sqrt;
123013ln = Math.log;
123014pow = curry$(function (x$, y$) {
123015 return Math.pow(x$, y$);
123016});
123017sin = Math.sin;
123018tan = Math.tan;
123019cos = Math.cos;
123020asin = Math.asin;
123021acos = Math.acos;
123022atan = Math.atan;
123023atan2 = curry$(function (x, y) {
123024 return Math.atan2(x, y);
123025});
123026
123027truncate = function truncate(x) {
123028 return ~~x;
123029};
123030
123031round = Math.round;
123032ceiling = Math.ceil;
123033floor = Math.floor;
123034
123035isItNaN = function isItNaN(x) {
123036 return x !== x;
123037};
123038
123039even = function even(x) {
123040 return x % 2 === 0;
123041};
123042
123043odd = function odd(x) {
123044 return x % 2 !== 0;
123045};
123046
123047gcd = curry$(function (x, y) {
123048 var z;
123049 x = Math.abs(x);
123050 y = Math.abs(y);
123051
123052 while (y !== 0) {
123053 z = x % y;
123054 x = y;
123055 y = z;
123056 }
123057
123058 return x;
123059});
123060lcm = curry$(function (x, y) {
123061 return Math.abs(Math.floor(x / gcd(x, y) * y));
123062});
123063module.exports = {
123064 max: max,
123065 min: min,
123066 negate: negate,
123067 abs: abs,
123068 signum: signum,
123069 quot: quot,
123070 rem: rem,
123071 div: div,
123072 mod: mod,
123073 recip: recip,
123074 pi: pi,
123075 tau: tau,
123076 exp: exp,
123077 sqrt: sqrt,
123078 ln: ln,
123079 pow: pow,
123080 sin: sin,
123081 tan: tan,
123082 cos: cos,
123083 acos: acos,
123084 asin: asin,
123085 atan: atan,
123086 atan2: atan2,
123087 truncate: truncate,
123088 round: round,
123089 ceiling: ceiling,
123090 floor: floor,
123091 isItNaN: isItNaN,
123092 even: even,
123093 odd: odd,
123094 gcd: gcd,
123095 lcm: lcm
123096};
123097
123098function curry$(f, bound) {
123099 var context,
123100 _curry = function _curry(args) {
123101 return f.length > 1 ? function () {
123102 var params = args ? args.concat() : [];
123103 context = bound ? context || this : this;
123104 return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params);
123105 } : f;
123106 };
123107
123108 return _curry();
123109}
123110
123111/***/ }),
6a5a0f88 123112/* 808 */
eb39fafa
DC
123113/***/ (function(module, exports, __webpack_require__) {
123114
56c4a2cb 123115// Generated by LiveScript 1.6.0
eb39fafa
DC
123116(function () {
123117 var parsedTypeCheck,
123118 types,
123119 toString$ = {}.toString;
6a5a0f88 123120 parsedTypeCheck = __webpack_require__(809).parsedTypeCheck;
eb39fafa
DC
123121 types = {
123122 '*': function _(value, options) {
123123 switch (toString$.call(value).slice(8, -1)) {
123124 case 'Array':
123125 return typeCast(value, {
123126 type: 'Array'
123127 }, options);
123128
123129 case 'Object':
123130 return typeCast(value, {
123131 type: 'Object'
123132 }, options);
123133
123134 default:
123135 return {
123136 type: 'Just',
123137 value: typesCast(value, [{
123138 type: 'Undefined'
123139 }, {
123140 type: 'Null'
123141 }, {
123142 type: 'NaN'
123143 }, {
123144 type: 'Boolean'
123145 }, {
123146 type: 'Number'
123147 }, {
123148 type: 'Date'
123149 }, {
123150 type: 'RegExp'
123151 }, {
123152 type: 'Array'
123153 }, {
123154 type: 'Object'
123155 }, {
123156 type: 'String'
123157 }], (options.explicit = true, options))
123158 };
123159 }
123160 },
123161 Undefined: function Undefined(it) {
123162 if (it === 'undefined' || it === void 8) {
123163 return {
123164 type: 'Just',
123165 value: void 8
123166 };
123167 } else {
123168 return {
123169 type: 'Nothing'
123170 };
123171 }
123172 },
123173 Null: function Null(it) {
123174 if (it === 'null') {
123175 return {
123176 type: 'Just',
123177 value: null
123178 };
123179 } else {
123180 return {
123181 type: 'Nothing'
123182 };
123183 }
123184 },
123185 NaN: function (_NaN) {
123186 function NaN(_x) {
123187 return _NaN.apply(this, arguments);
123188 }
123189
123190 NaN.toString = function () {
123191 return _NaN.toString();
123192 };
123193
123194 return NaN;
123195 }(function (it) {
123196 if (it === 'NaN') {
123197 return {
123198 type: 'Just',
123199 value: NaN
123200 };
123201 } else {
123202 return {
123203 type: 'Nothing'
123204 };
123205 }
123206 }),
123207 Boolean: function Boolean(it) {
123208 if (it === 'true') {
123209 return {
123210 type: 'Just',
123211 value: true
123212 };
123213 } else if (it === 'false') {
123214 return {
123215 type: 'Just',
123216 value: false
123217 };
123218 } else {
123219 return {
123220 type: 'Nothing'
123221 };
123222 }
123223 },
123224 Number: function Number(it) {
123225 return {
123226 type: 'Just',
123227 value: +it
123228 };
123229 },
123230 Int: function Int(it) {
123231 return {
123232 type: 'Just',
123233 value: +it
123234 };
123235 },
123236 Float: function Float(it) {
123237 return {
123238 type: 'Just',
123239 value: +it
123240 };
123241 },
123242 Date: function (_Date) {
123243 function Date(_x2, _x3) {
123244 return _Date.apply(this, arguments);
123245 }
123246
123247 Date.toString = function () {
123248 return _Date.toString();
123249 };
123250
123251 return Date;
123252 }(function (value, options) {
123253 var that;
123254
123255 if (that = /^\#([\s\S]*)\#$/.exec(value)) {
123256 return {
123257 type: 'Just',
123258 value: new Date(+that[1] || that[1])
123259 };
123260 } else if (options.explicit) {
123261 return {
123262 type: 'Nothing'
123263 };
123264 } else {
123265 return {
123266 type: 'Just',
123267 value: new Date(+value || value)
123268 };
123269 }
123270 }),
123271 RegExp: function (_RegExp) {
123272 function RegExp(_x4, _x5) {
123273 return _RegExp.apply(this, arguments);
123274 }
123275
123276 RegExp.toString = function () {
123277 return _RegExp.toString();
123278 };
123279
123280 return RegExp;
123281 }(function (value, options) {
123282 var that;
123283
123284 if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) {
123285 return {
123286 type: 'Just',
123287 value: new RegExp(that[1], that[2])
123288 };
123289 } else if (options.explicit) {
123290 return {
123291 type: 'Nothing'
123292 };
123293 } else {
123294 return {
123295 type: 'Just',
123296 value: new RegExp(value)
123297 };
123298 }
123299 }),
123300 Array: function Array(value, options) {
123301 return castArray(value, {
123302 of: [{
123303 type: '*'
123304 }]
123305 }, options);
123306 },
123307 Object: function Object(value, options) {
123308 return castFields(value, {
123309 of: {}
123310 }, options);
123311 },
123312 String: function String(it) {
56c4a2cb 123313 var replace, that;
eb39fafa
DC
123314
123315 if (toString$.call(it).slice(8, -1) !== 'String') {
123316 return {
123317 type: 'Nothing'
123318 };
123319 }
123320
56c4a2cb
DC
123321 replace = function replace(value, quote) {
123322 return value.replace(/\\([^u]|u[0-9a-fA-F]{4})/g, function (all, escaped) {
123323 switch (escaped[0]) {
123324 case quote:
123325 return quote;
123326
123327 case '\\':
123328 return '\\';
123329
123330 case 'b':
123331 return '\b';
123332
123333 case 'f':
123334 return '\f';
123335
123336 case 'n':
123337 return '\n';
123338
123339 case 'r':
123340 return '\r';
123341
123342 case 't':
123343 return '\t';
123344
123345 case 'u':
123346 return JSON.parse("\"" + all + "\"");
123347
123348 default:
123349 return escaped;
123350 }
123351 });
123352 };
123353
eb39fafa
DC
123354 if (that = it.match(/^'([\s\S]*)'$/)) {
123355 return {
123356 type: 'Just',
56c4a2cb 123357 value: replace(that[1], "'")
eb39fafa
DC
123358 };
123359 } else if (that = it.match(/^"([\s\S]*)"$/)) {
123360 return {
123361 type: 'Just',
56c4a2cb 123362 value: replace(that[1], '"')
eb39fafa
DC
123363 };
123364 } else {
123365 return {
123366 type: 'Just',
123367 value: it
123368 };
123369 }
123370 }
123371 };
123372
123373 function castArray(node, type, options) {
123374 var typeOf, element;
123375
123376 if (toString$.call(node).slice(8, -1) !== 'Array') {
123377 return {
123378 type: 'Nothing'
123379 };
123380 }
123381
123382 typeOf = type.of;
123383 return {
123384 type: 'Just',
123385 value: function () {
123386 var i$,
123387 ref$,
123388 len$,
123389 results$ = [];
123390
123391 for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
123392 element = ref$[i$];
123393 results$.push(typesCast(element, typeOf, options));
123394 }
123395
123396 return results$;
123397 }()
123398 };
123399 }
123400
123401 function castTuple(node, type, options) {
123402 var result, i, i$, ref$, len$, types, cast;
123403
123404 if (toString$.call(node).slice(8, -1) !== 'Array') {
123405 return {
123406 type: 'Nothing'
123407 };
123408 }
123409
123410 result = [];
123411 i = 0;
123412
123413 for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
123414 types = ref$[i$];
123415 cast = typesCast(node[i], types, options);
123416
123417 if (toString$.call(cast).slice(8, -1) !== 'Undefined') {
123418 result.push(cast);
123419 }
123420
123421 i++;
123422 }
123423
123424 if (node.length <= i) {
123425 return {
123426 type: 'Just',
123427 value: result
123428 };
123429 } else {
123430 return {
123431 type: 'Nothing'
123432 };
123433 }
123434 }
123435
123436 function castFields(node, type, options) {
123437 var typeOf, key, value;
123438
123439 if (toString$.call(node).slice(8, -1) !== 'Object') {
123440 return {
123441 type: 'Nothing'
123442 };
123443 }
123444
123445 typeOf = type.of;
123446 return {
123447 type: 'Just',
123448 value: function () {
123449 var ref$,
123450 resultObj$ = {};
123451
123452 for (key in ref$ = node) {
123453 value = ref$[key];
123454 resultObj$[typesCast(key, [{
123455 type: 'String'
123456 }], options)] = typesCast(value, typeOf[key] || [{
123457 type: '*'
123458 }], options);
123459 }
123460
123461 return resultObj$;
123462 }()
123463 };
123464 }
123465
123466 function typeCast(node, typeObj, options) {
123467 var type, structure, castFunc, ref$;
123468 type = typeObj.type, structure = typeObj.structure;
123469
123470 if (type) {
123471 castFunc = ((ref$ = options.customTypes[type]) != null ? ref$.cast : void 8) || types[type];
123472
123473 if (!castFunc) {
123474 throw new Error("Type not defined: " + type + ".");
123475 }
123476
123477 return castFunc(node, options, typesCast);
123478 } else {
123479 switch (structure) {
123480 case 'array':
123481 return castArray(node, typeObj, options);
123482
123483 case 'tuple':
123484 return castTuple(node, typeObj, options);
123485
123486 case 'fields':
123487 return castFields(node, typeObj, options);
123488 }
123489 }
123490 }
123491
123492 function typesCast(node, types, options) {
123493 var i$, len$, type, ref$, valueType, value;
123494
123495 for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
123496 type = types[i$];
123497 ref$ = typeCast(node, type, options), valueType = ref$.type, value = ref$.value;
123498
123499 if (valueType === 'Nothing') {
123500 continue;
123501 }
123502
123503 if (parsedTypeCheck([type], value, {
123504 customTypes: options.customTypes
123505 })) {
123506 return value;
123507 }
123508 }
123509
123510 throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
123511 }
123512
56c4a2cb
DC
123513 module.exports = function (node, types, options) {
123514 if (!options.explicit && types.length === 1 && types[0].type === 'String') {
123515 return node;
123516 }
123517
123518 return typesCast(node, types, options);
123519 };
eb39fafa
DC
123520}).call(this);
123521
123522/***/ }),
6a5a0f88 123523/* 809 */
eb39fafa
DC
123524/***/ (function(module, exports, __webpack_require__) {
123525
56c4a2cb 123526// Generated by LiveScript 1.6.0
eb39fafa
DC
123527(function () {
123528 var VERSION, parseType, parsedTypeCheck, typeCheck;
56c4a2cb 123529 VERSION = '0.4.0';
6a5a0f88
TL
123530 parseType = __webpack_require__(810);
123531 parsedTypeCheck = __webpack_require__(811);
eb39fafa
DC
123532
123533 typeCheck = function typeCheck(type, input, options) {
123534 return parsedTypeCheck(parseType(type), input, options);
123535 };
123536
123537 module.exports = {
123538 VERSION: VERSION,
123539 typeCheck: typeCheck,
123540 parsedTypeCheck: parsedTypeCheck,
123541 parseType: parseType
123542 };
123543}).call(this);
123544
123545/***/ }),
6a5a0f88 123546/* 810 */
eb39fafa
DC
123547/***/ (function(module, exports) {
123548
56c4a2cb 123549// Generated by LiveScript 1.6.0
eb39fafa
DC
123550(function () {
123551 var identifierRegex, tokenRegex;
123552 identifierRegex = /[\$\w]+/;
123553
123554 function peek(tokens) {
123555 var token;
123556 token = tokens[0];
123557
123558 if (token == null) {
123559 throw new Error('Unexpected end of input.');
123560 }
123561
123562 return token;
123563 }
123564
123565 function consumeIdent(tokens) {
123566 var token;
123567 token = peek(tokens);
123568
123569 if (!identifierRegex.test(token)) {
123570 throw new Error("Expected text, got '" + token + "' instead.");
123571 }
123572
123573 return tokens.shift();
123574 }
123575
123576 function consumeOp(tokens, op) {
123577 var token;
123578 token = peek(tokens);
123579
123580 if (token !== op) {
123581 throw new Error("Expected '" + op + "', got '" + token + "' instead.");
123582 }
123583
123584 return tokens.shift();
123585 }
123586
123587 function maybeConsumeOp(tokens, op) {
123588 var token;
123589 token = tokens[0];
123590
123591 if (token === op) {
123592 return tokens.shift();
123593 } else {
123594 return null;
123595 }
123596 }
123597
123598 function consumeArray(tokens) {
123599 var types;
123600 consumeOp(tokens, '[');
123601
123602 if (peek(tokens) === ']') {
123603 throw new Error("Must specify type of Array - eg. [Type], got [] instead.");
123604 }
123605
123606 types = consumeTypes(tokens);
123607 consumeOp(tokens, ']');
123608 return {
123609 structure: 'array',
123610 of: types
123611 };
123612 }
123613
123614 function consumeTuple(tokens) {
123615 var components;
123616 components = [];
123617 consumeOp(tokens, '(');
123618
123619 if (peek(tokens) === ')') {
123620 throw new Error("Tuple must be of at least length 1 - eg. (Type), got () instead.");
123621 }
123622
123623 for (;;) {
123624 components.push(consumeTypes(tokens));
123625 maybeConsumeOp(tokens, ',');
123626
123627 if (')' === peek(tokens)) {
123628 break;
123629 }
123630 }
123631
123632 consumeOp(tokens, ')');
123633 return {
123634 structure: 'tuple',
123635 of: components
123636 };
123637 }
123638
123639 function consumeFields(tokens) {
123640 var fields, subset, ref$, key, types;
123641 fields = {};
123642 consumeOp(tokens, '{');
123643 subset = false;
123644
123645 for (;;) {
123646 if (maybeConsumeOp(tokens, '...')) {
123647 subset = true;
123648 break;
123649 }
123650
123651 ref$ = consumeField(tokens), key = ref$[0], types = ref$[1];
123652 fields[key] = types;
123653 maybeConsumeOp(tokens, ',');
123654
123655 if ('}' === peek(tokens)) {
123656 break;
123657 }
123658 }
123659
123660 consumeOp(tokens, '}');
123661 return {
123662 structure: 'fields',
123663 of: fields,
123664 subset: subset
123665 };
123666 }
123667
123668 function consumeField(tokens) {
123669 var key, types;
123670 key = consumeIdent(tokens);
123671 consumeOp(tokens, ':');
123672 types = consumeTypes(tokens);
123673 return [key, types];
123674 }
123675
123676 function maybeConsumeStructure(tokens) {
123677 switch (tokens[0]) {
123678 case '[':
123679 return consumeArray(tokens);
123680
123681 case '(':
123682 return consumeTuple(tokens);
123683
123684 case '{':
123685 return consumeFields(tokens);
123686 }
123687 }
123688
123689 function consumeType(tokens) {
123690 var token, wildcard, type, structure;
123691 token = peek(tokens);
123692 wildcard = token === '*';
123693
123694 if (wildcard || identifierRegex.test(token)) {
123695 type = wildcard ? consumeOp(tokens, '*') : consumeIdent(tokens);
123696 structure = maybeConsumeStructure(tokens);
123697
123698 if (structure) {
123699 return structure.type = type, structure;
123700 } else {
123701 return {
123702 type: type
123703 };
123704 }
123705 } else {
123706 structure = maybeConsumeStructure(tokens);
123707
123708 if (!structure) {
123709 throw new Error("Unexpected character: " + token);
123710 }
123711
123712 return structure;
123713 }
123714 }
123715
123716 function consumeTypes(tokens) {
56c4a2cb 123717 var lookahead, types, typesSoFar, typeObj, type, structure;
eb39fafa
DC
123718
123719 if ('::' === peek(tokens)) {
123720 throw new Error("No comment before comment separator '::' found.");
123721 }
123722
123723 lookahead = tokens[1];
123724
123725 if (lookahead != null && lookahead === '::') {
123726 tokens.shift();
123727 tokens.shift();
123728 }
123729
123730 types = [];
123731 typesSoFar = {};
123732
123733 if ('Maybe' === peek(tokens)) {
123734 tokens.shift();
123735 types = [{
123736 type: 'Undefined'
123737 }, {
123738 type: 'Null'
123739 }];
123740 typesSoFar = {
123741 Undefined: true,
123742 Null: true
123743 };
123744 }
123745
123746 for (;;) {
56c4a2cb 123747 typeObj = consumeType(tokens), type = typeObj.type, structure = typeObj.structure;
eb39fafa
DC
123748
123749 if (!typesSoFar[type]) {
123750 types.push(typeObj);
123751 }
123752
56c4a2cb
DC
123753 if (structure == null) {
123754 typesSoFar[type] = true;
123755 }
eb39fafa
DC
123756
123757 if (!maybeConsumeOp(tokens, '|')) {
123758 break;
123759 }
123760 }
123761
123762 return types;
123763 }
123764
123765 tokenRegex = RegExp('\\.\\.\\.|::|->|' + identifierRegex.source + '|\\S', 'g');
123766
123767 module.exports = function (input) {
123768 var tokens, e;
123769
123770 if (!input.length) {
123771 throw new Error('No type specified.');
123772 }
123773
123774 tokens = input.match(tokenRegex) || [];
123775
123776 if (in$('->', tokens)) {
123777 throw new Error("Function types are not supported.\ To validate that something is a function, you may use 'Function'.");
123778 }
123779
123780 try {
123781 return consumeTypes(tokens);
123782 } catch (e$) {
123783 e = e$;
123784 throw new Error(e.message + " - Remaining tokens: " + JSON.stringify(tokens) + " - Initial input: '" + input + "'");
123785 }
123786 };
123787
123788 function in$(x, xs) {
123789 var i = -1,
123790 l = xs.length >>> 0;
123791
123792 while (++i < l) if (x === xs[i]) return true;
123793
123794 return false;
123795 }
123796}).call(this);
123797
123798/***/ }),
6a5a0f88 123799/* 811 */
eb39fafa
DC
123800/***/ (function(module, exports, __webpack_require__) {
123801
56c4a2cb 123802// Generated by LiveScript 1.6.0
eb39fafa
DC
123803(function () {
123804 var ref$,
123805 any,
123806 all,
123807 isItNaN,
123808 types,
123809 defaultType,
eb39fafa 123810 toString$ = {}.toString;
6a5a0f88 123811 ref$ = __webpack_require__(802), any = ref$.any, all = ref$.all, isItNaN = ref$.isItNaN;
eb39fafa
DC
123812 types = {
123813 Number: {
123814 typeOf: 'Number',
123815 validate: function validate(it) {
123816 return !isItNaN(it);
123817 }
123818 },
123819 NaN: {
123820 typeOf: 'Number',
123821 validate: isItNaN
123822 },
123823 Int: {
123824 typeOf: 'Number',
123825 validate: function validate(it) {
123826 return !isItNaN(it) && it % 1 === 0;
123827 }
123828 },
123829 Float: {
123830 typeOf: 'Number',
123831 validate: function validate(it) {
123832 return !isItNaN(it);
123833 }
123834 },
123835 Date: {
123836 typeOf: 'Date',
123837 validate: function validate(it) {
123838 return !isItNaN(it.getTime());
123839 }
123840 }
123841 };
123842 defaultType = {
123843 array: 'Array',
123844 tuple: 'Array'
123845 };
123846
56c4a2cb 123847 function checkArray(input, type, options) {
eb39fafa 123848 return all(function (it) {
56c4a2cb 123849 return checkMultiple(it, type.of, options);
eb39fafa
DC
123850 }, input);
123851 }
123852
56c4a2cb 123853 function checkTuple(input, type, options) {
eb39fafa
DC
123854 var i, i$, ref$, len$, types;
123855 i = 0;
123856
123857 for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
123858 types = ref$[i$];
123859
56c4a2cb 123860 if (!checkMultiple(input[i], types, options)) {
eb39fafa
DC
123861 return false;
123862 }
123863
123864 i++;
123865 }
123866
123867 return input.length <= i;
123868 }
123869
56c4a2cb 123870 function checkFields(input, type, options) {
eb39fafa
DC
123871 var inputKeys, numInputKeys, k, numOfKeys, key, ref$, types;
123872 inputKeys = {};
123873 numInputKeys = 0;
123874
123875 for (k in input) {
123876 inputKeys[k] = true;
123877 numInputKeys++;
123878 }
123879
123880 numOfKeys = 0;
123881
123882 for (key in ref$ = type.of) {
123883 types = ref$[key];
123884
56c4a2cb 123885 if (!checkMultiple(input[key], types, options)) {
eb39fafa
DC
123886 return false;
123887 }
123888
123889 if (inputKeys[key]) {
123890 numOfKeys++;
123891 }
123892 }
123893
123894 return type.subset || numInputKeys === numOfKeys;
123895 }
123896
56c4a2cb 123897 function checkStructure(input, type, options) {
eb39fafa
DC
123898 if (!(input instanceof Object)) {
123899 return false;
123900 }
123901
123902 switch (type.structure) {
123903 case 'fields':
56c4a2cb 123904 return checkFields(input, type, options);
eb39fafa
DC
123905
123906 case 'array':
56c4a2cb 123907 return checkArray(input, type, options);
eb39fafa
DC
123908
123909 case 'tuple':
56c4a2cb 123910 return checkTuple(input, type, options);
eb39fafa
DC
123911 }
123912 }
123913
56c4a2cb 123914 function check(input, typeObj, options) {
eb39fafa
DC
123915 var type, structure, setting, that;
123916 type = typeObj.type, structure = typeObj.structure;
123917
123918 if (type) {
123919 if (type === '*') {
123920 return true;
123921 }
123922
56c4a2cb 123923 setting = options.customTypes[type] || types[type];
eb39fafa
DC
123924
123925 if (setting) {
56c4a2cb 123926 return (setting.typeOf === void 8 || setting.typeOf === toString$.call(input).slice(8, -1)) && setting.validate(input);
eb39fafa 123927 } else {
56c4a2cb 123928 return type === toString$.call(input).slice(8, -1) && (!structure || checkStructure(input, typeObj, options));
eb39fafa
DC
123929 }
123930 } else if (structure) {
123931 if (that = defaultType[structure]) {
123932 if (that !== toString$.call(input).slice(8, -1)) {
123933 return false;
123934 }
123935 }
123936
56c4a2cb 123937 return checkStructure(input, typeObj, options);
eb39fafa
DC
123938 } else {
123939 throw new Error("No type defined. Input: " + input + ".");
123940 }
123941 }
123942
56c4a2cb 123943 function checkMultiple(input, types, options) {
eb39fafa
DC
123944 if (toString$.call(types).slice(8, -1) !== 'Array') {
123945 throw new Error("Types must be in an array. Input: " + input + ".");
123946 }
123947
123948 return any(function (it) {
56c4a2cb 123949 return check(input, it, options);
eb39fafa
DC
123950 }, types);
123951 }
123952
123953 module.exports = function (parsedType, input, options) {
123954 options == null && (options = {});
56c4a2cb
DC
123955
123956 if (options.customTypes == null) {
123957 options.customTypes = {};
123958 }
123959
123960 return checkMultiple(input, parsedType, options);
eb39fafa
DC
123961 };
123962}).call(this);
123963
123964/***/ }),
6a5a0f88 123965/* 812 */
eb39fafa
DC
123966/***/ (function(module, exports, __webpack_require__) {
123967
123968"use strict";
123969/**
123970 * @fileoverview The event generator for AST nodes.
123971 * @author Toru Nagashima
123972 */
123973 //------------------------------------------------------------------------------
123974// Requirements
123975//------------------------------------------------------------------------------
123976
6a5a0f88 123977const esquery = __webpack_require__(813);
eb39fafa
DC
123978
123979const lodash = __webpack_require__(403); //------------------------------------------------------------------------------
123980// Typedefs
123981//------------------------------------------------------------------------------
123982
123983/**
123984 * An object describing an AST selector
123985 * @typedef {Object} ASTSelector
123986 * @property {string} rawSelector The string that was parsed into this selector
123987 * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering
123988 * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
123989 * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match,
123990 * or `null` if all node types could cause a match
123991 * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector
123992 * @property {number} identifierCount The total number of identifier queries in this selector
123993 */
123994//------------------------------------------------------------------------------
123995// Helpers
123996//------------------------------------------------------------------------------
123997
123998/**
123999 * Gets the possible types of a selector
124000 * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
124001 * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it
124002 */
124003
124004
124005function getPossibleTypes(parsedSelector) {
124006 switch (parsedSelector.type) {
124007 case "identifier":
124008 return [parsedSelector.value];
124009
124010 case "matches":
124011 {
124012 const typesForComponents = parsedSelector.selectors.map(getPossibleTypes);
124013
124014 if (typesForComponents.every(Boolean)) {
124015 return lodash.union(...typesForComponents);
124016 }
124017
124018 return null;
124019 }
124020
124021 case "compound":
124022 {
124023 const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent); // If all of the components could match any type, then the compound could also match any type.
124024
124025 if (!typesForComponents.length) {
124026 return null;
124027 }
124028 /*
124029 * If at least one of the components could only match a particular type, the compound could only match
124030 * the intersection of those types.
124031 */
124032
124033
124034 return lodash.intersection(...typesForComponents);
124035 }
124036
124037 case "child":
124038 case "descendant":
124039 case "sibling":
124040 case "adjacent":
124041 return getPossibleTypes(parsedSelector.right);
124042
124043 default:
124044 return null;
124045 }
124046}
124047/**
124048 * Counts the number of class, pseudo-class, and attribute queries in this selector
124049 * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
124050 * @returns {number} The number of class, pseudo-class, and attribute queries in this selector
124051 */
124052
124053
124054function countClassAttributes(parsedSelector) {
124055 switch (parsedSelector.type) {
124056 case "child":
124057 case "descendant":
124058 case "sibling":
124059 case "adjacent":
124060 return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
124061
124062 case "compound":
124063 case "not":
124064 case "matches":
124065 return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
124066
124067 case "attribute":
124068 case "field":
124069 case "nth-child":
124070 case "nth-last-child":
124071 return 1;
124072
124073 default:
124074 return 0;
124075 }
124076}
124077/**
124078 * Counts the number of identifier queries in this selector
124079 * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
124080 * @returns {number} The number of identifier queries
124081 */
124082
124083
124084function countIdentifiers(parsedSelector) {
124085 switch (parsedSelector.type) {
124086 case "child":
124087 case "descendant":
124088 case "sibling":
124089 case "adjacent":
124090 return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
124091
124092 case "compound":
124093 case "not":
124094 case "matches":
124095 return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
124096
124097 case "identifier":
124098 return 1;
124099
124100 default:
124101 return 0;
124102 }
124103}
124104/**
124105 * Compares the specificity of two selector objects, with CSS-like rules.
124106 * @param {ASTSelector} selectorA An AST selector descriptor
124107 * @param {ASTSelector} selectorB Another AST selector descriptor
124108 * @returns {number}
124109 * a value less than 0 if selectorA is less specific than selectorB
124110 * a value greater than 0 if selectorA is more specific than selectorB
124111 * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically
124112 * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically
124113 */
124114
124115
124116function compareSpecificity(selectorA, selectorB) {
124117 return selectorA.attributeCount - selectorB.attributeCount || selectorA.identifierCount - selectorB.identifierCount || (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
124118}
124119/**
124120 * Parses a raw selector string, and throws a useful error if parsing fails.
124121 * @param {string} rawSelector A raw AST selector
124122 * @returns {Object} An object (from esquery) describing the matching behavior of this selector
124123 * @throws {Error} An error if the selector is invalid
124124 */
124125
124126
124127function tryParseSelector(rawSelector) {
124128 try {
124129 return esquery.parse(rawSelector.replace(/:exit$/u, ""));
124130 } catch (err) {
124131 if (err.location && err.location.start && typeof err.location.start.offset === "number") {
124132 throw new SyntaxError("Syntax error in selector \"".concat(rawSelector, "\" at position ").concat(err.location.start.offset, ": ").concat(err.message));
124133 }
124134
124135 throw err;
124136 }
124137}
124138/**
124139 * Parses a raw selector string, and returns the parsed selector along with specificity and type information.
124140 * @param {string} rawSelector A raw AST selector
124141 * @returns {ASTSelector} A selector descriptor
124142 */
124143
124144
124145const parseSelector = lodash.memoize(rawSelector => {
124146 const parsedSelector = tryParseSelector(rawSelector);
124147 return {
124148 rawSelector,
124149 isExit: rawSelector.endsWith(":exit"),
124150 parsedSelector,
124151 listenerTypes: getPossibleTypes(parsedSelector),
124152 attributeCount: countClassAttributes(parsedSelector),
124153 identifierCount: countIdentifiers(parsedSelector)
124154 };
124155}); //------------------------------------------------------------------------------
124156// Public Interface
124157//------------------------------------------------------------------------------
124158
124159/**
124160 * The event generator for AST nodes.
124161 * This implements below interface.
124162 *
124163 * ```ts
124164 * interface EventGenerator {
124165 * emitter: SafeEmitter;
124166 * enterNode(node: ASTNode): void;
124167 * leaveNode(node: ASTNode): void;
124168 * }
124169 * ```
124170 */
124171
124172class NodeEventGenerator {
124173 // eslint-disable-next-line jsdoc/require-description
124174
124175 /**
124176 * @param {SafeEmitter} emitter
124177 * An SafeEmitter which is the destination of events. This emitter must already
124178 * have registered listeners for all of the events that it needs to listen for.
124179 * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.)
124180 * @returns {NodeEventGenerator} new instance
124181 */
124182 constructor(emitter) {
124183 this.emitter = emitter;
124184 this.currentAncestry = [];
124185 this.enterSelectorsByNodeType = new Map();
124186 this.exitSelectorsByNodeType = new Map();
124187 this.anyTypeEnterSelectors = [];
124188 this.anyTypeExitSelectors = [];
124189 emitter.eventNames().forEach(rawSelector => {
124190 const selector = parseSelector(rawSelector);
124191
124192 if (selector.listenerTypes) {
124193 const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
124194 selector.listenerTypes.forEach(nodeType => {
124195 if (!typeMap.has(nodeType)) {
124196 typeMap.set(nodeType, []);
124197 }
124198
124199 typeMap.get(nodeType).push(selector);
124200 });
124201 return;
124202 }
124203
124204 const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
124205 selectors.push(selector);
124206 });
124207 this.anyTypeEnterSelectors.sort(compareSpecificity);
124208 this.anyTypeExitSelectors.sort(compareSpecificity);
124209 this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
124210 this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
124211 }
124212 /**
124213 * Checks a selector against a node, and emits it if it matches
124214 * @param {ASTNode} node The node to check
124215 * @param {ASTSelector} selector An AST selector descriptor
124216 * @returns {void}
124217 */
124218
124219
124220 applySelector(node, selector) {
124221 if (esquery.matches(node, selector.parsedSelector, this.currentAncestry)) {
124222 this.emitter.emit(selector.rawSelector, node);
124223 }
124224 }
124225 /**
124226 * Applies all appropriate selectors to a node, in specificity order
124227 * @param {ASTNode} node The node to check
124228 * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
124229 * @returns {void}
124230 */
124231
124232
124233 applySelectors(node, isExit) {
124234 const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
124235 const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
124236 /*
124237 * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
124238 * Iterate through each of them, applying selectors in the right order.
124239 */
124240
124241 let selectorsByTypeIndex = 0;
124242 let anyTypeSelectorsIndex = 0;
124243
124244 while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
124245 if (selectorsByTypeIndex >= selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length && compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0) {
124246 this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
124247 } else {
124248 this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
124249 }
124250 }
124251 }
124252 /**
124253 * Emits an event of entering AST node.
124254 * @param {ASTNode} node A node which was entered.
124255 * @returns {void}
124256 */
124257
124258
124259 enterNode(node) {
124260 if (node.parent) {
124261 this.currentAncestry.unshift(node.parent);
124262 }
124263
124264 this.applySelectors(node, false);
124265 }
124266 /**
124267 * Emits an event of leaving AST node.
124268 * @param {ASTNode} node A node which was left.
124269 * @returns {void}
124270 */
124271
124272
124273 leaveNode(node) {
124274 this.applySelectors(node, true);
124275 this.currentAncestry.shift();
124276 }
124277
124278}
124279
124280module.exports = NodeEventGenerator;
124281
124282/***/ }),
6a5a0f88 124283/* 813 */
eb39fafa
DC
124284/***/ (function(module, exports, __webpack_require__) {
124285
124286!function (e, t) {
124287 true ? module.exports = t() : undefined;
124288}(this, function () {
124289 "use strict";
124290
56c4a2cb
DC
124291 function e(t) {
124292 return (e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) {
124293 return typeof e;
124294 } : function (e) {
124295 return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
124296 })(t);
124297 }
124298
124299 function t(e, t) {
124300 return function (e) {
124301 if (Array.isArray(e)) return e;
124302 }(e) || function (e, t) {
124303 if ("undefined" == typeof Symbol || !(Symbol.iterator in Object(e))) return;
124304 var r = [],
124305 n = !0,
124306 o = !1,
124307 a = void 0;
124308
124309 try {
124310 for (var s, i = e[Symbol.iterator](); !(n = (s = i.next()).done) && (r.push(s.value), !t || r.length !== t); n = !0);
124311 } catch (e) {
124312 o = !0, a = e;
124313 } finally {
124314 try {
124315 n || null == i.return || i.return();
124316 } finally {
124317 if (o) throw a;
124318 }
124319 }
124320
124321 return r;
124322 }(e, t) || n(e, t) || function () {
124323 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
124324 }();
124325 }
124326
124327 function r(e) {
124328 return function (e) {
124329 if (Array.isArray(e)) return o(e);
124330 }(e) || function (e) {
124331 if ("undefined" != typeof Symbol && Symbol.iterator in Object(e)) return Array.from(e);
124332 }(e) || n(e) || function () {
124333 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
124334 }();
124335 }
124336
124337 function n(e, t) {
124338 if (e) {
124339 if ("string" == typeof e) return o(e, t);
124340 var r = Object.prototype.toString.call(e).slice(8, -1);
124341 return "Object" === r && e.constructor && (r = e.constructor.name), "Map" === r || "Set" === r ? Array.from(r) : "Arguments" === r || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r) ? o(e, t) : void 0;
124342 }
124343 }
124344
124345 function o(e, t) {
124346 (null == t || t > e.length) && (t = e.length);
124347
124348 for (var r = 0, n = new Array(t); r < t; r++) n[r] = e[r];
124349
124350 return n;
124351 }
124352
eb39fafa
DC
124353 "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self && self;
124354
56c4a2cb 124355 function a(e, t) {
eb39fafa
DC
124356 return e(t = {
124357 exports: {}
124358 }, t.exports), t.exports;
124359 }
124360
56c4a2cb 124361 var s = a(function (e, t) {
eb39fafa 124362 !function e(t) {
56c4a2cb 124363 var r, n, o, a, s, i;
eb39fafa
DC
124364
124365 function l(e) {
124366 var t,
124367 r,
124368 n = {};
124369
124370 for (t in e) e.hasOwnProperty(t) && (r = e[t], n[t] = "object" == typeof r && null !== r ? l(r) : r);
124371
124372 return n;
124373 }
124374
124375 function u(e, t) {
124376 this.parent = e, this.key = t;
124377 }
124378
124379 function c(e, t, r, n) {
124380 this.node = e, this.path = t, this.wrap = r, this.ref = n;
124381 }
124382
56c4a2cb 124383 function f() {}
eb39fafa 124384
56c4a2cb 124385 function p(e) {
eb39fafa
DC
124386 return null != e && "object" == typeof e && "string" == typeof e.type;
124387 }
124388
124389 function h(e, t) {
124390 return (e === r.ObjectExpression || e === r.ObjectPattern) && "properties" === t;
124391 }
124392
124393 function d(e, t) {
56c4a2cb
DC
124394 for (var r = e.length - 1; r >= 0; --r) if (e[r].node === t) return !0;
124395
124396 return !1;
eb39fafa
DC
124397 }
124398
56c4a2cb
DC
124399 function y(e, t) {
124400 return new f().traverse(e, t);
124401 }
124402
124403 function m(e, t) {
eb39fafa
DC
124404 var r;
124405 return r = function (e, t) {
56c4a2cb 124406 var r, n, o, a;
eb39fafa 124407
56c4a2cb 124408 for (n = e.length, o = 0; n;) t(e[a = o + (r = n >>> 1)]) ? n = r : (o = a + 1, n -= r + 1);
eb39fafa 124409
56c4a2cb 124410 return o;
eb39fafa
DC
124411 }(t, function (t) {
124412 return t.range[0] > e.range[0];
124413 }), e.extendedRange = [e.range[0], e.range[1]], r !== t.length && (e.extendedRange[1] = t[r].range[0]), (r -= 1) >= 0 && (e.extendedRange[0] = t[r].range[1]), e;
124414 }
124415
124416 return r = {
124417 AssignmentExpression: "AssignmentExpression",
124418 AssignmentPattern: "AssignmentPattern",
124419 ArrayExpression: "ArrayExpression",
124420 ArrayPattern: "ArrayPattern",
124421 ArrowFunctionExpression: "ArrowFunctionExpression",
124422 AwaitExpression: "AwaitExpression",
124423 BlockStatement: "BlockStatement",
124424 BinaryExpression: "BinaryExpression",
124425 BreakStatement: "BreakStatement",
124426 CallExpression: "CallExpression",
124427 CatchClause: "CatchClause",
124428 ClassBody: "ClassBody",
124429 ClassDeclaration: "ClassDeclaration",
124430 ClassExpression: "ClassExpression",
124431 ComprehensionBlock: "ComprehensionBlock",
124432 ComprehensionExpression: "ComprehensionExpression",
124433 ConditionalExpression: "ConditionalExpression",
124434 ContinueStatement: "ContinueStatement",
124435 DebuggerStatement: "DebuggerStatement",
124436 DirectiveStatement: "DirectiveStatement",
124437 DoWhileStatement: "DoWhileStatement",
124438 EmptyStatement: "EmptyStatement",
124439 ExportAllDeclaration: "ExportAllDeclaration",
124440 ExportDefaultDeclaration: "ExportDefaultDeclaration",
124441 ExportNamedDeclaration: "ExportNamedDeclaration",
124442 ExportSpecifier: "ExportSpecifier",
124443 ExpressionStatement: "ExpressionStatement",
124444 ForStatement: "ForStatement",
124445 ForInStatement: "ForInStatement",
124446 ForOfStatement: "ForOfStatement",
124447 FunctionDeclaration: "FunctionDeclaration",
124448 FunctionExpression: "FunctionExpression",
124449 GeneratorExpression: "GeneratorExpression",
124450 Identifier: "Identifier",
124451 IfStatement: "IfStatement",
124452 ImportExpression: "ImportExpression",
124453 ImportDeclaration: "ImportDeclaration",
124454 ImportDefaultSpecifier: "ImportDefaultSpecifier",
124455 ImportNamespaceSpecifier: "ImportNamespaceSpecifier",
124456 ImportSpecifier: "ImportSpecifier",
124457 Literal: "Literal",
124458 LabeledStatement: "LabeledStatement",
124459 LogicalExpression: "LogicalExpression",
124460 MemberExpression: "MemberExpression",
124461 MetaProperty: "MetaProperty",
124462 MethodDefinition: "MethodDefinition",
124463 ModuleSpecifier: "ModuleSpecifier",
124464 NewExpression: "NewExpression",
124465 ObjectExpression: "ObjectExpression",
124466 ObjectPattern: "ObjectPattern",
124467 Program: "Program",
124468 Property: "Property",
124469 RestElement: "RestElement",
124470 ReturnStatement: "ReturnStatement",
124471 SequenceExpression: "SequenceExpression",
124472 SpreadElement: "SpreadElement",
124473 Super: "Super",
124474 SwitchStatement: "SwitchStatement",
124475 SwitchCase: "SwitchCase",
124476 TaggedTemplateExpression: "TaggedTemplateExpression",
124477 TemplateElement: "TemplateElement",
124478 TemplateLiteral: "TemplateLiteral",
124479 ThisExpression: "ThisExpression",
124480 ThrowStatement: "ThrowStatement",
124481 TryStatement: "TryStatement",
124482 UnaryExpression: "UnaryExpression",
124483 UpdateExpression: "UpdateExpression",
124484 VariableDeclaration: "VariableDeclaration",
124485 VariableDeclarator: "VariableDeclarator",
124486 WhileStatement: "WhileStatement",
124487 WithStatement: "WithStatement",
124488 YieldExpression: "YieldExpression"
56c4a2cb 124489 }, o = {
eb39fafa
DC
124490 AssignmentExpression: ["left", "right"],
124491 AssignmentPattern: ["left", "right"],
124492 ArrayExpression: ["elements"],
124493 ArrayPattern: ["elements"],
124494 ArrowFunctionExpression: ["params", "body"],
124495 AwaitExpression: ["argument"],
124496 BlockStatement: ["body"],
124497 BinaryExpression: ["left", "right"],
124498 BreakStatement: ["label"],
124499 CallExpression: ["callee", "arguments"],
124500 CatchClause: ["param", "body"],
124501 ClassBody: ["body"],
124502 ClassDeclaration: ["id", "superClass", "body"],
124503 ClassExpression: ["id", "superClass", "body"],
124504 ComprehensionBlock: ["left", "right"],
124505 ComprehensionExpression: ["blocks", "filter", "body"],
124506 ConditionalExpression: ["test", "consequent", "alternate"],
124507 ContinueStatement: ["label"],
124508 DebuggerStatement: [],
124509 DirectiveStatement: [],
124510 DoWhileStatement: ["body", "test"],
124511 EmptyStatement: [],
124512 ExportAllDeclaration: ["source"],
124513 ExportDefaultDeclaration: ["declaration"],
124514 ExportNamedDeclaration: ["declaration", "specifiers", "source"],
124515 ExportSpecifier: ["exported", "local"],
124516 ExpressionStatement: ["expression"],
124517 ForStatement: ["init", "test", "update", "body"],
124518 ForInStatement: ["left", "right", "body"],
124519 ForOfStatement: ["left", "right", "body"],
124520 FunctionDeclaration: ["id", "params", "body"],
124521 FunctionExpression: ["id", "params", "body"],
124522 GeneratorExpression: ["blocks", "filter", "body"],
124523 Identifier: [],
124524 IfStatement: ["test", "consequent", "alternate"],
124525 ImportExpression: ["source"],
124526 ImportDeclaration: ["specifiers", "source"],
124527 ImportDefaultSpecifier: ["local"],
124528 ImportNamespaceSpecifier: ["local"],
124529 ImportSpecifier: ["imported", "local"],
124530 Literal: [],
124531 LabeledStatement: ["label", "body"],
124532 LogicalExpression: ["left", "right"],
124533 MemberExpression: ["object", "property"],
124534 MetaProperty: ["meta", "property"],
124535 MethodDefinition: ["key", "value"],
124536 ModuleSpecifier: [],
124537 NewExpression: ["callee", "arguments"],
124538 ObjectExpression: ["properties"],
124539 ObjectPattern: ["properties"],
124540 Program: ["body"],
124541 Property: ["key", "value"],
124542 RestElement: ["argument"],
124543 ReturnStatement: ["argument"],
124544 SequenceExpression: ["expressions"],
124545 SpreadElement: ["argument"],
124546 Super: [],
124547 SwitchStatement: ["discriminant", "cases"],
124548 SwitchCase: ["test", "consequent"],
124549 TaggedTemplateExpression: ["tag", "quasi"],
124550 TemplateElement: [],
124551 TemplateLiteral: ["quasis", "expressions"],
124552 ThisExpression: [],
124553 ThrowStatement: ["argument"],
124554 TryStatement: ["block", "handler", "finalizer"],
124555 UnaryExpression: ["argument"],
124556 UpdateExpression: ["argument"],
124557 VariableDeclaration: ["declarations"],
124558 VariableDeclarator: ["id", "init"],
124559 WhileStatement: ["test", "body"],
124560 WithStatement: ["object", "body"],
124561 YieldExpression: ["argument"]
124562 }, n = {
56c4a2cb
DC
124563 Break: a = {},
124564 Skip: s = {},
eb39fafa
DC
124565 Remove: i = {}
124566 }, u.prototype.replace = function (e) {
124567 this.parent[this.key] = e;
124568 }, u.prototype.remove = function () {
124569 return Array.isArray(this.parent) ? (this.parent.splice(this.key, 1), !0) : (this.replace(null), !1);
56c4a2cb
DC
124570 }, f.prototype.path = function () {
124571 var e, t, r, n, o;
eb39fafa 124572
56c4a2cb 124573 function a(e, t) {
eb39fafa
DC
124574 if (Array.isArray(t)) for (r = 0, n = t.length; r < n; ++r) e.push(t[r]);else e.push(t);
124575 }
124576
124577 if (!this.__current.path) return null;
124578
56c4a2cb 124579 for (o = [], e = 2, t = this.__leavelist.length; e < t; ++e) a(o, this.__leavelist[e].path);
eb39fafa 124580
56c4a2cb
DC
124581 return a(o, this.__current.path), o;
124582 }, f.prototype.type = function () {
eb39fafa 124583 return this.current().type || this.__current.wrap;
56c4a2cb 124584 }, f.prototype.parents = function () {
eb39fafa
DC
124585 var e, t, r;
124586
124587 for (r = [], e = 1, t = this.__leavelist.length; e < t; ++e) r.push(this.__leavelist[e].node);
124588
124589 return r;
56c4a2cb 124590 }, f.prototype.current = function () {
eb39fafa 124591 return this.__current.node;
56c4a2cb 124592 }, f.prototype.__execute = function (e, t) {
eb39fafa
DC
124593 var r, n;
124594 return n = void 0, r = this.__current, this.__current = t, this.__state = null, e && (n = e.call(this, t.node, this.__leavelist[this.__leavelist.length - 1].node)), this.__current = r, n;
56c4a2cb 124595 }, f.prototype.notify = function (e) {
eb39fafa 124596 this.__state = e;
56c4a2cb
DC
124597 }, f.prototype.skip = function () {
124598 this.notify(s);
124599 }, f.prototype.break = function () {
eb39fafa 124600 this.notify(a);
56c4a2cb 124601 }, f.prototype.remove = function () {
eb39fafa 124602 this.notify(i);
56c4a2cb
DC
124603 }, f.prototype.__initialize = function (e, t) {
124604 this.visitor = t, this.root = e, this.__worklist = [], this.__leavelist = [], this.__current = null, this.__state = null, this.__fallback = null, "iteration" === t.fallback ? this.__fallback = Object.keys : "function" == typeof t.fallback && (this.__fallback = t.fallback), this.__keys = o, t.keys && (this.__keys = Object.assign(Object.create(this.__keys), t.keys));
124605 }, f.prototype.traverse = function (e, t) {
124606 var r, n, o, i, l, u, f, y, m, x, g, v;
eb39fafa 124607
56c4a2cb
DC
124608 for (this.__initialize(e, t), v = {}, r = this.__worklist, n = this.__leavelist, r.push(new c(e, null, null, null)), n.push(new c(null, null, null, null)); r.length;) if ((o = r.pop()) !== v) {
124609 if (o.node) {
124610 if (u = this.__execute(t.enter, o), this.__state === a || u === a) return;
124611 if (r.push(v), n.push(o), this.__state === s || u === s) continue;
eb39fafa 124612
56c4a2cb 124613 if (l = (i = o.node).type || o.wrap, !(x = this.__keys[l])) {
eb39fafa 124614 if (!this.__fallback) throw new Error("Unknown node type " + l + ".");
56c4a2cb 124615 x = this.__fallback(i);
eb39fafa
DC
124616 }
124617
56c4a2cb
DC
124618 for (y = x.length; (y -= 1) >= 0;) if (g = i[f = x[y]]) if (Array.isArray(g)) {
124619 for (m = g.length; (m -= 1) >= 0;) if (g[m] && !d(n, g[m])) {
124620 if (h(l, x[y])) o = new c(g[m], [f, m], "Property", null);else {
124621 if (!p(g[m])) continue;
124622 o = new c(g[m], [f, m], null, null);
eb39fafa 124623 }
56c4a2cb 124624 r.push(o);
eb39fafa 124625 }
56c4a2cb
DC
124626 } else if (p(g)) {
124627 if (d(n, g)) continue;
124628 r.push(new c(g, f, null, null));
124629 }
eb39fafa 124630 }
56c4a2cb
DC
124631 } else if (o = n.pop(), u = this.__execute(t.leave, o), this.__state === a || u === a) return;
124632 }, f.prototype.replace = function (e, t) {
124633 var r, n, o, l, f, d, y, m, x, g, v, A, b;
eb39fafa 124634
56c4a2cb
DC
124635 function E(e) {
124636 var t, n, o, a;
124637 if (e.ref.remove()) for (n = e.ref.key, a = e.ref.parent, t = r.length; t--;) if ((o = r[t]).ref && o.ref.parent === a) {
124638 if (o.ref.key < n) break;
124639 --o.ref.key;
eb39fafa
DC
124640 }
124641 }
124642
124643 for (this.__initialize(e, t), v = {}, r = this.__worklist, n = this.__leavelist, d = new c(e, null, null, new u(A = {
124644 root: e
124645 }, "root")), r.push(d), n.push(d); r.length;) if ((d = r.pop()) !== v) {
56c4a2cb 124646 if (void 0 !== (f = this.__execute(t.enter, d)) && f !== a && f !== s && f !== i && (d.ref.replace(f), d.node = f), this.__state !== i && f !== i || (E(d), d.node = null), this.__state === a || f === a) return A.root;
eb39fafa 124647
56c4a2cb
DC
124648 if ((o = d.node) && (r.push(v), n.push(d), this.__state !== s && f !== s)) {
124649 if (l = o.type || d.wrap, !(x = this.__keys[l])) {
eb39fafa 124650 if (!this.__fallback) throw new Error("Unknown node type " + l + ".");
56c4a2cb 124651 x = this.__fallback(o);
eb39fafa
DC
124652 }
124653
56c4a2cb 124654 for (y = x.length; (y -= 1) >= 0;) if (g = o[b = x[y]]) if (Array.isArray(g)) {
eb39fafa 124655 for (m = g.length; (m -= 1) >= 0;) if (g[m]) {
56c4a2cb
DC
124656 if (h(l, x[y])) d = new c(g[m], [b, m], "Property", new u(g, m));else {
124657 if (!p(g[m])) continue;
124658 d = new c(g[m], [b, m], null, new u(g, m));
eb39fafa
DC
124659 }
124660 r.push(d);
124661 }
56c4a2cb 124662 } else p(g) && r.push(new c(g, b, null, new u(o, b)));
eb39fafa 124663 }
56c4a2cb 124664 } else if (d = n.pop(), void 0 !== (f = this.__execute(t.leave, d)) && f !== a && f !== s && f !== i && d.ref.replace(f), this.__state !== i && f !== i || E(d), this.__state === a || f === a) return A.root;
eb39fafa
DC
124665
124666 return A.root;
56c4a2cb
DC
124667 }, t.Syntax = r, t.traverse = y, t.replace = function (e, t) {
124668 return new f().replace(e, t);
eb39fafa 124669 }, t.attachComments = function (e, t, r) {
56c4a2cb 124670 var o,
eb39fafa 124671 a,
56c4a2cb 124672 s,
eb39fafa
DC
124673 i,
124674 u = [];
124675 if (!e.range) throw new Error("attachComments needs range information");
124676
124677 if (!r.length) {
124678 if (t.length) {
56c4a2cb 124679 for (s = 0, a = t.length; s < a; s += 1) (o = l(t[s])).extendedRange = [0, e.range[0]], u.push(o);
eb39fafa
DC
124680
124681 e.leadingComments = u;
124682 }
124683
124684 return e;
124685 }
124686
56c4a2cb 124687 for (s = 0, a = t.length; s < a; s += 1) u.push(m(l(t[s]), r));
eb39fafa 124688
56c4a2cb 124689 return i = 0, y(e, {
eb39fafa
DC
124690 enter: function enter(e) {
124691 for (var t; i < u.length && !((t = u[i]).extendedRange[1] > e.range[0]);) t.extendedRange[1] === e.range[0] ? (e.leadingComments || (e.leadingComments = []), e.leadingComments.push(t), u.splice(i, 1)) : i += 1;
124692
124693 return i === u.length ? n.Break : u[i].extendedRange[0] > e.range[1] ? n.Skip : void 0;
124694 }
56c4a2cb 124695 }), i = 0, y(e, {
eb39fafa
DC
124696 leave: function leave(e) {
124697 for (var t; i < u.length && (t = u[i], !(e.range[1] < t.extendedRange[0]));) e.range[1] === t.extendedRange[0] ? (e.trailingComments || (e.trailingComments = []), e.trailingComments.push(t), u.splice(i, 1)) : i += 1;
124698
124699 return i === u.length ? n.Break : u[i].extendedRange[0] > e.range[1] ? n.Skip : void 0;
124700 }
124701 }), e;
56c4a2cb 124702 }, t.VisitorKeys = o, t.VisitorOption = n, t.Controller = f, t.cloneEnvironment = function () {
eb39fafa
DC
124703 return e({});
124704 }, t;
124705 }(t);
124706 }),
56c4a2cb 124707 i = a(function (e) {
eb39fafa 124708 e.exports && (e.exports = function () {
56c4a2cb
DC
124709 function e(t, r, n, o) {
124710 this.message = t, this.expected = r, this.found = n, this.location = o, this.name = "SyntaxError", "function" == typeof Error.captureStackTrace && Error.captureStackTrace(this, e);
eb39fafa
DC
124711 }
124712
124713 return function (e, t) {
124714 function r() {
124715 this.constructor = e;
124716 }
124717
124718 r.prototype = t.prototype, e.prototype = new r();
124719 }(e, Error), e.buildMessage = function (e, t) {
124720 var r = {
124721 literal: function literal(e) {
56c4a2cb 124722 return '"' + o(e.text) + '"';
eb39fafa
DC
124723 },
124724 class: function _class(e) {
124725 var t,
124726 r = "";
124727
56c4a2cb 124728 for (t = 0; t < e.parts.length; t++) r += e.parts[t] instanceof Array ? a(e.parts[t][0]) + "-" + a(e.parts[t][1]) : a(e.parts[t]);
eb39fafa
DC
124729
124730 return "[" + (e.inverted ? "^" : "") + r + "]";
124731 },
124732 any: function any(e) {
124733 return "any character";
124734 },
124735 end: function end(e) {
124736 return "end of input";
124737 },
124738 other: function other(e) {
124739 return e.description;
124740 }
124741 };
124742
124743 function n(e) {
124744 return e.charCodeAt(0).toString(16).toUpperCase();
124745 }
124746
56c4a2cb 124747 function o(e) {
eb39fafa
DC
124748 return e.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function (e) {
124749 return "\\x0" + n(e);
124750 }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (e) {
124751 return "\\x" + n(e);
124752 });
124753 }
124754
56c4a2cb 124755 function a(e) {
eb39fafa
DC
124756 return e.replace(/\\/g, "\\\\").replace(/\]/g, "\\]").replace(/\^/g, "\\^").replace(/-/g, "\\-").replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function (e) {
124757 return "\\x0" + n(e);
124758 }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (e) {
124759 return "\\x" + n(e);
124760 });
124761 }
124762
124763 return "Expected " + function (e) {
124764 var t,
124765 n,
56c4a2cb
DC
124766 o,
124767 a = new Array(e.length);
eb39fafa 124768
56c4a2cb 124769 for (t = 0; t < e.length; t++) a[t] = (o = e[t], r[o.type](o));
eb39fafa 124770
56c4a2cb
DC
124771 if (a.sort(), a.length > 0) {
124772 for (t = 1, n = 1; t < a.length; t++) a[t - 1] !== a[t] && (a[n] = a[t], n++);
eb39fafa 124773
56c4a2cb 124774 a.length = n;
eb39fafa
DC
124775 }
124776
56c4a2cb 124777 switch (a.length) {
eb39fafa 124778 case 1:
56c4a2cb 124779 return a[0];
eb39fafa
DC
124780
124781 case 2:
56c4a2cb 124782 return a[0] + " or " + a[1];
eb39fafa
DC
124783
124784 default:
56c4a2cb 124785 return a.slice(0, -1).join(", ") + ", or " + a[a.length - 1];
eb39fafa
DC
124786 }
124787 }(e) + " but " + function (e) {
56c4a2cb 124788 return e ? '"' + o(e) + '"' : "end of input";
eb39fafa
DC
124789 }(t) + " found.";
124790 }, {
124791 SyntaxError: e,
124792 parse: function parse(t, r) {
124793 r = void 0 !== r ? r : {};
124794
124795 var n,
eb39fafa
DC
124796 o,
124797 a,
56c4a2cb 124798 s,
eb39fafa
DC
124799 i = {},
124800 l = {
56c4a2cb 124801 start: be
eb39fafa 124802 },
56c4a2cb 124803 u = be,
eb39fafa 124804 c = me(" ", !1),
56c4a2cb
DC
124805 f = /^[^ [\],():#!=><~+.]/,
124806 p = xe([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], !0, !1),
eb39fafa
DC
124807 h = function h(e) {
124808 return e.join("");
124809 },
124810 d = me(">", !1),
56c4a2cb 124811 y = me("~", !1),
eb39fafa 124812 m = me("+", !1),
56c4a2cb 124813 x = me(",", !1),
eb39fafa
DC
124814 g = me("!", !1),
124815 v = me("*", !1),
124816 A = me("#", !1),
56c4a2cb
DC
124817 b = me("[", !1),
124818 E = me("]", !1),
124819 S = /^[><!]/,
124820 _ = xe([">", "<", "!"], !1, !1),
124821 w = me("=", !1),
124822 C = function C(e) {
eb39fafa
DC
124823 return (e || "") + "=";
124824 },
124825 P = /^[><]/,
56c4a2cb 124826 k = xe([">", "<"], !1, !1),
eb39fafa
DC
124827 D = me(".", !1),
124828 I = function I(e, t, r) {
124829 return {
124830 type: "attribute",
124831 name: e,
124832 operator: t,
124833 value: r
124834 };
124835 },
124836 j = me('"', !1),
124837 F = /^[^\\"]/,
56c4a2cb 124838 T = xe(["\\", '"'], !0, !1),
eb39fafa
DC
124839 L = me("\\", !1),
124840 R = {
124841 type: "any"
124842 },
124843 O = function O(e, t) {
124844 return e + t;
124845 },
124846 B = function B(e) {
124847 return {
124848 type: "literal",
124849 value: (t = e.join(""), t.replace(/\\(.)/g, function (e, t) {
124850 switch (t) {
124851 case "b":
124852 return "\b";
124853
124854 case "f":
124855 return "\f";
124856
124857 case "n":
124858 return "\n";
124859
124860 case "r":
124861 return "\r";
124862
124863 case "t":
124864 return "\t";
124865
124866 case "v":
124867 return "\v";
124868
124869 default:
124870 return t;
124871 }
124872 }))
124873 };
124874 var t;
124875 },
124876 M = me("'", !1),
124877 U = /^[^\\']/,
56c4a2cb 124878 V = xe(["\\", "'"], !0, !1),
eb39fafa 124879 q = /^[0-9]/,
56c4a2cb 124880 N = xe([["0", "9"]], !1, !1),
eb39fafa 124881 W = me("type(", !1),
56c4a2cb
DC
124882 G = /^[^ )]/,
124883 z = xe([" ", ")"], !0, !1),
124884 K = me(")", !1),
124885 H = /^[imsu]/,
124886 Y = xe(["i", "m", "s", "u"], !1, !1),
124887 $ = me("/", !1),
eb39fafa 124888 J = /^[^\/]/,
56c4a2cb 124889 Q = xe(["/"], !0, !1),
eb39fafa
DC
124890 X = me(":not(", !1),
124891 Z = me(":matches(", !1),
124892 ee = me(":has(", !1),
124893 te = me(":first-child", !1),
124894 re = me(":last-child", !1),
124895 ne = me(":nth-child(", !1),
56c4a2cb
DC
124896 oe = me(":nth-last-child(", !1),
124897 ae = me(":", !1),
124898 se = me("statement", !0),
eb39fafa
DC
124899 ie = me("expression", !0),
124900 le = me("declaration", !0),
124901 ue = me("function", !0),
124902 ce = me("pattern", !0),
56c4a2cb
DC
124903 fe = 0,
124904 pe = [{
eb39fafa
DC
124905 line: 1,
124906 column: 1
124907 }],
124908 he = 0,
124909 de = [],
56c4a2cb 124910 ye = {};
eb39fafa
DC
124911
124912 if ("startRule" in r) {
124913 if (!(r.startRule in l)) throw new Error("Can't start parsing from rule \"" + r.startRule + '".');
124914 u = l[r.startRule];
124915 }
124916
124917 function me(e, t) {
124918 return {
124919 type: "literal",
124920 text: e,
124921 ignoreCase: t
124922 };
124923 }
124924
56c4a2cb 124925 function xe(e, t, r) {
eb39fafa
DC
124926 return {
124927 type: "class",
124928 parts: e,
124929 inverted: t,
124930 ignoreCase: r
124931 };
124932 }
124933
124934 function ge(e) {
124935 var r,
56c4a2cb 124936 n = pe[e];
eb39fafa
DC
124937 if (n) return n;
124938
56c4a2cb 124939 for (r = e - 1; !pe[r];) r--;
eb39fafa
DC
124940
124941 for (n = {
56c4a2cb 124942 line: (n = pe[r]).line,
eb39fafa
DC
124943 column: n.column
124944 }; r < e;) 10 === t.charCodeAt(r) ? (n.line++, n.column = 1) : n.column++, r++;
124945
56c4a2cb 124946 return pe[e] = n, n;
eb39fafa
DC
124947 }
124948
124949 function ve(e, t) {
124950 var r = ge(e),
124951 n = ge(t);
124952 return {
124953 start: {
124954 offset: e,
124955 line: r.line,
124956 column: r.column
124957 },
124958 end: {
124959 offset: t,
124960 line: n.line,
124961 column: n.column
124962 }
124963 };
124964 }
124965
124966 function Ae(e) {
56c4a2cb 124967 fe < he || (fe > he && (he = fe, de = []), de.push(e));
eb39fafa
DC
124968 }
124969
56c4a2cb 124970 function be() {
eb39fafa
DC
124971 var e,
124972 t,
124973 r,
124974 n,
56c4a2cb
DC
124975 o = 30 * fe + 0,
124976 a = ye[o];
124977 return a ? (fe = a.nextPos, a.result) : (e = fe, (t = Ee()) !== i && (r = we()) !== i && Ee() !== i ? e = t = 1 === (n = r).length ? n[0] : {
eb39fafa
DC
124978 type: "matches",
124979 selectors: n
56c4a2cb
DC
124980 } : (fe = e, e = i), e === i && (e = fe, (t = Ee()) !== i && (t = void 0), e = t), ye[o] = {
124981 nextPos: fe,
eb39fafa
DC
124982 result: e
124983 }, e);
124984 }
124985
56c4a2cb 124986 function Ee() {
eb39fafa
DC
124987 var e,
124988 r,
56c4a2cb
DC
124989 n = 30 * fe + 1,
124990 o = ye[n];
124991 if (o) return fe = o.nextPos, o.result;
eb39fafa 124992
56c4a2cb 124993 for (e = [], 32 === t.charCodeAt(fe) ? (r = " ", fe++) : (r = i, Ae(c)); r !== i;) e.push(r), 32 === t.charCodeAt(fe) ? (r = " ", fe++) : (r = i, Ae(c));
eb39fafa 124994
56c4a2cb
DC
124995 return ye[n] = {
124996 nextPos: fe,
eb39fafa
DC
124997 result: e
124998 }, e;
124999 }
125000
56c4a2cb 125001 function Se() {
eb39fafa
DC
125002 var e,
125003 r,
125004 n,
56c4a2cb
DC
125005 o = 30 * fe + 2,
125006 a = ye[o];
125007 if (a) return fe = a.nextPos, a.result;
125008 if (r = [], f.test(t.charAt(fe)) ? (n = t.charAt(fe), fe++) : (n = i, Ae(p)), n !== i) for (; n !== i;) r.push(n), f.test(t.charAt(fe)) ? (n = t.charAt(fe), fe++) : (n = i, Ae(p));else r = i;
125009 return r !== i && (r = h(r)), e = r, ye[o] = {
125010 nextPos: fe,
eb39fafa
DC
125011 result: e
125012 }, e;
125013 }
125014
56c4a2cb 125015 function _e() {
eb39fafa
DC
125016 var e,
125017 r,
125018 n,
56c4a2cb
DC
125019 o = 30 * fe + 3,
125020 a = ye[o];
125021 return a ? (fe = a.nextPos, a.result) : (e = fe, (r = Ee()) !== i ? (62 === t.charCodeAt(fe) ? (n = ">", fe++) : (n = i, Ae(d)), n !== i && Ee() !== i ? e = r = "child" : (fe = e, e = i)) : (fe = e, e = i), e === i && (e = fe, (r = Ee()) !== i ? (126 === t.charCodeAt(fe) ? (n = "~", fe++) : (n = i, Ae(y)), n !== i && Ee() !== i ? e = r = "sibling" : (fe = e, e = i)) : (fe = e, e = i), e === i && (e = fe, (r = Ee()) !== i ? (43 === t.charCodeAt(fe) ? (n = "+", fe++) : (n = i, Ae(m)), n !== i && Ee() !== i ? e = r = "adjacent" : (fe = e, e = i)) : (fe = e, e = i), e === i && (e = fe, 32 === t.charCodeAt(fe) ? (r = " ", fe++) : (r = i, Ae(c)), r !== i && (n = Ee()) !== i ? e = r = "descendant" : (fe = e, e = i)))), ye[o] = {
125022 nextPos: fe,
eb39fafa
DC
125023 result: e
125024 }, e);
125025 }
125026
56c4a2cb 125027 function we() {
eb39fafa
DC
125028 var e,
125029 r,
125030 n,
eb39fafa
DC
125031 o,
125032 a,
56c4a2cb 125033 s,
eb39fafa
DC
125034 l,
125035 u,
56c4a2cb
DC
125036 c = 30 * fe + 4,
125037 f = ye[c];
125038 if (f) return fe = f.nextPos, f.result;
eb39fafa 125039
56c4a2cb
DC
125040 if (e = fe, (r = Ce()) !== i) {
125041 for (n = [], o = fe, (a = Ee()) !== i ? (44 === t.charCodeAt(fe) ? (s = ",", fe++) : (s = i, Ae(x)), s !== i && (l = Ee()) !== i && (u = Ce()) !== i ? o = a = [a, s, l, u] : (fe = o, o = i)) : (fe = o, o = i); o !== i;) n.push(o), o = fe, (a = Ee()) !== i ? (44 === t.charCodeAt(fe) ? (s = ",", fe++) : (s = i, Ae(x)), s !== i && (l = Ee()) !== i && (u = Ce()) !== i ? o = a = [a, s, l, u] : (fe = o, o = i)) : (fe = o, o = i);
eb39fafa
DC
125042
125043 n !== i ? e = r = [r].concat(n.map(function (e) {
125044 return e[3];
56c4a2cb
DC
125045 })) : (fe = e, e = i);
125046 } else fe = e, e = i;
eb39fafa 125047
56c4a2cb
DC
125048 return ye[c] = {
125049 nextPos: fe,
eb39fafa
DC
125050 result: e
125051 }, e;
125052 }
125053
56c4a2cb 125054 function Ce() {
eb39fafa
DC
125055 var e,
125056 t,
125057 r,
125058 n,
eb39fafa
DC
125059 o,
125060 a,
56c4a2cb
DC
125061 s,
125062 l = 30 * fe + 5,
125063 u = ye[l];
125064 if (u) return fe = u.nextPos, u.result;
eb39fafa 125065
56c4a2cb
DC
125066 if (e = fe, (t = Pe()) !== i) {
125067 for (r = [], n = fe, (o = _e()) !== i && (a = Pe()) !== i ? n = o = [o, a] : (fe = n, n = i); n !== i;) r.push(n), n = fe, (o = _e()) !== i && (a = Pe()) !== i ? n = o = [o, a] : (fe = n, n = i);
eb39fafa 125068
56c4a2cb 125069 r !== i ? (s = t, e = t = r.reduce(function (e, t) {
eb39fafa
DC
125070 return {
125071 type: t[0],
125072 left: e,
125073 right: t[1]
125074 };
56c4a2cb
DC
125075 }, s)) : (fe = e, e = i);
125076 } else fe = e, e = i;
eb39fafa 125077
56c4a2cb
DC
125078 return ye[l] = {
125079 nextPos: fe,
eb39fafa
DC
125080 result: e
125081 }, e;
125082 }
125083
125084 function Pe() {
125085 var e,
125086 r,
125087 n,
56c4a2cb
DC
125088 o,
125089 a,
eb39fafa 125090 s,
56c4a2cb
DC
125091 l,
125092 u = 30 * fe + 6,
125093 c = ye[u];
125094 if (c) return fe = c.nextPos, c.result;
125095
125096 if (e = fe, 33 === t.charCodeAt(fe) ? (r = "!", fe++) : (r = i, Ae(g)), r === i && (r = null), r !== i) {
125097 if (n = [], (o = ke()) !== i) for (; o !== i;) n.push(o), o = ke();else n = i;
125098 n !== i ? (a = r, l = 1 === (s = n).length ? s[0] : {
125099 type: "compound",
125100 selectors: s
125101 }, a && (l.subject = !0), e = r = l) : (fe = e, e = i);
125102 } else fe = e, e = i;
125103
125104 return ye[u] = {
125105 nextPos: fe,
eb39fafa
DC
125106 result: e
125107 }, e;
125108 }
125109
125110 function ke() {
125111 var e,
56c4a2cb
DC
125112 r = 30 * fe + 7,
125113 n = ye[r];
125114 return n ? (fe = n.nextPos, n.result) : ((e = function () {
eb39fafa
DC
125115 var e,
125116 r,
56c4a2cb
DC
125117 n = 30 * fe + 8,
125118 o = ye[n];
125119 return o ? (fe = o.nextPos, o.result) : (42 === t.charCodeAt(fe) ? (r = "*", fe++) : (r = i, Ae(v)), r !== i && (r = {
eb39fafa
DC
125120 type: "wildcard",
125121 value: r
56c4a2cb
DC
125122 }), e = r, ye[n] = {
125123 nextPos: fe,
eb39fafa
DC
125124 result: e
125125 }, e);
125126 }()) === i && (e = function () {
125127 var e,
125128 r,
125129 n,
56c4a2cb
DC
125130 o = 30 * fe + 9,
125131 a = ye[o];
125132 return a ? (fe = a.nextPos, a.result) : (e = fe, 35 === t.charCodeAt(fe) ? (r = "#", fe++) : (r = i, Ae(A)), r === i && (r = null), r !== i && (n = Se()) !== i ? e = r = {
eb39fafa
DC
125133 type: "identifier",
125134 value: n
56c4a2cb
DC
125135 } : (fe = e, e = i), ye[o] = {
125136 nextPos: fe,
eb39fafa
DC
125137 result: e
125138 }, e);
125139 }()) === i && (e = function () {
125140 var e,
125141 r,
125142 n,
56c4a2cb
DC
125143 o,
125144 a = 30 * fe + 10,
125145 s = ye[a];
125146 return s ? (fe = s.nextPos, s.result) : (e = fe, 91 === t.charCodeAt(fe) ? (r = "[", fe++) : (r = i, Ae(b)), r !== i && Ee() !== i && (n = function () {
eb39fafa
DC
125147 var e,
125148 r,
125149 n,
56c4a2cb
DC
125150 o,
125151 a = 30 * fe + 14,
125152 s = ye[a];
125153 return s ? (fe = s.nextPos, s.result) : (e = fe, (r = De()) !== i && Ee() !== i && (n = function () {
eb39fafa
DC
125154 var e,
125155 r,
125156 n,
56c4a2cb
DC
125157 o = 30 * fe + 12,
125158 a = ye[o];
125159 return a ? (fe = a.nextPos, a.result) : (e = fe, 33 === t.charCodeAt(fe) ? (r = "!", fe++) : (r = i, Ae(g)), r === i && (r = null), r !== i ? (61 === t.charCodeAt(fe) ? (n = "=", fe++) : (n = i, Ae(w)), n !== i ? (r = C(r), e = r) : (fe = e, e = i)) : (fe = e, e = i), ye[o] = {
125160 nextPos: fe,
eb39fafa
DC
125161 result: e
125162 }, e);
56c4a2cb 125163 }()) !== i && Ee() !== i ? ((o = function () {
eb39fafa
DC
125164 var e,
125165 r,
125166 n,
eb39fafa 125167 o,
56c4a2cb
DC
125168 a,
125169 s = 30 * fe + 18,
125170 l = ye[s];
125171 if (l) return fe = l.nextPos, l.result;
125172 if (e = fe, "type(" === t.substr(fe, 5) ? (r = "type(", fe += 5) : (r = i, Ae(W)), r !== i) {
125173 if (Ee() !== i) {
125174 if (n = [], G.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(z)), o !== i) for (; o !== i;) n.push(o), G.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(z));else n = i;
125175 n !== i && (o = Ee()) !== i ? (41 === t.charCodeAt(fe) ? (a = ")", fe++) : (a = i, Ae(K)), a !== i ? (r = {
eb39fafa
DC
125176 type: "type",
125177 value: n.join("")
56c4a2cb
DC
125178 }, e = r) : (fe = e, e = i)) : (fe = e, e = i);
125179 } else fe = e, e = i;
125180 } else fe = e, e = i;
125181 return ye[s] = {
125182 nextPos: fe,
eb39fafa
DC
125183 result: e
125184 }, e;
56c4a2cb 125185 }()) === i && (o = function () {
eb39fafa
DC
125186 var e,
125187 r,
125188 n,
eb39fafa
DC
125189 o,
125190 a,
56c4a2cb
DC
125191 s,
125192 l = 30 * fe + 20,
125193 u = ye[l];
125194 if (u) return fe = u.nextPos, u.result;
eb39fafa 125195
56c4a2cb
DC
125196 if (e = fe, 47 === t.charCodeAt(fe) ? (r = "/", fe++) : (r = i, Ae($)), r !== i) {
125197 if (n = [], J.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(Q)), o !== i) for (; o !== i;) n.push(o), J.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(Q));else n = i;
125198 n !== i ? (47 === t.charCodeAt(fe) ? (o = "/", fe++) : (o = i, Ae($)), o !== i ? ((a = function () {
eb39fafa
DC
125199 var e,
125200 r,
56c4a2cb
DC
125201 n = 30 * fe + 19,
125202 o = ye[n];
125203 if (o) return fe = o.nextPos, o.result;
125204 if (e = [], H.test(t.charAt(fe)) ? (r = t.charAt(fe), fe++) : (r = i, Ae(Y)), r !== i) for (; r !== i;) e.push(r), H.test(t.charAt(fe)) ? (r = t.charAt(fe), fe++) : (r = i, Ae(Y));else e = i;
125205 return ye[n] = {
125206 nextPos: fe,
eb39fafa
DC
125207 result: e
125208 }, e;
56c4a2cb 125209 }()) === i && (a = null), a !== i ? (s = a, r = {
eb39fafa 125210 type: "regexp",
56c4a2cb
DC
125211 value: new RegExp(n.join(""), s ? s.join("") : "")
125212 }, e = r) : (fe = e, e = i)) : (fe = e, e = i)) : (fe = e, e = i);
125213 } else fe = e, e = i;
eb39fafa 125214
56c4a2cb
DC
125215 return ye[l] = {
125216 nextPos: fe,
eb39fafa
DC
125217 result: e
125218 }, e;
56c4a2cb 125219 }()), o !== i ? (r = I(r, n, o), e = r) : (fe = e, e = i)) : (fe = e, e = i), e === i && (e = fe, (r = De()) !== i && Ee() !== i && (n = function () {
eb39fafa
DC
125220 var e,
125221 r,
125222 n,
56c4a2cb
DC
125223 o = 30 * fe + 11,
125224 a = ye[o];
125225 return a ? (fe = a.nextPos, a.result) : (e = fe, S.test(t.charAt(fe)) ? (r = t.charAt(fe), fe++) : (r = i, Ae(_)), r === i && (r = null), r !== i ? (61 === t.charCodeAt(fe) ? (n = "=", fe++) : (n = i, Ae(w)), n !== i ? (r = C(r), e = r) : (fe = e, e = i)) : (fe = e, e = i), e === i && (P.test(t.charAt(fe)) ? (e = t.charAt(fe), fe++) : (e = i, Ae(k))), ye[o] = {
125226 nextPos: fe,
eb39fafa
DC
125227 result: e
125228 }, e);
56c4a2cb 125229 }()) !== i && Ee() !== i ? ((o = function () {
eb39fafa
DC
125230 var e,
125231 r,
125232 n,
eb39fafa
DC
125233 o,
125234 a,
56c4a2cb
DC
125235 s,
125236 l = 30 * fe + 15,
125237 u = ye[l];
125238 if (u) return fe = u.nextPos, u.result;
eb39fafa 125239
56c4a2cb
DC
125240 if (e = fe, 34 === t.charCodeAt(fe) ? (r = '"', fe++) : (r = i, Ae(j)), r !== i) {
125241 for (n = [], F.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(T)), o === i && (o = fe, 92 === t.charCodeAt(fe) ? (a = "\\", fe++) : (a = i, Ae(L)), a !== i ? (t.length > fe ? (s = t.charAt(fe), fe++) : (s = i, Ae(R)), s !== i ? (a = O(a, s), o = a) : (fe = o, o = i)) : (fe = o, o = i)); o !== i;) n.push(o), F.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(T)), o === i && (o = fe, 92 === t.charCodeAt(fe) ? (a = "\\", fe++) : (a = i, Ae(L)), a !== i ? (t.length > fe ? (s = t.charAt(fe), fe++) : (s = i, Ae(R)), s !== i ? (a = O(a, s), o = a) : (fe = o, o = i)) : (fe = o, o = i));
eb39fafa 125242
56c4a2cb
DC
125243 n !== i ? (34 === t.charCodeAt(fe) ? (o = '"', fe++) : (o = i, Ae(j)), o !== i ? (r = B(n), e = r) : (fe = e, e = i)) : (fe = e, e = i);
125244 } else fe = e, e = i;
eb39fafa 125245
56c4a2cb
DC
125246 if (e === i) if (e = fe, 39 === t.charCodeAt(fe) ? (r = "'", fe++) : (r = i, Ae(M)), r !== i) {
125247 for (n = [], U.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(V)), o === i && (o = fe, 92 === t.charCodeAt(fe) ? (a = "\\", fe++) : (a = i, Ae(L)), a !== i ? (t.length > fe ? (s = t.charAt(fe), fe++) : (s = i, Ae(R)), s !== i ? (a = O(a, s), o = a) : (fe = o, o = i)) : (fe = o, o = i)); o !== i;) n.push(o), U.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(V)), o === i && (o = fe, 92 === t.charCodeAt(fe) ? (a = "\\", fe++) : (a = i, Ae(L)), a !== i ? (t.length > fe ? (s = t.charAt(fe), fe++) : (s = i, Ae(R)), s !== i ? (a = O(a, s), o = a) : (fe = o, o = i)) : (fe = o, o = i));
eb39fafa 125248
56c4a2cb
DC
125249 n !== i ? (39 === t.charCodeAt(fe) ? (o = "'", fe++) : (o = i, Ae(M)), o !== i ? (r = B(n), e = r) : (fe = e, e = i)) : (fe = e, e = i);
125250 } else fe = e, e = i;
125251 return ye[l] = {
125252 nextPos: fe,
eb39fafa
DC
125253 result: e
125254 }, e;
56c4a2cb 125255 }()) === i && (o = function () {
eb39fafa
DC
125256 var e,
125257 r,
125258 n,
56c4a2cb
DC
125259 o,
125260 a,
eb39fafa 125261 s,
56c4a2cb
DC
125262 l,
125263 u = 30 * fe + 16,
125264 c = ye[u];
125265 if (c) return fe = c.nextPos, c.result;
125266
125267 for (e = fe, r = fe, n = [], q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N)); o !== i;) n.push(o), q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N));
125268
125269 if (n !== i ? (46 === t.charCodeAt(fe) ? (o = ".", fe++) : (o = i, Ae(D)), o !== i ? r = n = [n, o] : (fe = r, r = i)) : (fe = r, r = i), r === i && (r = null), r !== i) {
125270 if (n = [], q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N)), o !== i) for (; o !== i;) n.push(o), q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N));else n = i;
125271 n !== i ? (s = n, l = (a = r) ? [].concat.apply([], a).join("") : "", r = {
125272 type: "literal",
125273 value: parseFloat(l + s.join(""))
125274 }, e = r) : (fe = e, e = i);
125275 } else fe = e, e = i;
125276
125277 return ye[u] = {
125278 nextPos: fe,
eb39fafa
DC
125279 result: e
125280 }, e;
56c4a2cb 125281 }()) === i && (o = function () {
eb39fafa
DC
125282 var e,
125283 t,
56c4a2cb
DC
125284 r = 30 * fe + 17,
125285 n = ye[r];
125286 return n ? (fe = n.nextPos, n.result) : ((t = Se()) !== i && (t = {
eb39fafa
DC
125287 type: "literal",
125288 value: t
56c4a2cb
DC
125289 }), e = t, ye[r] = {
125290 nextPos: fe,
eb39fafa
DC
125291 result: e
125292 }, e);
56c4a2cb 125293 }()), o !== i ? (r = I(r, n, o), e = r) : (fe = e, e = i)) : (fe = e, e = i), e === i && (e = fe, (r = De()) !== i && (r = {
eb39fafa
DC
125294 type: "attribute",
125295 name: r
56c4a2cb
DC
125296 }), e = r)), ye[a] = {
125297 nextPos: fe,
eb39fafa
DC
125298 result: e
125299 }, e);
56c4a2cb
DC
125300 }()) !== i && Ee() !== i ? (93 === t.charCodeAt(fe) ? (o = "]", fe++) : (o = i, Ae(E)), o !== i ? e = r = n : (fe = e, e = i)) : (fe = e, e = i), ye[a] = {
125301 nextPos: fe,
eb39fafa
DC
125302 result: e
125303 }, e);
125304 }()) === i && (e = function () {
125305 var e,
125306 r,
125307 n,
eb39fafa
DC
125308 o,
125309 a,
56c4a2cb 125310 s,
eb39fafa
DC
125311 l,
125312 u,
56c4a2cb
DC
125313 c = 30 * fe + 21,
125314 f = ye[c];
125315 if (f) return fe = f.nextPos, f.result;
125316 if (e = fe, 46 === t.charCodeAt(fe) ? (r = ".", fe++) : (r = i, Ae(D)), r !== i) {
125317 if ((n = Se()) !== i) {
125318 for (o = [], a = fe, 46 === t.charCodeAt(fe) ? (s = ".", fe++) : (s = i, Ae(D)), s !== i && (l = Se()) !== i ? a = s = [s, l] : (fe = a, a = i); a !== i;) o.push(a), a = fe, 46 === t.charCodeAt(fe) ? (s = ".", fe++) : (s = i, Ae(D)), s !== i && (l = Se()) !== i ? a = s = [s, l] : (fe = a, a = i);
125319
125320 o !== i ? (u = n, r = {
eb39fafa 125321 type: "field",
56c4a2cb 125322 name: o.reduce(function (e, t) {
eb39fafa
DC
125323 return e + t[0] + t[1];
125324 }, u)
56c4a2cb
DC
125325 }, e = r) : (fe = e, e = i);
125326 } else fe = e, e = i;
125327 } else fe = e, e = i;
125328 return ye[c] = {
125329 nextPos: fe,
eb39fafa
DC
125330 result: e
125331 }, e;
125332 }()) === i && (e = function () {
125333 var e,
125334 r,
125335 n,
56c4a2cb
DC
125336 o,
125337 a = 30 * fe + 22,
125338 s = ye[a];
125339 return s ? (fe = s.nextPos, s.result) : (e = fe, ":not(" === t.substr(fe, 5) ? (r = ":not(", fe += 5) : (r = i, Ae(X)), r !== i && Ee() !== i && (n = we()) !== i && Ee() !== i ? (41 === t.charCodeAt(fe) ? (o = ")", fe++) : (o = i, Ae(K)), o !== i ? e = r = {
eb39fafa
DC
125340 type: "not",
125341 selectors: n
56c4a2cb
DC
125342 } : (fe = e, e = i)) : (fe = e, e = i), ye[a] = {
125343 nextPos: fe,
eb39fafa
DC
125344 result: e
125345 }, e);
125346 }()) === i && (e = function () {
125347 var e,
125348 r,
125349 n,
56c4a2cb
DC
125350 o,
125351 a = 30 * fe + 23,
125352 s = ye[a];
125353 return s ? (fe = s.nextPos, s.result) : (e = fe, ":matches(" === t.substr(fe, 9) ? (r = ":matches(", fe += 9) : (r = i, Ae(Z)), r !== i && Ee() !== i && (n = we()) !== i && Ee() !== i ? (41 === t.charCodeAt(fe) ? (o = ")", fe++) : (o = i, Ae(K)), o !== i ? e = r = {
eb39fafa
DC
125354 type: "matches",
125355 selectors: n
56c4a2cb
DC
125356 } : (fe = e, e = i)) : (fe = e, e = i), ye[a] = {
125357 nextPos: fe,
eb39fafa
DC
125358 result: e
125359 }, e);
125360 }()) === i && (e = function () {
125361 var e,
125362 r,
125363 n,
56c4a2cb
DC
125364 o,
125365 a = 30 * fe + 24,
125366 s = ye[a];
125367 return s ? (fe = s.nextPos, s.result) : (e = fe, ":has(" === t.substr(fe, 5) ? (r = ":has(", fe += 5) : (r = i, Ae(ee)), r !== i && Ee() !== i && (n = we()) !== i && Ee() !== i ? (41 === t.charCodeAt(fe) ? (o = ")", fe++) : (o = i, Ae(K)), o !== i ? e = r = {
eb39fafa
DC
125368 type: "has",
125369 selectors: n
56c4a2cb
DC
125370 } : (fe = e, e = i)) : (fe = e, e = i), ye[a] = {
125371 nextPos: fe,
eb39fafa
DC
125372 result: e
125373 }, e);
125374 }()) === i && (e = function () {
125375 var e,
125376 r,
56c4a2cb
DC
125377 n = 30 * fe + 25,
125378 o = ye[n];
125379 return o ? (fe = o.nextPos, o.result) : (":first-child" === t.substr(fe, 12) ? (r = ":first-child", fe += 12) : (r = i, Ae(te)), r !== i && (r = Ie(1)), e = r, ye[n] = {
125380 nextPos: fe,
eb39fafa
DC
125381 result: e
125382 }, e);
125383 }()) === i && (e = function () {
125384 var e,
125385 r,
56c4a2cb
DC
125386 n = 30 * fe + 26,
125387 o = ye[n];
125388 return o ? (fe = o.nextPos, o.result) : (":last-child" === t.substr(fe, 11) ? (r = ":last-child", fe += 11) : (r = i, Ae(re)), r !== i && (r = je(1)), e = r, ye[n] = {
125389 nextPos: fe,
eb39fafa
DC
125390 result: e
125391 }, e);
125392 }()) === i && (e = function () {
125393 var e,
125394 r,
125395 n,
eb39fafa 125396 o,
56c4a2cb
DC
125397 a,
125398 s = 30 * fe + 27,
125399 l = ye[s];
125400 if (l) return fe = l.nextPos, l.result;
125401 if (e = fe, ":nth-child(" === t.substr(fe, 11) ? (r = ":nth-child(", fe += 11) : (r = i, Ae(ne)), r !== i) {
125402 if (Ee() !== i) {
125403 if (n = [], q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N)), o !== i) for (; o !== i;) n.push(o), q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N));else n = i;
125404 n !== i && (o = Ee()) !== i ? (41 === t.charCodeAt(fe) ? (a = ")", fe++) : (a = i, Ae(K)), a !== i ? (r = Ie(parseInt(n.join(""), 10)), e = r) : (fe = e, e = i)) : (fe = e, e = i);
125405 } else fe = e, e = i;
125406 } else fe = e, e = i;
125407 return ye[s] = {
125408 nextPos: fe,
eb39fafa
DC
125409 result: e
125410 }, e;
125411 }()) === i && (e = function () {
125412 var e,
125413 r,
125414 n,
eb39fafa 125415 o,
56c4a2cb
DC
125416 a,
125417 s = 30 * fe + 28,
125418 l = ye[s];
125419 if (l) return fe = l.nextPos, l.result;
125420 if (e = fe, ":nth-last-child(" === t.substr(fe, 16) ? (r = ":nth-last-child(", fe += 16) : (r = i, Ae(oe)), r !== i) {
125421 if (Ee() !== i) {
125422 if (n = [], q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N)), o !== i) for (; o !== i;) n.push(o), q.test(t.charAt(fe)) ? (o = t.charAt(fe), fe++) : (o = i, Ae(N));else n = i;
125423 n !== i && (o = Ee()) !== i ? (41 === t.charCodeAt(fe) ? (a = ")", fe++) : (a = i, Ae(K)), a !== i ? (r = je(parseInt(n.join(""), 10)), e = r) : (fe = e, e = i)) : (fe = e, e = i);
125424 } else fe = e, e = i;
125425 } else fe = e, e = i;
125426 return ye[s] = {
125427 nextPos: fe,
eb39fafa
DC
125428 result: e
125429 }, e;
125430 }()) === i && (e = function () {
125431 var e,
125432 r,
125433 n,
56c4a2cb
DC
125434 o = 30 * fe + 29,
125435 a = ye[o];
125436 return a ? (fe = a.nextPos, a.result) : (e = fe, 58 === t.charCodeAt(fe) ? (r = ":", fe++) : (r = i, Ae(ae)), r !== i ? ("statement" === t.substr(fe, 9).toLowerCase() ? (n = t.substr(fe, 9), fe += 9) : (n = i, Ae(se)), n === i && ("expression" === t.substr(fe, 10).toLowerCase() ? (n = t.substr(fe, 10), fe += 10) : (n = i, Ae(ie)), n === i && ("declaration" === t.substr(fe, 11).toLowerCase() ? (n = t.substr(fe, 11), fe += 11) : (n = i, Ae(le)), n === i && ("function" === t.substr(fe, 8).toLowerCase() ? (n = t.substr(fe, 8), fe += 8) : (n = i, Ae(ue)), n === i && ("pattern" === t.substr(fe, 7).toLowerCase() ? (n = t.substr(fe, 7), fe += 7) : (n = i, Ae(ce)))))), n !== i ? e = r = {
eb39fafa
DC
125437 type: "class",
125438 name: n
56c4a2cb
DC
125439 } : (fe = e, e = i)) : (fe = e, e = i), ye[o] = {
125440 nextPos: fe,
eb39fafa
DC
125441 result: e
125442 }, e);
56c4a2cb
DC
125443 }()), ye[r] = {
125444 nextPos: fe,
eb39fafa
DC
125445 result: e
125446 }, e);
125447 }
125448
125449 function De() {
125450 var e,
125451 r,
125452 n,
56c4a2cb
DC
125453 o = 30 * fe + 13,
125454 a = ye[o];
125455 if (a) return fe = a.nextPos, a.result;
125456 if (r = [], (n = Se()) === i && (46 === t.charCodeAt(fe) ? (n = ".", fe++) : (n = i, Ae(D))), n !== i) for (; n !== i;) r.push(n), (n = Se()) === i && (46 === t.charCodeAt(fe) ? (n = ".", fe++) : (n = i, Ae(D)));else r = i;
125457 return r !== i && (r = h(r)), e = r, ye[o] = {
125458 nextPos: fe,
eb39fafa
DC
125459 result: e
125460 }, e;
125461 }
125462
125463 function Ie(e) {
125464 return {
125465 type: "nth-child",
125466 index: {
125467 type: "literal",
125468 value: e
125469 }
125470 };
125471 }
125472
125473 function je(e) {
125474 return {
125475 type: "nth-last-child",
125476 index: {
125477 type: "literal",
125478 value: e
125479 }
125480 };
125481 }
125482
56c4a2cb
DC
125483 if ((n = u()) !== i && fe === t.length) return n;
125484 throw n !== i && fe < t.length && Ae({
eb39fafa 125485 type: "end"
56c4a2cb 125486 }), o = de, a = he < t.length ? t.charAt(he) : null, s = he < t.length ? ve(he, he + 1) : ve(he, he), new e(e.buildMessage(o, a), o, a, s);
eb39fafa
DC
125487 }
125488 };
125489 }());
125490 });
125491
56c4a2cb 125492 function l(t, r, n) {
eb39fafa 125493 if (!r) return !0;
56c4a2cb 125494 if (!t) return !1;
eb39fafa 125495
56c4a2cb 125496 switch (n || (n = []), r.type) {
eb39fafa
DC
125497 case "wildcard":
125498 return !0;
125499
125500 case "identifier":
56c4a2cb 125501 return r.value.toLowerCase() === t.type.toLowerCase();
eb39fafa
DC
125502
125503 case "field":
56c4a2cb
DC
125504 var o = r.name.split("."),
125505 a = n[o.length - 1];
125506 return function e(t, r, n) {
125507 if (0 === n.length) return t === r;
125508 if (null == r) return !1;
125509 var o = r[n[0]],
125510 a = n.slice(1);
eb39fafa 125511
56c4a2cb
DC
125512 if (Array.isArray(o)) {
125513 for (var s = 0, i = o.length; s < i; ++s) if (e(t, o[s], a)) return !0;
eb39fafa 125514
56c4a2cb
DC
125515 return !1;
125516 }
eb39fafa 125517
56c4a2cb
DC
125518 return e(t, o, a);
125519 }(t, a, o);
eb39fafa
DC
125520
125521 case "matches":
56c4a2cb 125522 for (var i = 0, p = r.selectors.length; i < p; ++i) if (l(t, r.selectors[i], n)) return !0;
eb39fafa
DC
125523
125524 return !1;
125525
125526 case "compound":
56c4a2cb 125527 for (var h = 0, d = r.selectors.length; h < d; ++h) if (!l(t, r.selectors[h], n)) return !1;
eb39fafa
DC
125528
125529 return !0;
125530
125531 case "not":
56c4a2cb 125532 for (var y = 0, m = r.selectors.length; y < m; ++y) if (l(t, r.selectors[y], n)) return !1;
eb39fafa
DC
125533
125534 return !0;
125535
125536 case "has":
56c4a2cb
DC
125537 var x = function () {
125538 for (var e = [], n = function n(_n, o) {
125539 var a = [];
125540 s.traverse(t, {
125541 enter: function enter(t, o) {
125542 null != o && a.unshift(o), l(t, r.selectors[_n], a) && e.push(t);
eb39fafa 125543 },
56c4a2cb 125544 leave: function leave() {
eb39fafa
DC
125545 a.shift();
125546 },
eb39fafa
DC
125547 fallback: "iteration"
125548 });
56c4a2cb 125549 }, o = 0, a = r.selectors.length; o < a; ++o) n(o);
eb39fafa 125550
56c4a2cb
DC
125551 return {
125552 v: 0 !== e.length
125553 };
125554 }();
125555
125556 if ("object" === e(x)) return x.v;
eb39fafa
DC
125557
125558 case "child":
56c4a2cb 125559 return !!l(t, r.right, n) && l(n[0], r.left, n.slice(1));
eb39fafa
DC
125560
125561 case "descendant":
56c4a2cb 125562 if (l(t, r.right, n)) for (var g = 0, v = n.length; g < v; ++g) if (l(n[g], r.left, n.slice(g + 1))) return !0;
eb39fafa
DC
125563 return !1;
125564
125565 case "attribute":
56c4a2cb
DC
125566 var A = function (e, t) {
125567 for (var r = t.split("."), n = 0; n < r.length; n++) {
125568 if (null == e) return e;
125569 e = e[r[n]];
125570 }
eb39fafa 125571
56c4a2cb
DC
125572 return e;
125573 }(t, r.name);
eb39fafa 125574
56c4a2cb
DC
125575 switch (r.operator) {
125576 case void 0:
125577 return null != A;
eb39fafa 125578
56c4a2cb
DC
125579 case "=":
125580 switch (r.value.type) {
125581 case "regexp":
125582 return "string" == typeof A && r.value.value.test(A);
eb39fafa 125583
56c4a2cb
DC
125584 case "literal":
125585 return "".concat(r.value.value) === "".concat(A);
eb39fafa 125586
56c4a2cb
DC
125587 case "type":
125588 return r.value.value === e(A);
125589 }
eb39fafa 125590
56c4a2cb 125591 throw new Error("Unknown selector value type: ".concat(r.value.type));
eb39fafa 125592
56c4a2cb
DC
125593 case "!=":
125594 switch (r.value.type) {
125595 case "regexp":
125596 return !r.value.value.test(A);
eb39fafa 125597
56c4a2cb
DC
125598 case "literal":
125599 return "".concat(r.value.value) !== "".concat(A);
eb39fafa 125600
56c4a2cb
DC
125601 case "type":
125602 return r.value.value !== e(A);
125603 }
eb39fafa 125604
56c4a2cb 125605 throw new Error("Unknown selector value type: ".concat(r.value.type));
eb39fafa 125606
56c4a2cb
DC
125607 case "<=":
125608 return A <= r.value.value;
eb39fafa 125609
56c4a2cb
DC
125610 case "<":
125611 return A < r.value.value;
eb39fafa 125612
56c4a2cb
DC
125613 case ">":
125614 return A > r.value.value;
eb39fafa 125615
56c4a2cb
DC
125616 case ">=":
125617 return A >= r.value.value;
eb39fafa
DC
125618 }
125619
56c4a2cb
DC
125620 throw new Error("Unknown operator: ".concat(r.operator));
125621
eb39fafa 125622 case "sibling":
56c4a2cb 125623 return l(t, r.right, n) && u(t, r.left, n, "LEFT_SIDE") || r.left.subject && l(t, r.left, n) && u(t, r.right, n, "RIGHT_SIDE");
eb39fafa
DC
125624
125625 case "adjacent":
56c4a2cb 125626 return l(t, r.right, n) && c(t, r.left, n, "LEFT_SIDE") || r.right.subject && l(t, r.left, n) && c(t, r.right, n, "RIGHT_SIDE");
eb39fafa
DC
125627
125628 case "nth-child":
56c4a2cb 125629 return l(t, r.right, n) && f(t, n, function () {
eb39fafa
DC
125630 return r.index.value - 1;
125631 });
125632
125633 case "nth-last-child":
56c4a2cb 125634 return l(t, r.right, n) && f(t, n, function (e) {
eb39fafa
DC
125635 return e - r.index.value;
125636 });
125637
125638 case "class":
125639 switch (r.name.toLowerCase()) {
125640 case "statement":
56c4a2cb 125641 if ("Statement" === t.type.slice(-9)) return !0;
eb39fafa
DC
125642
125643 case "declaration":
56c4a2cb 125644 return "Declaration" === t.type.slice(-11);
eb39fafa
DC
125645
125646 case "pattern":
56c4a2cb 125647 if ("Pattern" === t.type.slice(-7)) return !0;
eb39fafa
DC
125648
125649 case "expression":
56c4a2cb 125650 return "Expression" === t.type.slice(-10) || "Literal" === t.type.slice(-7) || "Identifier" === t.type && (0 === n.length || "MetaProperty" !== n[0].type) || "MetaProperty" === t.type;
eb39fafa
DC
125651
125652 case "function":
56c4a2cb 125653 return "FunctionDeclaration" === t.type || "FunctionExpression" === t.type || "ArrowFunctionExpression" === t.type;
eb39fafa
DC
125654 }
125655
125656 throw new Error("Unknown class name: ".concat(r.name));
125657 }
125658
125659 throw new Error("Unknown selector type: ".concat(r.type));
125660 }
125661
56c4a2cb
DC
125662 function u(e, r, n, o) {
125663 var a = t(n, 1)[0];
eb39fafa 125664 if (!a) return !1;
eb39fafa 125665
56c4a2cb
DC
125666 for (var i = s.VisitorKeys[a.type], u = 0, c = i.length; u < c; ++u) {
125667 var f = a[i[u]];
eb39fafa 125668
56c4a2cb
DC
125669 if (Array.isArray(f)) {
125670 var p = f.indexOf(e);
125671 if (p < 0) continue;
125672 var h = void 0,
125673 d = void 0;
125674 "LEFT_SIDE" === o ? (h = 0, d = p) : (h = p + 1, d = f.length);
eb39fafa 125675
56c4a2cb 125676 for (var y = h; y < d; ++y) if (l(f[y], r, n)) return !0;
eb39fafa
DC
125677 }
125678 }
125679
125680 return !1;
125681 }
125682
56c4a2cb
DC
125683 function c(e, r, n, o) {
125684 var a = t(n, 1)[0];
eb39fafa 125685 if (!a) return !1;
eb39fafa 125686
56c4a2cb
DC
125687 for (var i = s.VisitorKeys[a.type], u = 0, c = i.length; u < c; ++u) {
125688 var f = a[i[u]];
eb39fafa 125689
56c4a2cb
DC
125690 if (Array.isArray(f)) {
125691 var p = f.indexOf(e);
125692 if (p < 0) continue;
125693 if ("LEFT_SIDE" === o && p > 0 && l(f[p - 1], r, n)) return !0;
125694 if ("RIGHT_SIDE" === o && p < f.length - 1 && l(f[p + 1], r, n)) return !0;
eb39fafa
DC
125695 }
125696 }
125697
125698 return !1;
125699 }
125700
56c4a2cb
DC
125701 function f(e, r, n) {
125702 var o = t(r, 1)[0];
125703 if (!o) return !1;
eb39fafa 125704
56c4a2cb
DC
125705 for (var a = s.VisitorKeys[o.type], i = 0, l = a.length; i < l; ++i) {
125706 var u = o[a[i]];
eb39fafa 125707
56c4a2cb
DC
125708 if (Array.isArray(u)) {
125709 var c = u.indexOf(e);
125710 if (c >= 0 && c === n(u.length)) return !0;
eb39fafa
DC
125711 }
125712 }
125713
125714 return !1;
125715 }
125716
56c4a2cb
DC
125717 function p(n, o) {
125718 if (null == n || "object" != e(n)) return [];
125719 null == o && (o = n);
eb39fafa 125720
56c4a2cb
DC
125721 for (var a = n.subject ? [o] : [], s = 0, i = function (e) {
125722 for (var t = [], r = Object.keys(e), n = 0; n < r.length; n++) t.push([r[n], e[r[n]]]);
eb39fafa 125723
56c4a2cb
DC
125724 return t;
125725 }(n); s < i.length; s++) {
125726 var l = t(i[s], 2),
125727 u = l[0],
125728 c = l[1];
125729 a.push.apply(a, r(p(c, "left" === u ? c : o)));
125730 }
eb39fafa 125731
56c4a2cb
DC
125732 return a;
125733 }
eb39fafa 125734
56c4a2cb
DC
125735 function h(e, t, r) {
125736 if (t) {
125737 var n = [],
125738 o = p(t);
125739 s.traverse(e, {
125740 enter: function enter(e, a) {
125741 if (null != a && n.unshift(a), l(e, t, n)) if (o.length) for (var s = 0, i = o.length; s < i; ++s) {
125742 l(e, o[s], n) && r(e, a, n);
eb39fafa 125743
56c4a2cb
DC
125744 for (var u = 0, c = n.length; u < c; ++u) {
125745 var f = n.slice(u + 1);
125746 l(n[u], o[s], f) && r(n[u], a, f);
125747 }
125748 } else r(e, a, n);
125749 },
125750 leave: function leave() {
125751 n.shift();
125752 },
125753 fallback: "iteration"
125754 });
125755 }
125756 }
eb39fafa 125757
56c4a2cb
DC
125758 function d(e, t) {
125759 var r = [];
125760 return h(e, t, function (e) {
125761 r.push(e);
125762 }), r;
eb39fafa
DC
125763 }
125764
56c4a2cb
DC
125765 function y(e) {
125766 return i.parse(e);
eb39fafa
DC
125767 }
125768
56c4a2cb
DC
125769 function m(e, t) {
125770 return d(e, y(t));
eb39fafa
DC
125771 }
125772
56c4a2cb 125773 return m.parse = y, m.match = d, m.traverse = h, m.matches = l, m.query = m, m;
eb39fafa
DC
125774});
125775
125776/***/ }),
6a5a0f88 125777/* 814 */
eb39fafa
DC
125778/***/ (function(module, exports, __webpack_require__) {
125779
125780"use strict";
125781/**
125782 * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects
125783 * @author Teddy Katz
125784 */
125785 //------------------------------------------------------------------------------
125786// Requirements
125787//------------------------------------------------------------------------------
125788
125789function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
125790
125791function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
125792
125793function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
125794
125795const assert = __webpack_require__(379);
125796
6a5a0f88 125797const ruleFixer = __webpack_require__(815);
eb39fafa 125798
6a5a0f88 125799const interpolate = __webpack_require__(816); //------------------------------------------------------------------------------
eb39fafa
DC
125800// Typedefs
125801//------------------------------------------------------------------------------
125802
125803/**
125804 * An error message description
125805 * @typedef {Object} MessageDescriptor
125806 * @property {ASTNode} [node] The reported node
125807 * @property {Location} loc The location of the problem.
125808 * @property {string} message The problem message.
125809 * @property {Object} [data] Optional data to use to fill in placeholders in the
125810 * message.
125811 * @property {Function} [fix] The function to call that creates a fix command.
125812 * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes.
125813 */
125814
125815/**
125816 * Information about the report
125817 * @typedef {Object} ReportInfo
125818 * @property {string} ruleId
125819 * @property {(0|1|2)} severity
125820 * @property {(string|undefined)} message
125821 * @property {(string|undefined)} [messageId]
125822 * @property {number} line
125823 * @property {number} column
125824 * @property {(number|undefined)} [endLine]
125825 * @property {(number|undefined)} [endColumn]
125826 * @property {(string|null)} nodeType
125827 * @property {string} source
125828 * @property {({text: string, range: (number[]|null)}|null)} [fix]
125829 * @property {Array<{text: string, range: (number[]|null)}|null>} [suggestions]
125830 */
125831//------------------------------------------------------------------------------
125832// Module Definition
125833//------------------------------------------------------------------------------
125834
125835/**
125836 * Translates a multi-argument context.report() call into a single object argument call
125837 * @param {...*} args A list of arguments passed to `context.report`
125838 * @returns {MessageDescriptor} A normalized object containing report information
125839 */
125840
125841
125842function normalizeMultiArgReportCall(...args) {
125843 // If there is one argument, it is considered to be a new-style call already.
125844 if (args.length === 1) {
125845 // Shallow clone the object to avoid surprises if reusing the descriptor
125846 return Object.assign({}, args[0]);
125847 } // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
125848
125849
125850 if (typeof args[1] === "string") {
125851 return {
125852 node: args[0],
125853 message: args[1],
125854 data: args[2],
125855 fix: args[3]
125856 };
125857 } // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
125858
125859
125860 return {
125861 node: args[0],
125862 loc: args[1],
125863 message: args[2],
125864 data: args[3],
125865 fix: args[4]
125866 };
125867}
125868/**
125869 * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
125870 * @param {MessageDescriptor} descriptor A descriptor to validate
125871 * @returns {void}
125872 * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
125873 */
125874
125875
125876function assertValidNodeInfo(descriptor) {
125877 if (descriptor.node) {
125878 assert(typeof descriptor.node === "object", "Node must be an object");
125879 } else {
125880 assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
125881 }
125882}
125883/**
125884 * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
125885 * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
125886 * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
125887 * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
125888 */
125889
125890
125891function normalizeReportLoc(descriptor) {
125892 if (descriptor.loc) {
125893 if (descriptor.loc.start) {
125894 return descriptor.loc;
125895 }
125896
125897 return {
125898 start: descriptor.loc,
125899 end: null
125900 };
125901 }
125902
125903 return descriptor.node.loc;
125904}
125905/**
125906 * Compares items in a fixes array by range.
125907 * @param {Fix} a The first message.
125908 * @param {Fix} b The second message.
125909 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
125910 * @private
125911 */
125912
125913
125914function compareFixesByRange(a, b) {
125915 return a.range[0] - b.range[0] || a.range[1] - b.range[1];
125916}
125917/**
125918 * Merges the given fixes array into one.
125919 * @param {Fix[]} fixes The fixes to merge.
125920 * @param {SourceCode} sourceCode The source code object to get the text between fixes.
125921 * @returns {{text: string, range: number[]}} The merged fixes
125922 */
125923
125924
125925function mergeFixes(fixes, sourceCode) {
125926 if (fixes.length === 0) {
125927 return null;
125928 }
125929
125930 if (fixes.length === 1) {
125931 return fixes[0];
125932 }
125933
125934 fixes.sort(compareFixesByRange);
125935 const originalText = sourceCode.text;
125936 const start = fixes[0].range[0];
125937 const end = fixes[fixes.length - 1].range[1];
125938 let text = "";
125939 let lastPos = Number.MIN_SAFE_INTEGER;
125940
125941 for (const fix of fixes) {
125942 assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
125943
125944 if (fix.range[0] >= 0) {
125945 text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
125946 }
125947
125948 text += fix.text;
125949 lastPos = fix.range[1];
125950 }
125951
125952 text += originalText.slice(Math.max(0, start, lastPos), end);
125953 return {
125954 range: [start, end],
125955 text
125956 };
125957}
125958/**
125959 * Gets one fix object from the given descriptor.
125960 * If the descriptor retrieves multiple fixes, this merges those to one.
125961 * @param {MessageDescriptor} descriptor The report descriptor.
125962 * @param {SourceCode} sourceCode The source code object to get text between fixes.
125963 * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
125964 */
125965
125966
125967function normalizeFixes(descriptor, sourceCode) {
125968 if (typeof descriptor.fix !== "function") {
125969 return null;
125970 } // @type {null | Fix | Fix[] | IterableIterator<Fix>}
125971
125972
125973 const fix = descriptor.fix(ruleFixer); // Merge to one.
125974
125975 if (fix && Symbol.iterator in fix) {
125976 return mergeFixes(Array.from(fix), sourceCode);
125977 }
125978
125979 return fix;
125980}
125981/**
125982 * Gets an array of suggestion objects from the given descriptor.
125983 * @param {MessageDescriptor} descriptor The report descriptor.
125984 * @param {SourceCode} sourceCode The source code object to get text between fixes.
125985 * @param {Object} messages Object of meta messages for the rule.
125986 * @returns {Array<SuggestionResult>} The suggestions for the descriptor
125987 */
125988
125989
125990function mapSuggestions(descriptor, sourceCode, messages) {
125991 if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) {
125992 return [];
125993 }
125994
125995 return descriptor.suggest.map(suggestInfo => {
125996 const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId];
56c4a2cb 125997 return _objectSpread(_objectSpread({}, suggestInfo), {}, {
eb39fafa
DC
125998 desc: interpolate(computedDesc, suggestInfo.data),
125999 fix: normalizeFixes(suggestInfo, sourceCode)
126000 });
126001 });
126002}
126003/**
126004 * Creates information about the report from a descriptor
126005 * @param {Object} options Information about the problem
126006 * @param {string} options.ruleId Rule ID
126007 * @param {(0|1|2)} options.severity Rule severity
126008 * @param {(ASTNode|null)} options.node Node
126009 * @param {string} options.message Error message
126010 * @param {string} [options.messageId] The error message ID.
126011 * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
126012 * @param {{text: string, range: (number[]|null)}} options.fix The fix object
126013 * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
126014 * @returns {function(...args): ReportInfo} Function that returns information about the report
126015 */
126016
126017
126018function createProblem(options) {
126019 const problem = {
126020 ruleId: options.ruleId,
126021 severity: options.severity,
126022 message: options.message,
126023 line: options.loc.start.line,
126024 column: options.loc.start.column + 1,
126025 nodeType: options.node && options.node.type || null
126026 };
126027 /*
126028 * If this isn’t in the conditional, some of the tests fail
126029 * because `messageId` is present in the problem object
126030 */
126031
126032 if (options.messageId) {
126033 problem.messageId = options.messageId;
126034 }
126035
126036 if (options.loc.end) {
126037 problem.endLine = options.loc.end.line;
126038 problem.endColumn = options.loc.end.column + 1;
126039 }
126040
126041 if (options.fix) {
126042 problem.fix = options.fix;
126043 }
126044
126045 if (options.suggestions && options.suggestions.length > 0) {
126046 problem.suggestions = options.suggestions;
126047 }
126048
126049 return problem;
126050}
126051/**
126052 * Validates that suggestions are properly defined. Throws if an error is detected.
126053 * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
126054 * @param {Object} messages Object of meta messages for the rule.
126055 * @returns {void}
126056 */
126057
126058
126059function validateSuggestions(suggest, messages) {
126060 if (suggest && Array.isArray(suggest)) {
126061 suggest.forEach(suggestion => {
126062 if (suggestion.messageId) {
126063 const {
126064 messageId
126065 } = suggestion;
126066
126067 if (!messages) {
126068 throw new TypeError("context.report() called with a suggest option with a messageId '".concat(messageId, "', but no messages were present in the rule metadata."));
126069 }
126070
126071 if (!messages[messageId]) {
126072 throw new TypeError("context.report() called with a suggest option with a messageId '".concat(messageId, "' which is not present in the 'messages' config: ").concat(JSON.stringify(messages, null, 2)));
126073 }
126074
126075 if (suggestion.desc) {
126076 throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.");
126077 }
126078 } else if (!suggestion.desc) {
126079 throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`");
126080 }
126081
126082 if (typeof suggestion.fix !== "function") {
126083 throw new TypeError("context.report() called with a suggest option without a fix function. See: ".concat(suggestion));
126084 }
126085 });
126086 }
126087}
126088/**
126089 * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
126090 * problem for the Node.js API.
126091 * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem
126092 * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
126093 * @returns {function(...args): ReportInfo} Function that returns information about the report
126094 */
126095
126096
126097module.exports = function createReportTranslator(metadata) {
126098 /*
126099 * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
126100 * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
126101 * called every time a rule reports a problem, which happens much less frequently (usually, the vast
126102 * majority of rules don't report any problems for a given file).
126103 */
126104 return (...args) => {
126105 const descriptor = normalizeMultiArgReportCall(...args);
126106 const messages = metadata.messageIds;
126107 assertValidNodeInfo(descriptor);
126108 let computedMessage;
126109
126110 if (descriptor.messageId) {
126111 if (!messages) {
126112 throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
126113 }
126114
126115 const id = descriptor.messageId;
126116
126117 if (descriptor.message) {
126118 throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
126119 }
126120
126121 if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) {
126122 throw new TypeError("context.report() called with a messageId of '".concat(id, "' which is not present in the 'messages' config: ").concat(JSON.stringify(messages, null, 2)));
126123 }
126124
126125 computedMessage = messages[id];
126126 } else if (descriptor.message) {
126127 computedMessage = descriptor.message;
126128 } else {
126129 throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem.");
126130 }
126131
126132 validateSuggestions(descriptor.suggest, messages);
126133 return createProblem({
126134 ruleId: metadata.ruleId,
126135 severity: metadata.severity,
126136 node: descriptor.node,
126137 message: interpolate(computedMessage, descriptor.data),
126138 messageId: descriptor.messageId,
126139 loc: normalizeReportLoc(descriptor),
126140 fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode),
126141 suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, metadata.sourceCode, messages)
126142 });
126143 };
126144};
126145
126146/***/ }),
6a5a0f88 126147/* 815 */
eb39fafa
DC
126148/***/ (function(module, exports, __webpack_require__) {
126149
126150"use strict";
126151/**
126152 * @fileoverview An object that creates fix commands for rules.
126153 * @author Nicholas C. Zakas
126154 */
126155 //------------------------------------------------------------------------------
126156// Requirements
126157//------------------------------------------------------------------------------
126158// none!
126159//------------------------------------------------------------------------------
126160// Helpers
126161//------------------------------------------------------------------------------
126162
126163/**
126164 * Creates a fix command that inserts text at the specified index in the source text.
126165 * @param {int} index The 0-based index at which to insert the new text.
126166 * @param {string} text The text to insert.
126167 * @returns {Object} The fix command.
126168 * @private
126169 */
126170
126171function insertTextAt(index, text) {
126172 return {
126173 range: [index, index],
126174 text
126175 };
126176} //------------------------------------------------------------------------------
126177// Public Interface
126178//------------------------------------------------------------------------------
126179
126180/**
126181 * Creates code fixing commands for rules.
126182 */
126183
126184
126185const ruleFixer = Object.freeze({
126186 /**
126187 * Creates a fix command that inserts text after the given node or token.
126188 * The fix is not applied until applyFixes() is called.
126189 * @param {ASTNode|Token} nodeOrToken The node or token to insert after.
126190 * @param {string} text The text to insert.
126191 * @returns {Object} The fix command.
126192 */
126193 insertTextAfter(nodeOrToken, text) {
126194 return this.insertTextAfterRange(nodeOrToken.range, text);
126195 },
126196
126197 /**
126198 * Creates a fix command that inserts text after the specified range in the source text.
126199 * The fix is not applied until applyFixes() is called.
126200 * @param {int[]} range The range to replace, first item is start of range, second
126201 * is end of range.
126202 * @param {string} text The text to insert.
126203 * @returns {Object} The fix command.
126204 */
126205 insertTextAfterRange(range, text) {
126206 return insertTextAt(range[1], text);
126207 },
126208
126209 /**
126210 * Creates a fix command that inserts text before the given node or token.
126211 * The fix is not applied until applyFixes() is called.
126212 * @param {ASTNode|Token} nodeOrToken The node or token to insert before.
126213 * @param {string} text The text to insert.
126214 * @returns {Object} The fix command.
126215 */
126216 insertTextBefore(nodeOrToken, text) {
126217 return this.insertTextBeforeRange(nodeOrToken.range, text);
126218 },
126219
126220 /**
126221 * Creates a fix command that inserts text before the specified range in the source text.
126222 * The fix is not applied until applyFixes() is called.
126223 * @param {int[]} range The range to replace, first item is start of range, second
126224 * is end of range.
126225 * @param {string} text The text to insert.
126226 * @returns {Object} The fix command.
126227 */
126228 insertTextBeforeRange(range, text) {
126229 return insertTextAt(range[0], text);
126230 },
126231
126232 /**
126233 * Creates a fix command that replaces text at the node or token.
126234 * The fix is not applied until applyFixes() is called.
126235 * @param {ASTNode|Token} nodeOrToken The node or token to remove.
126236 * @param {string} text The text to insert.
126237 * @returns {Object} The fix command.
126238 */
126239 replaceText(nodeOrToken, text) {
126240 return this.replaceTextRange(nodeOrToken.range, text);
126241 },
126242
126243 /**
126244 * Creates a fix command that replaces text at the specified range in the source text.
126245 * The fix is not applied until applyFixes() is called.
126246 * @param {int[]} range The range to replace, first item is start of range, second
126247 * is end of range.
126248 * @param {string} text The text to insert.
126249 * @returns {Object} The fix command.
126250 */
126251 replaceTextRange(range, text) {
126252 return {
126253 range,
126254 text
126255 };
126256 },
126257
126258 /**
126259 * Creates a fix command that removes the node or token from the source.
126260 * The fix is not applied until applyFixes() is called.
126261 * @param {ASTNode|Token} nodeOrToken The node or token to remove.
126262 * @returns {Object} The fix command.
126263 */
126264 remove(nodeOrToken) {
126265 return this.removeRange(nodeOrToken.range);
126266 },
126267
126268 /**
126269 * Creates a fix command that removes the specified range of text from the source.
126270 * The fix is not applied until applyFixes() is called.
126271 * @param {int[]} range The range to remove, first item is start of range, second
126272 * is end of range.
126273 * @returns {Object} The fix command.
126274 */
126275 removeRange(range) {
126276 return {
126277 range,
126278 text: ""
126279 };
126280 }
126281
126282});
126283module.exports = ruleFixer;
126284
126285/***/ }),
6a5a0f88 126286/* 816 */
eb39fafa
DC
126287/***/ (function(module, exports, __webpack_require__) {
126288
126289"use strict";
126290/**
126291 * @fileoverview Interpolate keys from an object into a string with {{ }} markers.
126292 * @author Jed Fox
126293 */
126294 //------------------------------------------------------------------------------
126295// Public Interface
126296//------------------------------------------------------------------------------
126297
126298module.exports = (text, data) => {
126299 if (!data) {
126300 return text;
126301 } // Substitution content for any {{ }} markers.
126302
126303
126304 return text.replace(/\{\{([^{}]+?)\}\}/gu, (fullMatch, termWithWhitespace) => {
126305 const term = termWithWhitespace.trim();
126306
126307 if (term in data) {
126308 return data[term];
126309 } // Preserve old behavior: If parameter name not provided, don't replace it.
126310
126311
126312 return fullMatch;
126313 });
126314};
126315
126316/***/ }),
6a5a0f88 126317/* 817 */
eb39fafa
DC
126318/***/ (function(module, exports, __webpack_require__) {
126319
126320"use strict";
126321/**
126322 * @fileoverview Defines a storage for rules.
126323 * @author Nicholas C. Zakas
126324 * @author aladdin-add
126325 */
126326 //------------------------------------------------------------------------------
126327// Requirements
126328//------------------------------------------------------------------------------
126329
126330const builtInRules = __webpack_require__(414); //------------------------------------------------------------------------------
126331// Helpers
126332//------------------------------------------------------------------------------
126333
126334/**
126335 * Normalizes a rule module to the new-style API
126336 * @param {(Function|{create: Function})} rule A rule object, which can either be a function
126337 * ("old-style") or an object with a `create` method ("new-style")
126338 * @returns {{create: Function}} A new-style rule.
126339 */
126340
126341
126342function normalizeRule(rule) {
126343 return typeof rule === "function" ? Object.assign({
126344 create: rule
126345 }, rule) : rule;
126346} //------------------------------------------------------------------------------
126347// Public Interface
126348//------------------------------------------------------------------------------
126349
126350
126351class Rules {
126352 constructor() {
126353 this._rules = Object.create(null);
126354 }
126355 /**
126356 * Registers a rule module for rule id in storage.
126357 * @param {string} ruleId Rule id (file name).
126358 * @param {Function} ruleModule Rule handler.
126359 * @returns {void}
126360 */
126361
126362
126363 define(ruleId, ruleModule) {
126364 this._rules[ruleId] = normalizeRule(ruleModule);
126365 }
126366 /**
126367 * Access rule handler by id (file name).
126368 * @param {string} ruleId Rule id (file name).
126369 * @returns {{create: Function, schema: JsonSchema[]}}
126370 * A rule. This is normalized to always have the new-style shape with a `create` method.
126371 */
126372
126373
126374 get(ruleId) {
126375 if (typeof this._rules[ruleId] === "string") {
6a5a0f88 126376 this.define(ruleId, __webpack_require__(818)(this._rules[ruleId]));
eb39fafa
DC
126377 }
126378
126379 if (this._rules[ruleId]) {
126380 return this._rules[ruleId];
126381 }
126382
126383 if (builtInRules.has(ruleId)) {
126384 return builtInRules.get(ruleId);
126385 }
126386
126387 return null;
126388 }
126389
126390 *[Symbol.iterator]() {
126391 yield* builtInRules;
126392
126393 for (const ruleId of Object.keys(this._rules)) {
126394 yield [ruleId, this.get(ruleId)];
126395 }
126396 }
126397
126398}
126399
126400module.exports = Rules;
126401
126402/***/ }),
6a5a0f88 126403/* 818 */
eb39fafa
DC
126404/***/ (function(module, exports) {
126405
126406function webpackEmptyContext(req) {
126407 var e = new Error("Cannot find module '" + req + "'");
126408 e.code = 'MODULE_NOT_FOUND';
126409 throw e;
126410}
126411webpackEmptyContext.keys = function() { return []; };
126412webpackEmptyContext.resolve = webpackEmptyContext;
126413module.exports = webpackEmptyContext;
6a5a0f88 126414webpackEmptyContext.id = 818;
eb39fafa
DC
126415
126416/***/ }),
6a5a0f88 126417/* 819 */
eb39fafa
DC
126418/***/ (function(module, exports, __webpack_require__) {
126419
126420"use strict";
126421/**
126422 * @fileoverview A variant of EventEmitter which does not give listeners information about each other
126423 * @author Teddy Katz
126424 */
126425 //------------------------------------------------------------------------------
126426// Typedefs
126427//------------------------------------------------------------------------------
126428
126429/**
126430 * An event emitter
126431 * @typedef {Object} SafeEmitter
126432 * @property {function(eventName: string, listenerFunc: Function): void} on Adds a listener for a given event name
126433 * @property {function(eventName: string, arg1?: any, arg2?: any, arg3?: any)} emit Emits an event with a given name.
126434 * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments.
126435 * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners.
126436 */
126437
126438/**
126439 * Creates an object which can listen for and emit events.
126440 * This is similar to the EventEmitter API in Node's standard library, but it has a few differences.
126441 * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without
126442 * letting the modules know about each other at all.
126443 * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when
126444 * another module throws an error or registers a listener.
126445 * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a
126446 * `this` value of the emitter instance, which would give listeners access to other listeners.)
126447 * @returns {SafeEmitter} An emitter
126448 */
126449
126450module.exports = () => {
126451 const listeners = Object.create(null);
126452 return Object.freeze({
126453 on(eventName, listener) {
126454 if (eventName in listeners) {
126455 listeners[eventName].push(listener);
126456 } else {
126457 listeners[eventName] = [listener];
126458 }
126459 },
126460
126461 emit(eventName, ...args) {
126462 if (eventName in listeners) {
126463 listeners[eventName].forEach(listener => listener(...args));
126464 }
126465 },
126466
126467 eventNames() {
126468 return Object.keys(listeners);
126469 }
126470
126471 });
126472};
126473
126474/***/ }),
6a5a0f88 126475/* 820 */
eb39fafa
DC
126476/***/ (function(module, exports, __webpack_require__) {
126477
126478"use strict";
126479/**
126480 * @fileoverview An object that caches and applies source code fixes.
126481 * @author Nicholas C. Zakas
126482 */
126483 //------------------------------------------------------------------------------
126484// Requirements
126485//------------------------------------------------------------------------------
126486
126487const debug = __webpack_require__(416)("eslint:source-code-fixer"); //------------------------------------------------------------------------------
126488// Helpers
126489//------------------------------------------------------------------------------
126490
126491
126492const BOM = "\uFEFF";
126493/**
126494 * Compares items in a messages array by range.
126495 * @param {Message} a The first message.
126496 * @param {Message} b The second message.
126497 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
126498 * @private
126499 */
126500
126501function compareMessagesByFixRange(a, b) {
126502 return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1];
126503}
126504/**
126505 * Compares items in a messages array by line and column.
126506 * @param {Message} a The first message.
126507 * @param {Message} b The second message.
126508 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
126509 * @private
126510 */
126511
126512
126513function compareMessagesByLocation(a, b) {
126514 return a.line - b.line || a.column - b.column;
126515} //------------------------------------------------------------------------------
126516// Public Interface
126517//------------------------------------------------------------------------------
126518
126519/**
126520 * Utility for apply fixes to source code.
126521 * @constructor
126522 */
126523
126524
126525function SourceCodeFixer() {
126526 Object.freeze(this);
126527}
126528/**
126529 * Applies the fixes specified by the messages to the given text. Tries to be
126530 * smart about the fixes and won't apply fixes over the same area in the text.
126531 * @param {string} sourceText The text to apply the changes to.
126532 * @param {Message[]} messages The array of messages reported by ESLint.
126533 * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed
126534 * @returns {Object} An object containing the fixed text and any unfixed messages.
126535 */
126536
126537
126538SourceCodeFixer.applyFixes = function (sourceText, messages, shouldFix) {
126539 debug("Applying fixes");
126540
126541 if (shouldFix === false) {
126542 debug("shouldFix parameter was false, not attempting fixes");
126543 return {
126544 fixed: false,
126545 messages,
126546 output: sourceText
126547 };
126548 } // clone the array
126549
126550
126551 const remainingMessages = [],
126552 fixes = [],
126553 bom = sourceText.startsWith(BOM) ? BOM : "",
126554 text = bom ? sourceText.slice(1) : sourceText;
126555 let lastPos = Number.NEGATIVE_INFINITY,
126556 output = bom;
126557 /**
126558 * Try to use the 'fix' from a problem.
126559 * @param {Message} problem The message object to apply fixes from
126560 * @returns {boolean} Whether fix was successfully applied
126561 */
126562
126563 function attemptFix(problem) {
126564 const fix = problem.fix;
126565 const start = fix.range[0];
126566 const end = fix.range[1]; // Remain it as a problem if it's overlapped or it's a negative range
126567
126568 if (lastPos >= start || start > end) {
126569 remainingMessages.push(problem);
126570 return false;
126571 } // Remove BOM.
126572
126573
126574 if (start < 0 && end >= 0 || start === 0 && fix.text.startsWith(BOM)) {
126575 output = "";
126576 } // Make output to this fix.
126577
126578
126579 output += text.slice(Math.max(0, lastPos), Math.max(0, start));
126580 output += fix.text;
126581 lastPos = end;
126582 return true;
126583 }
126584
126585 messages.forEach(problem => {
126586 if (Object.prototype.hasOwnProperty.call(problem, "fix")) {
126587 fixes.push(problem);
126588 } else {
126589 remainingMessages.push(problem);
126590 }
126591 });
126592
126593 if (fixes.length) {
126594 debug("Found fixes to apply");
126595 let fixesWereApplied = false;
126596
126597 for (const problem of fixes.sort(compareMessagesByFixRange)) {
126598 if (typeof shouldFix !== "function" || shouldFix(problem)) {
126599 attemptFix(problem);
126600 /*
126601 * The only time attemptFix will fail is if a previous fix was
126602 * applied which conflicts with it. So we can mark this as true.
126603 */
126604
126605 fixesWereApplied = true;
126606 } else {
126607 remainingMessages.push(problem);
126608 }
126609 }
126610
126611 output += text.slice(Math.max(0, lastPos));
126612 return {
126613 fixed: fixesWereApplied,
126614 messages: remainingMessages.sort(compareMessagesByLocation),
126615 output
126616 };
126617 }
126618
126619 debug("No fixes to apply");
126620 return {
126621 fixed: false,
126622 messages,
126623 output: bom + text
126624 };
126625};
126626
126627module.exports = SourceCodeFixer;
126628
126629/***/ }),
6a5a0f88 126630/* 821 */
eb39fafa
DC
126631/***/ (function(module, exports, __webpack_require__) {
126632
126633"use strict";
126634/**
126635 * @fileoverview Tracks performance of individual rules.
126636 * @author Brandon Mills
126637 */
126638 //------------------------------------------------------------------------------
126639// Helpers
126640//------------------------------------------------------------------------------
126641
126642/* istanbul ignore next */
126643
126644/**
126645 * Align the string to left
126646 * @param {string} str string to evaluate
126647 * @param {int} len length of the string
126648 * @param {string} ch delimiter character
126649 * @returns {string} modified string
126650 * @private
126651 */
126652
126653function alignLeft(str, len, ch) {
126654 return str + new Array(len - str.length + 1).join(ch || " ");
126655}
126656/* istanbul ignore next */
126657
126658/**
126659 * Align the string to right
126660 * @param {string} str string to evaluate
126661 * @param {int} len length of the string
126662 * @param {string} ch delimiter character
126663 * @returns {string} modified string
126664 * @private
126665 */
126666
126667
126668function alignRight(str, len, ch) {
126669 return new Array(len - str.length + 1).join(ch || " ") + str;
126670} //------------------------------------------------------------------------------
126671// Module definition
126672//------------------------------------------------------------------------------
126673
126674
126675const enabled = !!process.env.TIMING;
126676const HEADERS = ["Rule", "Time (ms)", "Relative"];
126677const ALIGN = [alignLeft, alignRight, alignRight];
126678/* istanbul ignore next */
126679
126680/**
126681 * display the data
126682 * @param {Object} data Data object to be displayed
126683 * @returns {void} prints modified string with console.log
126684 * @private
126685 */
126686
126687function display(data) {
126688 let total = 0;
126689 const rows = Object.keys(data).map(key => {
126690 const time = data[key];
126691 total += time;
126692 return [key, time];
126693 }).sort((a, b) => b[1] - a[1]).slice(0, 10);
126694 rows.forEach(row => {
126695 row.push("".concat((row[1] * 100 / total).toFixed(1), "%"));
126696 row[1] = row[1].toFixed(3);
126697 });
126698 rows.unshift(HEADERS);
126699 const widths = [];
126700 rows.forEach(row => {
126701 const len = row.length;
126702
126703 for (let i = 0; i < len; i++) {
126704 const n = row[i].length;
126705
126706 if (!widths[i] || n > widths[i]) {
126707 widths[i] = n;
126708 }
126709 }
126710 });
126711 const table = rows.map(row => row.map((cell, index) => ALIGN[index](cell, widths[index])).join(" | "));
126712 table.splice(1, 0, widths.map((width, index) => {
126713 const extraAlignment = index !== 0 && index !== widths.length - 1 ? 2 : 1;
126714 return ALIGN[index](":", width + extraAlignment, "-");
126715 }).join("|"));
126716 console.log(table.join("\n")); // eslint-disable-line no-console
126717}
126718/* istanbul ignore next */
126719
126720
126721module.exports = function () {
126722 const data = Object.create(null);
126723 /**
126724 * Time the run
126725 * @param {*} key key from the data object
126726 * @param {Function} fn function to be called
126727 * @returns {Function} function to be executed
126728 * @private
126729 */
126730
126731 function time(key, fn) {
126732 if (typeof data[key] === "undefined") {
126733 data[key] = 0;
126734 }
126735
126736 return function (...args) {
126737 let t = process.hrtime();
126738 fn(...args);
126739 t = process.hrtime(t);
126740 data[key] += t[0] * 1e3 + t[1] / 1e6;
126741 };
126742 }
126743
126744 if (enabled) {
126745 process.on("exit", () => {
126746 display(data);
126747 });
126748 }
126749
126750 return {
126751 time,
126752 enabled
126753 };
126754}();
126755
126756/***/ }),
6a5a0f88 126757/* 822 */
eb39fafa
DC
126758/***/ (function(module) {
126759
126760module.exports = JSON.parse("{\"rules\":{\"generator-star\":[\"generator-star-spacing\"],\"global-strict\":[\"strict\"],\"no-arrow-condition\":[\"no-confusing-arrow\",\"no-constant-condition\"],\"no-comma-dangle\":[\"comma-dangle\"],\"no-empty-class\":[\"no-empty-character-class\"],\"no-empty-label\":[\"no-labels\"],\"no-extra-strict\":[\"strict\"],\"no-reserved-keys\":[\"quote-props\"],\"no-space-before-semi\":[\"semi-spacing\"],\"no-wrap-func\":[\"no-extra-parens\"],\"space-after-function-name\":[\"space-before-function-paren\"],\"space-after-keywords\":[\"keyword-spacing\"],\"space-before-function-parentheses\":[\"space-before-function-paren\"],\"space-before-keywords\":[\"keyword-spacing\"],\"space-in-brackets\":[\"object-curly-spacing\",\"array-bracket-spacing\",\"computed-property-spacing\"],\"space-return-throw-case\":[\"keyword-spacing\"],\"space-unary-word-ops\":[\"space-unary-ops\"],\"spaced-line-comment\":[\"spaced-comment\"]}}");
126761
126762/***/ }),
6a5a0f88 126763/* 823 */
eb39fafa
DC
126764/***/ (function(module, exports, __webpack_require__) {
126765
126766"use strict";
126767
126768
126769const {
126770 CLIEngine
6a5a0f88 126771} = __webpack_require__(824);
eb39fafa
DC
126772
126773module.exports = {
126774 CLIEngine
126775};
126776
126777/***/ }),
6a5a0f88 126778/* 824 */
eb39fafa
DC
126779/***/ (function(module, exports, __webpack_require__) {
126780
126781"use strict";
126782/* WEBPACK VAR INJECTION */(function(__dirname) {/**
126783 * @fileoverview Main CLI object.
126784 * @author Nicholas C. Zakas
126785 */
126786
126787/*
126788 * The CLI object should *not* call process.exit() directly. It should only return
126789 * exit codes. This allows other programs to use the CLI object and still control
126790 * when the program exits.
126791 */
126792//------------------------------------------------------------------------------
126793// Requirements
126794//------------------------------------------------------------------------------
126795
126796function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
126797
126798function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
126799
126800function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
126801
6a5a0f88 126802const fs = __webpack_require__(825);
eb39fafa
DC
126803
126804const path = __webpack_require__(377);
126805
6a5a0f88 126806const defaultOptions = __webpack_require__(826);
eb39fafa
DC
126807
126808const pkg = __webpack_require__(408);
126809
126810const ConfigOps = __webpack_require__(410);
126811
6a5a0f88 126812const naming = __webpack_require__(827);
eb39fafa 126813
6a5a0f88 126814const ModuleResolver = __webpack_require__(828);
eb39fafa
DC
126815
126816const {
126817 Linter
6a5a0f88 126818} = __webpack_require__(830);
eb39fafa
DC
126819
126820const builtInRules = __webpack_require__(414);
126821
126822const {
126823 CascadingConfigArrayFactory
6a5a0f88 126824} = __webpack_require__(831);
eb39fafa
DC
126825
126826const {
126827 IgnorePattern,
126828 getUsedExtractedConfigs
6a5a0f88 126829} = __webpack_require__(839);
eb39fafa
DC
126830
126831const {
126832 FileEnumerator
6a5a0f88 126833} = __webpack_require__(883);
eb39fafa 126834
6a5a0f88 126835const hash = __webpack_require__(887);
eb39fafa 126836
6a5a0f88 126837const LintResultCache = __webpack_require__(889);
eb39fafa
DC
126838
126839const debug = __webpack_require__(416)("eslint:cli-engine");
126840
126841const validFixTypes = new Set(["problem", "suggestion", "layout"]); //------------------------------------------------------------------------------
126842// Typedefs
126843//------------------------------------------------------------------------------
126844// For VSCode IntelliSense
126845
126846/** @typedef {import("../shared/types").ConfigData} ConfigData */
126847
56c4a2cb
DC
126848/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
126849
eb39fafa
DC
126850/** @typedef {import("../shared/types").LintMessage} LintMessage */
126851
126852/** @typedef {import("../shared/types").ParserOptions} ParserOptions */
126853
126854/** @typedef {import("../shared/types").Plugin} Plugin */
126855
126856/** @typedef {import("../shared/types").RuleConf} RuleConf */
126857
126858/** @typedef {import("../shared/types").Rule} Rule */
126859
126860/** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
126861
126862/** @typedef {ReturnType<ConfigArray["extractConfig"]>} ExtractedConfig */
126863
126864/**
126865 * The options to configure a CLI engine with.
126866 * @typedef {Object} CLIEngineOptions
56c4a2cb
DC
126867 * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
126868 * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance
126869 * @property {boolean} [cache] Enable result caching.
126870 * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
126871 * @property {string} [configFile] The configuration file to use.
126872 * @property {string} [cwd] The value to use for the current working directory.
126873 * @property {string[]} [envs] An array of environments to load.
126874 * @property {string[]|null} [extensions] An array of file extensions to check.
126875 * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
126876 * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
126877 * @property {string[]} [globals] An array of global variables to declare.
126878 * @property {boolean} [ignore] False disables use of .eslintignore.
126879 * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
126880 * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore.
126881 * @property {boolean} [useEslintrc] False disables looking for .eslintrc
126882 * @property {string} [parser] The name of the parser to use.
126883 * @property {ParserOptions} [parserOptions] An object of parserOption settings to use.
126884 * @property {string[]} [plugins] An array of plugins to load.
126885 * @property {Record<string,RuleConf>} [rules] An object of rules to use.
126886 * @property {string[]} [rulePaths] An array of directories to load custom rules from.
126887 * @property {boolean} [reportUnusedDisableDirectives] `true` adds reports for unused eslint-disable directives
126888 * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
126889 * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD
eb39fafa
DC
126890 */
126891
126892/**
126893 * A linting result.
126894 * @typedef {Object} LintResult
126895 * @property {string} filePath The path to the file that was linted.
126896 * @property {LintMessage[]} messages All of the messages for the result.
126897 * @property {number} errorCount Number of errors for the result.
126898 * @property {number} warningCount Number of warnings for the result.
126899 * @property {number} fixableErrorCount Number of fixable errors for the result.
126900 * @property {number} fixableWarningCount Number of fixable warnings for the result.
126901 * @property {string} [source] The source code of the file that was linted.
126902 * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
126903 */
126904
eb39fafa
DC
126905/**
126906 * Linting results.
126907 * @typedef {Object} LintReport
126908 * @property {LintResult[]} results All of the result.
126909 * @property {number} errorCount Number of errors for the result.
126910 * @property {number} warningCount Number of warnings for the result.
126911 * @property {number} fixableErrorCount Number of fixable errors for the result.
126912 * @property {number} fixableWarningCount Number of fixable warnings for the result.
126913 * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules.
126914 */
126915
126916/**
126917 * Private data for CLIEngine.
126918 * @typedef {Object} CLIEngineInternalSlots
126919 * @property {Map<string, Plugin>} additionalPluginPool The map for additional plugins.
126920 * @property {string} cacheFilePath The path to the cache of lint results.
126921 * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs.
126922 * @property {(filePath: string) => boolean} defaultIgnores The default predicate function to check if a file ignored or not.
126923 * @property {FileEnumerator} fileEnumerator The file enumerator.
126924 * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used.
126925 * @property {LintResultCache|null} lintResultCache The cache of lint results.
126926 * @property {Linter} linter The linter instance which has loaded rules.
126927 * @property {CLIEngineOptions} options The normalized options of this instance.
126928 */
126929//------------------------------------------------------------------------------
126930// Helpers
126931//------------------------------------------------------------------------------
126932
126933/** @type {WeakMap<CLIEngine, CLIEngineInternalSlots>} */
126934
126935const internalSlotsMap = new WeakMap();
126936/**
126937 * Determines if each fix type in an array is supported by ESLint and throws
126938 * an error if not.
126939 * @param {string[]} fixTypes An array of fix types to check.
126940 * @returns {void}
126941 * @throws {Error} If an invalid fix type is found.
126942 */
126943
126944function validateFixTypes(fixTypes) {
126945 for (const fixType of fixTypes) {
126946 if (!validFixTypes.has(fixType)) {
126947 throw new Error("Invalid fix type \"".concat(fixType, "\" found."));
126948 }
126949 }
126950}
126951/**
126952 * It will calculate the error and warning count for collection of messages per file
126953 * @param {LintMessage[]} messages Collection of messages
126954 * @returns {Object} Contains the stats
126955 * @private
126956 */
126957
126958
126959function calculateStatsPerFile(messages) {
126960 return messages.reduce((stat, message) => {
126961 if (message.fatal || message.severity === 2) {
126962 stat.errorCount++;
126963
126964 if (message.fix) {
126965 stat.fixableErrorCount++;
126966 }
126967 } else {
126968 stat.warningCount++;
126969
126970 if (message.fix) {
126971 stat.fixableWarningCount++;
126972 }
126973 }
126974
126975 return stat;
126976 }, {
126977 errorCount: 0,
126978 warningCount: 0,
126979 fixableErrorCount: 0,
126980 fixableWarningCount: 0
126981 });
126982}
126983/**
126984 * It will calculate the error and warning count for collection of results from all files
126985 * @param {LintResult[]} results Collection of messages from all the files
126986 * @returns {Object} Contains the stats
126987 * @private
126988 */
126989
126990
126991function calculateStatsPerRun(results) {
126992 return results.reduce((stat, result) => {
126993 stat.errorCount += result.errorCount;
126994 stat.warningCount += result.warningCount;
126995 stat.fixableErrorCount += result.fixableErrorCount;
126996 stat.fixableWarningCount += result.fixableWarningCount;
126997 return stat;
126998 }, {
126999 errorCount: 0,
127000 warningCount: 0,
127001 fixableErrorCount: 0,
127002 fixableWarningCount: 0
127003 });
127004}
127005/**
127006 * Processes an source code using ESLint.
127007 * @param {Object} config The config object.
127008 * @param {string} config.text The source code to verify.
127009 * @param {string} config.cwd The path to the current working directory.
127010 * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
127011 * @param {ConfigArray} config.config The config.
127012 * @param {boolean} config.fix If `true` then it does fix.
127013 * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
127014 * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
127015 * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not.
127016 * @param {Linter} config.linter The linter instance to verify.
127017 * @returns {LintResult} The result of linting.
127018 * @private
127019 */
127020
127021
127022function verifyText({
127023 text,
127024 cwd,
127025 filePath: providedFilePath,
127026 config,
127027 fix,
127028 allowInlineConfig,
127029 reportUnusedDisableDirectives,
127030 fileEnumerator,
127031 linter
127032}) {
127033 const filePath = providedFilePath || "<text>";
127034 debug("Lint ".concat(filePath));
127035 /*
127036 * Verify.
127037 * `config.extractConfig(filePath)` requires an absolute path, but `linter`
127038 * doesn't know CWD, so it gives `linter` an absolute path always.
127039 */
127040
127041 const filePathToVerify = filePath === "<text>" ? path.join(cwd, filePath) : filePath;
127042 const {
127043 fixed,
127044 messages,
127045 output
127046 } = linter.verifyAndFix(text, config, {
127047 allowInlineConfig,
127048 filename: filePathToVerify,
127049 fix,
127050 reportUnusedDisableDirectives,
127051
127052 /**
127053 * Check if the linter should adopt a given code block or not.
127054 * @param {string} blockFilename The virtual filename of a code block.
127055 * @returns {boolean} `true` if the linter should adopt the code block.
127056 */
127057 filterCodeBlock(blockFilename) {
127058 return fileEnumerator.isTargetPath(blockFilename);
127059 }
127060
127061 }); // Tweak and return.
127062
127063 const result = _objectSpread({
127064 filePath,
127065 messages
127066 }, calculateStatsPerFile(messages));
127067
127068 if (fixed) {
127069 result.output = output;
127070 }
127071
127072 if (result.errorCount + result.warningCount > 0 && typeof result.output === "undefined") {
127073 result.source = text;
127074 }
127075
127076 return result;
127077}
127078/**
127079 * Returns result with warning by ignore settings
127080 * @param {string} filePath File path of checked code
127081 * @param {string} baseDir Absolute path of base directory
127082 * @returns {LintResult} Result with single warning
127083 * @private
127084 */
127085
127086
127087function createIgnoreResult(filePath, baseDir) {
127088 let message;
127089 const isHidden = filePath.split(path.sep).find(segment => /^\./u.test(segment));
127090 const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
127091
127092 if (isHidden) {
127093 message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!<relative/path/to/filename>'\") to override.";
127094 } else if (isInNodeModules) {
127095 message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
127096 } else {
127097 message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
127098 }
127099
127100 return {
127101 filePath: path.resolve(filePath),
127102 messages: [{
127103 fatal: false,
127104 severity: 1,
127105 message
127106 }],
127107 errorCount: 0,
127108 warningCount: 1,
127109 fixableErrorCount: 0,
127110 fixableWarningCount: 0
127111 };
127112}
127113/**
127114 * Get a rule.
127115 * @param {string} ruleId The rule ID to get.
127116 * @param {ConfigArray[]} configArrays The config arrays that have plugin rules.
127117 * @returns {Rule|null} The rule or null.
127118 */
127119
127120
127121function getRule(ruleId, configArrays) {
127122 for (const configArray of configArrays) {
127123 const rule = configArray.pluginRules.get(ruleId);
127124
127125 if (rule) {
127126 return rule;
127127 }
127128 }
127129
127130 return builtInRules.get(ruleId) || null;
127131}
127132/**
127133 * Collect used deprecated rules.
127134 * @param {ConfigArray[]} usedConfigArrays The config arrays which were used.
127135 * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
127136 */
127137
127138
127139function* iterateRuleDeprecationWarnings(usedConfigArrays) {
127140 const processedRuleIds = new Set(); // Flatten used configs.
127141
127142 /** @type {ExtractedConfig[]} */
127143
127144 const configs = [].concat(...usedConfigArrays.map(getUsedExtractedConfigs)); // Traverse rule configs.
127145
127146 for (const config of configs) {
127147 for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
127148 // Skip if it was processed.
127149 if (processedRuleIds.has(ruleId)) {
127150 continue;
127151 }
127152
127153 processedRuleIds.add(ruleId); // Skip if it's not used.
127154
127155 if (!ConfigOps.getRuleSeverity(ruleConfig)) {
127156 continue;
127157 }
127158
127159 const rule = getRule(ruleId, usedConfigArrays); // Skip if it's not deprecated.
127160
127161 if (!(rule && rule.meta && rule.meta.deprecated)) {
127162 continue;
127163 } // This rule was used and deprecated.
127164
127165
127166 yield {
127167 ruleId,
127168 replacedBy: rule.meta.replacedBy || []
127169 };
127170 }
127171 }
127172}
127173/**
127174 * Checks if the given message is an error message.
127175 * @param {LintMessage} message The message to check.
127176 * @returns {boolean} Whether or not the message is an error message.
127177 * @private
127178 */
127179
127180
127181function isErrorMessage(message) {
127182 return message.severity === 2;
127183}
127184/**
127185 * return the cacheFile to be used by eslint, based on whether the provided parameter is
127186 * a directory or looks like a directory (ends in `path.sep`), in which case the file
127187 * name will be the `cacheFile/.cache_hashOfCWD`
127188 *
127189 * if cacheFile points to a file or looks like a file then in will just use that file
127190 * @param {string} cacheFile The name of file to be used to store the cache
127191 * @param {string} cwd Current working directory
127192 * @returns {string} the resolved path to the cache file
127193 */
127194
127195
127196function getCacheFile(cacheFile, cwd) {
127197 /*
127198 * make sure the path separators are normalized for the environment/os
127199 * keeping the trailing path separator if present
127200 */
127201 const normalizedCacheFile = path.normalize(cacheFile);
127202 const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
127203 const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
127204 /**
127205 * return the name for the cache file in case the provided parameter is a directory
127206 * @returns {string} the resolved path to the cacheFile
127207 */
127208
127209 function getCacheFileForDirectory() {
127210 return path.join(resolvedCacheFile, ".cache_".concat(hash(cwd)));
127211 }
127212
127213 let fileStats;
127214
127215 try {
127216 fileStats = fs.lstatSync(resolvedCacheFile);
127217 } catch (ex) {
127218 fileStats = null;
127219 }
127220 /*
127221 * in case the file exists we need to verify if the provided path
127222 * is a directory or a file. If it is a directory we want to create a file
127223 * inside that directory
127224 */
127225
127226
127227 if (fileStats) {
127228 /*
127229 * is a directory or is a file, but the original file the user provided
127230 * looks like a directory but `path.resolve` removed the `last path.sep`
127231 * so we need to still treat this like a directory
127232 */
127233 if (fileStats.isDirectory() || looksLikeADirectory) {
127234 return getCacheFileForDirectory();
127235 } // is file so just use that file
127236
127237
127238 return resolvedCacheFile;
127239 }
127240 /*
127241 * here we known the file or directory doesn't exist,
127242 * so we will try to infer if its a directory if it looks like a directory
127243 * for the current operating system.
127244 */
127245 // if the last character passed is a path separator we assume is a directory
127246
127247
127248 if (looksLikeADirectory) {
127249 return getCacheFileForDirectory();
127250 }
127251
127252 return resolvedCacheFile;
127253}
127254/**
127255 * Convert a string array to a boolean map.
127256 * @param {string[]|null} keys The keys to assign true.
127257 * @param {boolean} defaultValue The default value for each property.
127258 * @param {string} displayName The property name which is used in error message.
127259 * @returns {Record<string,boolean>} The boolean map.
127260 */
127261
127262
127263function toBooleanMap(keys, defaultValue, displayName) {
127264 if (keys && !Array.isArray(keys)) {
127265 throw new Error("".concat(displayName, " must be an array."));
127266 }
127267
127268 if (keys && keys.length > 0) {
127269 return keys.reduce((map, def) => {
127270 const [key, value] = def.split(":");
127271
127272 if (key !== "__proto__") {
127273 map[key] = value === void 0 ? defaultValue : value === "true";
127274 }
127275
127276 return map;
127277 }, {});
127278 }
127279
127280 return void 0;
127281}
127282/**
127283 * Create a config data from CLI options.
127284 * @param {CLIEngineOptions} options The options
127285 * @returns {ConfigData|null} The created config data.
127286 */
127287
127288
127289function createConfigDataFromOptions(options) {
127290 const {
127291 ignorePattern,
127292 parser,
127293 parserOptions,
127294 plugins,
127295 rules
127296 } = options;
127297 const env = toBooleanMap(options.envs, true, "envs");
127298 const globals = toBooleanMap(options.globals, false, "globals");
127299
127300 if (env === void 0 && globals === void 0 && (ignorePattern === void 0 || ignorePattern.length === 0) && parser === void 0 && parserOptions === void 0 && plugins === void 0 && rules === void 0) {
127301 return null;
127302 }
127303
127304 return {
127305 env,
127306 globals,
127307 ignorePatterns: ignorePattern,
127308 parser,
127309 parserOptions,
127310 plugins,
127311 rules
127312 };
127313}
127314/**
127315 * Checks whether a directory exists at the given location
127316 * @param {string} resolvedPath A path from the CWD
127317 * @returns {boolean} `true` if a directory exists
127318 */
127319
127320
127321function directoryExists(resolvedPath) {
127322 try {
127323 return fs.statSync(resolvedPath).isDirectory();
127324 } catch (error) {
127325 if (error && error.code === "ENOENT") {
127326 return false;
127327 }
127328
127329 throw error;
127330 }
127331} //------------------------------------------------------------------------------
127332// Public Interface
127333//------------------------------------------------------------------------------
127334
127335
127336class CLIEngine {
127337 /**
127338 * Creates a new instance of the core CLI engine.
127339 * @param {CLIEngineOptions} providedOptions The options for this instance.
127340 */
127341 constructor(providedOptions) {
127342 const options = Object.assign(Object.create(null), defaultOptions, {
127343 cwd: process.cwd()
127344 }, providedOptions);
127345
127346 if (options.fix === void 0) {
127347 options.fix = false;
127348 }
127349
127350 const additionalPluginPool = new Map();
127351 const cacheFilePath = getCacheFile(options.cacheLocation || options.cacheFile, options.cwd);
127352 const configArrayFactory = new CascadingConfigArrayFactory({
127353 additionalPluginPool,
127354 baseConfig: options.baseConfig || null,
127355 cliConfig: createConfigDataFromOptions(options),
127356 cwd: options.cwd,
127357 ignorePath: options.ignorePath,
127358 resolvePluginsRelativeTo: options.resolvePluginsRelativeTo,
127359 rulePaths: options.rulePaths,
127360 specificConfigPath: options.configFile,
127361 useEslintrc: options.useEslintrc
127362 });
127363 const fileEnumerator = new FileEnumerator({
127364 configArrayFactory,
127365 cwd: options.cwd,
127366 extensions: options.extensions,
127367 globInputPaths: options.globInputPaths,
127368 errorOnUnmatchedPattern: options.errorOnUnmatchedPattern,
127369 ignore: options.ignore
127370 });
127371 const lintResultCache = options.cache ? new LintResultCache(cacheFilePath) : null;
127372 const linter = new Linter({
127373 cwd: options.cwd
127374 });
127375 /** @type {ConfigArray[]} */
127376
127377 const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()]; // Store private data.
127378
127379 internalSlotsMap.set(this, {
127380 additionalPluginPool,
127381 cacheFilePath,
127382 configArrayFactory,
127383 defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd),
127384 fileEnumerator,
127385 lastConfigArrays,
127386 lintResultCache,
127387 linter,
127388 options
127389 }); // setup special filter for fixes
127390
127391 if (options.fix && options.fixTypes && options.fixTypes.length > 0) {
127392 debug("Using fix types ".concat(options.fixTypes)); // throw an error if any invalid fix types are found
127393
127394 validateFixTypes(options.fixTypes); // convert to Set for faster lookup
127395
127396 const fixTypes = new Set(options.fixTypes); // save original value of options.fix in case it's a function
127397
127398 const originalFix = typeof options.fix === "function" ? options.fix : () => true;
127399
127400 options.fix = message => {
127401 const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays);
127402 const matches = rule && rule.meta && fixTypes.has(rule.meta.type);
127403 return matches && originalFix(message);
127404 };
127405 }
127406 }
127407
127408 getRules() {
127409 const {
127410 lastConfigArrays
127411 } = internalSlotsMap.get(this);
127412 return new Map(function* () {
127413 yield* builtInRules;
127414
127415 for (const configArray of lastConfigArrays) {
127416 yield* configArray.pluginRules;
127417 }
127418 }());
127419 }
127420 /**
127421 * Returns results that only contains errors.
127422 * @param {LintResult[]} results The results to filter.
127423 * @returns {LintResult[]} The filtered results.
127424 */
127425
127426
127427 static getErrorResults(results) {
127428 const filtered = [];
127429 results.forEach(result => {
127430 const filteredMessages = result.messages.filter(isErrorMessage);
127431
127432 if (filteredMessages.length > 0) {
56c4a2cb 127433 filtered.push(_objectSpread(_objectSpread({}, result), {}, {
eb39fafa
DC
127434 messages: filteredMessages,
127435 errorCount: filteredMessages.length,
127436 warningCount: 0,
127437 fixableErrorCount: result.fixableErrorCount,
127438 fixableWarningCount: 0
127439 }));
127440 }
127441 });
127442 return filtered;
127443 }
127444 /**
127445 * Outputs fixes from the given results to files.
127446 * @param {LintReport} report The report object created by CLIEngine.
127447 * @returns {void}
127448 */
127449
127450
127451 static outputFixes(report) {
127452 report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => {
127453 fs.writeFileSync(result.filePath, result.output);
127454 });
127455 }
127456 /**
127457 * Add a plugin by passing its configuration
127458 * @param {string} name Name of the plugin.
127459 * @param {Plugin} pluginObject Plugin configuration object.
127460 * @returns {void}
127461 */
127462
127463
127464 addPlugin(name, pluginObject) {
127465 const {
127466 additionalPluginPool,
127467 configArrayFactory,
127468 lastConfigArrays
127469 } = internalSlotsMap.get(this);
127470 additionalPluginPool.set(name, pluginObject);
127471 configArrayFactory.clearCache();
127472 lastConfigArrays.length = 1;
127473 lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
127474 }
127475 /**
127476 * Resolves the patterns passed into executeOnFiles() into glob-based patterns
127477 * for easier handling.
127478 * @param {string[]} patterns The file patterns passed on the command line.
127479 * @returns {string[]} The equivalent glob patterns.
127480 */
127481
127482
127483 resolveFileGlobPatterns(patterns) {
127484 const {
127485 options
127486 } = internalSlotsMap.get(this);
127487
127488 if (options.globInputPaths === false) {
127489 return patterns.filter(Boolean);
127490 }
127491
127492 const extensions = (options.extensions || [".js"]).map(ext => ext.replace(/^\./u, ""));
127493 const dirSuffix = "/**/*.{".concat(extensions.join(","), "}");
127494 return patterns.filter(Boolean).map(pathname => {
127495 const resolvedPath = path.resolve(options.cwd, pathname);
127496 const newPath = directoryExists(resolvedPath) ? pathname.replace(/[/\\]$/u, "") + dirSuffix : pathname;
127497 return path.normalize(newPath).replace(/\\/gu, "/");
127498 });
127499 }
127500 /**
127501 * Executes the current configuration on an array of file and directory names.
127502 * @param {string[]} patterns An array of file and directory names.
127503 * @returns {LintReport} The results for all files that were linted.
127504 */
127505
127506
127507 executeOnFiles(patterns) {
127508 const {
127509 cacheFilePath,
127510 fileEnumerator,
127511 lastConfigArrays,
127512 lintResultCache,
127513 linter,
127514 options: {
127515 allowInlineConfig,
127516 cache,
127517 cwd,
127518 fix,
127519 reportUnusedDisableDirectives
127520 }
127521 } = internalSlotsMap.get(this);
127522 const results = [];
127523 const startTime = Date.now(); // Clear the last used config arrays.
127524
127525 lastConfigArrays.length = 0; // Delete cache file; should this do here?
127526
127527 if (!cache) {
127528 try {
127529 fs.unlinkSync(cacheFilePath);
127530 } catch (error) {
127531 const errorCode = error && error.code; // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
127532
127533 if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath))) {
127534 throw error;
127535 }
127536 }
127537 } // Iterate source code files.
127538
127539
127540 for (const {
127541 config,
127542 filePath,
127543 ignored
127544 } of fileEnumerator.iterateFiles(patterns)) {
127545 if (ignored) {
127546 results.push(createIgnoreResult(filePath, cwd));
127547 continue;
127548 }
127549 /*
127550 * Store used configs for:
127551 * - this method uses to collect used deprecated rules.
127552 * - `getRules()` method uses to collect all loaded rules.
127553 * - `--fix-type` option uses to get the loaded rule's meta data.
127554 */
127555
127556
127557 if (!lastConfigArrays.includes(config)) {
127558 lastConfigArrays.push(config);
127559 } // Skip if there is cached result.
127560
127561
127562 if (lintResultCache) {
127563 const cachedResult = lintResultCache.getCachedLintResults(filePath, config);
127564
127565 if (cachedResult) {
127566 const hadMessages = cachedResult.messages && cachedResult.messages.length > 0;
127567
127568 if (hadMessages && fix) {
127569 debug("Reprocessing cached file to allow autofix: ".concat(filePath));
127570 } else {
127571 debug("Skipping file since it hasn't changed: ".concat(filePath));
127572 results.push(cachedResult);
127573 continue;
127574 }
127575 }
127576 } // Do lint.
127577
127578
127579 const result = verifyText({
127580 text: fs.readFileSync(filePath, "utf8"),
127581 filePath,
127582 config,
127583 cwd,
127584 fix,
127585 allowInlineConfig,
127586 reportUnusedDisableDirectives,
127587 fileEnumerator,
127588 linter
127589 });
127590 results.push(result);
127591 /*
127592 * Store the lint result in the LintResultCache.
127593 * NOTE: The LintResultCache will remove the file source and any
127594 * other properties that are difficult to serialize, and will
127595 * hydrate those properties back in on future lint runs.
127596 */
127597
127598 if (lintResultCache) {
127599 lintResultCache.setCachedLintResults(filePath, config, result);
127600 }
127601 } // Persist the cache to disk.
127602
127603
127604 if (lintResultCache) {
127605 lintResultCache.reconcile();
56c4a2cb 127606 }
eb39fafa 127607
eb39fafa 127608 debug("Linting complete in: ".concat(Date.now() - startTime, "ms"));
56c4a2cb
DC
127609 let usedDeprecatedRules;
127610 return _objectSpread(_objectSpread({
eb39fafa 127611 results
56c4a2cb
DC
127612 }, calculateStatsPerRun(results)), {}, {
127613 // Initialize it lazily because CLI and `ESLint` API don't use it.
127614 get usedDeprecatedRules() {
127615 if (!usedDeprecatedRules) {
127616 usedDeprecatedRules = Array.from(iterateRuleDeprecationWarnings(lastConfigArrays));
127617 }
127618
127619 return usedDeprecatedRules;
127620 }
127621
eb39fafa
DC
127622 });
127623 }
127624 /**
127625 * Executes the current configuration on text.
127626 * @param {string} text A string of JavaScript code to lint.
127627 * @param {string} [filename] An optional string representing the texts filename.
127628 * @param {boolean} [warnIgnored] Always warn when a file is ignored
127629 * @returns {LintReport} The results for the linting.
127630 */
127631
127632
127633 executeOnText(text, filename, warnIgnored) {
127634 const {
127635 configArrayFactory,
127636 fileEnumerator,
127637 lastConfigArrays,
127638 linter,
127639 options: {
127640 allowInlineConfig,
127641 cwd,
127642 fix,
127643 reportUnusedDisableDirectives
127644 }
127645 } = internalSlotsMap.get(this);
127646 const results = [];
127647 const startTime = Date.now();
127648 const resolvedFilename = filename && path.resolve(cwd, filename); // Clear the last used config arrays.
127649
127650 lastConfigArrays.length = 0;
127651
127652 if (resolvedFilename && this.isPathIgnored(resolvedFilename)) {
127653 if (warnIgnored) {
127654 results.push(createIgnoreResult(resolvedFilename, cwd));
127655 }
127656 } else {
127657 const config = configArrayFactory.getConfigArrayForFile(resolvedFilename || "__placeholder__.js");
127658 /*
127659 * Store used configs for:
127660 * - this method uses to collect used deprecated rules.
127661 * - `getRules()` method uses to collect all loaded rules.
127662 * - `--fix-type` option uses to get the loaded rule's meta data.
127663 */
127664
127665 lastConfigArrays.push(config); // Do lint.
127666
127667 results.push(verifyText({
127668 text,
127669 filePath: resolvedFilename,
127670 config,
127671 cwd,
127672 fix,
127673 allowInlineConfig,
127674 reportUnusedDisableDirectives,
127675 fileEnumerator,
127676 linter
127677 }));
56c4a2cb 127678 }
eb39fafa 127679
eb39fafa 127680 debug("Linting complete in: ".concat(Date.now() - startTime, "ms"));
56c4a2cb
DC
127681 let usedDeprecatedRules;
127682 return _objectSpread(_objectSpread({
eb39fafa 127683 results
56c4a2cb
DC
127684 }, calculateStatsPerRun(results)), {}, {
127685 // Initialize it lazily because CLI and `ESLint` API don't use it.
127686 get usedDeprecatedRules() {
127687 if (!usedDeprecatedRules) {
127688 usedDeprecatedRules = Array.from(iterateRuleDeprecationWarnings(lastConfigArrays));
127689 }
127690
127691 return usedDeprecatedRules;
127692 }
127693
eb39fafa
DC
127694 });
127695 }
127696 /**
127697 * Returns a configuration object for the given file based on the CLI options.
127698 * This is the same logic used by the ESLint CLI executable to determine
127699 * configuration for each file it processes.
127700 * @param {string} filePath The path of the file to retrieve a config object for.
127701 * @returns {ConfigData} A configuration object for the file.
127702 */
127703
127704
127705 getConfigForFile(filePath) {
127706 const {
127707 configArrayFactory,
127708 options
127709 } = internalSlotsMap.get(this);
127710 const absolutePath = path.resolve(options.cwd, filePath);
127711
127712 if (directoryExists(absolutePath)) {
127713 throw Object.assign(new Error("'filePath' should not be a directory path."), {
127714 messageTemplate: "print-config-with-directory-path"
127715 });
127716 }
127717
127718 return configArrayFactory.getConfigArrayForFile(absolutePath).extractConfig(absolutePath).toCompatibleObjectAsConfigFileContent();
127719 }
127720 /**
127721 * Checks if a given path is ignored by ESLint.
127722 * @param {string} filePath The path of the file to check.
127723 * @returns {boolean} Whether or not the given path is ignored.
127724 */
127725
127726
127727 isPathIgnored(filePath) {
127728 const {
127729 configArrayFactory,
127730 defaultIgnores,
127731 options: {
127732 cwd,
127733 ignore
127734 }
127735 } = internalSlotsMap.get(this);
127736 const absolutePath = path.resolve(cwd, filePath);
127737
127738 if (ignore) {
127739 const config = configArrayFactory.getConfigArrayForFile(absolutePath).extractConfig(absolutePath);
127740 const ignores = config.ignores || defaultIgnores;
127741 return ignores(absolutePath);
127742 }
127743
127744 return defaultIgnores(absolutePath);
127745 }
127746 /**
56c4a2cb 127747 * Returns the formatter representing the given format or null if the `format` is not a string.
eb39fafa
DC
127748 * @param {string} [format] The name of the format to load or the path to a
127749 * custom formatter.
56c4a2cb 127750 * @returns {(Function|null)} The formatter function or null if the `format` is not a string.
eb39fafa
DC
127751 */
127752
127753
127754 getFormatter(format) {
127755 // default is stylish
127756 const resolvedFormatName = format || "stylish"; // only strings are valid formatters
127757
127758 if (typeof resolvedFormatName === "string") {
127759 // replace \ with / for Windows compatibility
127760 const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");
127761 const slots = internalSlotsMap.get(this);
127762 const cwd = slots ? slots.options.cwd : process.cwd();
127763 const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
127764 let formatterPath; // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
127765
127766 if (!namespace && normalizedFormatName.indexOf("/") > -1) {
127767 formatterPath = path.resolve(cwd, normalizedFormatName);
127768 } else {
127769 try {
127770 const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
127771 formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
127772 } catch (e) {
127773 formatterPath = path.resolve(__dirname, "formatters", normalizedFormatName);
127774 }
127775 }
127776
127777 try {
6a5a0f88 127778 return __webpack_require__(881)(formatterPath);
eb39fafa
DC
127779 } catch (ex) {
127780 ex.message = "There was a problem loading formatter: ".concat(formatterPath, "\nError: ").concat(ex.message);
127781 throw ex;
127782 }
127783 } else {
127784 return null;
127785 }
127786 }
127787
127788}
127789
127790CLIEngine.version = pkg.version;
127791CLIEngine.getFormatter = CLIEngine.prototype.getFormatter;
127792module.exports = {
127793 CLIEngine,
127794
127795 /**
127796 * Get the internal slots of a given CLIEngine instance for tests.
127797 * @param {CLIEngine} instance The CLIEngine instance to get.
127798 * @returns {CLIEngineInternalSlots} The internal slots.
127799 */
127800 getCLIEngineInternalSlots(instance) {
127801 return internalSlotsMap.get(instance);
127802 }
127803
127804};
127805/* WEBPACK VAR INJECTION */}.call(this, "/"))
127806
127807/***/ }),
6a5a0f88 127808/* 825 */
eb39fafa
DC
127809/***/ (function(module, exports) {
127810
127811module.exports = require("fs");
127812
127813/***/ }),
6a5a0f88 127814/* 826 */
eb39fafa
DC
127815/***/ (function(module, exports, __webpack_require__) {
127816
127817"use strict";
127818/**
127819 * @fileoverview Default CLIEngineOptions.
127820 * @author Ian VanSchooten
127821 */
127822
127823
127824module.exports = {
127825 configFile: null,
127826 baseConfig: false,
127827 rulePaths: [],
127828 useEslintrc: true,
127829 envs: [],
127830 globals: [],
127831 extensions: null,
127832 ignore: true,
127833 ignorePath: void 0,
127834 cache: false,
127835
127836 /*
127837 * in order to honor the cacheFile option if specified
127838 * this option should not have a default value otherwise
127839 * it will always be used
127840 */
127841 cacheLocation: "",
127842 cacheFile: ".eslintcache",
127843 fix: false,
127844 allowInlineConfig: true,
127845 reportUnusedDisableDirectives: void 0,
127846 globInputPaths: true
127847};
127848
127849/***/ }),
6a5a0f88 127850/* 827 */
eb39fafa
DC
127851/***/ (function(module, exports, __webpack_require__) {
127852
127853"use strict";
127854/**
127855 * @fileoverview Common helpers for naming of plugins, formatters and configs
127856 */
127857
127858
127859const NAMESPACE_REGEX = /^@.*\//iu;
127860/**
127861 * Brings package name to correct format based on prefix
127862 * @param {string} name The name of the package.
127863 * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
127864 * @returns {string} Normalized name of the package
127865 * @private
127866 */
127867
127868function normalizePackageName(name, prefix) {
127869 let normalizedName = name;
127870 /**
127871 * On Windows, name can come in with Windows slashes instead of Unix slashes.
127872 * Normalize to Unix first to avoid errors later on.
127873 * https://github.com/eslint/eslint/issues/5644
127874 */
127875
127876 if (normalizedName.includes("\\")) {
127877 normalizedName = normalizedName.replace(/\\/gu, "/");
127878 }
127879
127880 if (normalizedName.charAt(0) === "@") {
127881 /**
127882 * it's a scoped package
127883 * package name is the prefix, or just a username
127884 */
127885 const scopedPackageShortcutRegex = new RegExp("^(@[^/]+)(?:/(?:".concat(prefix, ")?)?$"), "u"),
127886 scopedPackageNameRegex = new RegExp("^".concat(prefix, "(-|$)"), "u");
127887
127888 if (scopedPackageShortcutRegex.test(normalizedName)) {
127889 normalizedName = normalizedName.replace(scopedPackageShortcutRegex, "$1/".concat(prefix));
127890 } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
127891 /**
127892 * for scoped packages, insert the prefix after the first / unless
127893 * the path is already @scope/eslint or @scope/eslint-xxx-yyy
127894 */
127895 normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, "@$1/".concat(prefix, "-$2"));
127896 }
127897 } else if (!normalizedName.startsWith("".concat(prefix, "-"))) {
127898 normalizedName = "".concat(prefix, "-").concat(normalizedName);
127899 }
127900
127901 return normalizedName;
127902}
127903/**
127904 * Removes the prefix from a fullname.
127905 * @param {string} fullname The term which may have the prefix.
127906 * @param {string} prefix The prefix to remove.
127907 * @returns {string} The term without prefix.
127908 */
127909
127910
127911function getShorthandName(fullname, prefix) {
127912 if (fullname[0] === "@") {
127913 let matchResult = new RegExp("^(@[^/]+)/".concat(prefix, "$"), "u").exec(fullname);
127914
127915 if (matchResult) {
127916 return matchResult[1];
127917 }
127918
127919 matchResult = new RegExp("^(@[^/]+)/".concat(prefix, "-(.+)$"), "u").exec(fullname);
127920
127921 if (matchResult) {
127922 return "".concat(matchResult[1], "/").concat(matchResult[2]);
127923 }
127924 } else if (fullname.startsWith("".concat(prefix, "-"))) {
127925 return fullname.slice(prefix.length + 1);
127926 }
127927
127928 return fullname;
127929}
127930/**
127931 * Gets the scope (namespace) of a term.
127932 * @param {string} term The term which may have the namespace.
127933 * @returns {string} The namespace of the term if it has one.
127934 */
127935
127936
127937function getNamespaceFromTerm(term) {
127938 const match = term.match(NAMESPACE_REGEX);
127939 return match ? match[0] : "";
127940} //------------------------------------------------------------------------------
127941// Public Interface
127942//------------------------------------------------------------------------------
127943
127944
127945module.exports = {
127946 normalizePackageName,
127947 getShorthandName,
127948 getNamespaceFromTerm
127949};
127950
127951/***/ }),
6a5a0f88 127952/* 828 */
eb39fafa
DC
127953/***/ (function(module, exports, __webpack_require__) {
127954
127955"use strict";
127956/**
127957 * Utility for resolving a module relative to another module
127958 * @author Teddy Katz
127959 */
127960
127961
6a5a0f88 127962const Module = __webpack_require__(829);
eb39fafa
DC
127963/*
127964 * `Module.createRequire` is added in v12.2.0. It supports URL as well.
127965 * We only support the case where the argument is a filepath, not a URL.
127966 */
56c4a2cb 127967// eslint-disable-next-line node/no-unsupported-features/node-builtins, node/no-deprecated-api
eb39fafa
DC
127968
127969
127970const createRequire = Module.createRequire || Module.createRequireFromPath;
127971module.exports = {
127972 /**
127973 * Resolves a Node module relative to another module
127974 * @param {string} moduleName The name of a Node module, or a path to a Node module.
127975 * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
127976 * a file rather than a directory, but the file need not actually exist.
127977 * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
127978 */
127979 resolve(moduleName, relativeToPath) {
127980 try {
127981 return createRequire(relativeToPath).resolve(moduleName);
127982 } catch (error) {
127983 // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
127984 if (typeof error === "object" && error !== null && error.code === "MODULE_NOT_FOUND" && !error.requireStack && error.message.includes(moduleName)) {
127985 error.message += "\nRequire stack:\n- ".concat(relativeToPath);
127986 }
127987
127988 throw error;
127989 }
127990 }
127991
127992};
127993
127994/***/ }),
6a5a0f88 127995/* 829 */
eb39fafa
DC
127996/***/ (function(module, exports) {
127997
127998module.exports = require("module");
127999
128000/***/ }),
6a5a0f88 128001/* 830 */
eb39fafa
DC
128002/***/ (function(module, exports, __webpack_require__) {
128003
128004"use strict";
128005
128006
128007const {
128008 Linter
128009} = __webpack_require__(376);
128010
6a5a0f88 128011const interpolate = __webpack_require__(816);
eb39fafa 128012
6a5a0f88 128013const SourceCodeFixer = __webpack_require__(820);
eb39fafa
DC
128014
128015module.exports = {
128016 Linter,
128017 // For testers.
128018 SourceCodeFixer,
128019 interpolate
128020};
128021
128022/***/ }),
6a5a0f88 128023/* 831 */
eb39fafa
DC
128024/***/ (function(module, exports, __webpack_require__) {
128025
128026"use strict";
128027/**
128028 * @fileoverview `CascadingConfigArrayFactory` class.
128029 *
128030 * `CascadingConfigArrayFactory` class has a responsibility:
128031 *
128032 * 1. Handles cascading of config files.
128033 *
128034 * It provides two methods:
128035 *
128036 * - `getConfigArrayForFile(filePath)`
128037 * Get the corresponded configuration of a given file. This method doesn't
128038 * throw even if the given file didn't exist.
128039 * - `clearCache()`
128040 * Clear the internal cache. You have to call this method when
128041 * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
128042 * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
128043 *
128044 * @author Toru Nagashima <https://github.com/mysticatea>
128045 */
128046 //------------------------------------------------------------------------------
128047// Requirements
128048//------------------------------------------------------------------------------
128049
128050const os = __webpack_require__(423);
128051
128052const path = __webpack_require__(377);
128053
128054const {
128055 validateConfigArray
128056} = __webpack_require__(411);
128057
128058const {
128059 emitDeprecationWarning
6a5a0f88 128060} = __webpack_require__(727);
eb39fafa
DC
128061
128062const {
128063 ConfigArrayFactory
6a5a0f88 128064} = __webpack_require__(832);
eb39fafa
DC
128065
128066const {
128067 ConfigArray,
128068 ConfigDependency,
128069 IgnorePattern
6a5a0f88 128070} = __webpack_require__(839);
eb39fafa 128071
6a5a0f88 128072const loadRules = __webpack_require__(882);
eb39fafa
DC
128073
128074const debug = __webpack_require__(416)("eslint:cascading-config-array-factory"); //------------------------------------------------------------------------------
128075// Helpers
128076//------------------------------------------------------------------------------
128077// Define types for VSCode IntelliSense.
128078
128079/** @typedef {import("../shared/types").ConfigData} ConfigData */
128080
128081/** @typedef {import("../shared/types").Parser} Parser */
128082
128083/** @typedef {import("../shared/types").Plugin} Plugin */
128084
128085/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
128086
128087/**
128088 * @typedef {Object} CascadingConfigArrayFactoryOptions
128089 * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
128090 * @property {ConfigData} [baseConfig] The config by `baseConfig` option.
128091 * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
128092 * @property {string} [cwd] The base directory to start lookup.
128093 * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
128094 * @property {string[]} [rulePaths] The value of `--rulesdir` option.
128095 * @property {string} [specificConfigPath] The value of `--config` option.
128096 * @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
128097 */
128098
128099/**
128100 * @typedef {Object} CascadingConfigArrayFactoryInternalSlots
128101 * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
128102 * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
128103 * @property {ConfigArray} cliConfigArray The config array of CLI options.
128104 * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
128105 * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
128106 * @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
128107 * @property {string} cwd The base directory to start lookup.
128108 * @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
128109 * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
128110 * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
128111 * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
128112 * @property {boolean} useEslintrc if `false` then it doesn't load config files.
128113 */
128114
128115/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
128116
128117
128118const internalSlotsMap = new WeakMap();
128119/**
128120 * Create the config array from `baseConfig` and `rulePaths`.
128121 * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
128122 * @returns {ConfigArray} The config array of the base configs.
128123 */
128124
128125function createBaseConfigArray({
128126 configArrayFactory,
128127 baseConfigData,
128128 rulePaths,
128129 cwd
128130}) {
128131 const baseConfigArray = configArrayFactory.create(baseConfigData, {
128132 name: "BaseConfig"
128133 });
128134 /*
128135 * Create the config array element for the default ignore patterns.
128136 * This element has `ignorePattern` property that ignores the default
128137 * patterns in the current working directory.
128138 */
128139
128140 baseConfigArray.unshift(configArrayFactory.create({
128141 ignorePatterns: IgnorePattern.DefaultPatterns
128142 }, {
128143 name: "DefaultIgnorePattern"
128144 })[0]);
128145 /*
128146 * Load rules `--rulesdir` option as a pseudo plugin.
128147 * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
128148 * the rule's options with only information in the config array.
128149 */
128150
128151 if (rulePaths && rulePaths.length > 0) {
128152 baseConfigArray.push({
128153 type: "config",
128154 name: "--rulesdir",
128155 filePath: "",
128156 plugins: {
128157 "": new ConfigDependency({
128158 definition: {
128159 rules: rulePaths.reduce((map, rulesPath) => Object.assign(map, loadRules(rulesPath, cwd)), {})
128160 },
128161 filePath: "",
128162 id: "",
128163 importerName: "--rulesdir",
128164 importerPath: ""
128165 })
128166 }
128167 });
128168 }
128169
128170 return baseConfigArray;
128171}
128172/**
128173 * Create the config array from CLI options.
128174 * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
128175 * @returns {ConfigArray} The config array of the base configs.
128176 */
128177
128178
128179function createCLIConfigArray({
128180 cliConfigData,
128181 configArrayFactory,
128182 cwd,
128183 ignorePath,
128184 specificConfigPath
128185}) {
128186 const cliConfigArray = configArrayFactory.create(cliConfigData, {
128187 name: "CLIOptions"
128188 });
128189 cliConfigArray.unshift(...(ignorePath ? configArrayFactory.loadESLintIgnore(ignorePath) : configArrayFactory.loadDefaultESLintIgnore()));
128190
128191 if (specificConfigPath) {
128192 cliConfigArray.unshift(...configArrayFactory.loadFile(specificConfigPath, {
128193 name: "--config",
128194 basePath: cwd
128195 }));
128196 }
128197
128198 return cliConfigArray;
128199}
128200/**
128201 * The error type when there are files matched by a glob, but all of them have been ignored.
128202 */
128203
128204
128205class ConfigurationNotFoundError extends Error {
128206 // eslint-disable-next-line jsdoc/require-description
128207
128208 /**
128209 * @param {string} directoryPath The directory path.
128210 */
128211 constructor(directoryPath) {
128212 super("No ESLint configuration found in ".concat(directoryPath, "."));
128213 this.messageTemplate = "no-config-found";
128214 this.messageData = {
128215 directoryPath
128216 };
128217 }
128218
128219}
128220/**
128221 * This class provides the functionality that enumerates every file which is
128222 * matched by given glob patterns and that configuration.
128223 */
128224
128225
128226class CascadingConfigArrayFactory {
128227 /**
128228 * Initialize this enumerator.
128229 * @param {CascadingConfigArrayFactoryOptions} options The options.
128230 */
128231 constructor({
128232 additionalPluginPool = new Map(),
128233 baseConfig: baseConfigData = null,
128234 cliConfig: cliConfigData = null,
128235 cwd = process.cwd(),
128236 ignorePath,
128237 resolvePluginsRelativeTo,
128238 rulePaths = [],
128239 specificConfigPath = null,
128240 useEslintrc = true
128241 } = {}) {
128242 const configArrayFactory = new ConfigArrayFactory({
128243 additionalPluginPool,
128244 cwd,
128245 resolvePluginsRelativeTo
128246 });
128247 internalSlotsMap.set(this, {
128248 baseConfigArray: createBaseConfigArray({
128249 baseConfigData,
128250 configArrayFactory,
128251 cwd,
128252 rulePaths
128253 }),
128254 baseConfigData,
128255 cliConfigArray: createCLIConfigArray({
128256 cliConfigData,
128257 configArrayFactory,
128258 cwd,
128259 ignorePath,
128260 specificConfigPath
128261 }),
128262 cliConfigData,
128263 configArrayFactory,
128264 configCache: new Map(),
128265 cwd,
128266 finalizeCache: new WeakMap(),
128267 ignorePath,
128268 rulePaths,
128269 specificConfigPath,
128270 useEslintrc
128271 });
128272 }
128273 /**
128274 * The path to the current working directory.
128275 * This is used by tests.
128276 * @type {string}
128277 */
128278
128279
128280 get cwd() {
128281 const {
128282 cwd
128283 } = internalSlotsMap.get(this);
128284 return cwd;
128285 }
128286 /**
128287 * Get the config array of a given file.
128288 * If `filePath` was not given, it returns the config which contains only
128289 * `baseConfigData` and `cliConfigData`.
128290 * @param {string} [filePath] The file path to a file.
128291 * @param {Object} [options] The options.
128292 * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
128293 * @returns {ConfigArray} The config array of the file.
128294 */
128295
128296
128297 getConfigArrayForFile(filePath, {
128298 ignoreNotFoundError = false
128299 } = {}) {
128300 const {
128301 baseConfigArray,
128302 cliConfigArray,
128303 cwd
128304 } = internalSlotsMap.get(this);
128305
128306 if (!filePath) {
128307 return new ConfigArray(...baseConfigArray, ...cliConfigArray);
128308 }
128309
128310 const directoryPath = path.dirname(path.resolve(cwd, filePath));
128311 debug("Load config files for ".concat(directoryPath, "."));
128312 return this._finalizeConfigArray(this._loadConfigInAncestors(directoryPath), directoryPath, ignoreNotFoundError);
128313 }
56c4a2cb
DC
128314 /**
128315 * Set the config data to override all configs.
128316 * Require to call `clearCache()` method after this method is called.
128317 * @param {ConfigData} configData The config data to override all configs.
128318 * @returns {void}
128319 */
128320
128321
128322 setOverrideConfig(configData) {
128323 const slots = internalSlotsMap.get(this);
128324 slots.cliConfigData = configData;
128325 }
eb39fafa
DC
128326 /**
128327 * Clear config cache.
128328 * @returns {void}
128329 */
128330
128331
128332 clearCache() {
128333 const slots = internalSlotsMap.get(this);
128334 slots.baseConfigArray = createBaseConfigArray(slots);
128335 slots.cliConfigArray = createCLIConfigArray(slots);
128336 slots.configCache.clear();
128337 }
128338 /**
128339 * Load and normalize config files from the ancestor directories.
128340 * @param {string} directoryPath The path to a leaf directory.
128341 * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
128342 * @returns {ConfigArray} The loaded config.
128343 * @private
128344 */
128345
128346
128347 _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
128348 const {
128349 baseConfigArray,
128350 configArrayFactory,
128351 configCache,
128352 cwd,
128353 useEslintrc
128354 } = internalSlotsMap.get(this);
128355
128356 if (!useEslintrc) {
128357 return baseConfigArray;
128358 }
128359
128360 let configArray = configCache.get(directoryPath); // Hit cache.
128361
128362 if (configArray) {
128363 debug("Cache hit: ".concat(directoryPath, "."));
128364 return configArray;
128365 }
128366
128367 debug("No cache found: ".concat(directoryPath, "."));
128368 const homePath = os.homedir(); // Consider this is root.
128369
128370 if (directoryPath === homePath && cwd !== homePath) {
128371 debug("Stop traversing because of considered root.");
128372
128373 if (configsExistInSubdirs) {
128374 const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
128375
128376 if (filePath) {
128377 emitDeprecationWarning(filePath, "ESLINT_PERSONAL_CONFIG_SUPPRESS");
128378 }
128379 }
128380
128381 return this._cacheConfig(directoryPath, baseConfigArray);
128382 } // Load the config on this directory.
128383
128384
128385 try {
128386 configArray = configArrayFactory.loadInDirectory(directoryPath);
128387 } catch (error) {
128388 /* istanbul ignore next */
128389 if (error.code === "EACCES") {
128390 debug("Stop traversing because of 'EACCES' error.");
128391 return this._cacheConfig(directoryPath, baseConfigArray);
128392 }
128393
128394 throw error;
128395 }
128396
128397 if (configArray.length > 0 && configArray.isRoot()) {
128398 debug("Stop traversing because of 'root:true'.");
128399 configArray.unshift(...baseConfigArray);
128400 return this._cacheConfig(directoryPath, configArray);
128401 } // Load from the ancestors and merge it.
128402
128403
128404 const parentPath = path.dirname(directoryPath);
128405 const parentConfigArray = parentPath && parentPath !== directoryPath ? this._loadConfigInAncestors(parentPath, configsExistInSubdirs || configArray.length > 0) : baseConfigArray;
128406
128407 if (configArray.length > 0) {
128408 configArray.unshift(...parentConfigArray);
128409 } else {
128410 configArray = parentConfigArray;
128411 } // Cache and return.
128412
128413
128414 return this._cacheConfig(directoryPath, configArray);
128415 }
128416 /**
128417 * Freeze and cache a given config.
128418 * @param {string} directoryPath The path to a directory as a cache key.
128419 * @param {ConfigArray} configArray The config array as a cache value.
128420 * @returns {ConfigArray} The `configArray` (frozen).
128421 */
128422
128423
128424 _cacheConfig(directoryPath, configArray) {
128425 const {
128426 configCache
128427 } = internalSlotsMap.get(this);
128428 Object.freeze(configArray);
128429 configCache.set(directoryPath, configArray);
128430 return configArray;
128431 }
128432 /**
128433 * Finalize a given config array.
128434 * Concatenate `--config` and other CLI options.
128435 * @param {ConfigArray} configArray The parent config array.
128436 * @param {string} directoryPath The path to the leaf directory to find config files.
128437 * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
128438 * @returns {ConfigArray} The loaded config.
128439 * @private
128440 */
128441
128442
128443 _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
128444 const {
128445 cliConfigArray,
128446 configArrayFactory,
128447 finalizeCache,
128448 useEslintrc
128449 } = internalSlotsMap.get(this);
128450 let finalConfigArray = finalizeCache.get(configArray);
128451
128452 if (!finalConfigArray) {
128453 finalConfigArray = configArray; // Load the personal config if there are no regular config files.
128454
128455 if (useEslintrc && configArray.every(c => !c.filePath) && cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
128456 ) {
128457 const homePath = os.homedir();
128458 debug("Loading the config file of the home directory:", homePath);
128459 const personalConfigArray = configArrayFactory.loadInDirectory(homePath, {
128460 name: "PersonalConfig"
128461 });
128462
128463 if (personalConfigArray.length > 0 && !directoryPath.startsWith(homePath)) {
128464 const lastElement = personalConfigArray[personalConfigArray.length - 1];
128465 emitDeprecationWarning(lastElement.filePath, "ESLINT_PERSONAL_CONFIG_LOAD");
128466 }
128467
128468 finalConfigArray = finalConfigArray.concat(personalConfigArray);
128469 } // Apply CLI options.
128470
128471
128472 if (cliConfigArray.length > 0) {
128473 finalConfigArray = finalConfigArray.concat(cliConfigArray);
128474 } // Validate rule settings and environments.
128475
128476
128477 validateConfigArray(finalConfigArray); // Cache it.
128478
128479 Object.freeze(finalConfigArray);
128480 finalizeCache.set(configArray, finalConfigArray);
128481 debug("Configuration was determined: %o on %s", finalConfigArray, directoryPath);
128482 } // At least one element (the default ignore patterns) exists.
128483
128484
128485 if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
128486 throw new ConfigurationNotFoundError(directoryPath);
128487 }
128488
128489 return finalConfigArray;
128490 }
128491
128492} //------------------------------------------------------------------------------
128493// Public Interface
128494//------------------------------------------------------------------------------
128495
128496
128497module.exports = {
128498 CascadingConfigArrayFactory
128499};
128500
128501/***/ }),
6a5a0f88 128502/* 832 */
eb39fafa
DC
128503/***/ (function(module, exports, __webpack_require__) {
128504
128505"use strict";
128506/* WEBPACK VAR INJECTION */(function(__dirname) {/**
128507 * @fileoverview The factory of `ConfigArray` objects.
128508 *
128509 * This class provides methods to create `ConfigArray` instance.
128510 *
128511 * - `create(configData, options)`
128512 * Create a `ConfigArray` instance from a config data. This is to handle CLI
128513 * options except `--config`.
128514 * - `loadFile(filePath, options)`
128515 * Create a `ConfigArray` instance from a config file. This is to handle
128516 * `--config` option. If the file was not found, throws the following error:
128517 * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
128518 * - If the filename was `package.json`, an IO error or an
128519 * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
128520 * - Otherwise, an IO error such as `ENOENT`.
128521 * - `loadInDirectory(directoryPath, options)`
128522 * Create a `ConfigArray` instance from a config file which is on a given
128523 * directory. This tries to load `.eslintrc.*` or `package.json`. If not
128524 * found, returns an empty `ConfigArray`.
128525 * - `loadESLintIgnore(filePath)`
128526 * Create a `ConfigArray` instance from a config file that is `.eslintignore`
128527 * format. This is to handle `--ignore-path` option.
128528 * - `loadDefaultESLintIgnore()`
128529 * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
128530 * the current working directory.
128531 *
128532 * `ConfigArrayFactory` class has the responsibility that loads configuration
128533 * files, including loading `extends`, `parser`, and `plugins`. The created
128534 * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
128535 *
128536 * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
128537 * handles cascading and hierarchy.
128538 *
128539 * @author Toru Nagashima <https://github.com/mysticatea>
128540 */
128541 //------------------------------------------------------------------------------
128542// Requirements
128543//------------------------------------------------------------------------------
128544
128545function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
128546
128547function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
128548
128549function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
128550
128551function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
128552
128553function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
128554
6a5a0f88 128555const fs = __webpack_require__(825);
eb39fafa
DC
128556
128557const path = __webpack_require__(377);
128558
6a5a0f88 128559const importFresh = __webpack_require__(833);
eb39fafa 128560
6a5a0f88 128561const stripComments = __webpack_require__(838);
eb39fafa
DC
128562
128563const {
128564 validateConfigSchema
128565} = __webpack_require__(411);
128566
6a5a0f88 128567const naming = __webpack_require__(827);
eb39fafa 128568
6a5a0f88 128569const ModuleResolver = __webpack_require__(828);
eb39fafa
DC
128570
128571const {
128572 ConfigArray,
128573 ConfigDependency,
128574 IgnorePattern,
128575 OverrideTester
6a5a0f88 128576} = __webpack_require__(839);
eb39fafa
DC
128577
128578const debug = __webpack_require__(416)("eslint:config-array-factory"); //------------------------------------------------------------------------------
128579// Helpers
128580//------------------------------------------------------------------------------
128581
128582
128583const eslintRecommendedPath = path.resolve(__dirname, "../../conf/eslint-recommended.js");
128584const eslintAllPath = path.resolve(__dirname, "../../conf/eslint-all.js");
128585const configFilenames = [".eslintrc.js", ".eslintrc.cjs", ".eslintrc.yaml", ".eslintrc.yml", ".eslintrc.json", ".eslintrc", "package.json"]; // Define types for VSCode IntelliSense.
128586
128587/** @typedef {import("../shared/types").ConfigData} ConfigData */
128588
128589/** @typedef {import("../shared/types").OverrideConfigData} OverrideConfigData */
128590
128591/** @typedef {import("../shared/types").Parser} Parser */
128592
128593/** @typedef {import("../shared/types").Plugin} Plugin */
128594
128595/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
128596
128597/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
128598
128599/** @typedef {ConfigArray[0]} ConfigArrayElement */
128600
128601/**
128602 * @typedef {Object} ConfigArrayFactoryOptions
128603 * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
128604 * @property {string} [cwd] The path to the current working directory.
128605 * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
128606 */
128607
128608/**
128609 * @typedef {Object} ConfigArrayFactoryInternalSlots
128610 * @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
128611 * @property {string} cwd The path to the current working directory.
128612 * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
128613 */
128614
128615/**
128616 * @typedef {Object} ConfigArrayFactoryLoadingContext
128617 * @property {string} filePath The path to the current configuration.
128618 * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
128619 * @property {string} name The name of the current configuration.
128620 * @property {string} pluginBasePath The base path to resolve plugins.
128621 * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
128622 */
128623
128624/**
128625 * @typedef {Object} ConfigArrayFactoryLoadingContext
128626 * @property {string} filePath The path to the current configuration.
128627 * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
128628 * @property {string} name The name of the current configuration.
128629 * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
128630 */
128631
128632/** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
128633
128634const internalSlotsMap = new WeakMap();
128635/**
128636 * Check if a given string is a file path.
128637 * @param {string} nameOrPath A module name or file path.
128638 * @returns {boolean} `true` if the `nameOrPath` is a file path.
128639 */
128640
128641function isFilePath(nameOrPath) {
128642 return /^\.{1,2}[/\\]/u.test(nameOrPath) || path.isAbsolute(nameOrPath);
128643}
128644/**
128645 * Convenience wrapper for synchronously reading file contents.
128646 * @param {string} filePath The filename to read.
128647 * @returns {string} The file contents, with the BOM removed.
128648 * @private
128649 */
128650
128651
128652function readFile(filePath) {
128653 return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
128654}
128655/**
128656 * Loads a YAML configuration from a file.
128657 * @param {string} filePath The filename to load.
128658 * @returns {ConfigData} The configuration object from the file.
128659 * @throws {Error} If the file cannot be read.
128660 * @private
128661 */
128662
128663
128664function loadYAMLConfigFile(filePath) {
128665 debug("Loading YAML config file: ".concat(filePath)); // lazy load YAML to improve performance when not used
128666
6a5a0f88 128667 const yaml = __webpack_require__(849);
eb39fafa
DC
128668
128669 try {
128670 // empty YAML file can be null, so always use
128671 return yaml.safeLoad(readFile(filePath)) || {};
128672 } catch (e) {
128673 debug("Error reading YAML file: ".concat(filePath));
128674 e.message = "Cannot read config file: ".concat(filePath, "\nError: ").concat(e.message);
128675 throw e;
128676 }
128677}
128678/**
128679 * Loads a JSON configuration from a file.
128680 * @param {string} filePath The filename to load.
128681 * @returns {ConfigData} The configuration object from the file.
128682 * @throws {Error} If the file cannot be read.
128683 * @private
128684 */
128685
128686
128687function loadJSONConfigFile(filePath) {
128688 debug("Loading JSON config file: ".concat(filePath));
128689
128690 try {
128691 return JSON.parse(stripComments(readFile(filePath)));
128692 } catch (e) {
128693 debug("Error reading JSON file: ".concat(filePath));
128694 e.message = "Cannot read config file: ".concat(filePath, "\nError: ").concat(e.message);
128695 e.messageTemplate = "failed-to-read-json";
128696 e.messageData = {
128697 path: filePath,
128698 message: e.message
128699 };
128700 throw e;
128701 }
128702}
128703/**
128704 * Loads a legacy (.eslintrc) configuration from a file.
128705 * @param {string} filePath The filename to load.
128706 * @returns {ConfigData} The configuration object from the file.
128707 * @throws {Error} If the file cannot be read.
128708 * @private
128709 */
128710
128711
128712function loadLegacyConfigFile(filePath) {
128713 debug("Loading legacy config file: ".concat(filePath)); // lazy load YAML to improve performance when not used
128714
6a5a0f88 128715 const yaml = __webpack_require__(849);
eb39fafa
DC
128716
128717 try {
128718 return yaml.safeLoad(stripComments(readFile(filePath))) ||
128719 /* istanbul ignore next */
128720 {};
128721 } catch (e) {
128722 debug("Error reading YAML file: %s\n%o", filePath, e);
128723 e.message = "Cannot read config file: ".concat(filePath, "\nError: ").concat(e.message);
128724 throw e;
128725 }
128726}
128727/**
128728 * Loads a JavaScript configuration from a file.
128729 * @param {string} filePath The filename to load.
128730 * @returns {ConfigData} The configuration object from the file.
128731 * @throws {Error} If the file cannot be read.
128732 * @private
128733 */
128734
128735
128736function loadJSConfigFile(filePath) {
128737 debug("Loading JS config file: ".concat(filePath));
128738
128739 try {
128740 return importFresh(filePath);
128741 } catch (e) {
128742 debug("Error reading JavaScript file: ".concat(filePath));
128743 e.message = "Cannot read config file: ".concat(filePath, "\nError: ").concat(e.message);
128744 throw e;
128745 }
128746}
128747/**
128748 * Loads a configuration from a package.json file.
128749 * @param {string} filePath The filename to load.
128750 * @returns {ConfigData} The configuration object from the file.
128751 * @throws {Error} If the file cannot be read.
128752 * @private
128753 */
128754
128755
128756function loadPackageJSONConfigFile(filePath) {
128757 debug("Loading package.json config file: ".concat(filePath));
128758
128759 try {
128760 const packageData = loadJSONConfigFile(filePath);
128761
128762 if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
128763 throw Object.assign(new Error("package.json file doesn't have 'eslintConfig' field."), {
128764 code: "ESLINT_CONFIG_FIELD_NOT_FOUND"
128765 });
128766 }
128767
128768 return packageData.eslintConfig;
128769 } catch (e) {
128770 debug("Error reading package.json file: ".concat(filePath));
128771 e.message = "Cannot read config file: ".concat(filePath, "\nError: ").concat(e.message);
128772 throw e;
128773 }
128774}
128775/**
128776 * Loads a `.eslintignore` from a file.
128777 * @param {string} filePath The filename to load.
128778 * @returns {string[]} The ignore patterns from the file.
128779 * @private
128780 */
128781
128782
128783function loadESLintIgnoreFile(filePath) {
128784 debug("Loading .eslintignore file: ".concat(filePath));
128785
128786 try {
128787 return readFile(filePath).split(/\r?\n/gu).filter(line => line.trim() !== "" && !line.startsWith("#"));
128788 } catch (e) {
128789 debug("Error reading .eslintignore file: ".concat(filePath));
128790 e.message = "Cannot read .eslintignore file: ".concat(filePath, "\nError: ").concat(e.message);
128791 throw e;
128792 }
128793}
128794/**
128795 * Creates an error to notify about a missing config to extend from.
128796 * @param {string} configName The name of the missing config.
128797 * @param {string} importerName The name of the config that imported the missing config
128798 * @returns {Error} The error object to throw
128799 * @private
128800 */
128801
128802
128803function configMissingError(configName, importerName) {
128804 return Object.assign(new Error("Failed to load config \"".concat(configName, "\" to extend from.")), {
128805 messageTemplate: "extend-config-missing",
128806 messageData: {
128807 configName,
128808 importerName
128809 }
128810 });
128811}
128812/**
128813 * Loads a configuration file regardless of the source. Inspects the file path
128814 * to determine the correctly way to load the config file.
128815 * @param {string} filePath The path to the configuration.
128816 * @returns {ConfigData|null} The configuration information.
128817 * @private
128818 */
128819
128820
128821function loadConfigFile(filePath) {
128822 switch (path.extname(filePath)) {
128823 case ".js":
128824 case ".cjs":
128825 return loadJSConfigFile(filePath);
128826
128827 case ".json":
128828 if (path.basename(filePath) === "package.json") {
128829 return loadPackageJSONConfigFile(filePath);
128830 }
128831
128832 return loadJSONConfigFile(filePath);
128833
128834 case ".yaml":
128835 case ".yml":
128836 return loadYAMLConfigFile(filePath);
128837
128838 default:
128839 return loadLegacyConfigFile(filePath);
128840 }
128841}
128842/**
128843 * Write debug log.
128844 * @param {string} request The requested module name.
128845 * @param {string} relativeTo The file path to resolve the request relative to.
128846 * @param {string} filePath The resolved file path.
128847 * @returns {void}
128848 */
128849
128850
128851function writeDebugLogForLoading(request, relativeTo, filePath) {
128852 /* istanbul ignore next */
128853 if (debug.enabled) {
128854 let nameAndVersion = null;
128855
128856 try {
128857 const packageJsonPath = ModuleResolver.resolve("".concat(request, "/package.json"), relativeTo);
128858
128859 const {
128860 version = "unknown"
6a5a0f88 128861 } = __webpack_require__(881)(packageJsonPath);
eb39fafa
DC
128862
128863 nameAndVersion = "".concat(request, "@").concat(version);
128864 } catch (error) {
128865 debug("package.json was not found:", error.message);
128866 nameAndVersion = request;
128867 }
128868
128869 debug("Loaded: %s (%s)", nameAndVersion, filePath);
128870 }
128871}
128872/**
128873 * Create a new context with default values.
128874 * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
128875 * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
128876 * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
128877 * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
128878 * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
128879 * @returns {ConfigArrayFactoryLoadingContext} The created context.
128880 */
128881
128882
128883function createContext({
128884 cwd,
128885 resolvePluginsRelativeTo
128886}, providedType, providedName, providedFilePath, providedMatchBasePath) {
128887 const filePath = providedFilePath ? path.resolve(cwd, providedFilePath) : "";
128888 const matchBasePath = providedMatchBasePath && path.resolve(cwd, providedMatchBasePath) || filePath && path.dirname(filePath) || cwd;
128889 const name = providedName || filePath && path.relative(cwd, filePath) || "";
128890 const pluginBasePath = resolvePluginsRelativeTo || filePath && path.dirname(filePath) || cwd;
128891 const type = providedType || "config";
128892 return {
128893 filePath,
128894 matchBasePath,
128895 name,
128896 pluginBasePath,
128897 type
128898 };
128899}
128900/**
128901 * Normalize a given plugin.
128902 * - Ensure the object to have four properties: configs, environments, processors, and rules.
128903 * - Ensure the object to not have other properties.
128904 * @param {Plugin} plugin The plugin to normalize.
128905 * @returns {Plugin} The normalized plugin.
128906 */
128907
128908
128909function normalizePlugin(plugin) {
128910 return {
128911 configs: plugin.configs || {},
128912 environments: plugin.environments || {},
128913 processors: plugin.processors || {},
128914 rules: plugin.rules || {}
128915 };
128916} //------------------------------------------------------------------------------
128917// Public Interface
128918//------------------------------------------------------------------------------
128919
128920/**
128921 * The factory of `ConfigArray` objects.
128922 */
128923
128924
128925class ConfigArrayFactory {
128926 /**
128927 * Initialize this instance.
128928 * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
128929 */
128930 constructor({
128931 additionalPluginPool = new Map(),
128932 cwd = process.cwd(),
128933 resolvePluginsRelativeTo
128934 } = {}) {
128935 internalSlotsMap.set(this, {
128936 additionalPluginPool,
128937 cwd,
128938 resolvePluginsRelativeTo: resolvePluginsRelativeTo && path.resolve(cwd, resolvePluginsRelativeTo)
128939 });
128940 }
128941 /**
128942 * Create `ConfigArray` instance from a config data.
128943 * @param {ConfigData|null} configData The config data to create.
128944 * @param {Object} [options] The options.
128945 * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
128946 * @param {string} [options.filePath] The path to this config data.
128947 * @param {string} [options.name] The config name.
128948 * @returns {ConfigArray} Loaded config.
128949 */
128950
128951
128952 create(configData, {
128953 basePath,
128954 filePath,
128955 name
128956 } = {}) {
128957 if (!configData) {
128958 return new ConfigArray();
128959 }
128960
128961 const slots = internalSlotsMap.get(this);
128962 const ctx = createContext(slots, "config", name, filePath, basePath);
128963
128964 const elements = this._normalizeConfigData(configData, ctx);
128965
128966 return new ConfigArray(...elements);
128967 }
128968 /**
128969 * Load a config file.
128970 * @param {string} filePath The path to a config file.
128971 * @param {Object} [options] The options.
128972 * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
128973 * @param {string} [options.name] The config name.
128974 * @returns {ConfigArray} Loaded config.
128975 */
128976
128977
128978 loadFile(filePath, {
128979 basePath,
128980 name
128981 } = {}) {
128982 const slots = internalSlotsMap.get(this);
128983 const ctx = createContext(slots, "config", name, filePath, basePath);
128984 return new ConfigArray(...this._loadConfigData(ctx));
128985 }
128986 /**
128987 * Load the config file on a given directory if exists.
128988 * @param {string} directoryPath The path to a directory.
128989 * @param {Object} [options] The options.
128990 * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
128991 * @param {string} [options.name] The config name.
128992 * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
128993 */
128994
128995
128996 loadInDirectory(directoryPath, {
128997 basePath,
128998 name
128999 } = {}) {
129000 const slots = internalSlotsMap.get(this);
129001
129002 for (const filename of configFilenames) {
129003 const ctx = createContext(slots, "config", name, path.join(directoryPath, filename), basePath);
129004
129005 if (fs.existsSync(ctx.filePath)) {
129006 let configData;
129007
129008 try {
129009 configData = loadConfigFile(ctx.filePath);
129010 } catch (error) {
129011 if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
129012 throw error;
129013 }
129014 }
129015
129016 if (configData) {
129017 debug("Config file found: ".concat(ctx.filePath));
129018 return new ConfigArray(...this._normalizeConfigData(configData, ctx));
129019 }
129020 }
129021 }
129022
129023 debug("Config file not found on ".concat(directoryPath));
129024 return new ConfigArray();
129025 }
129026 /**
129027 * Check if a config file on a given directory exists or not.
129028 * @param {string} directoryPath The path to a directory.
129029 * @returns {string | null} The path to the found config file. If not found then null.
129030 */
129031
129032
129033 static getPathToConfigFileInDirectory(directoryPath) {
129034 for (const filename of configFilenames) {
129035 const filePath = path.join(directoryPath, filename);
129036
129037 if (fs.existsSync(filePath)) {
129038 if (filename === "package.json") {
129039 try {
129040 loadPackageJSONConfigFile(filePath);
129041 return filePath;
129042 } catch (error) {
129043 /* ignore */
129044 }
129045 } else {
129046 return filePath;
129047 }
129048 }
129049 }
129050
129051 return null;
129052 }
129053 /**
129054 * Load `.eslintignore` file.
129055 * @param {string} filePath The path to a `.eslintignore` file to load.
129056 * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
129057 */
129058
129059
129060 loadESLintIgnore(filePath) {
129061 const slots = internalSlotsMap.get(this);
129062 const ctx = createContext(slots, "ignore", void 0, filePath, slots.cwd);
129063 const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
129064 return new ConfigArray(...this._normalizeESLintIgnoreData(ignorePatterns, ctx));
129065 }
129066 /**
129067 * Load `.eslintignore` file in the current working directory.
129068 * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
129069 */
129070
129071
129072 loadDefaultESLintIgnore() {
129073 const slots = internalSlotsMap.get(this);
129074 const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
129075 const packageJsonPath = path.resolve(slots.cwd, "package.json");
129076
129077 if (fs.existsSync(eslintIgnorePath)) {
129078 return this.loadESLintIgnore(eslintIgnorePath);
129079 }
129080
129081 if (fs.existsSync(packageJsonPath)) {
129082 const data = loadJSONConfigFile(packageJsonPath);
129083
129084 if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
129085 if (!Array.isArray(data.eslintIgnore)) {
129086 throw new Error("Package.json eslintIgnore property requires an array of paths");
129087 }
129088
129089 const ctx = createContext(slots, "ignore", "eslintIgnore in package.json", packageJsonPath, slots.cwd);
129090 return new ConfigArray(...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx));
129091 }
129092 }
129093
129094 return new ConfigArray();
129095 }
129096 /**
129097 * Load a given config file.
129098 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129099 * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
129100 * @private
129101 */
129102
129103
129104 _loadConfigData(ctx) {
129105 return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
129106 }
129107 /**
129108 * Normalize a given `.eslintignore` data to config array elements.
129109 * @param {string[]} ignorePatterns The patterns to ignore files.
129110 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129111 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129112 * @private
129113 */
129114
129115
129116 *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
129117 const elements = this._normalizeObjectConfigData({
129118 ignorePatterns
129119 }, ctx); // Set `ignorePattern.loose` flag for backward compatibility.
129120
129121
129122 for (const element of elements) {
129123 if (element.ignorePattern) {
129124 element.ignorePattern.loose = true;
129125 }
129126
129127 yield element;
129128 }
129129 }
129130 /**
129131 * Normalize a given config to an array.
129132 * @param {ConfigData} configData The config data to normalize.
129133 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129134 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129135 * @private
129136 */
129137
129138
129139 _normalizeConfigData(configData, ctx) {
129140 validateConfigSchema(configData, ctx.name || ctx.filePath);
129141 return this._normalizeObjectConfigData(configData, ctx);
129142 }
129143 /**
129144 * Normalize a given config to an array.
129145 * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
129146 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129147 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129148 * @private
129149 */
129150
129151
129152 *_normalizeObjectConfigData(configData, ctx) {
129153 const {
129154 files,
129155 excludedFiles
129156 } = configData,
129157 configBody = _objectWithoutProperties(configData, ["files", "excludedFiles"]);
129158
129159 const criteria = OverrideTester.create(files, excludedFiles, ctx.matchBasePath);
129160
129161 const elements = this._normalizeObjectConfigDataBody(configBody, ctx); // Apply the criteria to every element.
129162
129163
129164 for (const element of elements) {
129165 /*
129166 * Merge the criteria.
129167 * This is for the `overrides` entries that came from the
129168 * configurations of `overrides[].extends`.
129169 */
129170 element.criteria = OverrideTester.and(criteria, element.criteria);
129171 /*
129172 * Remove `root` property to ignore `root` settings which came from
129173 * `extends` in `overrides`.
129174 */
129175
129176 if (element.criteria) {
129177 element.root = void 0;
129178 }
129179
129180 yield element;
129181 }
129182 }
129183 /**
129184 * Normalize a given config to an array.
129185 * @param {ConfigData} configData The config data to normalize.
129186 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129187 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129188 * @private
129189 */
129190
129191
129192 *_normalizeObjectConfigDataBody({
129193 env,
129194 extends: extend,
129195 globals,
129196 ignorePatterns,
129197 noInlineConfig,
129198 parser: parserName,
129199 parserOptions,
129200 plugins: pluginList,
129201 processor,
129202 reportUnusedDisableDirectives,
129203 root,
129204 rules,
129205 settings,
129206 overrides: overrideList = []
129207 }, ctx) {
129208 const extendList = Array.isArray(extend) ? extend : [extend];
129209 const ignorePattern = ignorePatterns && new IgnorePattern(Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns], ctx.matchBasePath); // Flatten `extends`.
129210
129211 for (const extendName of extendList.filter(Boolean)) {
129212 yield* this._loadExtends(extendName, ctx);
129213 } // Load parser & plugins.
129214
129215
129216 const parser = parserName && this._loadParser(parserName, ctx);
129217
129218 const plugins = pluginList && this._loadPlugins(pluginList, ctx); // Yield pseudo config data for file extension processors.
129219
129220
129221 if (plugins) {
129222 yield* this._takeFileExtensionProcessors(plugins, ctx);
129223 } // Yield the config data except `extends` and `overrides`.
129224
129225
129226 yield {
129227 // Debug information.
129228 type: ctx.type,
129229 name: ctx.name,
129230 filePath: ctx.filePath,
129231 // Config data.
129232 criteria: null,
129233 env,
129234 globals,
129235 ignorePattern,
129236 noInlineConfig,
129237 parser,
129238 parserOptions,
129239 plugins,
129240 processor,
129241 reportUnusedDisableDirectives,
129242 root,
129243 rules,
129244 settings
129245 }; // Flatten `overries`.
129246
129247 for (let i = 0; i < overrideList.length; ++i) {
56c4a2cb 129248 yield* this._normalizeObjectConfigData(overrideList[i], _objectSpread(_objectSpread({}, ctx), {}, {
eb39fafa
DC
129249 name: "".concat(ctx.name, "#overrides[").concat(i, "]")
129250 }));
129251 }
129252 }
129253 /**
129254 * Load configs of an element in `extends`.
129255 * @param {string} extendName The name of a base config.
129256 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129257 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129258 * @private
129259 */
129260
129261
129262 _loadExtends(extendName, ctx) {
129263 debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
129264
129265 try {
129266 if (extendName.startsWith("eslint:")) {
129267 return this._loadExtendedBuiltInConfig(extendName, ctx);
129268 }
129269
129270 if (extendName.startsWith("plugin:")) {
129271 return this._loadExtendedPluginConfig(extendName, ctx);
129272 }
129273
129274 return this._loadExtendedShareableConfig(extendName, ctx);
129275 } catch (error) {
129276 error.message += "\nReferenced from: ".concat(ctx.filePath || ctx.name);
129277 throw error;
129278 }
129279 }
129280 /**
129281 * Load configs of an element in `extends`.
129282 * @param {string} extendName The name of a base config.
129283 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129284 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129285 * @private
129286 */
129287
129288
129289 _loadExtendedBuiltInConfig(extendName, ctx) {
129290 if (extendName === "eslint:recommended") {
56c4a2cb 129291 return this._loadConfigData(_objectSpread(_objectSpread({}, ctx), {}, {
eb39fafa
DC
129292 filePath: eslintRecommendedPath,
129293 name: "".concat(ctx.name, " \xBB ").concat(extendName)
129294 }));
129295 }
129296
129297 if (extendName === "eslint:all") {
56c4a2cb 129298 return this._loadConfigData(_objectSpread(_objectSpread({}, ctx), {}, {
eb39fafa
DC
129299 filePath: eslintAllPath,
129300 name: "".concat(ctx.name, " \xBB ").concat(extendName)
129301 }));
129302 }
129303
129304 throw configMissingError(extendName, ctx.name);
129305 }
129306 /**
129307 * Load configs of an element in `extends`.
129308 * @param {string} extendName The name of a base config.
129309 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129310 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129311 * @private
129312 */
129313
129314
129315 _loadExtendedPluginConfig(extendName, ctx) {
129316 const slashIndex = extendName.lastIndexOf("/");
129317 const pluginName = extendName.slice("plugin:".length, slashIndex);
129318 const configName = extendName.slice(slashIndex + 1);
129319
129320 if (isFilePath(pluginName)) {
129321 throw new Error("'extends' cannot use a file path for plugins.");
129322 }
129323
129324 const plugin = this._loadPlugin(pluginName, ctx);
129325
129326 const configData = plugin.definition && plugin.definition.configs[configName];
129327
129328 if (configData) {
56c4a2cb
DC
129329 return this._normalizeConfigData(configData, _objectSpread(_objectSpread({}, ctx), {}, {
129330 filePath: plugin.filePath || ctx.filePath,
eb39fafa
DC
129331 name: "".concat(ctx.name, " \xBB plugin:").concat(plugin.id, "/").concat(configName)
129332 }));
129333 }
129334
129335 throw plugin.error || configMissingError(extendName, ctx.filePath);
129336 }
129337 /**
129338 * Load configs of an element in `extends`.
129339 * @param {string} extendName The name of a base config.
129340 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129341 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
129342 * @private
129343 */
129344
129345
129346 _loadExtendedShareableConfig(extendName, ctx) {
129347 const {
129348 cwd
129349 } = internalSlotsMap.get(this);
129350 const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
129351 let request;
129352
129353 if (isFilePath(extendName)) {
129354 request = extendName;
129355 } else if (extendName.startsWith(".")) {
129356 request = "./".concat(extendName); // For backward compatibility. A ton of tests depended on this behavior.
129357 } else {
129358 request = naming.normalizePackageName(extendName, "eslint-config");
129359 }
129360
129361 let filePath;
129362
129363 try {
129364 filePath = ModuleResolver.resolve(request, relativeTo);
129365 } catch (error) {
129366 /* istanbul ignore else */
129367 if (error && error.code === "MODULE_NOT_FOUND") {
129368 throw configMissingError(extendName, ctx.filePath);
129369 }
129370
129371 throw error;
129372 }
129373
129374 writeDebugLogForLoading(request, relativeTo, filePath);
56c4a2cb 129375 return this._loadConfigData(_objectSpread(_objectSpread({}, ctx), {}, {
eb39fafa
DC
129376 filePath,
129377 name: "".concat(ctx.name, " \xBB ").concat(request)
129378 }));
129379 }
129380 /**
129381 * Load given plugins.
129382 * @param {string[]} names The plugin names to load.
129383 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129384 * @returns {Record<string,DependentPlugin>} The loaded parser.
129385 * @private
129386 */
129387
129388
129389 _loadPlugins(names, ctx) {
129390 return names.reduce((map, name) => {
129391 if (isFilePath(name)) {
129392 throw new Error("Plugins array cannot includes file paths.");
129393 }
129394
129395 const plugin = this._loadPlugin(name, ctx);
129396
129397 map[plugin.id] = plugin;
129398 return map;
129399 }, {});
129400 }
129401 /**
129402 * Load a given parser.
129403 * @param {string} nameOrPath The package name or the path to a parser file.
129404 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129405 * @returns {DependentParser} The loaded parser.
129406 */
129407
129408
129409 _loadParser(nameOrPath, ctx) {
129410 debug("Loading parser %j from %s", nameOrPath, ctx.filePath);
129411 const {
129412 cwd
129413 } = internalSlotsMap.get(this);
129414 const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
129415
129416 try {
129417 const filePath = ModuleResolver.resolve(nameOrPath, relativeTo);
129418 writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
129419 return new ConfigDependency({
6a5a0f88 129420 definition: __webpack_require__(881)(filePath),
eb39fafa
DC
129421 filePath,
129422 id: nameOrPath,
129423 importerName: ctx.name,
129424 importerPath: ctx.filePath
129425 });
129426 } catch (error) {
129427 // If the parser name is "espree", load the espree of ESLint.
129428 if (nameOrPath === "espree") {
129429 debug("Fallback espree.");
129430 return new ConfigDependency({
129431 definition: __webpack_require__(394),
129432 filePath: /*require.resolve*/(394),
129433 id: nameOrPath,
129434 importerName: ctx.name,
129435 importerPath: ctx.filePath
129436 });
129437 }
129438
129439 debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
129440 error.message = "Failed to load parser '".concat(nameOrPath, "' declared in '").concat(ctx.name, "': ").concat(error.message);
129441 return new ConfigDependency({
129442 error,
129443 id: nameOrPath,
129444 importerName: ctx.name,
129445 importerPath: ctx.filePath
129446 });
129447 }
129448 }
129449 /**
129450 * Load a given plugin.
129451 * @param {string} name The plugin name to load.
129452 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129453 * @returns {DependentPlugin} The loaded plugin.
129454 * @private
129455 */
129456
129457
129458 _loadPlugin(name, ctx) {
129459 debug("Loading plugin %j from %s", name, ctx.filePath);
129460 const {
129461 additionalPluginPool
129462 } = internalSlotsMap.get(this);
129463 const request = naming.normalizePackageName(name, "eslint-plugin");
129464 const id = naming.getShorthandName(request, "eslint-plugin");
129465 const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js");
129466
129467 if (name.match(/\s+/u)) {
129468 const error = Object.assign(new Error("Whitespace found in plugin name '".concat(name, "'")), {
129469 messageTemplate: "whitespace-found",
129470 messageData: {
129471 pluginName: request
129472 }
129473 });
129474 return new ConfigDependency({
129475 error,
129476 id,
129477 importerName: ctx.name,
129478 importerPath: ctx.filePath
129479 });
129480 } // Check for additional pool.
129481
129482
129483 const plugin = additionalPluginPool.get(request) || additionalPluginPool.get(id);
129484
129485 if (plugin) {
129486 return new ConfigDependency({
129487 definition: normalizePlugin(plugin),
56c4a2cb
DC
129488 filePath: "",
129489 // It's unknown where the plugin came from.
eb39fafa
DC
129490 id,
129491 importerName: ctx.name,
129492 importerPath: ctx.filePath
129493 });
129494 }
129495
129496 let filePath;
129497 let error;
129498
129499 try {
129500 filePath = ModuleResolver.resolve(request, relativeTo);
129501 } catch (resolveError) {
129502 error = resolveError;
129503 /* istanbul ignore else */
129504
129505 if (error && error.code === "MODULE_NOT_FOUND") {
129506 error.messageTemplate = "plugin-missing";
129507 error.messageData = {
129508 pluginName: request,
129509 resolvePluginsRelativeTo: ctx.pluginBasePath,
129510 importerName: ctx.name
129511 };
129512 }
129513 }
129514
129515 if (filePath) {
129516 try {
129517 writeDebugLogForLoading(request, relativeTo, filePath);
129518 const startTime = Date.now();
129519
6a5a0f88 129520 const pluginDefinition = __webpack_require__(881)(filePath);
eb39fafa
DC
129521
129522 debug("Plugin ".concat(filePath, " loaded in: ").concat(Date.now() - startTime, "ms"));
129523 return new ConfigDependency({
129524 definition: normalizePlugin(pluginDefinition),
129525 filePath,
129526 id,
129527 importerName: ctx.name,
129528 importerPath: ctx.filePath
129529 });
129530 } catch (loadError) {
129531 error = loadError;
129532 }
129533 }
129534
129535 debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
129536 error.message = "Failed to load plugin '".concat(name, "' declared in '").concat(ctx.name, "': ").concat(error.message);
129537 return new ConfigDependency({
129538 error,
129539 id,
129540 importerName: ctx.name,
129541 importerPath: ctx.filePath
129542 });
129543 }
129544 /**
129545 * Take file expression processors as config array elements.
129546 * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
129547 * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
129548 * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
129549 * @private
129550 */
129551
129552
129553 *_takeFileExtensionProcessors(plugins, ctx) {
129554 for (const pluginId of Object.keys(plugins)) {
129555 const processors = plugins[pluginId] && plugins[pluginId].definition && plugins[pluginId].definition.processors;
129556
129557 if (!processors) {
129558 continue;
129559 }
129560
129561 for (const processorId of Object.keys(processors)) {
129562 if (processorId.startsWith(".")) {
129563 yield* this._normalizeObjectConfigData({
129564 files: ["*".concat(processorId)],
129565 processor: "".concat(pluginId, "/").concat(processorId)
56c4a2cb 129566 }, _objectSpread(_objectSpread({}, ctx), {}, {
eb39fafa
DC
129567 type: "implicit-processor",
129568 name: "".concat(ctx.name, "#processors[\"").concat(pluginId, "/").concat(processorId, "\"]")
129569 }));
129570 }
129571 }
129572 }
129573 }
129574
129575}
129576
129577module.exports = {
129578 ConfigArrayFactory,
129579 createContext
129580};
129581/* WEBPACK VAR INJECTION */}.call(this, "/"))
129582
129583/***/ }),
6a5a0f88 129584/* 833 */
eb39fafa
DC
129585/***/ (function(module, exports, __webpack_require__) {
129586
129587"use strict";
129588/* WEBPACK VAR INJECTION */(function(__filename) {
129589
129590const path = __webpack_require__(377);
129591
6a5a0f88 129592const resolveFrom = __webpack_require__(834);
eb39fafa 129593
6a5a0f88 129594const parentModule = __webpack_require__(835);
eb39fafa
DC
129595
129596module.exports = moduleId => {
129597 if (typeof moduleId !== 'string') {
129598 throw new TypeError('Expected a string');
129599 }
129600
129601 const parentPath = parentModule(__filename);
129602 const filePath = resolveFrom(path.dirname(parentPath), moduleId);
129603 const oldModule = __webpack_require__.c[filePath]; // Delete itself from module parent
129604
129605 if (oldModule && oldModule.parent) {
129606 let i = oldModule.parent.children.length;
129607
129608 while (i--) {
129609 if (oldModule.parent.children[i].id === filePath) {
129610 oldModule.parent.children.splice(i, 1);
129611 }
129612 }
129613 }
129614
129615 delete __webpack_require__.c[filePath]; // Delete module from cache
129616
129617 const parent = __webpack_require__.c[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
129618
6a5a0f88 129619 return parent === undefined ? __webpack_require__(837)(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
eb39fafa
DC
129620};
129621/* WEBPACK VAR INJECTION */}.call(this, "/index.js"))
129622
129623/***/ }),
6a5a0f88 129624/* 834 */
eb39fafa
DC
129625/***/ (function(module, exports, __webpack_require__) {
129626
129627"use strict";
129628
129629
129630const path = __webpack_require__(377);
129631
6a5a0f88 129632const Module = __webpack_require__(829);
eb39fafa 129633
6a5a0f88 129634const fs = __webpack_require__(825);
eb39fafa
DC
129635
129636const resolveFrom = (fromDir, moduleId, silent) => {
129637 if (typeof fromDir !== 'string') {
129638 throw new TypeError("Expected `fromDir` to be of type `string`, got `".concat(typeof fromDir, "`"));
129639 }
129640
129641 if (typeof moduleId !== 'string') {
129642 throw new TypeError("Expected `moduleId` to be of type `string`, got `".concat(typeof moduleId, "`"));
129643 }
129644
129645 try {
129646 fromDir = fs.realpathSync(fromDir);
129647 } catch (err) {
129648 if (err.code === 'ENOENT') {
129649 fromDir = path.resolve(fromDir);
129650 } else if (silent) {
129651 return null;
129652 } else {
129653 throw err;
129654 }
129655 }
129656
129657 const fromFile = path.join(fromDir, 'noop.js');
129658
129659 const resolveFileName = () => Module._resolveFilename(moduleId, {
129660 id: fromFile,
129661 filename: fromFile,
129662 paths: Module._nodeModulePaths(fromDir)
129663 });
129664
129665 if (silent) {
129666 try {
129667 return resolveFileName();
129668 } catch (err) {
129669 return null;
129670 }
129671 }
129672
129673 return resolveFileName();
129674};
129675
129676module.exports = (fromDir, moduleId) => resolveFrom(fromDir, moduleId);
129677
129678module.exports.silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true);
129679
129680/***/ }),
6a5a0f88 129681/* 835 */
eb39fafa
DC
129682/***/ (function(module, exports, __webpack_require__) {
129683
129684"use strict";
129685
129686
6a5a0f88 129687const callsites = __webpack_require__(836);
eb39fafa
DC
129688
129689module.exports = filepath => {
129690 const stacks = callsites();
129691
129692 if (!filepath) {
129693 return stacks[2].getFileName();
129694 }
129695
129696 let seenVal = false; // Skip the first stack as it's this function
129697
129698 stacks.shift();
129699
129700 for (const stack of stacks) {
129701 const parentFilepath = stack.getFileName();
129702
129703 if (typeof parentFilepath !== 'string') {
129704 continue;
129705 }
129706
129707 if (parentFilepath === filepath) {
129708 seenVal = true;
129709 continue;
129710 } // Skip native modules
129711
129712
129713 if (parentFilepath === 'module.js') {
129714 continue;
129715 }
129716
129717 if (seenVal && parentFilepath !== filepath) {
129718 return parentFilepath;
129719 }
129720 }
129721};
129722
129723/***/ }),
6a5a0f88 129724/* 836 */
eb39fafa
DC
129725/***/ (function(module, exports, __webpack_require__) {
129726
129727"use strict";
129728
129729
129730const callsites = () => {
129731 const _prepareStackTrace = Error.prepareStackTrace;
129732
129733 Error.prepareStackTrace = (_, stack) => stack;
129734
129735 const stack = new Error().stack.slice(1);
129736 Error.prepareStackTrace = _prepareStackTrace;
129737 return stack;
129738};
129739
129740module.exports = callsites; // TODO: Remove this for the next major release
129741
129742module.exports.default = callsites;
129743
129744/***/ }),
6a5a0f88 129745/* 837 */
eb39fafa
DC
129746/***/ (function(module, exports) {
129747
129748function webpackEmptyContext(req) {
129749 var e = new Error("Cannot find module '" + req + "'");
129750 e.code = 'MODULE_NOT_FOUND';
129751 throw e;
129752}
129753webpackEmptyContext.keys = function() { return []; };
129754webpackEmptyContext.resolve = webpackEmptyContext;
129755module.exports = webpackEmptyContext;
6a5a0f88 129756webpackEmptyContext.id = 837;
eb39fafa
DC
129757
129758/***/ }),
6a5a0f88 129759/* 838 */
eb39fafa
DC
129760/***/ (function(module, exports, __webpack_require__) {
129761
129762"use strict";
129763
129764
129765const singleComment = Symbol('singleComment');
129766const multiComment = Symbol('multiComment');
129767
129768const stripWithoutWhitespace = () => '';
129769
129770const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');
129771
129772const isEscaped = (jsonString, quotePosition) => {
129773 let index = quotePosition - 1;
129774 let backslashCount = 0;
129775
129776 while (jsonString[index] === '\\') {
129777 index -= 1;
129778 backslashCount += 1;
129779 }
129780
129781 return Boolean(backslashCount % 2);
129782};
129783
129784module.exports = (jsonString, options = {}) => {
56c4a2cb
DC
129785 if (typeof jsonString !== 'string') {
129786 throw new TypeError("Expected argument `jsonString` to be a `string`, got `".concat(typeof jsonString, "`"));
129787 }
129788
eb39fafa
DC
129789 const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
129790 let insideString = false;
129791 let insideComment = false;
129792 let offset = 0;
129793 let result = '';
129794
129795 for (let i = 0; i < jsonString.length; i++) {
129796 const currentCharacter = jsonString[i];
129797 const nextCharacter = jsonString[i + 1];
129798
129799 if (!insideComment && currentCharacter === '"') {
129800 const escaped = isEscaped(jsonString, i);
129801
129802 if (!escaped) {
129803 insideString = !insideString;
129804 }
129805 }
129806
129807 if (insideString) {
129808 continue;
129809 }
129810
129811 if (!insideComment && currentCharacter + nextCharacter === '//') {
129812 result += jsonString.slice(offset, i);
129813 offset = i;
129814 insideComment = singleComment;
129815 i++;
129816 } else if (insideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
129817 i++;
129818 insideComment = false;
129819 result += strip(jsonString, offset, i);
129820 offset = i;
129821 continue;
129822 } else if (insideComment === singleComment && currentCharacter === '\n') {
129823 insideComment = false;
129824 result += strip(jsonString, offset, i);
129825 offset = i;
129826 } else if (!insideComment && currentCharacter + nextCharacter === '/*') {
129827 result += jsonString.slice(offset, i);
129828 offset = i;
129829 insideComment = multiComment;
129830 i++;
129831 continue;
129832 } else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') {
129833 i++;
129834 insideComment = false;
129835 result += strip(jsonString, offset, i + 1);
129836 offset = i + 1;
129837 continue;
129838 }
129839 }
129840
129841 return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
129842};
129843
129844/***/ }),
6a5a0f88 129845/* 839 */
eb39fafa
DC
129846/***/ (function(module, exports, __webpack_require__) {
129847
129848"use strict";
129849/**
129850 * @fileoverview `ConfigArray` class.
129851 * @author Toru Nagashima <https://github.com/mysticatea>
129852 */
129853
129854
129855const {
129856 ConfigArray,
129857 getUsedExtractedConfigs
6a5a0f88 129858} = __webpack_require__(840);
eb39fafa
DC
129859
129860const {
129861 ConfigDependency
6a5a0f88 129862} = __webpack_require__(843);
eb39fafa
DC
129863
129864const {
129865 ExtractedConfig
6a5a0f88 129866} = __webpack_require__(841);
eb39fafa
DC
129867
129868const {
129869 IgnorePattern
6a5a0f88 129870} = __webpack_require__(842);
eb39fafa
DC
129871
129872const {
129873 OverrideTester
6a5a0f88 129874} = __webpack_require__(844);
eb39fafa
DC
129875
129876module.exports = {
129877 ConfigArray,
129878 ConfigDependency,
129879 ExtractedConfig,
129880 IgnorePattern,
129881 OverrideTester,
129882 getUsedExtractedConfigs
129883};
129884
129885/***/ }),
6a5a0f88 129886/* 840 */
eb39fafa
DC
129887/***/ (function(module, exports, __webpack_require__) {
129888
129889"use strict";
129890/**
129891 * @fileoverview `ConfigArray` class.
129892 *
129893 * `ConfigArray` class expresses the full of a configuration. It has the entry
129894 * config file, base config files that were extended, loaded parsers, and loaded
129895 * plugins.
129896 *
129897 * `ConfigArray` class provides three properties and two methods.
129898 *
129899 * - `pluginEnvironments`
129900 * - `pluginProcessors`
129901 * - `pluginRules`
129902 * The `Map` objects that contain the members of all plugins that this
129903 * config array contains. Those map objects don't have mutation methods.
129904 * Those keys are the member ID such as `pluginId/memberName`.
129905 * - `isRoot()`
129906 * If `true` then this configuration has `root:true` property.
129907 * - `extractConfig(filePath)`
129908 * Extract the final configuration for a given file. This means merging
129909 * every config array element which that `criteria` property matched. The
129910 * `filePath` argument must be an absolute path.
129911 *
129912 * `ConfigArrayFactory` provides the loading logic of config files.
129913 *
129914 * @author Toru Nagashima <https://github.com/mysticatea>
129915 */
129916 //------------------------------------------------------------------------------
129917// Requirements
129918//------------------------------------------------------------------------------
129919
129920const {
129921 ExtractedConfig
6a5a0f88 129922} = __webpack_require__(841);
eb39fafa
DC
129923
129924const {
129925 IgnorePattern
6a5a0f88 129926} = __webpack_require__(842); //------------------------------------------------------------------------------
eb39fafa
DC
129927// Helpers
129928//------------------------------------------------------------------------------
129929// Define types for VSCode IntelliSense.
129930
129931/** @typedef {import("../../shared/types").Environment} Environment */
129932
129933/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
129934
129935/** @typedef {import("../../shared/types").RuleConf} RuleConf */
129936
129937/** @typedef {import("../../shared/types").Rule} Rule */
129938
129939/** @typedef {import("../../shared/types").Plugin} Plugin */
129940
129941/** @typedef {import("../../shared/types").Processor} Processor */
129942
129943/** @typedef {import("./config-dependency").DependentParser} DependentParser */
129944
129945/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
129946
129947/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
129948
129949/**
129950 * @typedef {Object} ConfigArrayElement
129951 * @property {string} name The name of this config element.
129952 * @property {string} filePath The path to the source file of this config element.
129953 * @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
129954 * @property {Record<string, boolean>|undefined} env The environment settings.
129955 * @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
129956 * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
129957 * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
129958 * @property {DependentParser|undefined} parser The parser loader.
129959 * @property {Object|undefined} parserOptions The parser options.
129960 * @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
129961 * @property {string|undefined} processor The processor name to refer plugin's processor.
129962 * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
129963 * @property {boolean|undefined} root The flag to express root.
129964 * @property {Record<string, RuleConf>|undefined} rules The rule settings
129965 * @property {Object|undefined} settings The shared settings.
129966 * @property {"config" | "ignore" | "implicit-processor"} type The element type.
129967 */
129968
129969/**
129970 * @typedef {Object} ConfigArrayInternalSlots
129971 * @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
129972 * @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
129973 * @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
129974 * @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
129975 */
129976
129977/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
129978
129979
129980const internalSlotsMap = new class extends WeakMap {
129981 get(key) {
129982 let value = super.get(key);
129983
129984 if (!value) {
129985 value = {
129986 cache: new Map(),
129987 envMap: null,
129988 processorMap: null,
129989 ruleMap: null
129990 };
129991 super.set(key, value);
129992 }
129993
129994 return value;
129995 }
129996
129997}();
129998/**
129999 * Get the indices which are matched to a given file.
130000 * @param {ConfigArrayElement[]} elements The elements.
130001 * @param {string} filePath The path to a target file.
130002 * @returns {number[]} The indices.
130003 */
130004
130005function getMatchedIndices(elements, filePath) {
130006 const indices = [];
130007
130008 for (let i = elements.length - 1; i >= 0; --i) {
130009 const element = elements[i];
130010
56c4a2cb 130011 if (!element.criteria || filePath && element.criteria.test(filePath)) {
eb39fafa
DC
130012 indices.push(i);
130013 }
130014 }
130015
130016 return indices;
130017}
130018/**
130019 * Check if a value is a non-null object.
130020 * @param {any} x The value to check.
130021 * @returns {boolean} `true` if the value is a non-null object.
130022 */
130023
130024
130025function isNonNullObject(x) {
130026 return typeof x === "object" && x !== null;
130027}
130028/**
130029 * Merge two objects.
130030 *
130031 * Assign every property values of `y` to `x` if `x` doesn't have the property.
130032 * If `x`'s property value is an object, it does recursive.
130033 * @param {Object} target The destination to merge
130034 * @param {Object|undefined} source The source to merge.
130035 * @returns {void}
130036 */
130037
130038
130039function mergeWithoutOverwrite(target, source) {
130040 if (!isNonNullObject(source)) {
130041 return;
130042 }
130043
130044 for (const key of Object.keys(source)) {
130045 if (key === "__proto__") {
130046 continue;
130047 }
130048
130049 if (isNonNullObject(target[key])) {
130050 mergeWithoutOverwrite(target[key], source[key]);
130051 } else if (target[key] === void 0) {
130052 if (isNonNullObject(source[key])) {
130053 target[key] = Array.isArray(source[key]) ? [] : {};
130054 mergeWithoutOverwrite(target[key], source[key]);
130055 } else if (source[key] !== void 0) {
130056 target[key] = source[key];
130057 }
130058 }
130059 }
130060}
130061/**
130062 * The error for plugin conflicts.
130063 */
130064
130065
130066class PluginConflictError extends Error {
130067 /**
130068 * Initialize this error object.
130069 * @param {string} pluginId The plugin ID.
130070 * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
130071 */
130072 constructor(pluginId, plugins) {
130073 super("Plugin \"".concat(pluginId, "\" was conflicted between ").concat(plugins.map(p => "\"".concat(p.importerName, "\"")).join(" and "), "."));
130074 this.messageTemplate = "plugin-conflict";
130075 this.messageData = {
130076 pluginId,
130077 plugins
130078 };
130079 }
130080
130081}
130082/**
130083 * Merge plugins.
130084 * `target`'s definition is prior to `source`'s.
130085 * @param {Record<string, DependentPlugin>} target The destination to merge
130086 * @param {Record<string, DependentPlugin>|undefined} source The source to merge.
130087 * @returns {void}
130088 */
130089
130090
130091function mergePlugins(target, source) {
130092 if (!isNonNullObject(source)) {
130093 return;
130094 }
130095
130096 for (const key of Object.keys(source)) {
130097 if (key === "__proto__") {
130098 continue;
130099 }
130100
130101 const targetValue = target[key];
130102 const sourceValue = source[key]; // Adopt the plugin which was found at first.
130103
130104 if (targetValue === void 0) {
130105 if (sourceValue.error) {
130106 throw sourceValue.error;
130107 }
130108
130109 target[key] = sourceValue;
130110 } else if (sourceValue.filePath !== targetValue.filePath) {
130111 throw new PluginConflictError(key, [{
130112 filePath: targetValue.filePath,
130113 importerName: targetValue.importerName
130114 }, {
130115 filePath: sourceValue.filePath,
130116 importerName: sourceValue.importerName
130117 }]);
130118 }
130119 }
130120}
130121/**
130122 * Merge rule configs.
130123 * `target`'s definition is prior to `source`'s.
130124 * @param {Record<string, Array>} target The destination to merge
130125 * @param {Record<string, RuleConf>|undefined} source The source to merge.
130126 * @returns {void}
130127 */
130128
130129
130130function mergeRuleConfigs(target, source) {
130131 if (!isNonNullObject(source)) {
130132 return;
130133 }
130134
130135 for (const key of Object.keys(source)) {
130136 if (key === "__proto__") {
130137 continue;
130138 }
130139
130140 const targetDef = target[key];
130141 const sourceDef = source[key]; // Adopt the rule config which was found at first.
130142
130143 if (targetDef === void 0) {
130144 if (Array.isArray(sourceDef)) {
130145 target[key] = [...sourceDef];
130146 } else {
130147 target[key] = [sourceDef];
130148 }
130149 /*
130150 * If the first found rule config is severity only and the current rule
130151 * config has options, merge the severity and the options.
130152 */
130153
130154 } else if (targetDef.length === 1 && Array.isArray(sourceDef) && sourceDef.length >= 2) {
130155 targetDef.push(...sourceDef.slice(1));
130156 }
130157 }
130158}
130159/**
130160 * Create the extracted config.
130161 * @param {ConfigArray} instance The config elements.
130162 * @param {number[]} indices The indices to use.
130163 * @returns {ExtractedConfig} The extracted config.
130164 */
130165
130166
130167function createConfig(instance, indices) {
130168 const config = new ExtractedConfig();
130169 const ignorePatterns = []; // Merge elements.
130170
130171 for (const index of indices) {
130172 const element = instance[index]; // Adopt the parser which was found at first.
130173
130174 if (!config.parser && element.parser) {
130175 if (element.parser.error) {
130176 throw element.parser.error;
130177 }
130178
130179 config.parser = element.parser;
130180 } // Adopt the processor which was found at first.
130181
130182
130183 if (!config.processor && element.processor) {
130184 config.processor = element.processor;
130185 } // Adopt the noInlineConfig which was found at first.
130186
130187
130188 if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
130189 config.noInlineConfig = element.noInlineConfig;
130190 config.configNameOfNoInlineConfig = element.name;
130191 } // Adopt the reportUnusedDisableDirectives which was found at first.
130192
130193
130194 if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
130195 config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
130196 } // Collect ignorePatterns
130197
130198
130199 if (element.ignorePattern) {
130200 ignorePatterns.push(element.ignorePattern);
130201 } // Merge others.
130202
130203
130204 mergeWithoutOverwrite(config.env, element.env);
130205 mergeWithoutOverwrite(config.globals, element.globals);
130206 mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
130207 mergeWithoutOverwrite(config.settings, element.settings);
130208 mergePlugins(config.plugins, element.plugins);
130209 mergeRuleConfigs(config.rules, element.rules);
130210 } // Create the predicate function for ignore patterns.
130211
130212
130213 if (ignorePatterns.length > 0) {
130214 config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
130215 }
130216
130217 return config;
130218}
130219/**
130220 * Collect definitions.
130221 * @template T, U
130222 * @param {string} pluginId The plugin ID for prefix.
130223 * @param {Record<string,T>} defs The definitions to collect.
130224 * @param {Map<string, U>} map The map to output.
130225 * @param {function(T): U} [normalize] The normalize function for each value.
130226 * @returns {void}
130227 */
130228
130229
130230function collect(pluginId, defs, map, normalize) {
130231 if (defs) {
130232 const prefix = pluginId && "".concat(pluginId, "/");
130233
130234 for (const [key, value] of Object.entries(defs)) {
130235 map.set("".concat(prefix).concat(key), normalize ? normalize(value) : value);
130236 }
130237 }
130238}
130239/**
130240 * Normalize a rule definition.
130241 * @param {Function|Rule} rule The rule definition to normalize.
130242 * @returns {Rule} The normalized rule definition.
130243 */
130244
130245
130246function normalizePluginRule(rule) {
130247 return typeof rule === "function" ? {
130248 create: rule
130249 } : rule;
130250}
130251/**
130252 * Delete the mutation methods from a given map.
130253 * @param {Map<any, any>} map The map object to delete.
130254 * @returns {void}
130255 */
130256
130257
130258function deleteMutationMethods(map) {
130259 Object.defineProperties(map, {
130260 clear: {
130261 configurable: true,
130262 value: void 0
130263 },
130264 delete: {
130265 configurable: true,
130266 value: void 0
130267 },
130268 set: {
130269 configurable: true,
130270 value: void 0
130271 }
130272 });
130273}
130274/**
130275 * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
130276 * @param {ConfigArrayElement[]} elements The config elements.
130277 * @param {ConfigArrayInternalSlots} slots The internal slots.
130278 * @returns {void}
130279 */
130280
130281
130282function initPluginMemberMaps(elements, slots) {
130283 const processed = new Set();
130284 slots.envMap = new Map();
130285 slots.processorMap = new Map();
130286 slots.ruleMap = new Map();
130287
130288 for (const element of elements) {
130289 if (!element.plugins) {
130290 continue;
130291 }
130292
130293 for (const [pluginId, value] of Object.entries(element.plugins)) {
130294 const plugin = value.definition;
130295
130296 if (!plugin || processed.has(pluginId)) {
130297 continue;
130298 }
130299
130300 processed.add(pluginId);
130301 collect(pluginId, plugin.environments, slots.envMap);
130302 collect(pluginId, plugin.processors, slots.processorMap);
130303 collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
130304 }
130305 }
130306
130307 deleteMutationMethods(slots.envMap);
130308 deleteMutationMethods(slots.processorMap);
130309 deleteMutationMethods(slots.ruleMap);
130310}
130311/**
130312 * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
130313 * @param {ConfigArray} instance The config elements.
130314 * @returns {ConfigArrayInternalSlots} The extracted config.
130315 */
130316
130317
130318function ensurePluginMemberMaps(instance) {
130319 const slots = internalSlotsMap.get(instance);
130320
130321 if (!slots.ruleMap) {
130322 initPluginMemberMaps(instance, slots);
130323 }
130324
130325 return slots;
130326} //------------------------------------------------------------------------------
130327// Public Interface
130328//------------------------------------------------------------------------------
130329
130330/**
130331 * The Config Array.
130332 *
130333 * `ConfigArray` instance contains all settings, parsers, and plugins.
130334 * You need to call `ConfigArray#extractConfig(filePath)` method in order to
130335 * extract, merge and get only the config data which is related to an arbitrary
130336 * file.
130337 * @extends {Array<ConfigArrayElement>}
130338 */
130339
130340
130341class ConfigArray extends Array {
130342 /**
130343 * Get the plugin environments.
130344 * The returned map cannot be mutated.
130345 * @type {ReadonlyMap<string, Environment>} The plugin environments.
130346 */
130347 get pluginEnvironments() {
130348 return ensurePluginMemberMaps(this).envMap;
130349 }
130350 /**
130351 * Get the plugin processors.
130352 * The returned map cannot be mutated.
130353 * @type {ReadonlyMap<string, Processor>} The plugin processors.
130354 */
130355
130356
130357 get pluginProcessors() {
130358 return ensurePluginMemberMaps(this).processorMap;
130359 }
130360 /**
130361 * Get the plugin rules.
130362 * The returned map cannot be mutated.
130363 * @returns {ReadonlyMap<string, Rule>} The plugin rules.
130364 */
130365
130366
130367 get pluginRules() {
130368 return ensurePluginMemberMaps(this).ruleMap;
130369 }
130370 /**
130371 * Check if this config has `root` flag.
130372 * @returns {boolean} `true` if this config array is root.
130373 */
130374
130375
130376 isRoot() {
130377 for (let i = this.length - 1; i >= 0; --i) {
130378 const root = this[i].root;
130379
130380 if (typeof root === "boolean") {
130381 return root;
130382 }
130383 }
130384
130385 return false;
130386 }
130387 /**
130388 * Extract the config data which is related to a given file.
130389 * @param {string} filePath The absolute path to the target file.
130390 * @returns {ExtractedConfig} The extracted config data.
130391 */
130392
130393
130394 extractConfig(filePath) {
130395 const {
130396 cache
130397 } = internalSlotsMap.get(this);
130398 const indices = getMatchedIndices(this, filePath);
130399 const cacheKey = indices.join(",");
130400
130401 if (!cache.has(cacheKey)) {
130402 cache.set(cacheKey, createConfig(this, indices));
130403 }
130404
130405 return cache.get(cacheKey);
130406 }
130407 /**
130408 * Check if a given path is an additional lint target.
130409 * @param {string} filePath The absolute path to the target file.
130410 * @returns {boolean} `true` if the file is an additional lint target.
130411 */
130412
130413
130414 isAdditionalTargetPath(filePath) {
130415 for (const {
130416 criteria,
130417 type
130418 } of this) {
130419 if (type === "config" && criteria && !criteria.endsWithWildcard && criteria.test(filePath)) {
130420 return true;
130421 }
130422 }
130423
130424 return false;
130425 }
130426
130427}
130428
130429const exportObject = {
130430 ConfigArray,
130431
130432 /**
130433 * Get the used extracted configs.
130434 * CLIEngine will use this method to collect used deprecated rules.
130435 * @param {ConfigArray} instance The config array object to get.
130436 * @returns {ExtractedConfig[]} The used extracted configs.
130437 * @private
130438 */
130439 getUsedExtractedConfigs(instance) {
130440 const {
130441 cache
130442 } = internalSlotsMap.get(instance);
130443 return Array.from(cache.values());
130444 }
130445
130446};
130447module.exports = exportObject;
130448
130449/***/ }),
6a5a0f88 130450/* 841 */
eb39fafa
DC
130451/***/ (function(module, exports, __webpack_require__) {
130452
130453"use strict";
130454/**
130455 * @fileoverview `ExtractedConfig` class.
130456 *
130457 * `ExtractedConfig` class expresses a final configuration for a specific file.
130458 *
130459 * It provides one method.
130460 *
130461 * - `toCompatibleObjectAsConfigFileContent()`
130462 * Convert this configuration to the compatible object as the content of
130463 * config files. It converts the loaded parser and plugins to strings.
130464 * `CLIEngine#getConfigForFile(filePath)` method uses this method.
130465 *
130466 * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
130467 *
130468 * @author Toru Nagashima <https://github.com/mysticatea>
130469 */
130470
130471
130472function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
130473
130474function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
130475
130476const {
130477 IgnorePattern
6a5a0f88 130478} = __webpack_require__(842); // For VSCode intellisense
eb39fafa
DC
130479
130480/** @typedef {import("../../shared/types").ConfigData} ConfigData */
130481
130482/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
130483
130484/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
130485
130486/** @typedef {import("./config-dependency").DependentParser} DependentParser */
130487
130488/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
130489
130490/**
130491 * Check if `xs` starts with `ys`.
130492 * @template T
130493 * @param {T[]} xs The array to check.
130494 * @param {T[]} ys The array that may be the first part of `xs`.
130495 * @returns {boolean} `true` if `xs` starts with `ys`.
130496 */
130497
130498
130499function startsWith(xs, ys) {
130500 return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
130501}
130502/**
130503 * The class for extracted config data.
130504 */
130505
130506
130507class ExtractedConfig {
130508 constructor() {
130509 /**
130510 * The config name what `noInlineConfig` setting came from.
130511 * @type {string}
130512 */
130513 this.configNameOfNoInlineConfig = "";
130514 /**
130515 * Environments.
130516 * @type {Record<string, boolean>}
130517 */
130518
130519 this.env = {};
130520 /**
130521 * Global variables.
130522 * @type {Record<string, GlobalConf>}
130523 */
130524
130525 this.globals = {};
130526 /**
130527 * The glob patterns that ignore to lint.
130528 * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
130529 */
130530
130531 this.ignores = void 0;
130532 /**
130533 * The flag that disables directive comments.
130534 * @type {boolean|undefined}
130535 */
130536
130537 this.noInlineConfig = void 0;
130538 /**
130539 * Parser definition.
130540 * @type {DependentParser|null}
130541 */
130542
130543 this.parser = null;
130544 /**
130545 * Options for the parser.
130546 * @type {Object}
130547 */
130548
130549 this.parserOptions = {};
130550 /**
130551 * Plugin definitions.
130552 * @type {Record<string, DependentPlugin>}
130553 */
130554
130555 this.plugins = {};
130556 /**
130557 * Processor ID.
130558 * @type {string|null}
130559 */
130560
130561 this.processor = null;
130562 /**
130563 * The flag that reports unused `eslint-disable` directive comments.
130564 * @type {boolean|undefined}
130565 */
130566
130567 this.reportUnusedDisableDirectives = void 0;
130568 /**
130569 * Rule settings.
130570 * @type {Record<string, [SeverityConf, ...any[]]>}
130571 */
130572
130573 this.rules = {};
130574 /**
130575 * Shared settings.
130576 * @type {Object}
130577 */
130578
130579 this.settings = {};
130580 }
130581 /**
130582 * Convert this config to the compatible object as a config file content.
130583 * @returns {ConfigData} The converted object.
130584 */
130585
130586
130587 toCompatibleObjectAsConfigFileContent() {
130588 const _this = this,
130589 {
130590 /* eslint-disable no-unused-vars */
130591 configNameOfNoInlineConfig: _ignore1,
130592 processor: _ignore2,
130593
130594 /* eslint-enable no-unused-vars */
130595 ignores
130596 } = _this,
130597 config = _objectWithoutProperties(_this, ["configNameOfNoInlineConfig", "processor", "ignores"]);
130598
130599 config.parser = config.parser && config.parser.filePath;
130600 config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
130601 config.ignorePatterns = ignores ? ignores.patterns : []; // Strip the default patterns from `ignorePatterns`.
130602
130603 if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
130604 config.ignorePatterns = config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
130605 }
130606
130607 return config;
130608 }
130609
130610}
130611
130612module.exports = {
130613 ExtractedConfig
130614};
130615
130616/***/ }),
6a5a0f88 130617/* 842 */
eb39fafa
DC
130618/***/ (function(module, exports, __webpack_require__) {
130619
130620"use strict";
130621/**
130622 * @fileoverview `IgnorePattern` class.
130623 *
130624 * `IgnorePattern` class has the set of glob patterns and the base path.
130625 *
130626 * It provides two static methods.
130627 *
130628 * - `IgnorePattern.createDefaultIgnore(cwd)`
130629 * Create the default predicate function.
130630 * - `IgnorePattern.createIgnore(ignorePatterns)`
130631 * Create the predicate function from multiple `IgnorePattern` objects.
130632 *
130633 * It provides two properties and a method.
130634 *
130635 * - `patterns`
130636 * The glob patterns that ignore to lint.
130637 * - `basePath`
130638 * The base path of the glob patterns. If absolute paths existed in the
130639 * glob patterns, those are handled as relative paths to the base path.
130640 * - `getPatternsRelativeTo(basePath)`
130641 * Get `patterns` as modified for a given base path. It modifies the
130642 * absolute paths in the patterns as prepending the difference of two base
130643 * paths.
130644 *
130645 * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
130646 * `ignorePatterns` properties.
130647 *
130648 * @author Toru Nagashima <https://github.com/mysticatea>
130649 */
130650 //------------------------------------------------------------------------------
130651// Requirements
130652//------------------------------------------------------------------------------
130653
130654const assert = __webpack_require__(379);
130655
130656const path = __webpack_require__(377);
130657
6a5a0f88 130658const ignore = __webpack_require__(612);
eb39fafa
DC
130659
130660const debug = __webpack_require__(416)("eslint:ignore-pattern");
130661/** @typedef {ReturnType<import("ignore").default>} Ignore */
130662//------------------------------------------------------------------------------
130663// Helpers
130664//------------------------------------------------------------------------------
130665
130666/**
130667 * Get the path to the common ancestor directory of given paths.
130668 * @param {string[]} sourcePaths The paths to calculate the common ancestor.
130669 * @returns {string} The path to the common ancestor directory.
130670 */
130671
130672
130673function getCommonAncestorPath(sourcePaths) {
130674 let result = sourcePaths[0];
130675
130676 for (let i = 1; i < sourcePaths.length; ++i) {
130677 const a = result;
130678 const b = sourcePaths[i]; // Set the shorter one (it's the common ancestor if one includes the other).
130679
130680 result = a.length < b.length ? a : b; // Set the common ancestor.
130681
130682 for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
130683 if (a[j] !== b[j]) {
130684 result = a.slice(0, lastSepPos);
130685 break;
130686 }
130687
130688 if (a[j] === path.sep) {
130689 lastSepPos = j;
130690 }
130691 }
130692 }
130693
56c4a2cb
DC
130694 let resolvedResult = result || path.sep; // if Windows common ancestor is root of drive must have trailing slash to be absolute.
130695
130696 if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
130697 resolvedResult += path.sep;
130698 }
130699
130700 return resolvedResult;
eb39fafa
DC
130701}
130702/**
130703 * Make relative path.
130704 * @param {string} from The source path to get relative path.
130705 * @param {string} to The destination path to get relative path.
130706 * @returns {string} The relative path.
130707 */
130708
130709
130710function relative(from, to) {
130711 const relPath = path.relative(from, to);
130712
130713 if (path.sep === "/") {
130714 return relPath;
130715 }
130716
130717 return relPath.split(path.sep).join("/");
130718}
130719/**
130720 * Get the trailing slash if existed.
130721 * @param {string} filePath The path to check.
130722 * @returns {string} The trailing slash if existed.
130723 */
130724
130725
130726function dirSuffix(filePath) {
130727 const isDir = filePath.endsWith(path.sep) || process.platform === "win32" && filePath.endsWith("/");
130728 return isDir ? "/" : "";
130729}
130730
130731const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
130732const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]); //------------------------------------------------------------------------------
130733// Public
130734//------------------------------------------------------------------------------
130735
130736class IgnorePattern {
130737 /**
130738 * The default patterns.
130739 * @type {string[]}
130740 */
130741 static get DefaultPatterns() {
130742 return DefaultPatterns;
130743 }
130744 /**
130745 * Create the default predicate function.
130746 * @param {string} cwd The current working directory.
130747 * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
130748 * The preficate function.
130749 * The first argument is an absolute path that is checked.
130750 * The second argument is the flag to not ignore dotfiles.
130751 * If the predicate function returned `true`, it means the path should be ignored.
130752 */
130753
130754
130755 static createDefaultIgnore(cwd) {
130756 return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
130757 }
130758 /**
130759 * Create the predicate function from multiple `IgnorePattern` objects.
130760 * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
130761 * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
130762 * The preficate function.
130763 * The first argument is an absolute path that is checked.
130764 * The second argument is the flag to not ignore dotfiles.
130765 * If the predicate function returned `true`, it means the path should be ignored.
130766 */
130767
130768
130769 static createIgnore(ignorePatterns) {
130770 debug("Create with: %o", ignorePatterns);
130771 const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
130772 const patterns = [].concat(...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath)));
130773 const ig = ignore().add([...DotPatterns, ...patterns]);
130774 const dotIg = ignore().add(patterns);
130775 debug(" processed: %o", {
130776 basePath,
130777 patterns
130778 });
130779 return Object.assign((filePath, dot = false) => {
130780 assert(path.isAbsolute(filePath), "'filePath' should be an absolute path.");
130781 const relPathRaw = relative(basePath, filePath);
130782 const relPath = relPathRaw && relPathRaw + dirSuffix(filePath);
130783 const adoptedIg = dot ? dotIg : ig;
130784 const result = relPath !== "" && adoptedIg.ignores(relPath);
130785 debug("Check", {
130786 filePath,
130787 dot,
130788 relativePath: relPath,
130789 result
130790 });
130791 return result;
130792 }, {
130793 basePath,
130794 patterns
130795 });
130796 }
130797 /**
130798 * Initialize a new `IgnorePattern` instance.
130799 * @param {string[]} patterns The glob patterns that ignore to lint.
130800 * @param {string} basePath The base path of `patterns`.
130801 */
130802
130803
130804 constructor(patterns, basePath) {
130805 assert(path.isAbsolute(basePath), "'basePath' should be an absolute path.");
130806 /**
130807 * The glob patterns that ignore to lint.
130808 * @type {string[]}
130809 */
130810
130811 this.patterns = patterns;
130812 /**
130813 * The base path of `patterns`.
130814 * @type {string}
130815 */
130816
130817 this.basePath = basePath;
130818 /**
130819 * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
130820 *
130821 * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
130822 * It's `false` as-is for `ignorePatterns` property in config files.
130823 * @type {boolean}
130824 */
130825
130826 this.loose = false;
130827 }
130828 /**
130829 * Get `patterns` as modified for a given base path. It modifies the
130830 * absolute paths in the patterns as prepending the difference of two base
130831 * paths.
130832 * @param {string} newBasePath The base path.
130833 * @returns {string[]} Modifired patterns.
130834 */
130835
130836
130837 getPatternsRelativeTo(newBasePath) {
130838 assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
130839 const {
130840 basePath,
130841 loose,
130842 patterns
130843 } = this;
130844
130845 if (newBasePath === basePath) {
130846 return patterns;
130847 }
130848
130849 const prefix = "/".concat(relative(newBasePath, basePath));
130850 return patterns.map(pattern => {
130851 const negative = pattern.startsWith("!");
130852 const head = negative ? "!" : "";
130853 const body = negative ? pattern.slice(1) : pattern;
130854
130855 if (body.startsWith("/") || body.startsWith("../")) {
130856 return "".concat(head).concat(prefix).concat(body);
130857 }
130858
130859 return loose ? pattern : "".concat(head).concat(prefix, "/**/").concat(body);
130860 });
130861 }
130862
130863}
130864
130865module.exports = {
130866 IgnorePattern
130867};
130868
130869/***/ }),
6a5a0f88 130870/* 843 */
eb39fafa
DC
130871/***/ (function(module, exports, __webpack_require__) {
130872
130873"use strict";
130874/**
130875 * @fileoverview `ConfigDependency` class.
130876 *
130877 * `ConfigDependency` class expresses a loaded parser or plugin.
130878 *
130879 * If the parser or plugin was loaded successfully, it has `definition` property
130880 * and `filePath` property. Otherwise, it has `error` property.
130881 *
130882 * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
130883 * omits `definition` property.
130884 *
130885 * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
130886 * or plugins.
130887 *
130888 * @author Toru Nagashima <https://github.com/mysticatea>
130889 */
130890
130891
130892function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
130893
130894function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
130895
130896function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
130897
130898function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
130899
130900function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
130901
130902const util = __webpack_require__(412);
130903/**
130904 * The class is to store parsers or plugins.
130905 * This class hides the loaded object from `JSON.stringify()` and `console.log`.
130906 * @template T
130907 */
130908
130909
130910class ConfigDependency {
130911 /**
130912 * Initialize this instance.
130913 * @param {Object} data The dependency data.
130914 * @param {T} [data.definition] The dependency if the loading succeeded.
130915 * @param {Error} [data.error] The error object if the loading failed.
130916 * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
130917 * @param {string} data.id The ID of this dependency.
130918 * @param {string} data.importerName The name of the config file which loads this dependency.
130919 * @param {string} data.importerPath The path to the config file which loads this dependency.
130920 */
130921 constructor({
130922 definition = null,
130923 error = null,
130924 filePath = null,
130925 id,
130926 importerName,
130927 importerPath
130928 }) {
130929 /**
130930 * The loaded dependency if the loading succeeded.
130931 * @type {T|null}
130932 */
130933 this.definition = definition;
130934 /**
130935 * The error object if the loading failed.
130936 * @type {Error|null}
130937 */
130938
130939 this.error = error;
130940 /**
130941 * The loaded dependency if the loading succeeded.
130942 * @type {string|null}
130943 */
130944
130945 this.filePath = filePath;
130946 /**
130947 * The ID of this dependency.
130948 * @type {string}
130949 */
130950
130951 this.id = id;
130952 /**
130953 * The name of the config file which loads this dependency.
130954 * @type {string}
130955 */
130956
130957 this.importerName = importerName;
130958 /**
130959 * The path to the config file which loads this dependency.
130960 * @type {string}
130961 */
130962
130963 this.importerPath = importerPath;
130964 } // eslint-disable-next-line jsdoc/require-description
130965
130966 /**
130967 * @returns {Object} a JSON compatible object.
130968 */
130969
130970
130971 toJSON() {
130972 const obj = this[util.inspect.custom](); // Display `error.message` (`Error#message` is unenumerable).
130973
130974 if (obj.error instanceof Error) {
56c4a2cb 130975 obj.error = _objectSpread(_objectSpread({}, obj.error), {}, {
eb39fafa
DC
130976 message: obj.error.message
130977 });
130978 }
130979
130980 return obj;
130981 } // eslint-disable-next-line jsdoc/require-description
130982
130983 /**
130984 * @returns {Object} an object to display by `console.log()`.
130985 */
130986
130987
130988 [util.inspect.custom]() {
130989 const _this = this,
130990 {
130991 definition: _ignore
130992 } = _this,
130993 obj = _objectWithoutProperties(_this, ["definition"]);
130994
130995 return obj;
130996 }
130997
130998}
130999/** @typedef {ConfigDependency<import("../../shared/types").Parser>} DependentParser */
131000
131001/** @typedef {ConfigDependency<import("../../shared/types").Plugin>} DependentPlugin */
131002
131003
131004module.exports = {
131005 ConfigDependency
131006};
131007
131008/***/ }),
6a5a0f88 131009/* 844 */
eb39fafa
DC
131010/***/ (function(module, exports, __webpack_require__) {
131011
131012"use strict";
131013/**
131014 * @fileoverview `OverrideTester` class.
131015 *
131016 * `OverrideTester` class handles `files` property and `excludedFiles` property
131017 * of `overrides` config.
131018 *
131019 * It provides one method.
131020 *
131021 * - `test(filePath)`
131022 * Test if a file path matches the pair of `files` property and
131023 * `excludedFiles` property. The `filePath` argument must be an absolute
131024 * path.
131025 *
131026 * `ConfigArrayFactory` creates `OverrideTester` objects when it processes
131027 * `overrides` properties.
131028 *
131029 * @author Toru Nagashima <https://github.com/mysticatea>
131030 */
131031
131032
131033function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
131034
131035function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
131036
131037function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
131038
131039const assert = __webpack_require__(379);
131040
131041const path = __webpack_require__(377);
131042
131043const util = __webpack_require__(412);
131044
131045const {
131046 Minimatch
6a5a0f88 131047} = __webpack_require__(845);
eb39fafa
DC
131048
131049const minimatchOpts = {
131050 dot: true,
131051 matchBase: true
131052};
131053/**
131054 * @typedef {Object} Pattern
131055 * @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
131056 * @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
131057 */
131058
131059/**
131060 * Normalize a given pattern to an array.
131061 * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
131062 * @returns {string[]|null} Normalized patterns.
131063 * @private
131064 */
131065
131066function normalizePatterns(patterns) {
131067 if (Array.isArray(patterns)) {
131068 return patterns.filter(Boolean);
131069 }
131070
131071 if (typeof patterns === "string" && patterns) {
131072 return [patterns];
131073 }
131074
131075 return [];
131076}
131077/**
131078 * Create the matchers of given patterns.
131079 * @param {string[]} patterns The patterns.
131080 * @returns {InstanceType<Minimatch>[] | null} The matchers.
131081 */
131082
131083
131084function toMatcher(patterns) {
131085 if (patterns.length === 0) {
131086 return null;
131087 }
131088
131089 return patterns.map(pattern => {
131090 if (/^\.[/\\]/u.test(pattern)) {
131091 return new Minimatch(pattern.slice(2), // `./*.js` should not match with `subdir/foo.js`
56c4a2cb 131092 _objectSpread(_objectSpread({}, minimatchOpts), {}, {
eb39fafa
DC
131093 matchBase: false
131094 }));
131095 }
131096
131097 return new Minimatch(pattern, minimatchOpts);
131098 });
131099}
131100/**
131101 * Convert a given matcher to string.
131102 * @param {Pattern} matchers The matchers.
131103 * @returns {string} The string expression of the matcher.
131104 */
131105
131106
131107function patternToJson({
131108 includes,
131109 excludes
131110}) {
131111 return {
131112 includes: includes && includes.map(m => m.pattern),
131113 excludes: excludes && excludes.map(m => m.pattern)
131114 };
131115}
131116/**
131117 * The class to test given paths are matched by the patterns.
131118 */
131119
131120
131121class OverrideTester {
131122 /**
131123 * Create a tester with given criteria.
131124 * If there are no criteria, returns `null`.
131125 * @param {string|string[]} files The glob patterns for included files.
131126 * @param {string|string[]} excludedFiles The glob patterns for excluded files.
131127 * @param {string} basePath The path to the base directory to test paths.
131128 * @returns {OverrideTester|null} The created instance or `null`.
131129 */
131130 static create(files, excludedFiles, basePath) {
131131 const includePatterns = normalizePatterns(files);
131132 const excludePatterns = normalizePatterns(excludedFiles);
131133 let endsWithWildcard = false;
131134
131135 if (includePatterns.length === 0) {
131136 return null;
131137 } // Rejects absolute paths or relative paths to parents.
131138
131139
131140 for (const pattern of includePatterns) {
131141 if (path.isAbsolute(pattern) || pattern.includes("..")) {
131142 throw new Error("Invalid override pattern (expected relative path not containing '..'): ".concat(pattern));
131143 }
131144
131145 if (pattern.endsWith("*")) {
131146 endsWithWildcard = true;
131147 }
131148 }
131149
131150 for (const pattern of excludePatterns) {
131151 if (path.isAbsolute(pattern) || pattern.includes("..")) {
131152 throw new Error("Invalid override pattern (expected relative path not containing '..'): ".concat(pattern));
131153 }
131154 }
131155
131156 const includes = toMatcher(includePatterns);
131157 const excludes = toMatcher(excludePatterns);
131158 return new OverrideTester([{
131159 includes,
131160 excludes
131161 }], basePath, endsWithWildcard);
131162 }
131163 /**
131164 * Combine two testers by logical and.
131165 * If either of the testers was `null`, returns the other tester.
131166 * The `basePath` property of the two must be the same value.
131167 * @param {OverrideTester|null} a A tester.
131168 * @param {OverrideTester|null} b Another tester.
131169 * @returns {OverrideTester|null} Combined tester.
131170 */
131171
131172
131173 static and(a, b) {
131174 if (!b) {
131175 return a && new OverrideTester(a.patterns, a.basePath, a.endsWithWildcard);
131176 }
131177
131178 if (!a) {
131179 return new OverrideTester(b.patterns, b.basePath, b.endsWithWildcard);
131180 }
131181
131182 assert.strictEqual(a.basePath, b.basePath);
131183 return new OverrideTester(a.patterns.concat(b.patterns), a.basePath, a.endsWithWildcard || b.endsWithWildcard);
131184 }
131185 /**
131186 * Initialize this instance.
131187 * @param {Pattern[]} patterns The matchers.
131188 * @param {string} basePath The base path.
131189 * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
131190 */
131191
131192
131193 constructor(patterns, basePath, endsWithWildcard = false) {
131194 /** @type {Pattern[]} */
131195 this.patterns = patterns;
131196 /** @type {string} */
131197
131198 this.basePath = basePath;
131199 /** @type {boolean} */
131200
131201 this.endsWithWildcard = endsWithWildcard;
131202 }
131203 /**
131204 * Test if a given path is matched or not.
131205 * @param {string} filePath The absolute path to the target file.
131206 * @returns {boolean} `true` if the path was matched.
131207 */
131208
131209
131210 test(filePath) {
131211 if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {
131212 throw new Error("'filePath' should be an absolute path, but got ".concat(filePath, "."));
131213 }
131214
131215 const relativePath = path.relative(this.basePath, filePath);
131216 return this.patterns.every(({
131217 includes,
131218 excludes
131219 }) => (!includes || includes.some(m => m.match(relativePath))) && (!excludes || !excludes.some(m => m.match(relativePath))));
131220 } // eslint-disable-next-line jsdoc/require-description
131221
131222 /**
131223 * @returns {Object} a JSON compatible object.
131224 */
131225
131226
131227 toJSON() {
131228 if (this.patterns.length === 1) {
56c4a2cb 131229 return _objectSpread(_objectSpread({}, patternToJson(this.patterns[0])), {}, {
eb39fafa
DC
131230 basePath: this.basePath
131231 });
131232 }
131233
131234 return {
131235 AND: this.patterns.map(patternToJson),
131236 basePath: this.basePath
131237 };
131238 } // eslint-disable-next-line jsdoc/require-description
131239
131240 /**
131241 * @returns {Object} an object to display by `console.log()`.
131242 */
131243
131244
131245 [util.inspect.custom]() {
131246 return this.toJSON();
131247 }
131248
131249}
131250
131251module.exports = {
131252 OverrideTester
131253};
131254
131255/***/ }),
6a5a0f88 131256/* 845 */
eb39fafa
DC
131257/***/ (function(module, exports, __webpack_require__) {
131258
131259module.exports = minimatch;
131260minimatch.Minimatch = Minimatch;
131261var path = {
131262 sep: '/'
131263};
131264
131265try {
131266 path = __webpack_require__(377);
131267} catch (er) {}
131268
131269var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
131270
6a5a0f88 131271var expand = __webpack_require__(846);
eb39fafa
DC
131272
131273var plTypes = {
131274 '!': {
131275 open: '(?:(?!(?:',
131276 close: '))[^/]*?)'
131277 },
131278 '?': {
131279 open: '(?:',
131280 close: ')?'
131281 },
131282 '+': {
131283 open: '(?:',
131284 close: ')+'
131285 },
131286 '*': {
131287 open: '(?:',
131288 close: ')*'
131289 },
131290 '@': {
131291 open: '(?:',
131292 close: ')'
131293 }
131294}; // any single thing other than /
131295// don't need to escape / when using new RegExp()
131296
131297var qmark = '[^/]'; // * => any number of characters
131298
131299var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
131300// not (^ or / followed by one or two dots followed by $ or /),
131301// followed by anything, any number of times.
131302
131303var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
131304// followed by anything, any number of times.
131305
131306var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
131307
131308var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
131309
131310function charSet(s) {
131311 return s.split('').reduce(function (set, c) {
131312 set[c] = true;
131313 return set;
131314 }, {});
131315} // normalizes slashes.
131316
131317
131318var slashSplit = /\/+/;
131319minimatch.filter = filter;
131320
131321function filter(pattern, options) {
131322 options = options || {};
131323 return function (p, i, list) {
131324 return minimatch(p, pattern, options);
131325 };
131326}
131327
131328function ext(a, b) {
131329 a = a || {};
131330 b = b || {};
131331 var t = {};
131332 Object.keys(b).forEach(function (k) {
131333 t[k] = b[k];
131334 });
131335 Object.keys(a).forEach(function (k) {
131336 t[k] = a[k];
131337 });
131338 return t;
131339}
131340
131341minimatch.defaults = function (def) {
131342 if (!def || !Object.keys(def).length) return minimatch;
131343 var orig = minimatch;
131344
131345 var m = function minimatch(p, pattern, options) {
131346 return orig.minimatch(p, pattern, ext(def, options));
131347 };
131348
131349 m.Minimatch = function Minimatch(pattern, options) {
131350 return new orig.Minimatch(pattern, ext(def, options));
131351 };
131352
131353 return m;
131354};
131355
131356Minimatch.defaults = function (def) {
131357 if (!def || !Object.keys(def).length) return Minimatch;
131358 return minimatch.defaults(def).Minimatch;
131359};
131360
131361function minimatch(p, pattern, options) {
131362 if (typeof pattern !== 'string') {
131363 throw new TypeError('glob pattern string required');
131364 }
131365
131366 if (!options) options = {}; // shortcut: comments match nothing.
131367
131368 if (!options.nocomment && pattern.charAt(0) === '#') {
131369 return false;
131370 } // "" only matches ""
131371
131372
131373 if (pattern.trim() === '') return p === '';
131374 return new Minimatch(pattern, options).match(p);
131375}
131376
131377function Minimatch(pattern, options) {
131378 if (!(this instanceof Minimatch)) {
131379 return new Minimatch(pattern, options);
131380 }
131381
131382 if (typeof pattern !== 'string') {
131383 throw new TypeError('glob pattern string required');
131384 }
131385
131386 if (!options) options = {};
131387 pattern = pattern.trim(); // windows support: need to use /, not \
131388
131389 if (path.sep !== '/') {
131390 pattern = pattern.split(path.sep).join('/');
131391 }
131392
131393 this.options = options;
131394 this.set = [];
131395 this.pattern = pattern;
131396 this.regexp = null;
131397 this.negate = false;
131398 this.comment = false;
131399 this.empty = false; // make the set of regexps etc.
131400
131401 this.make();
131402}
131403
131404Minimatch.prototype.debug = function () {};
131405
131406Minimatch.prototype.make = make;
131407
131408function make() {
131409 // don't do it more than once.
131410 if (this._made) return;
131411 var pattern = this.pattern;
131412 var options = this.options; // empty patterns and comments match nothing.
131413
131414 if (!options.nocomment && pattern.charAt(0) === '#') {
131415 this.comment = true;
131416 return;
131417 }
131418
131419 if (!pattern) {
131420 this.empty = true;
131421 return;
131422 } // step 1: figure out negation, etc.
131423
131424
131425 this.parseNegate(); // step 2: expand braces
131426
131427 var set = this.globSet = this.braceExpand();
131428 if (options.debug) this.debug = console.error;
131429 this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
131430 // matching patterns.
131431 // These will be regexps, except in the case of "**", which is
131432 // set to the GLOBSTAR object for globstar behavior,
131433 // and will not contain any / characters
131434
131435 set = this.globParts = set.map(function (s) {
131436 return s.split(slashSplit);
131437 });
131438 this.debug(this.pattern, set); // glob --> regexps
131439
131440 set = set.map(function (s, si, set) {
131441 return s.map(this.parse, this);
131442 }, this);
131443 this.debug(this.pattern, set); // filter out everything that didn't compile properly.
131444
131445 set = set.filter(function (s) {
131446 return s.indexOf(false) === -1;
131447 });
131448 this.debug(this.pattern, set);
131449 this.set = set;
131450}
131451
131452Minimatch.prototype.parseNegate = parseNegate;
131453
131454function parseNegate() {
131455 var pattern = this.pattern;
131456 var negate = false;
131457 var options = this.options;
131458 var negateOffset = 0;
131459 if (options.nonegate) return;
131460
131461 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
131462 negate = !negate;
131463 negateOffset++;
131464 }
131465
131466 if (negateOffset) this.pattern = pattern.substr(negateOffset);
131467 this.negate = negate;
131468} // Brace expansion:
131469// a{b,c}d -> abd acd
131470// a{b,}c -> abc ac
131471// a{0..3}d -> a0d a1d a2d a3d
131472// a{b,c{d,e}f}g -> abg acdfg acefg
131473// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
131474//
131475// Invalid sets are not expanded.
131476// a{2..}b -> a{2..}b
131477// a{b}c -> a{b}c
131478
131479
131480minimatch.braceExpand = function (pattern, options) {
131481 return braceExpand(pattern, options);
131482};
131483
131484Minimatch.prototype.braceExpand = braceExpand;
131485
131486function braceExpand(pattern, options) {
131487 if (!options) {
131488 if (this instanceof Minimatch) {
131489 options = this.options;
131490 } else {
131491 options = {};
131492 }
131493 }
131494
131495 pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
131496
131497 if (typeof pattern === 'undefined') {
131498 throw new TypeError('undefined pattern');
131499 }
131500
131501 if (options.nobrace || !pattern.match(/\{.*\}/)) {
131502 // shortcut. no need to expand.
131503 return [pattern];
131504 }
131505
131506 return expand(pattern);
131507} // parse a component of the expanded set.
131508// At this point, no pattern may contain "/" in it
131509// so we're going to return a 2d array, where each entry is the full
131510// pattern, split on '/', and then turned into a regular expression.
131511// A regexp is made at the end which joins each array with an
131512// escaped /, and another full one which joins each regexp with |.
131513//
131514// Following the lead of Bash 4.1, note that "**" only has special meaning
131515// when it is the *only* thing in a path portion. Otherwise, any series
131516// of * is equivalent to a single *. Globstar behavior is enabled by
131517// default, and can be disabled by setting options.noglobstar.
131518
131519
131520Minimatch.prototype.parse = parse;
131521var SUBPARSE = {};
131522
131523function parse(pattern, isSub) {
131524 if (pattern.length > 1024 * 64) {
131525 throw new TypeError('pattern is too long');
131526 }
131527
131528 var options = this.options; // shortcuts
131529
131530 if (!options.noglobstar && pattern === '**') return GLOBSTAR;
131531 if (pattern === '') return '';
131532 var re = '';
131533 var hasMagic = !!options.nocase;
131534 var escaping = false; // ? => one single character
131535
131536 var patternListStack = [];
131537 var negativeLists = [];
131538 var stateChar;
131539 var inClass = false;
131540 var reClassStart = -1;
131541 var classStart = -1; // . and .. never match anything that doesn't start with .,
131542 // even when options.dot is set.
131543
131544 var patternStart = pattern.charAt(0) === '.' ? '' // anything
131545 // not (start or / followed by . or .. followed by / or end)
131546 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
131547 var self = this;
131548
131549 function clearStateChar() {
131550 if (stateChar) {
131551 // we had some state-tracking character
131552 // that wasn't consumed by this pass.
131553 switch (stateChar) {
131554 case '*':
131555 re += star;
131556 hasMagic = true;
131557 break;
131558
131559 case '?':
131560 re += qmark;
131561 hasMagic = true;
131562 break;
131563
131564 default:
131565 re += '\\' + stateChar;
131566 break;
131567 }
131568
131569 self.debug('clearStateChar %j %j', stateChar, re);
131570 stateChar = false;
131571 }
131572 }
131573
131574 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
131575 this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
131576
131577 if (escaping && reSpecials[c]) {
131578 re += '\\' + c;
131579 escaping = false;
131580 continue;
131581 }
131582
131583 switch (c) {
131584 case '/':
131585 // completely not allowed, even escaped.
131586 // Should already be path-split by now.
131587 return false;
131588
131589 case '\\':
131590 clearStateChar();
131591 escaping = true;
131592 continue;
131593 // the various stateChar values
131594 // for the "extglob" stuff.
131595
131596 case '?':
131597 case '*':
131598 case '+':
131599 case '@':
131600 case '!':
131601 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
131602 // the glob [!a] means [^a] in regexp
131603
131604 if (inClass) {
131605 this.debug(' in class');
131606 if (c === '!' && i === classStart + 1) c = '^';
131607 re += c;
131608 continue;
131609 } // if we already have a stateChar, then it means
131610 // that there was something like ** or +? in there.
131611 // Handle the stateChar, then proceed with this one.
131612
131613
131614 self.debug('call clearStateChar %j', stateChar);
131615 clearStateChar();
131616 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
131617 // just clear the statechar *now*, rather than even diving into
131618 // the patternList stuff.
131619
131620 if (options.noext) clearStateChar();
131621 continue;
131622
131623 case '(':
131624 if (inClass) {
131625 re += '(';
131626 continue;
131627 }
131628
131629 if (!stateChar) {
131630 re += '\\(';
131631 continue;
131632 }
131633
131634 patternListStack.push({
131635 type: stateChar,
131636 start: i - 1,
131637 reStart: re.length,
131638 open: plTypes[stateChar].open,
131639 close: plTypes[stateChar].close
131640 }); // negation is (?:(?!js)[^/]*)
131641
131642 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
131643 this.debug('plType %j %j', stateChar, re);
131644 stateChar = false;
131645 continue;
131646
131647 case ')':
131648 if (inClass || !patternListStack.length) {
131649 re += '\\)';
131650 continue;
131651 }
131652
131653 clearStateChar();
131654 hasMagic = true;
131655 var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
131656 // The others are (?:<pattern>)<type>
131657
131658 re += pl.close;
131659
131660 if (pl.type === '!') {
131661 negativeLists.push(pl);
131662 }
131663
131664 pl.reEnd = re.length;
131665 continue;
131666
131667 case '|':
131668 if (inClass || !patternListStack.length || escaping) {
131669 re += '\\|';
131670 escaping = false;
131671 continue;
131672 }
131673
131674 clearStateChar();
131675 re += '|';
131676 continue;
131677 // these are mostly the same in regexp and glob
131678
131679 case '[':
131680 // swallow any state-tracking char before the [
131681 clearStateChar();
131682
131683 if (inClass) {
131684 re += '\\' + c;
131685 continue;
131686 }
131687
131688 inClass = true;
131689 classStart = i;
131690 reClassStart = re.length;
131691 re += c;
131692 continue;
131693
131694 case ']':
131695 // a right bracket shall lose its special
131696 // meaning and represent itself in
131697 // a bracket expression if it occurs
131698 // first in the list. -- POSIX.2 2.8.3.2
131699 if (i === classStart + 1 || !inClass) {
131700 re += '\\' + c;
131701 escaping = false;
131702 continue;
131703 } // handle the case where we left a class open.
131704 // "[z-a]" is valid, equivalent to "\[z-a\]"
131705
131706
131707 if (inClass) {
131708 // split where the last [ was, make sure we don't have
131709 // an invalid re. if so, re-walk the contents of the
131710 // would-be class to re-translate any characters that
131711 // were passed through as-is
131712 // TODO: It would probably be faster to determine this
131713 // without a try/catch and a new RegExp, but it's tricky
131714 // to do safely. For now, this is safe and works.
131715 var cs = pattern.substring(classStart + 1, i);
131716
131717 try {
131718 RegExp('[' + cs + ']');
131719 } catch (er) {
131720 // not a valid class!
131721 var sp = this.parse(cs, SUBPARSE);
131722 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
131723 hasMagic = hasMagic || sp[1];
131724 inClass = false;
131725 continue;
131726 }
131727 } // finish up the class.
131728
131729
131730 hasMagic = true;
131731 inClass = false;
131732 re += c;
131733 continue;
131734
131735 default:
131736 // swallow any state char that wasn't consumed
131737 clearStateChar();
131738
131739 if (escaping) {
131740 // no need
131741 escaping = false;
131742 } else if (reSpecials[c] && !(c === '^' && inClass)) {
131743 re += '\\';
131744 }
131745
131746 re += c;
131747 } // switch
131748
131749 } // for
131750 // handle the case where we left a class open.
131751 // "[abc" is valid, equivalent to "\[abc"
131752
131753
131754 if (inClass) {
131755 // split where the last [ was, and escape it
131756 // this is a huge pita. We now have to re-walk
131757 // the contents of the would-be class to re-translate
131758 // any characters that were passed through as-is
131759 cs = pattern.substr(classStart + 1);
131760 sp = this.parse(cs, SUBPARSE);
131761 re = re.substr(0, reClassStart) + '\\[' + sp[0];
131762 hasMagic = hasMagic || sp[1];
131763 } // handle the case where we had a +( thing at the *end*
131764 // of the pattern.
131765 // each pattern list stack adds 3 chars, and we need to go through
131766 // and escape any | chars that were passed through as-is for the regexp.
131767 // Go through and escape them, taking care not to double-escape any
131768 // | chars that were already escaped.
131769
131770
131771 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
131772 var tail = re.slice(pl.reStart + pl.open.length);
131773 this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
131774
131775 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
131776 if (!$2) {
131777 // the | isn't already escaped, so escape it.
131778 $2 = '\\';
131779 } // need to escape all those slashes *again*, without escaping the
131780 // one that we need for escaping the | character. As it works out,
131781 // escaping an even number of slashes can be done by simply repeating
131782 // it exactly after itself. That's why this trick works.
131783 //
131784 // I am sorry that you have to see this.
131785
131786
131787 return $1 + $1 + $2 + '|';
131788 });
131789 this.debug('tail=%j\n %s', tail, tail, pl, re);
131790 var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
131791 hasMagic = true;
131792 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
131793 } // handle trailing things that only matter at the very end.
131794
131795
131796 clearStateChar();
131797
131798 if (escaping) {
131799 // trailing \\
131800 re += '\\\\';
131801 } // only need to apply the nodot start if the re starts with
131802 // something that could conceivably capture a dot
131803
131804
131805 var addPatternStart = false;
131806
131807 switch (re.charAt(0)) {
131808 case '.':
131809 case '[':
131810 case '(':
131811 addPatternStart = true;
131812 } // Hack to work around lack of negative lookbehind in JS
131813 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
131814 // like 'a.xyz.yz' doesn't match. So, the first negative
131815 // lookahead, has to look ALL the way ahead, to the end of
131816 // the pattern.
131817
131818
131819 for (var n = negativeLists.length - 1; n > -1; n--) {
131820 var nl = negativeLists[n];
131821 var nlBefore = re.slice(0, nl.reStart);
131822 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
131823 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
131824 var nlAfter = re.slice(nl.reEnd);
131825 nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
131826 // mean that we should *not* include the ) in the bit that is considered
131827 // "after" the negated section.
131828
131829 var openParensBefore = nlBefore.split('(').length - 1;
131830 var cleanAfter = nlAfter;
131831
131832 for (i = 0; i < openParensBefore; i++) {
131833 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
131834 }
131835
131836 nlAfter = cleanAfter;
131837 var dollar = '';
131838
131839 if (nlAfter === '' && isSub !== SUBPARSE) {
131840 dollar = '$';
131841 }
131842
131843 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
131844 re = newRe;
131845 } // if the re is not "" at this point, then we need to make sure
131846 // it doesn't match against an empty path part.
131847 // Otherwise a/* will match a/, which it should not.
131848
131849
131850 if (re !== '' && hasMagic) {
131851 re = '(?=.)' + re;
131852 }
131853
131854 if (addPatternStart) {
131855 re = patternStart + re;
131856 } // parsing just a piece of a larger pattern.
131857
131858
131859 if (isSub === SUBPARSE) {
131860 return [re, hasMagic];
131861 } // skip the regexp for non-magical patterns
131862 // unescape anything in it, though, so that it'll be
131863 // an exact match against a file etc.
131864
131865
131866 if (!hasMagic) {
131867 return globUnescape(pattern);
131868 }
131869
131870 var flags = options.nocase ? 'i' : '';
131871
131872 try {
131873 var regExp = new RegExp('^' + re + '$', flags);
131874 } catch (er) {
131875 // If it was an invalid regular expression, then it can't match
131876 // anything. This trick looks for a character after the end of
131877 // the string, which is of course impossible, except in multi-line
131878 // mode, but it's not a /m regex.
131879 return new RegExp('$.');
131880 }
131881
131882 regExp._glob = pattern;
131883 regExp._src = re;
131884 return regExp;
131885}
131886
131887minimatch.makeRe = function (pattern, options) {
131888 return new Minimatch(pattern, options || {}).makeRe();
131889};
131890
131891Minimatch.prototype.makeRe = makeRe;
131892
131893function makeRe() {
131894 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
131895 // pattern strings, or "**".
131896 //
131897 // It's better to use .match(). This function shouldn't
131898 // be used, really, but it's pretty convenient sometimes,
131899 // when you just want to work with a regex.
131900
131901 var set = this.set;
131902
131903 if (!set.length) {
131904 this.regexp = false;
131905 return this.regexp;
131906 }
131907
131908 var options = this.options;
131909 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
131910 var flags = options.nocase ? 'i' : '';
131911 var re = set.map(function (pattern) {
131912 return pattern.map(function (p) {
131913 return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
131914 }).join('\\\/');
131915 }).join('|'); // must match entire pattern
131916 // ending in a * or ** will make it less strict.
131917
131918 re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
131919
131920 if (this.negate) re = '^(?!' + re + ').*$';
131921
131922 try {
131923 this.regexp = new RegExp(re, flags);
131924 } catch (ex) {
131925 this.regexp = false;
131926 }
131927
131928 return this.regexp;
131929}
131930
131931minimatch.match = function (list, pattern, options) {
131932 options = options || {};
131933 var mm = new Minimatch(pattern, options);
131934 list = list.filter(function (f) {
131935 return mm.match(f);
131936 });
131937
131938 if (mm.options.nonull && !list.length) {
131939 list.push(pattern);
131940 }
131941
131942 return list;
131943};
131944
131945Minimatch.prototype.match = match;
131946
131947function match(f, partial) {
131948 this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
131949 // comments, etc.
131950
131951 if (this.comment) return false;
131952 if (this.empty) return f === '';
131953 if (f === '/' && partial) return true;
131954 var options = this.options; // windows: need to use /, not \
131955
131956 if (path.sep !== '/') {
131957 f = f.split(path.sep).join('/');
131958 } // treat the test path as a set of pathparts.
131959
131960
131961 f = f.split(slashSplit);
131962 this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
131963 // in order for it to be valid. If negating, then just one
131964 // match means that we have failed.
131965 // Either way, return on the first hit.
131966
131967 var set = this.set;
131968 this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
131969
131970 var filename;
131971 var i;
131972
131973 for (i = f.length - 1; i >= 0; i--) {
131974 filename = f[i];
131975 if (filename) break;
131976 }
131977
131978 for (i = 0; i < set.length; i++) {
131979 var pattern = set[i];
131980 var file = f;
131981
131982 if (options.matchBase && pattern.length === 1) {
131983 file = [filename];
131984 }
131985
131986 var hit = this.matchOne(file, pattern, partial);
131987
131988 if (hit) {
131989 if (options.flipNegate) return true;
131990 return !this.negate;
131991 }
131992 } // didn't get any hits. this is success if it's a negative
131993 // pattern, failure otherwise.
131994
131995
131996 if (options.flipNegate) return false;
131997 return this.negate;
131998} // set partial to true to test if, for example,
131999// "/a/b" matches the start of "/*/b/*/d"
132000// Partial means, if you run out of file before you run
132001// out of pattern, then that's fine, as long as all
132002// the parts match.
132003
132004
132005Minimatch.prototype.matchOne = function (file, pattern, partial) {
132006 var options = this.options;
132007 this.debug('matchOne', {
132008 'this': this,
132009 file: file,
132010 pattern: pattern
132011 });
132012 this.debug('matchOne', file.length, pattern.length);
132013
132014 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
132015 this.debug('matchOne loop');
132016 var p = pattern[pi];
132017 var f = file[fi];
132018 this.debug(pattern, p, f); // should be impossible.
132019 // some invalid regexp stuff in the set.
132020
132021 if (p === false) return false;
132022
132023 if (p === GLOBSTAR) {
132024 this.debug('GLOBSTAR', [pattern, p, f]); // "**"
132025 // a/**/b/**/c would match the following:
132026 // a/b/x/y/z/c
132027 // a/x/y/z/b/c
132028 // a/b/x/b/x/c
132029 // a/b/c
132030 // To do this, take the rest of the pattern after
132031 // the **, and see if it would match the file remainder.
132032 // If so, return success.
132033 // If not, the ** "swallows" a segment, and try again.
132034 // This is recursively awful.
132035 //
132036 // a/**/b/**/c matching a/b/x/y/z/c
132037 // - a matches a
132038 // - doublestar
132039 // - matchOne(b/x/y/z/c, b/**/c)
132040 // - b matches b
132041 // - doublestar
132042 // - matchOne(x/y/z/c, c) -> no
132043 // - matchOne(y/z/c, c) -> no
132044 // - matchOne(z/c, c) -> no
132045 // - matchOne(c, c) yes, hit
132046
132047 var fr = fi;
132048 var pr = pi + 1;
132049
132050 if (pr === pl) {
132051 this.debug('** at the end'); // a ** at the end will just swallow the rest.
132052 // We have found a match.
132053 // however, it will not swallow /.x, unless
132054 // options.dot is set.
132055 // . and .. are *never* matched by **, for explosively
132056 // exponential reasons.
132057
132058 for (; fi < fl; fi++) {
132059 if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
132060 }
132061
132062 return true;
132063 } // ok, let's see if we can swallow whatever we can.
132064
132065
132066 while (fr < fl) {
132067 var swallowee = file[fr];
132068 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
132069
132070 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
132071 this.debug('globstar found match!', fr, fl, swallowee); // found a match.
132072
132073 return true;
132074 } else {
132075 // can't swallow "." or ".." ever.
132076 // can only swallow ".foo" when explicitly asked.
132077 if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
132078 this.debug('dot detected!', file, fr, pattern, pr);
132079 break;
132080 } // ** swallows a segment, and continue.
132081
132082
132083 this.debug('globstar swallow a segment, and continue');
132084 fr++;
132085 }
132086 } // no match was found.
132087 // However, in partial mode, we can't say this is necessarily over.
132088 // If there's more *pattern* left, then
132089
132090
132091 if (partial) {
132092 // ran out of file
132093 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
132094 if (fr === fl) return true;
132095 }
132096
132097 return false;
132098 } // something other than **
132099 // non-magic patterns just have to match exactly
132100 // patterns with magic have been turned into regexps.
132101
132102
132103 var hit;
132104
132105 if (typeof p === 'string') {
132106 if (options.nocase) {
132107 hit = f.toLowerCase() === p.toLowerCase();
132108 } else {
132109 hit = f === p;
132110 }
132111
132112 this.debug('string match', p, f, hit);
132113 } else {
132114 hit = f.match(p);
132115 this.debug('pattern match', p, f, hit);
132116 }
132117
132118 if (!hit) return false;
132119 } // Note: ending in / means that we'll get a final ""
132120 // at the end of the pattern. This can only match a
132121 // corresponding "" at the end of the file.
132122 // If the file ends in /, then it can only match a
132123 // a pattern that ends in /, unless the pattern just
132124 // doesn't have any more for it. But, a/b/ should *not*
132125 // match "a/b/*", even though "" matches against the
132126 // [^/]*? pattern, except in partial mode, where it might
132127 // simply not be reached yet.
132128 // However, a/b/ should still satisfy a/*
132129 // now either we fell off the end of the pattern, or we're done.
132130
132131
132132 if (fi === fl && pi === pl) {
132133 // ran out of pattern and filename at the same time.
132134 // an exact hit!
132135 return true;
132136 } else if (fi === fl) {
132137 // ran out of file, but still had pattern left.
132138 // this is ok if we're doing the match as part of
132139 // a glob fs traversal.
132140 return partial;
132141 } else if (pi === pl) {
132142 // ran out of pattern, still have file left.
132143 // this is only acceptable if we're on the very last
132144 // empty segment of a file with a trailing slash.
132145 // a/* should match a/b/
132146 var emptyFileEnd = fi === fl - 1 && file[fi] === '';
132147 return emptyFileEnd;
132148 } // should be unreachable.
132149
132150
132151 throw new Error('wtf?');
132152}; // replace stuff like \* with *
132153
132154
132155function globUnescape(s) {
132156 return s.replace(/\\(.)/g, '$1');
132157}
132158
132159function regExpEscape(s) {
132160 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
132161}
132162
132163/***/ }),
6a5a0f88 132164/* 846 */
eb39fafa
DC
132165/***/ (function(module, exports, __webpack_require__) {
132166
6a5a0f88 132167var concatMap = __webpack_require__(847);
eb39fafa 132168
6a5a0f88 132169var balanced = __webpack_require__(848);
eb39fafa
DC
132170
132171module.exports = expandTop;
132172var escSlash = '\0SLASH' + Math.random() + '\0';
132173var escOpen = '\0OPEN' + Math.random() + '\0';
132174var escClose = '\0CLOSE' + Math.random() + '\0';
132175var escComma = '\0COMMA' + Math.random() + '\0';
132176var escPeriod = '\0PERIOD' + Math.random() + '\0';
132177
132178function numeric(str) {
132179 return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
132180}
132181
132182function escapeBraces(str) {
132183 return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
132184}
132185
132186function unescapeBraces(str) {
132187 return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
132188} // Basically just str.split(","), but handling cases
132189// where we have nested braced sections, which should be
132190// treated as individual members, like {a,{b,c},d}
132191
132192
132193function parseCommaParts(str) {
132194 if (!str) return [''];
132195 var parts = [];
132196 var m = balanced('{', '}', str);
132197 if (!m) return str.split(',');
132198 var pre = m.pre;
132199 var body = m.body;
132200 var post = m.post;
132201 var p = pre.split(',');
132202 p[p.length - 1] += '{' + body + '}';
132203 var postParts = parseCommaParts(post);
132204
132205 if (post.length) {
132206 p[p.length - 1] += postParts.shift();
132207 p.push.apply(p, postParts);
132208 }
132209
132210 parts.push.apply(parts, p);
132211 return parts;
132212}
132213
132214function expandTop(str) {
132215 if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
132216 // Anything starting with {} will have the first two bytes preserved
132217 // but *only* at the top level, so {},a}b will not expand to anything,
132218 // but a{},b}c will be expanded to [a}c,abc].
132219 // One could argue that this is a bug in Bash, but since the goal of
132220 // this module is to match Bash's rules, we escape a leading {}
132221
132222 if (str.substr(0, 2) === '{}') {
132223 str = '\\{\\}' + str.substr(2);
132224 }
132225
132226 return expand(escapeBraces(str), true).map(unescapeBraces);
132227}
132228
132229function identity(e) {
132230 return e;
132231}
132232
132233function embrace(str) {
132234 return '{' + str + '}';
132235}
132236
132237function isPadded(el) {
132238 return /^-?0\d/.test(el);
132239}
132240
132241function lte(i, y) {
132242 return i <= y;
132243}
132244
132245function gte(i, y) {
132246 return i >= y;
132247}
132248
132249function expand(str, isTop) {
132250 var expansions = [];
132251 var m = balanced('{', '}', str);
132252 if (!m || /\$$/.test(m.pre)) return [str];
132253 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
132254 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
132255 var isSequence = isNumericSequence || isAlphaSequence;
132256 var isOptions = m.body.indexOf(',') >= 0;
132257
132258 if (!isSequence && !isOptions) {
132259 // {a},b}
132260 if (m.post.match(/,.*\}/)) {
132261 str = m.pre + '{' + m.body + escClose + m.post;
132262 return expand(str);
132263 }
132264
132265 return [str];
132266 }
132267
132268 var n;
132269
132270 if (isSequence) {
132271 n = m.body.split(/\.\./);
132272 } else {
132273 n = parseCommaParts(m.body);
132274
132275 if (n.length === 1) {
132276 // x{{a,b}}y ==> x{a}y x{b}y
132277 n = expand(n[0], false).map(embrace);
132278
132279 if (n.length === 1) {
132280 var post = m.post.length ? expand(m.post, false) : [''];
132281 return post.map(function (p) {
132282 return m.pre + n[0] + p;
132283 });
132284 }
132285 }
132286 } // at this point, n is the parts, and we know it's not a comma set
132287 // with a single entry.
132288 // no need to expand pre, since it is guaranteed to be free of brace-sets
132289
132290
132291 var pre = m.pre;
132292 var post = m.post.length ? expand(m.post, false) : [''];
132293 var N;
132294
132295 if (isSequence) {
132296 var x = numeric(n[0]);
132297 var y = numeric(n[1]);
132298 var width = Math.max(n[0].length, n[1].length);
132299 var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
132300 var test = lte;
132301 var reverse = y < x;
132302
132303 if (reverse) {
132304 incr *= -1;
132305 test = gte;
132306 }
132307
132308 var pad = n.some(isPadded);
132309 N = [];
132310
132311 for (var i = x; test(i, y); i += incr) {
132312 var c;
132313
132314 if (isAlphaSequence) {
132315 c = String.fromCharCode(i);
132316 if (c === '\\') c = '';
132317 } else {
132318 c = String(i);
132319
132320 if (pad) {
132321 var need = width - c.length;
132322
132323 if (need > 0) {
132324 var z = new Array(need + 1).join('0');
132325 if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
132326 }
132327 }
132328 }
132329
132330 N.push(c);
132331 }
132332 } else {
132333 N = concatMap(n, function (el) {
132334 return expand(el, false);
132335 });
132336 }
132337
132338 for (var j = 0; j < N.length; j++) {
132339 for (var k = 0; k < post.length; k++) {
132340 var expansion = pre + N[j] + post[k];
132341 if (!isTop || isSequence || expansion) expansions.push(expansion);
132342 }
132343 }
132344
132345 return expansions;
132346}
132347
132348/***/ }),
6a5a0f88 132349/* 847 */
eb39fafa
DC
132350/***/ (function(module, exports) {
132351
132352module.exports = function (xs, fn) {
132353 var res = [];
132354
132355 for (var i = 0; i < xs.length; i++) {
132356 var x = fn(xs[i], i);
132357 if (isArray(x)) res.push.apply(res, x);else res.push(x);
132358 }
132359
132360 return res;
132361};
132362
132363var isArray = Array.isArray || function (xs) {
132364 return Object.prototype.toString.call(xs) === '[object Array]';
132365};
132366
132367/***/ }),
6a5a0f88 132368/* 848 */
eb39fafa
DC
132369/***/ (function(module, exports, __webpack_require__) {
132370
132371"use strict";
132372
132373
132374module.exports = balanced;
132375
132376function balanced(a, b, str) {
132377 if (a instanceof RegExp) a = maybeMatch(a, str);
132378 if (b instanceof RegExp) b = maybeMatch(b, str);
132379 var r = range(a, b, str);
132380 return r && {
132381 start: r[0],
132382 end: r[1],
132383 pre: str.slice(0, r[0]),
132384 body: str.slice(r[0] + a.length, r[1]),
132385 post: str.slice(r[1] + b.length)
132386 };
132387}
132388
132389function maybeMatch(reg, str) {
132390 var m = str.match(reg);
132391 return m ? m[0] : null;
132392}
132393
132394balanced.range = range;
132395
132396function range(a, b, str) {
132397 var begs, beg, left, right, result;
132398 var ai = str.indexOf(a);
132399 var bi = str.indexOf(b, ai + 1);
132400 var i = ai;
132401
132402 if (ai >= 0 && bi > 0) {
132403 begs = [];
132404 left = str.length;
132405
132406 while (i >= 0 && !result) {
132407 if (i == ai) {
132408 begs.push(i);
132409 ai = str.indexOf(a, i + 1);
132410 } else if (begs.length == 1) {
132411 result = [begs.pop(), bi];
132412 } else {
132413 beg = begs.pop();
132414
132415 if (beg < left) {
132416 left = beg;
132417 right = bi;
132418 }
132419
132420 bi = str.indexOf(b, i + 1);
132421 }
132422
132423 i = ai < bi && ai >= 0 ? ai : bi;
132424 }
132425
132426 if (begs.length) {
132427 result = [left, right];
132428 }
132429 }
132430
132431 return result;
132432}
132433
132434/***/ }),
6a5a0f88 132435/* 849 */
eb39fafa
DC
132436/***/ (function(module, exports, __webpack_require__) {
132437
132438"use strict";
132439
132440
6a5a0f88 132441var yaml = __webpack_require__(850);
eb39fafa
DC
132442
132443module.exports = yaml;
132444
132445/***/ }),
6a5a0f88 132446/* 850 */
eb39fafa
DC
132447/***/ (function(module, exports, __webpack_require__) {
132448
132449"use strict";
132450
132451
6a5a0f88 132452var loader = __webpack_require__(851);
eb39fafa 132453
6a5a0f88 132454var dumper = __webpack_require__(880);
eb39fafa
DC
132455
132456function deprecated(name) {
132457 return function () {
132458 throw new Error('Function ' + name + ' is deprecated and cannot be used.');
132459 };
132460}
132461
6a5a0f88
TL
132462module.exports.Type = __webpack_require__(857);
132463module.exports.Schema = __webpack_require__(856);
132464module.exports.FAILSAFE_SCHEMA = __webpack_require__(860);
132465module.exports.JSON_SCHEMA = __webpack_require__(859);
132466module.exports.CORE_SCHEMA = __webpack_require__(858);
132467module.exports.DEFAULT_SAFE_SCHEMA = __webpack_require__(855);
132468module.exports.DEFAULT_FULL_SCHEMA = __webpack_require__(875);
eb39fafa
DC
132469module.exports.load = loader.load;
132470module.exports.loadAll = loader.loadAll;
132471module.exports.safeLoad = loader.safeLoad;
132472module.exports.safeLoadAll = loader.safeLoadAll;
132473module.exports.dump = dumper.dump;
132474module.exports.safeDump = dumper.safeDump;
6a5a0f88 132475module.exports.YAMLException = __webpack_require__(853); // Deprecated schema names from JS-YAML 2.0.x
eb39fafa 132476
6a5a0f88
TL
132477module.exports.MINIMAL_SCHEMA = __webpack_require__(860);
132478module.exports.SAFE_SCHEMA = __webpack_require__(855);
132479module.exports.DEFAULT_SCHEMA = __webpack_require__(875); // Deprecated functions from JS-YAML 1.x.x
eb39fafa
DC
132480
132481module.exports.scan = deprecated('scan');
132482module.exports.parse = deprecated('parse');
132483module.exports.compose = deprecated('compose');
132484module.exports.addConstructor = deprecated('addConstructor');
132485
132486/***/ }),
6a5a0f88 132487/* 851 */
eb39fafa
DC
132488/***/ (function(module, exports, __webpack_require__) {
132489
132490"use strict";
132491
132492/*eslint-disable max-len,no-use-before-define*/
132493
6a5a0f88 132494var common = __webpack_require__(852);
eb39fafa 132495
6a5a0f88 132496var YAMLException = __webpack_require__(853);
eb39fafa 132497
6a5a0f88 132498var Mark = __webpack_require__(854);
eb39fafa 132499
6a5a0f88 132500var DEFAULT_SAFE_SCHEMA = __webpack_require__(855);
eb39fafa 132501
6a5a0f88 132502var DEFAULT_FULL_SCHEMA = __webpack_require__(875);
eb39fafa
DC
132503
132504var _hasOwnProperty = Object.prototype.hasOwnProperty;
132505var CONTEXT_FLOW_IN = 1;
132506var CONTEXT_FLOW_OUT = 2;
132507var CONTEXT_BLOCK_IN = 3;
132508var CONTEXT_BLOCK_OUT = 4;
132509var CHOMPING_CLIP = 1;
132510var CHOMPING_STRIP = 2;
132511var CHOMPING_KEEP = 3;
132512var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
132513var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
132514var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
132515var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
132516var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
132517
132518function _class(obj) {
132519 return Object.prototype.toString.call(obj);
132520}
132521
132522function is_EOL(c) {
132523 return c === 0x0A
132524 /* LF */
132525 || c === 0x0D
132526 /* CR */
132527 ;
132528}
132529
132530function is_WHITE_SPACE(c) {
132531 return c === 0x09
132532 /* Tab */
132533 || c === 0x20
132534 /* Space */
132535 ;
132536}
132537
132538function is_WS_OR_EOL(c) {
132539 return c === 0x09
132540 /* Tab */
132541 || c === 0x20
132542 /* Space */
132543 || c === 0x0A
132544 /* LF */
132545 || c === 0x0D
132546 /* CR */
132547 ;
132548}
132549
132550function is_FLOW_INDICATOR(c) {
132551 return c === 0x2C
132552 /* , */
132553 || c === 0x5B
132554 /* [ */
132555 || c === 0x5D
132556 /* ] */
132557 || c === 0x7B
132558 /* { */
132559 || c === 0x7D
132560 /* } */
132561 ;
132562}
132563
132564function fromHexCode(c) {
132565 var lc;
132566
132567 if (0x30
132568 /* 0 */
132569 <= c && c <= 0x39
132570 /* 9 */
132571 ) {
132572 return c - 0x30;
132573 }
132574 /*eslint-disable no-bitwise*/
132575
132576
132577 lc = c | 0x20;
132578
132579 if (0x61
132580 /* a */
132581 <= lc && lc <= 0x66
132582 /* f */
132583 ) {
132584 return lc - 0x61 + 10;
132585 }
132586
132587 return -1;
132588}
132589
132590function escapedHexLen(c) {
132591 if (c === 0x78
132592 /* x */
132593 ) {
132594 return 2;
132595 }
132596
132597 if (c === 0x75
132598 /* u */
132599 ) {
132600 return 4;
132601 }
132602
132603 if (c === 0x55
132604 /* U */
132605 ) {
132606 return 8;
132607 }
132608
132609 return 0;
132610}
132611
132612function fromDecimalCode(c) {
132613 if (0x30
132614 /* 0 */
132615 <= c && c <= 0x39
132616 /* 9 */
132617 ) {
132618 return c - 0x30;
132619 }
132620
132621 return -1;
132622}
132623
132624function simpleEscapeSequence(c) {
132625 /* eslint-disable indent */
132626 return c === 0x30
132627 /* 0 */
132628 ? '\x00' : c === 0x61
132629 /* a */
132630 ? '\x07' : c === 0x62
132631 /* b */
132632 ? '\x08' : c === 0x74
132633 /* t */
132634 ? '\x09' : c === 0x09
132635 /* Tab */
132636 ? '\x09' : c === 0x6E
132637 /* n */
132638 ? '\x0A' : c === 0x76
132639 /* v */
132640 ? '\x0B' : c === 0x66
132641 /* f */
132642 ? '\x0C' : c === 0x72
132643 /* r */
132644 ? '\x0D' : c === 0x65
132645 /* e */
132646 ? '\x1B' : c === 0x20
132647 /* Space */
132648 ? ' ' : c === 0x22
132649 /* " */
132650 ? '\x22' : c === 0x2F
132651 /* / */
132652 ? '/' : c === 0x5C
132653 /* \ */
132654 ? '\x5C' : c === 0x4E
132655 /* N */
132656 ? '\x85' : c === 0x5F
132657 /* _ */
132658 ? '\xA0' : c === 0x4C
132659 /* L */
132660 ? '\u2028' : c === 0x50
132661 /* P */
132662 ? '\u2029' : '';
132663}
132664
132665function charFromCodepoint(c) {
132666 if (c <= 0xFFFF) {
132667 return String.fromCharCode(c);
132668 } // Encode UTF-16 surrogate pair
132669 // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
132670
132671
132672 return String.fromCharCode((c - 0x010000 >> 10) + 0xD800, (c - 0x010000 & 0x03FF) + 0xDC00);
132673}
132674
132675var simpleEscapeCheck = new Array(256); // integer, for fast access
132676
132677var simpleEscapeMap = new Array(256);
132678
132679for (var i = 0; i < 256; i++) {
132680 simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
132681 simpleEscapeMap[i] = simpleEscapeSequence(i);
132682}
132683
132684function State(input, options) {
132685 this.input = input;
132686 this.filename = options['filename'] || null;
132687 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
132688 this.onWarning = options['onWarning'] || null;
132689 this.legacy = options['legacy'] || false;
132690 this.json = options['json'] || false;
132691 this.listener = options['listener'] || null;
132692 this.implicitTypes = this.schema.compiledImplicit;
132693 this.typeMap = this.schema.compiledTypeMap;
132694 this.length = input.length;
132695 this.position = 0;
132696 this.line = 0;
132697 this.lineStart = 0;
132698 this.lineIndent = 0;
132699 this.documents = [];
132700 /*
132701 this.version;
132702 this.checkLineBreaks;
132703 this.tagMap;
132704 this.anchorMap;
132705 this.tag;
132706 this.anchor;
132707 this.kind;
132708 this.result;*/
132709}
132710
132711function generateError(state, message) {
132712 return new YAMLException(message, new Mark(state.filename, state.input, state.position, state.line, state.position - state.lineStart));
132713}
132714
132715function throwError(state, message) {
132716 throw generateError(state, message);
132717}
132718
132719function throwWarning(state, message) {
132720 if (state.onWarning) {
132721 state.onWarning.call(null, generateError(state, message));
132722 }
132723}
132724
132725var directiveHandlers = {
132726 YAML: function handleYamlDirective(state, name, args) {
132727 var match, major, minor;
132728
132729 if (state.version !== null) {
132730 throwError(state, 'duplication of %YAML directive');
132731 }
132732
132733 if (args.length !== 1) {
132734 throwError(state, 'YAML directive accepts exactly one argument');
132735 }
132736
132737 match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
132738
132739 if (match === null) {
132740 throwError(state, 'ill-formed argument of the YAML directive');
132741 }
132742
132743 major = parseInt(match[1], 10);
132744 minor = parseInt(match[2], 10);
132745
132746 if (major !== 1) {
132747 throwError(state, 'unacceptable YAML version of the document');
132748 }
132749
132750 state.version = args[0];
132751 state.checkLineBreaks = minor < 2;
132752
132753 if (minor !== 1 && minor !== 2) {
132754 throwWarning(state, 'unsupported YAML version of the document');
132755 }
132756 },
132757 TAG: function handleTagDirective(state, name, args) {
132758 var handle, prefix;
132759
132760 if (args.length !== 2) {
132761 throwError(state, 'TAG directive accepts exactly two arguments');
132762 }
132763
132764 handle = args[0];
132765 prefix = args[1];
132766
132767 if (!PATTERN_TAG_HANDLE.test(handle)) {
132768 throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
132769 }
132770
132771 if (_hasOwnProperty.call(state.tagMap, handle)) {
132772 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
132773 }
132774
132775 if (!PATTERN_TAG_URI.test(prefix)) {
132776 throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
132777 }
132778
132779 state.tagMap[handle] = prefix;
132780 }
132781};
132782
132783function captureSegment(state, start, end, checkJson) {
132784 var _position, _length, _character, _result;
132785
132786 if (start < end) {
132787 _result = state.input.slice(start, end);
132788
132789 if (checkJson) {
132790 for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
132791 _character = _result.charCodeAt(_position);
132792
132793 if (!(_character === 0x09 || 0x20 <= _character && _character <= 0x10FFFF)) {
132794 throwError(state, 'expected valid JSON character');
132795 }
132796 }
132797 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
132798 throwError(state, 'the stream contains non-printable characters');
132799 }
132800
132801 state.result += _result;
132802 }
132803}
132804
132805function mergeMappings(state, destination, source, overridableKeys) {
132806 var sourceKeys, key, index, quantity;
132807
132808 if (!common.isObject(source)) {
132809 throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
132810 }
132811
132812 sourceKeys = Object.keys(source);
132813
132814 for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
132815 key = sourceKeys[index];
132816
132817 if (!_hasOwnProperty.call(destination, key)) {
132818 destination[key] = source[key];
132819 overridableKeys[key] = true;
132820 }
132821 }
132822}
132823
132824function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
132825 var index, quantity; // The output is a plain object here, so keys can only be strings.
132826 // We need to convert keyNode to a string, but doing so can hang the process
132827 // (deeply nested arrays that explode exponentially using aliases).
132828
132829 if (Array.isArray(keyNode)) {
132830 keyNode = Array.prototype.slice.call(keyNode);
132831
132832 for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
132833 if (Array.isArray(keyNode[index])) {
132834 throwError(state, 'nested arrays are not supported inside keys');
132835 }
132836
132837 if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
132838 keyNode[index] = '[object Object]';
132839 }
132840 }
132841 } // Avoid code execution in load() via toString property
132842 // (still use its own toString for arrays, timestamps,
132843 // and whatever user schema extensions happen to have @@toStringTag)
132844
132845
132846 if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
132847 keyNode = '[object Object]';
132848 }
132849
132850 keyNode = String(keyNode);
132851
132852 if (_result === null) {
132853 _result = {};
132854 }
132855
132856 if (keyTag === 'tag:yaml.org,2002:merge') {
132857 if (Array.isArray(valueNode)) {
132858 for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
132859 mergeMappings(state, _result, valueNode[index], overridableKeys);
132860 }
132861 } else {
132862 mergeMappings(state, _result, valueNode, overridableKeys);
132863 }
132864 } else {
132865 if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
132866 state.line = startLine || state.line;
132867 state.position = startPos || state.position;
132868 throwError(state, 'duplicated mapping key');
132869 }
132870
132871 _result[keyNode] = valueNode;
132872 delete overridableKeys[keyNode];
132873 }
132874
132875 return _result;
132876}
132877
132878function readLineBreak(state) {
132879 var ch;
132880 ch = state.input.charCodeAt(state.position);
132881
132882 if (ch === 0x0A
132883 /* LF */
132884 ) {
132885 state.position++;
132886 } else if (ch === 0x0D
132887 /* CR */
132888 ) {
132889 state.position++;
132890
132891 if (state.input.charCodeAt(state.position) === 0x0A
132892 /* LF */
132893 ) {
132894 state.position++;
132895 }
132896 } else {
132897 throwError(state, 'a line break is expected');
132898 }
132899
132900 state.line += 1;
132901 state.lineStart = state.position;
132902}
132903
132904function skipSeparationSpace(state, allowComments, checkIndent) {
132905 var lineBreaks = 0,
132906 ch = state.input.charCodeAt(state.position);
132907
132908 while (ch !== 0) {
132909 while (is_WHITE_SPACE(ch)) {
132910 ch = state.input.charCodeAt(++state.position);
132911 }
132912
132913 if (allowComments && ch === 0x23
132914 /* # */
132915 ) {
132916 do {
132917 ch = state.input.charCodeAt(++state.position);
132918 } while (ch !== 0x0A
132919 /* LF */
132920 && ch !== 0x0D
132921 /* CR */
132922 && ch !== 0);
132923 }
132924
132925 if (is_EOL(ch)) {
132926 readLineBreak(state);
132927 ch = state.input.charCodeAt(state.position);
132928 lineBreaks++;
132929 state.lineIndent = 0;
132930
132931 while (ch === 0x20
132932 /* Space */
132933 ) {
132934 state.lineIndent++;
132935 ch = state.input.charCodeAt(++state.position);
132936 }
132937 } else {
132938 break;
132939 }
132940 }
132941
132942 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
132943 throwWarning(state, 'deficient indentation');
132944 }
132945
132946 return lineBreaks;
132947}
132948
132949function testDocumentSeparator(state) {
132950 var _position = state.position,
132951 ch;
132952 ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested
132953 // in parent on each call, for efficiency. No needs to test here again.
132954
132955 if ((ch === 0x2D
132956 /* - */
132957 || ch === 0x2E
132958 /* . */
132959 ) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
132960 _position += 3;
132961 ch = state.input.charCodeAt(_position);
132962
132963 if (ch === 0 || is_WS_OR_EOL(ch)) {
132964 return true;
132965 }
132966 }
132967
132968 return false;
132969}
132970
132971function writeFoldedLines(state, count) {
132972 if (count === 1) {
132973 state.result += ' ';
132974 } else if (count > 1) {
132975 state.result += common.repeat('\n', count - 1);
132976 }
132977}
132978
132979function readPlainScalar(state, nodeIndent, withinFlowCollection) {
132980 var preceding,
132981 following,
132982 captureStart,
132983 captureEnd,
132984 hasPendingContent,
132985 _line,
132986 _lineStart,
132987 _lineIndent,
132988 _kind = state.kind,
132989 _result = state.result,
132990 ch;
132991
132992 ch = state.input.charCodeAt(state.position);
132993
132994 if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23
132995 /* # */
132996 || ch === 0x26
132997 /* & */
132998 || ch === 0x2A
132999 /* * */
133000 || ch === 0x21
133001 /* ! */
133002 || ch === 0x7C
133003 /* | */
133004 || ch === 0x3E
133005 /* > */
133006 || ch === 0x27
133007 /* ' */
133008 || ch === 0x22
133009 /* " */
133010 || ch === 0x25
133011 /* % */
133012 || ch === 0x40
133013 /* @ */
133014 || ch === 0x60
133015 /* ` */
133016 ) {
133017 return false;
133018 }
133019
133020 if (ch === 0x3F
133021 /* ? */
133022 || ch === 0x2D
133023 /* - */
133024 ) {
133025 following = state.input.charCodeAt(state.position + 1);
133026
133027 if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
133028 return false;
133029 }
133030 }
133031
133032 state.kind = 'scalar';
133033 state.result = '';
133034 captureStart = captureEnd = state.position;
133035 hasPendingContent = false;
133036
133037 while (ch !== 0) {
133038 if (ch === 0x3A
133039 /* : */
133040 ) {
133041 following = state.input.charCodeAt(state.position + 1);
133042
133043 if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
133044 break;
133045 }
133046 } else if (ch === 0x23
133047 /* # */
133048 ) {
133049 preceding = state.input.charCodeAt(state.position - 1);
133050
133051 if (is_WS_OR_EOL(preceding)) {
133052 break;
133053 }
133054 } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
133055 break;
133056 } else if (is_EOL(ch)) {
133057 _line = state.line;
133058 _lineStart = state.lineStart;
133059 _lineIndent = state.lineIndent;
133060 skipSeparationSpace(state, false, -1);
133061
133062 if (state.lineIndent >= nodeIndent) {
133063 hasPendingContent = true;
133064 ch = state.input.charCodeAt(state.position);
133065 continue;
133066 } else {
133067 state.position = captureEnd;
133068 state.line = _line;
133069 state.lineStart = _lineStart;
133070 state.lineIndent = _lineIndent;
133071 break;
133072 }
133073 }
133074
133075 if (hasPendingContent) {
133076 captureSegment(state, captureStart, captureEnd, false);
133077 writeFoldedLines(state, state.line - _line);
133078 captureStart = captureEnd = state.position;
133079 hasPendingContent = false;
133080 }
133081
133082 if (!is_WHITE_SPACE(ch)) {
133083 captureEnd = state.position + 1;
133084 }
133085
133086 ch = state.input.charCodeAt(++state.position);
133087 }
133088
133089 captureSegment(state, captureStart, captureEnd, false);
133090
133091 if (state.result) {
133092 return true;
133093 }
133094
133095 state.kind = _kind;
133096 state.result = _result;
133097 return false;
133098}
133099
133100function readSingleQuotedScalar(state, nodeIndent) {
133101 var ch, captureStart, captureEnd;
133102 ch = state.input.charCodeAt(state.position);
133103
133104 if (ch !== 0x27
133105 /* ' */
133106 ) {
133107 return false;
133108 }
133109
133110 state.kind = 'scalar';
133111 state.result = '';
133112 state.position++;
133113 captureStart = captureEnd = state.position;
133114
133115 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
133116 if (ch === 0x27
133117 /* ' */
133118 ) {
133119 captureSegment(state, captureStart, state.position, true);
133120 ch = state.input.charCodeAt(++state.position);
133121
133122 if (ch === 0x27
133123 /* ' */
133124 ) {
133125 captureStart = state.position;
133126 state.position++;
133127 captureEnd = state.position;
133128 } else {
133129 return true;
133130 }
133131 } else if (is_EOL(ch)) {
133132 captureSegment(state, captureStart, captureEnd, true);
133133 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
133134 captureStart = captureEnd = state.position;
133135 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
133136 throwError(state, 'unexpected end of the document within a single quoted scalar');
133137 } else {
133138 state.position++;
133139 captureEnd = state.position;
133140 }
133141 }
133142
133143 throwError(state, 'unexpected end of the stream within a single quoted scalar');
133144}
133145
133146function readDoubleQuotedScalar(state, nodeIndent) {
133147 var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
133148 ch = state.input.charCodeAt(state.position);
133149
133150 if (ch !== 0x22
133151 /* " */
133152 ) {
133153 return false;
133154 }
133155
133156 state.kind = 'scalar';
133157 state.result = '';
133158 state.position++;
133159 captureStart = captureEnd = state.position;
133160
133161 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
133162 if (ch === 0x22
133163 /* " */
133164 ) {
133165 captureSegment(state, captureStart, state.position, true);
133166 state.position++;
133167 return true;
133168 } else if (ch === 0x5C
133169 /* \ */
133170 ) {
133171 captureSegment(state, captureStart, state.position, true);
133172 ch = state.input.charCodeAt(++state.position);
133173
133174 if (is_EOL(ch)) {
133175 skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast?
133176 } else if (ch < 256 && simpleEscapeCheck[ch]) {
133177 state.result += simpleEscapeMap[ch];
133178 state.position++;
133179 } else if ((tmp = escapedHexLen(ch)) > 0) {
133180 hexLength = tmp;
133181 hexResult = 0;
133182
133183 for (; hexLength > 0; hexLength--) {
133184 ch = state.input.charCodeAt(++state.position);
133185
133186 if ((tmp = fromHexCode(ch)) >= 0) {
133187 hexResult = (hexResult << 4) + tmp;
133188 } else {
133189 throwError(state, 'expected hexadecimal character');
133190 }
133191 }
133192
133193 state.result += charFromCodepoint(hexResult);
133194 state.position++;
133195 } else {
133196 throwError(state, 'unknown escape sequence');
133197 }
133198
133199 captureStart = captureEnd = state.position;
133200 } else if (is_EOL(ch)) {
133201 captureSegment(state, captureStart, captureEnd, true);
133202 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
133203 captureStart = captureEnd = state.position;
133204 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
133205 throwError(state, 'unexpected end of the document within a double quoted scalar');
133206 } else {
133207 state.position++;
133208 captureEnd = state.position;
133209 }
133210 }
133211
133212 throwError(state, 'unexpected end of the stream within a double quoted scalar');
133213}
133214
133215function readFlowCollection(state, nodeIndent) {
133216 var readNext = true,
133217 _line,
133218 _tag = state.tag,
133219 _result,
133220 _anchor = state.anchor,
133221 following,
133222 terminator,
133223 isPair,
133224 isExplicitPair,
133225 isMapping,
133226 overridableKeys = {},
133227 keyNode,
133228 keyTag,
133229 valueNode,
133230 ch;
133231
133232 ch = state.input.charCodeAt(state.position);
133233
133234 if (ch === 0x5B
133235 /* [ */
133236 ) {
133237 terminator = 0x5D;
133238 /* ] */
133239
133240 isMapping = false;
133241 _result = [];
133242 } else if (ch === 0x7B
133243 /* { */
133244 ) {
133245 terminator = 0x7D;
133246 /* } */
133247
133248 isMapping = true;
133249 _result = {};
133250 } else {
133251 return false;
133252 }
133253
133254 if (state.anchor !== null) {
133255 state.anchorMap[state.anchor] = _result;
133256 }
133257
133258 ch = state.input.charCodeAt(++state.position);
133259
133260 while (ch !== 0) {
133261 skipSeparationSpace(state, true, nodeIndent);
133262 ch = state.input.charCodeAt(state.position);
133263
133264 if (ch === terminator) {
133265 state.position++;
133266 state.tag = _tag;
133267 state.anchor = _anchor;
133268 state.kind = isMapping ? 'mapping' : 'sequence';
133269 state.result = _result;
133270 return true;
133271 } else if (!readNext) {
133272 throwError(state, 'missed comma between flow collection entries');
133273 }
133274
133275 keyTag = keyNode = valueNode = null;
133276 isPair = isExplicitPair = false;
133277
133278 if (ch === 0x3F
133279 /* ? */
133280 ) {
133281 following = state.input.charCodeAt(state.position + 1);
133282
133283 if (is_WS_OR_EOL(following)) {
133284 isPair = isExplicitPair = true;
133285 state.position++;
133286 skipSeparationSpace(state, true, nodeIndent);
133287 }
133288 }
133289
133290 _line = state.line;
133291 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
133292 keyTag = state.tag;
133293 keyNode = state.result;
133294 skipSeparationSpace(state, true, nodeIndent);
133295 ch = state.input.charCodeAt(state.position);
133296
133297 if ((isExplicitPair || state.line === _line) && ch === 0x3A
133298 /* : */
133299 ) {
133300 isPair = true;
133301 ch = state.input.charCodeAt(++state.position);
133302 skipSeparationSpace(state, true, nodeIndent);
133303 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
133304 valueNode = state.result;
133305 }
133306
133307 if (isMapping) {
133308 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
133309 } else if (isPair) {
133310 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
133311 } else {
133312 _result.push(keyNode);
133313 }
133314
133315 skipSeparationSpace(state, true, nodeIndent);
133316 ch = state.input.charCodeAt(state.position);
133317
133318 if (ch === 0x2C
133319 /* , */
133320 ) {
133321 readNext = true;
133322 ch = state.input.charCodeAt(++state.position);
133323 } else {
133324 readNext = false;
133325 }
133326 }
133327
133328 throwError(state, 'unexpected end of the stream within a flow collection');
133329}
133330
133331function readBlockScalar(state, nodeIndent) {
133332 var captureStart,
133333 folding,
133334 chomping = CHOMPING_CLIP,
133335 didReadContent = false,
133336 detectedIndent = false,
133337 textIndent = nodeIndent,
133338 emptyLines = 0,
133339 atMoreIndented = false,
133340 tmp,
133341 ch;
133342 ch = state.input.charCodeAt(state.position);
133343
133344 if (ch === 0x7C
133345 /* | */
133346 ) {
133347 folding = false;
133348 } else if (ch === 0x3E
133349 /* > */
133350 ) {
133351 folding = true;
133352 } else {
133353 return false;
133354 }
133355
133356 state.kind = 'scalar';
133357 state.result = '';
133358
133359 while (ch !== 0) {
133360 ch = state.input.charCodeAt(++state.position);
133361
133362 if (ch === 0x2B
133363 /* + */
133364 || ch === 0x2D
133365 /* - */
133366 ) {
133367 if (CHOMPING_CLIP === chomping) {
133368 chomping = ch === 0x2B
133369 /* + */
133370 ? CHOMPING_KEEP : CHOMPING_STRIP;
133371 } else {
133372 throwError(state, 'repeat of a chomping mode identifier');
133373 }
133374 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
133375 if (tmp === 0) {
133376 throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
133377 } else if (!detectedIndent) {
133378 textIndent = nodeIndent + tmp - 1;
133379 detectedIndent = true;
133380 } else {
133381 throwError(state, 'repeat of an indentation width identifier');
133382 }
133383 } else {
133384 break;
133385 }
133386 }
133387
133388 if (is_WHITE_SPACE(ch)) {
133389 do {
133390 ch = state.input.charCodeAt(++state.position);
133391 } while (is_WHITE_SPACE(ch));
133392
133393 if (ch === 0x23
133394 /* # */
133395 ) {
133396 do {
133397 ch = state.input.charCodeAt(++state.position);
133398 } while (!is_EOL(ch) && ch !== 0);
133399 }
133400 }
133401
133402 while (ch !== 0) {
133403 readLineBreak(state);
133404 state.lineIndent = 0;
133405 ch = state.input.charCodeAt(state.position);
133406
133407 while ((!detectedIndent || state.lineIndent < textIndent) && ch === 0x20
133408 /* Space */
133409 ) {
133410 state.lineIndent++;
133411 ch = state.input.charCodeAt(++state.position);
133412 }
133413
133414 if (!detectedIndent && state.lineIndent > textIndent) {
133415 textIndent = state.lineIndent;
133416 }
133417
133418 if (is_EOL(ch)) {
133419 emptyLines++;
133420 continue;
133421 } // End of the scalar.
133422
133423
133424 if (state.lineIndent < textIndent) {
133425 // Perform the chomping.
133426 if (chomping === CHOMPING_KEEP) {
133427 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
133428 } else if (chomping === CHOMPING_CLIP) {
133429 if (didReadContent) {
133430 // i.e. only if the scalar is not empty.
133431 state.result += '\n';
133432 }
133433 } // Break this `while` cycle and go to the funciton's epilogue.
133434
133435
133436 break;
133437 } // Folded style: use fancy rules to handle line breaks.
133438
133439
133440 if (folding) {
133441 // Lines starting with white space characters (more-indented lines) are not folded.
133442 if (is_WHITE_SPACE(ch)) {
133443 atMoreIndented = true; // except for the first content line (cf. Example 8.1)
133444
133445 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block.
133446 } else if (atMoreIndented) {
133447 atMoreIndented = false;
133448 state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line.
133449 } else if (emptyLines === 0) {
133450 if (didReadContent) {
133451 // i.e. only if we have already read some scalar content.
133452 state.result += ' ';
133453 } // Several line breaks - perceive as different lines.
133454
133455 } else {
133456 state.result += common.repeat('\n', emptyLines);
133457 } // Literal style: just add exact number of line breaks between content lines.
133458
133459 } else {
133460 // Keep all line breaks except the header line break.
133461 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
133462 }
133463
133464 didReadContent = true;
133465 detectedIndent = true;
133466 emptyLines = 0;
133467 captureStart = state.position;
133468
133469 while (!is_EOL(ch) && ch !== 0) {
133470 ch = state.input.charCodeAt(++state.position);
133471 }
133472
133473 captureSegment(state, captureStart, state.position, false);
133474 }
133475
133476 return true;
133477}
133478
133479function readBlockSequence(state, nodeIndent) {
133480 var _line,
133481 _tag = state.tag,
133482 _anchor = state.anchor,
133483 _result = [],
133484 following,
133485 detected = false,
133486 ch;
133487
133488 if (state.anchor !== null) {
133489 state.anchorMap[state.anchor] = _result;
133490 }
133491
133492 ch = state.input.charCodeAt(state.position);
133493
133494 while (ch !== 0) {
133495 if (ch !== 0x2D
133496 /* - */
133497 ) {
133498 break;
133499 }
133500
133501 following = state.input.charCodeAt(state.position + 1);
133502
133503 if (!is_WS_OR_EOL(following)) {
133504 break;
133505 }
133506
133507 detected = true;
133508 state.position++;
133509
133510 if (skipSeparationSpace(state, true, -1)) {
133511 if (state.lineIndent <= nodeIndent) {
133512 _result.push(null);
133513
133514 ch = state.input.charCodeAt(state.position);
133515 continue;
133516 }
133517 }
133518
133519 _line = state.line;
133520 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
133521
133522 _result.push(state.result);
133523
133524 skipSeparationSpace(state, true, -1);
133525 ch = state.input.charCodeAt(state.position);
133526
133527 if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
133528 throwError(state, 'bad indentation of a sequence entry');
133529 } else if (state.lineIndent < nodeIndent) {
133530 break;
133531 }
133532 }
133533
133534 if (detected) {
133535 state.tag = _tag;
133536 state.anchor = _anchor;
133537 state.kind = 'sequence';
133538 state.result = _result;
133539 return true;
133540 }
133541
133542 return false;
133543}
133544
133545function readBlockMapping(state, nodeIndent, flowIndent) {
133546 var following,
133547 allowCompact,
133548 _line,
133549 _pos,
133550 _tag = state.tag,
133551 _anchor = state.anchor,
133552 _result = {},
133553 overridableKeys = {},
133554 keyTag = null,
133555 keyNode = null,
133556 valueNode = null,
133557 atExplicitKey = false,
133558 detected = false,
133559 ch;
133560
133561 if (state.anchor !== null) {
133562 state.anchorMap[state.anchor] = _result;
133563 }
133564
133565 ch = state.input.charCodeAt(state.position);
133566
133567 while (ch !== 0) {
133568 following = state.input.charCodeAt(state.position + 1);
133569 _line = state.line; // Save the current line.
133570
133571 _pos = state.position; //
133572 // Explicit notation case. There are two separate blocks:
133573 // first for the key (denoted by "?") and second for the value (denoted by ":")
133574 //
133575
133576 if ((ch === 0x3F
133577 /* ? */
133578 || ch === 0x3A
133579 /* : */
133580 ) && is_WS_OR_EOL(following)) {
133581 if (ch === 0x3F
133582 /* ? */
133583 ) {
133584 if (atExplicitKey) {
133585 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
133586 keyTag = keyNode = valueNode = null;
133587 }
133588
133589 detected = true;
133590 atExplicitKey = true;
133591 allowCompact = true;
133592 } else if (atExplicitKey) {
133593 // i.e. 0x3A/* : */ === character after the explicit key.
133594 atExplicitKey = false;
133595 allowCompact = true;
133596 } else {
133597 throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
133598 }
133599
133600 state.position += 1;
133601 ch = following; //
133602 // Implicit notation case. Flow-style node as the key first, then ":", and the value.
133603 //
133604 } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
133605 if (state.line === _line) {
133606 ch = state.input.charCodeAt(state.position);
133607
133608 while (is_WHITE_SPACE(ch)) {
133609 ch = state.input.charCodeAt(++state.position);
133610 }
133611
133612 if (ch === 0x3A
133613 /* : */
133614 ) {
133615 ch = state.input.charCodeAt(++state.position);
133616
133617 if (!is_WS_OR_EOL(ch)) {
133618 throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
133619 }
133620
133621 if (atExplicitKey) {
133622 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
133623 keyTag = keyNode = valueNode = null;
133624 }
133625
133626 detected = true;
133627 atExplicitKey = false;
133628 allowCompact = false;
133629 keyTag = state.tag;
133630 keyNode = state.result;
133631 } else if (detected) {
133632 throwError(state, 'can not read an implicit mapping pair; a colon is missed');
133633 } else {
133634 state.tag = _tag;
133635 state.anchor = _anchor;
133636 return true; // Keep the result of `composeNode`.
133637 }
133638 } else if (detected) {
133639 throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
133640 } else {
133641 state.tag = _tag;
133642 state.anchor = _anchor;
133643 return true; // Keep the result of `composeNode`.
133644 }
133645 } else {
133646 break; // Reading is done. Go to the epilogue.
133647 } //
133648 // Common reading code for both explicit and implicit notations.
133649 //
133650
133651
133652 if (state.line === _line || state.lineIndent > nodeIndent) {
133653 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
133654 if (atExplicitKey) {
133655 keyNode = state.result;
133656 } else {
133657 valueNode = state.result;
133658 }
133659 }
133660
133661 if (!atExplicitKey) {
133662 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
133663 keyTag = keyNode = valueNode = null;
133664 }
133665
133666 skipSeparationSpace(state, true, -1);
133667 ch = state.input.charCodeAt(state.position);
133668 }
133669
133670 if (state.lineIndent > nodeIndent && ch !== 0) {
133671 throwError(state, 'bad indentation of a mapping entry');
133672 } else if (state.lineIndent < nodeIndent) {
133673 break;
133674 }
133675 } //
133676 // Epilogue.
133677 //
133678 // Special case: last mapping's node contains only the key in explicit notation.
133679
133680
133681 if (atExplicitKey) {
133682 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
133683 } // Expose the resulting mapping.
133684
133685
133686 if (detected) {
133687 state.tag = _tag;
133688 state.anchor = _anchor;
133689 state.kind = 'mapping';
133690 state.result = _result;
133691 }
133692
133693 return detected;
133694}
133695
133696function readTagProperty(state) {
133697 var _position,
133698 isVerbatim = false,
133699 isNamed = false,
133700 tagHandle,
133701 tagName,
133702 ch;
133703
133704 ch = state.input.charCodeAt(state.position);
133705 if (ch !== 0x21
133706 /* ! */
133707 ) return false;
133708
133709 if (state.tag !== null) {
133710 throwError(state, 'duplication of a tag property');
133711 }
133712
133713 ch = state.input.charCodeAt(++state.position);
133714
133715 if (ch === 0x3C
133716 /* < */
133717 ) {
133718 isVerbatim = true;
133719 ch = state.input.charCodeAt(++state.position);
133720 } else if (ch === 0x21
133721 /* ! */
133722 ) {
133723 isNamed = true;
133724 tagHandle = '!!';
133725 ch = state.input.charCodeAt(++state.position);
133726 } else {
133727 tagHandle = '!';
133728 }
133729
133730 _position = state.position;
133731
133732 if (isVerbatim) {
133733 do {
133734 ch = state.input.charCodeAt(++state.position);
133735 } while (ch !== 0 && ch !== 0x3E
133736 /* > */
133737 );
133738
133739 if (state.position < state.length) {
133740 tagName = state.input.slice(_position, state.position);
133741 ch = state.input.charCodeAt(++state.position);
133742 } else {
133743 throwError(state, 'unexpected end of the stream within a verbatim tag');
133744 }
133745 } else {
133746 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
133747 if (ch === 0x21
133748 /* ! */
133749 ) {
133750 if (!isNamed) {
133751 tagHandle = state.input.slice(_position - 1, state.position + 1);
133752
133753 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
133754 throwError(state, 'named tag handle cannot contain such characters');
133755 }
133756
133757 isNamed = true;
133758 _position = state.position + 1;
133759 } else {
133760 throwError(state, 'tag suffix cannot contain exclamation marks');
133761 }
133762 }
133763
133764 ch = state.input.charCodeAt(++state.position);
133765 }
133766
133767 tagName = state.input.slice(_position, state.position);
133768
133769 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
133770 throwError(state, 'tag suffix cannot contain flow indicator characters');
133771 }
133772 }
133773
133774 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
133775 throwError(state, 'tag name cannot contain such characters: ' + tagName);
133776 }
133777
133778 if (isVerbatim) {
133779 state.tag = tagName;
133780 } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
133781 state.tag = state.tagMap[tagHandle] + tagName;
133782 } else if (tagHandle === '!') {
133783 state.tag = '!' + tagName;
133784 } else if (tagHandle === '!!') {
133785 state.tag = 'tag:yaml.org,2002:' + tagName;
133786 } else {
133787 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
133788 }
133789
133790 return true;
133791}
133792
133793function readAnchorProperty(state) {
133794 var _position, ch;
133795
133796 ch = state.input.charCodeAt(state.position);
133797 if (ch !== 0x26
133798 /* & */
133799 ) return false;
133800
133801 if (state.anchor !== null) {
133802 throwError(state, 'duplication of an anchor property');
133803 }
133804
133805 ch = state.input.charCodeAt(++state.position);
133806 _position = state.position;
133807
133808 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
133809 ch = state.input.charCodeAt(++state.position);
133810 }
133811
133812 if (state.position === _position) {
133813 throwError(state, 'name of an anchor node must contain at least one character');
133814 }
133815
133816 state.anchor = state.input.slice(_position, state.position);
133817 return true;
133818}
133819
133820function readAlias(state) {
133821 var _position, alias, ch;
133822
133823 ch = state.input.charCodeAt(state.position);
133824 if (ch !== 0x2A
133825 /* * */
133826 ) return false;
133827 ch = state.input.charCodeAt(++state.position);
133828 _position = state.position;
133829
133830 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
133831 ch = state.input.charCodeAt(++state.position);
133832 }
133833
133834 if (state.position === _position) {
133835 throwError(state, 'name of an alias node must contain at least one character');
133836 }
133837
133838 alias = state.input.slice(_position, state.position);
133839
133840 if (!state.anchorMap.hasOwnProperty(alias)) {
133841 throwError(state, 'unidentified alias "' + alias + '"');
133842 }
133843
133844 state.result = state.anchorMap[alias];
133845 skipSeparationSpace(state, true, -1);
133846 return true;
133847}
133848
133849function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
133850 var allowBlockStyles,
133851 allowBlockScalars,
133852 allowBlockCollections,
133853 indentStatus = 1,
133854 // 1: this>parent, 0: this=parent, -1: this<parent
133855 atNewLine = false,
133856 hasContent = false,
133857 typeIndex,
133858 typeQuantity,
133859 type,
133860 flowIndent,
133861 blockIndent;
133862
133863 if (state.listener !== null) {
133864 state.listener('open', state);
133865 }
133866
133867 state.tag = null;
133868 state.anchor = null;
133869 state.kind = null;
133870 state.result = null;
133871 allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
133872
133873 if (allowToSeek) {
133874 if (skipSeparationSpace(state, true, -1)) {
133875 atNewLine = true;
133876
133877 if (state.lineIndent > parentIndent) {
133878 indentStatus = 1;
133879 } else if (state.lineIndent === parentIndent) {
133880 indentStatus = 0;
133881 } else if (state.lineIndent < parentIndent) {
133882 indentStatus = -1;
133883 }
133884 }
133885 }
133886
133887 if (indentStatus === 1) {
133888 while (readTagProperty(state) || readAnchorProperty(state)) {
133889 if (skipSeparationSpace(state, true, -1)) {
133890 atNewLine = true;
133891 allowBlockCollections = allowBlockStyles;
133892
133893 if (state.lineIndent > parentIndent) {
133894 indentStatus = 1;
133895 } else if (state.lineIndent === parentIndent) {
133896 indentStatus = 0;
133897 } else if (state.lineIndent < parentIndent) {
133898 indentStatus = -1;
133899 }
133900 } else {
133901 allowBlockCollections = false;
133902 }
133903 }
133904 }
133905
133906 if (allowBlockCollections) {
133907 allowBlockCollections = atNewLine || allowCompact;
133908 }
133909
133910 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
133911 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
133912 flowIndent = parentIndent;
133913 } else {
133914 flowIndent = parentIndent + 1;
133915 }
133916
133917 blockIndent = state.position - state.lineStart;
133918
133919 if (indentStatus === 1) {
133920 if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
133921 hasContent = true;
133922 } else {
133923 if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
133924 hasContent = true;
133925 } else if (readAlias(state)) {
133926 hasContent = true;
133927
133928 if (state.tag !== null || state.anchor !== null) {
133929 throwError(state, 'alias node should not have any properties');
133930 }
133931 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
133932 hasContent = true;
133933
133934 if (state.tag === null) {
133935 state.tag = '?';
133936 }
133937 }
133938
133939 if (state.anchor !== null) {
133940 state.anchorMap[state.anchor] = state.result;
133941 }
133942 }
133943 } else if (indentStatus === 0) {
133944 // Special case: block sequences are allowed to have same indentation level as the parent.
133945 // http://www.yaml.org/spec/1.2/spec.html#id2799784
133946 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
133947 }
133948 }
133949
133950 if (state.tag !== null && state.tag !== '!') {
133951 if (state.tag === '?') {
6a5a0f88
TL
133952 // Implicit resolving is not allowed for non-scalar types, and '?'
133953 // non-specific tag is only automatically assigned to plain scalars.
133954 //
133955 // We only need to check kind conformity in case user explicitly assigns '?'
133956 // tag, for example like this: "!<?> [0]"
133957 //
133958 if (state.result !== null && state.kind !== 'scalar') {
133959 throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
133960 }
133961
eb39fafa 133962 for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
6a5a0f88 133963 type = state.implicitTypes[typeIndex];
eb39fafa
DC
133964
133965 if (type.resolve(state.result)) {
133966 // `state.result` updated in resolver if matched
133967 state.result = type.construct(state.result);
133968 state.tag = type.tag;
133969
133970 if (state.anchor !== null) {
133971 state.anchorMap[state.anchor] = state.result;
133972 }
133973
133974 break;
133975 }
133976 }
133977 } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
133978 type = state.typeMap[state.kind || 'fallback'][state.tag];
133979
133980 if (state.result !== null && type.kind !== state.kind) {
133981 throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
133982 }
133983
133984 if (!type.resolve(state.result)) {
133985 // `state.result` updated in resolver if matched
133986 throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
133987 } else {
133988 state.result = type.construct(state.result);
133989
133990 if (state.anchor !== null) {
133991 state.anchorMap[state.anchor] = state.result;
133992 }
133993 }
133994 } else {
133995 throwError(state, 'unknown tag !<' + state.tag + '>');
133996 }
133997 }
133998
133999 if (state.listener !== null) {
134000 state.listener('close', state);
134001 }
134002
134003 return state.tag !== null || state.anchor !== null || hasContent;
134004}
134005
134006function readDocument(state) {
134007 var documentStart = state.position,
134008 _position,
134009 directiveName,
134010 directiveArgs,
134011 hasDirectives = false,
134012 ch;
134013
134014 state.version = null;
134015 state.checkLineBreaks = state.legacy;
134016 state.tagMap = {};
134017 state.anchorMap = {};
134018
134019 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
134020 skipSeparationSpace(state, true, -1);
134021 ch = state.input.charCodeAt(state.position);
134022
134023 if (state.lineIndent > 0 || ch !== 0x25
134024 /* % */
134025 ) {
134026 break;
134027 }
134028
134029 hasDirectives = true;
134030 ch = state.input.charCodeAt(++state.position);
134031 _position = state.position;
134032
134033 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
134034 ch = state.input.charCodeAt(++state.position);
134035 }
134036
134037 directiveName = state.input.slice(_position, state.position);
134038 directiveArgs = [];
134039
134040 if (directiveName.length < 1) {
134041 throwError(state, 'directive name must not be less than one character in length');
134042 }
134043
134044 while (ch !== 0) {
134045 while (is_WHITE_SPACE(ch)) {
134046 ch = state.input.charCodeAt(++state.position);
134047 }
134048
134049 if (ch === 0x23
134050 /* # */
134051 ) {
134052 do {
134053 ch = state.input.charCodeAt(++state.position);
134054 } while (ch !== 0 && !is_EOL(ch));
134055
134056 break;
134057 }
134058
134059 if (is_EOL(ch)) break;
134060 _position = state.position;
134061
134062 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
134063 ch = state.input.charCodeAt(++state.position);
134064 }
134065
134066 directiveArgs.push(state.input.slice(_position, state.position));
134067 }
134068
134069 if (ch !== 0) readLineBreak(state);
134070
134071 if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
134072 directiveHandlers[directiveName](state, directiveName, directiveArgs);
134073 } else {
134074 throwWarning(state, 'unknown document directive "' + directiveName + '"');
134075 }
134076 }
134077
134078 skipSeparationSpace(state, true, -1);
134079
134080 if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D
134081 /* - */
134082 && state.input.charCodeAt(state.position + 1) === 0x2D
134083 /* - */
134084 && state.input.charCodeAt(state.position + 2) === 0x2D
134085 /* - */
134086 ) {
134087 state.position += 3;
134088 skipSeparationSpace(state, true, -1);
134089 } else if (hasDirectives) {
134090 throwError(state, 'directives end mark is expected');
134091 }
134092
134093 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
134094 skipSeparationSpace(state, true, -1);
134095
134096 if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
134097 throwWarning(state, 'non-ASCII line breaks are interpreted as content');
134098 }
134099
134100 state.documents.push(state.result);
134101
134102 if (state.position === state.lineStart && testDocumentSeparator(state)) {
134103 if (state.input.charCodeAt(state.position) === 0x2E
134104 /* . */
134105 ) {
134106 state.position += 3;
134107 skipSeparationSpace(state, true, -1);
134108 }
134109
134110 return;
134111 }
134112
134113 if (state.position < state.length - 1) {
134114 throwError(state, 'end of the stream or a document separator is expected');
134115 } else {
134116 return;
134117 }
134118}
134119
134120function loadDocuments(input, options) {
134121 input = String(input);
134122 options = options || {};
134123
134124 if (input.length !== 0) {
134125 // Add tailing `\n` if not exists
134126 if (input.charCodeAt(input.length - 1) !== 0x0A
134127 /* LF */
134128 && input.charCodeAt(input.length - 1) !== 0x0D
134129 /* CR */
134130 ) {
134131 input += '\n';
134132 } // Strip BOM
134133
134134
134135 if (input.charCodeAt(0) === 0xFEFF) {
134136 input = input.slice(1);
134137 }
134138 }
134139
6a5a0f88
TL
134140 var state = new State(input, options);
134141 var nullpos = input.indexOf('\0');
134142
134143 if (nullpos !== -1) {
134144 state.position = nullpos;
134145 throwError(state, 'null byte is not allowed in input');
134146 } // Use 0 as string terminator. That significantly simplifies bounds check.
134147
eb39fafa
DC
134148
134149 state.input += '\0';
134150
134151 while (state.input.charCodeAt(state.position) === 0x20
134152 /* Space */
134153 ) {
134154 state.lineIndent += 1;
134155 state.position += 1;
134156 }
134157
134158 while (state.position < state.length - 1) {
134159 readDocument(state);
134160 }
134161
134162 return state.documents;
134163}
134164
134165function loadAll(input, iterator, options) {
6a5a0f88
TL
134166 if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
134167 options = iterator;
134168 iterator = null;
134169 }
134170
134171 var documents = loadDocuments(input, options);
eb39fafa
DC
134172
134173 if (typeof iterator !== 'function') {
134174 return documents;
134175 }
134176
6a5a0f88 134177 for (var index = 0, length = documents.length; index < length; index += 1) {
eb39fafa
DC
134178 iterator(documents[index]);
134179 }
134180}
134181
134182function load(input, options) {
134183 var documents = loadDocuments(input, options);
134184
134185 if (documents.length === 0) {
134186 /*eslint-disable no-undefined*/
134187 return undefined;
134188 } else if (documents.length === 1) {
134189 return documents[0];
134190 }
134191
134192 throw new YAMLException('expected a single document in the stream, but found more');
134193}
134194
6a5a0f88
TL
134195function safeLoadAll(input, iterator, options) {
134196 if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {
134197 options = iterator;
134198 iterator = null;
eb39fafa 134199 }
6a5a0f88
TL
134200
134201 return loadAll(input, iterator, common.extend({
134202 schema: DEFAULT_SAFE_SCHEMA
134203 }, options));
eb39fafa
DC
134204}
134205
134206function safeLoad(input, options) {
134207 return load(input, common.extend({
134208 schema: DEFAULT_SAFE_SCHEMA
134209 }, options));
134210}
134211
134212module.exports.loadAll = loadAll;
134213module.exports.load = load;
134214module.exports.safeLoadAll = safeLoadAll;
134215module.exports.safeLoad = safeLoad;
134216
134217/***/ }),
6a5a0f88 134218/* 852 */
eb39fafa
DC
134219/***/ (function(module, exports, __webpack_require__) {
134220
134221"use strict";
134222
134223
134224function isNothing(subject) {
134225 return typeof subject === 'undefined' || subject === null;
134226}
134227
134228function isObject(subject) {
134229 return typeof subject === 'object' && subject !== null;
134230}
134231
134232function toArray(sequence) {
134233 if (Array.isArray(sequence)) return sequence;else if (isNothing(sequence)) return [];
134234 return [sequence];
134235}
134236
134237function extend(target, source) {
134238 var index, length, key, sourceKeys;
134239
134240 if (source) {
134241 sourceKeys = Object.keys(source);
134242
134243 for (index = 0, length = sourceKeys.length; index < length; index += 1) {
134244 key = sourceKeys[index];
134245 target[key] = source[key];
134246 }
134247 }
134248
134249 return target;
134250}
134251
134252function repeat(string, count) {
134253 var result = '',
134254 cycle;
134255
134256 for (cycle = 0; cycle < count; cycle += 1) {
134257 result += string;
134258 }
134259
134260 return result;
134261}
134262
134263function isNegativeZero(number) {
134264 return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
134265}
134266
134267module.exports.isNothing = isNothing;
134268module.exports.isObject = isObject;
134269module.exports.toArray = toArray;
134270module.exports.repeat = repeat;
134271module.exports.isNegativeZero = isNegativeZero;
134272module.exports.extend = extend;
134273
134274/***/ }),
6a5a0f88 134275/* 853 */
eb39fafa
DC
134276/***/ (function(module, exports, __webpack_require__) {
134277
134278"use strict";
134279// YAML error class. http://stackoverflow.com/questions/8458984
134280//
134281
134282
134283function YAMLException(reason, mark) {
134284 // Super constructor
134285 Error.call(this);
134286 this.name = 'YAMLException';
134287 this.reason = reason;
134288 this.mark = mark;
134289 this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); // Include stack trace in error object
134290
134291 if (Error.captureStackTrace) {
134292 // Chrome and NodeJS
134293 Error.captureStackTrace(this, this.constructor);
134294 } else {
134295 // FF, IE 10+ and Safari 6+. Fallback for others
134296 this.stack = new Error().stack || '';
134297 }
134298} // Inherit from Error
134299
134300
134301YAMLException.prototype = Object.create(Error.prototype);
134302YAMLException.prototype.constructor = YAMLException;
134303
134304YAMLException.prototype.toString = function toString(compact) {
134305 var result = this.name + ': ';
134306 result += this.reason || '(unknown reason)';
134307
134308 if (!compact && this.mark) {
134309 result += ' ' + this.mark.toString();
134310 }
134311
134312 return result;
134313};
134314
134315module.exports = YAMLException;
134316
134317/***/ }),
6a5a0f88 134318/* 854 */
eb39fafa
DC
134319/***/ (function(module, exports, __webpack_require__) {
134320
134321"use strict";
134322
134323
6a5a0f88 134324var common = __webpack_require__(852);
eb39fafa
DC
134325
134326function Mark(name, buffer, position, line, column) {
134327 this.name = name;
134328 this.buffer = buffer;
134329 this.position = position;
134330 this.line = line;
134331 this.column = column;
134332}
134333
134334Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
134335 var head, start, tail, end, snippet;
134336 if (!this.buffer) return null;
134337 indent = indent || 4;
134338 maxLength = maxLength || 75;
134339 head = '';
134340 start = this.position;
134341
134342 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
134343 start -= 1;
134344
134345 if (this.position - start > maxLength / 2 - 1) {
134346 head = ' ... ';
134347 start += 5;
134348 break;
134349 }
134350 }
134351
134352 tail = '';
134353 end = this.position;
134354
134355 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
134356 end += 1;
134357
134358 if (end - this.position > maxLength / 2 - 1) {
134359 tail = ' ... ';
134360 end -= 5;
134361 break;
134362 }
134363 }
134364
134365 snippet = this.buffer.slice(start, end);
134366 return common.repeat(' ', indent) + head + snippet + tail + '\n' + common.repeat(' ', indent + this.position - start + head.length) + '^';
134367};
134368
134369Mark.prototype.toString = function toString(compact) {
134370 var snippet,
134371 where = '';
134372
134373 if (this.name) {
134374 where += 'in "' + this.name + '" ';
134375 }
134376
134377 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
134378
134379 if (!compact) {
134380 snippet = this.getSnippet();
134381
134382 if (snippet) {
134383 where += ':\n' + snippet;
134384 }
134385 }
134386
134387 return where;
134388};
134389
134390module.exports = Mark;
134391
134392/***/ }),
6a5a0f88 134393/* 855 */
eb39fafa
DC
134394/***/ (function(module, exports, __webpack_require__) {
134395
134396"use strict";
134397// JS-YAML's default schema for `safeLoad` function.
134398// It is not described in the YAML specification.
134399//
134400// This schema is based on standard YAML's Core schema and includes most of
134401// extra types described at YAML tag repository. (http://yaml.org/type/)
134402
134403
6a5a0f88 134404var Schema = __webpack_require__(856);
eb39fafa
DC
134405
134406module.exports = new Schema({
6a5a0f88
TL
134407 include: [__webpack_require__(858)],
134408 implicit: [__webpack_require__(868), __webpack_require__(869)],
134409 explicit: [__webpack_require__(870), __webpack_require__(872), __webpack_require__(873), __webpack_require__(874)]
eb39fafa
DC
134410});
134411
134412/***/ }),
6a5a0f88 134413/* 856 */
eb39fafa
DC
134414/***/ (function(module, exports, __webpack_require__) {
134415
134416"use strict";
134417
134418/*eslint-disable max-len*/
134419
6a5a0f88 134420var common = __webpack_require__(852);
eb39fafa 134421
6a5a0f88 134422var YAMLException = __webpack_require__(853);
eb39fafa 134423
6a5a0f88 134424var Type = __webpack_require__(857);
eb39fafa
DC
134425
134426function compileList(schema, name, result) {
134427 var exclude = [];
134428 schema.include.forEach(function (includedSchema) {
134429 result = compileList(includedSchema, name, result);
134430 });
134431 schema[name].forEach(function (currentType) {
134432 result.forEach(function (previousType, previousIndex) {
134433 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
134434 exclude.push(previousIndex);
134435 }
134436 });
134437 result.push(currentType);
134438 });
134439 return result.filter(function (type, index) {
134440 return exclude.indexOf(index) === -1;
134441 });
134442}
134443
134444function compileMap()
134445/* lists... */
134446{
134447 var result = {
134448 scalar: {},
134449 sequence: {},
134450 mapping: {},
134451 fallback: {}
134452 },
134453 index,
134454 length;
134455
134456 function collectType(type) {
134457 result[type.kind][type.tag] = result['fallback'][type.tag] = type;
134458 }
134459
134460 for (index = 0, length = arguments.length; index < length; index += 1) {
134461 arguments[index].forEach(collectType);
134462 }
134463
134464 return result;
134465}
134466
134467function Schema(definition) {
134468 this.include = definition.include || [];
134469 this.implicit = definition.implicit || [];
134470 this.explicit = definition.explicit || [];
134471 this.implicit.forEach(function (type) {
134472 if (type.loadKind && type.loadKind !== 'scalar') {
134473 throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
134474 }
134475 });
134476 this.compiledImplicit = compileList(this, 'implicit', []);
134477 this.compiledExplicit = compileList(this, 'explicit', []);
134478 this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
134479}
134480
134481Schema.DEFAULT = null;
134482
134483Schema.create = function createSchema() {
134484 var schemas, types;
134485
134486 switch (arguments.length) {
134487 case 1:
134488 schemas = Schema.DEFAULT;
134489 types = arguments[0];
134490 break;
134491
134492 case 2:
134493 schemas = arguments[0];
134494 types = arguments[1];
134495 break;
134496
134497 default:
134498 throw new YAMLException('Wrong number of arguments for Schema.create function');
134499 }
134500
134501 schemas = common.toArray(schemas);
134502 types = common.toArray(types);
134503
134504 if (!schemas.every(function (schema) {
134505 return schema instanceof Schema;
134506 })) {
134507 throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
134508 }
134509
134510 if (!types.every(function (type) {
134511 return type instanceof Type;
134512 })) {
134513 throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
134514 }
134515
134516 return new Schema({
134517 include: schemas,
134518 explicit: types
134519 });
134520};
134521
134522module.exports = Schema;
134523
134524/***/ }),
6a5a0f88 134525/* 857 */
eb39fafa
DC
134526/***/ (function(module, exports, __webpack_require__) {
134527
134528"use strict";
134529
134530
6a5a0f88 134531var YAMLException = __webpack_require__(853);
eb39fafa
DC
134532
134533var TYPE_CONSTRUCTOR_OPTIONS = ['kind', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'defaultStyle', 'styleAliases'];
134534var YAML_NODE_KINDS = ['scalar', 'sequence', 'mapping'];
134535
134536function compileStyleAliases(map) {
134537 var result = {};
134538
134539 if (map !== null) {
134540 Object.keys(map).forEach(function (style) {
134541 map[style].forEach(function (alias) {
134542 result[String(alias)] = style;
134543 });
134544 });
134545 }
134546
134547 return result;
134548}
134549
134550function Type(tag, options) {
134551 options = options || {};
134552 Object.keys(options).forEach(function (name) {
134553 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
134554 throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
134555 }
134556 }); // TODO: Add tag format check.
134557
134558 this.tag = tag;
134559 this.kind = options['kind'] || null;
134560
134561 this.resolve = options['resolve'] || function () {
134562 return true;
134563 };
134564
134565 this.construct = options['construct'] || function (data) {
134566 return data;
134567 };
134568
134569 this.instanceOf = options['instanceOf'] || null;
134570 this.predicate = options['predicate'] || null;
134571 this.represent = options['represent'] || null;
134572 this.defaultStyle = options['defaultStyle'] || null;
134573 this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
134574
134575 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
134576 throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
134577 }
134578}
134579
134580module.exports = Type;
134581
134582/***/ }),
6a5a0f88 134583/* 858 */
eb39fafa
DC
134584/***/ (function(module, exports, __webpack_require__) {
134585
134586"use strict";
134587// Standard YAML's Core schema.
134588// http://www.yaml.org/spec/1.2/spec.html#id2804923
134589//
134590// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
134591// So, Core schema has no distinctions from JSON schema is JS-YAML.
134592
134593
6a5a0f88 134594var Schema = __webpack_require__(856);
eb39fafa
DC
134595
134596module.exports = new Schema({
6a5a0f88 134597 include: [__webpack_require__(859)]
eb39fafa
DC
134598});
134599
134600/***/ }),
6a5a0f88 134601/* 859 */
eb39fafa
DC
134602/***/ (function(module, exports, __webpack_require__) {
134603
134604"use strict";
134605// Standard YAML's JSON schema.
134606// http://www.yaml.org/spec/1.2/spec.html#id2803231
134607//
134608// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
134609// So, this schema is not such strict as defined in the YAML specification.
134610// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
134611
134612
6a5a0f88 134613var Schema = __webpack_require__(856);
eb39fafa
DC
134614
134615module.exports = new Schema({
6a5a0f88
TL
134616 include: [__webpack_require__(860)],
134617 implicit: [__webpack_require__(864), __webpack_require__(865), __webpack_require__(866), __webpack_require__(867)]
eb39fafa
DC
134618});
134619
134620/***/ }),
6a5a0f88 134621/* 860 */
eb39fafa
DC
134622/***/ (function(module, exports, __webpack_require__) {
134623
134624"use strict";
134625// Standard YAML's Failsafe schema.
134626// http://www.yaml.org/spec/1.2/spec.html#id2802346
134627
134628
6a5a0f88 134629var Schema = __webpack_require__(856);
eb39fafa
DC
134630
134631module.exports = new Schema({
6a5a0f88 134632 explicit: [__webpack_require__(861), __webpack_require__(862), __webpack_require__(863)]
eb39fafa
DC
134633});
134634
134635/***/ }),
6a5a0f88 134636/* 861 */
eb39fafa
DC
134637/***/ (function(module, exports, __webpack_require__) {
134638
134639"use strict";
134640
134641
6a5a0f88 134642var Type = __webpack_require__(857);
eb39fafa
DC
134643
134644module.exports = new Type('tag:yaml.org,2002:str', {
134645 kind: 'scalar',
134646 construct: function construct(data) {
134647 return data !== null ? data : '';
134648 }
134649});
134650
134651/***/ }),
6a5a0f88 134652/* 862 */
eb39fafa
DC
134653/***/ (function(module, exports, __webpack_require__) {
134654
134655"use strict";
134656
134657
6a5a0f88 134658var Type = __webpack_require__(857);
eb39fafa
DC
134659
134660module.exports = new Type('tag:yaml.org,2002:seq', {
134661 kind: 'sequence',
134662 construct: function construct(data) {
134663 return data !== null ? data : [];
134664 }
134665});
134666
134667/***/ }),
6a5a0f88 134668/* 863 */
eb39fafa
DC
134669/***/ (function(module, exports, __webpack_require__) {
134670
134671"use strict";
134672
134673
6a5a0f88 134674var Type = __webpack_require__(857);
eb39fafa
DC
134675
134676module.exports = new Type('tag:yaml.org,2002:map', {
134677 kind: 'mapping',
134678 construct: function construct(data) {
134679 return data !== null ? data : {};
134680 }
134681});
134682
134683/***/ }),
6a5a0f88 134684/* 864 */
eb39fafa
DC
134685/***/ (function(module, exports, __webpack_require__) {
134686
134687"use strict";
134688
134689
6a5a0f88 134690var Type = __webpack_require__(857);
eb39fafa
DC
134691
134692function resolveYamlNull(data) {
134693 if (data === null) return true;
134694 var max = data.length;
134695 return max === 1 && data === '~' || max === 4 && (data === 'null' || data === 'Null' || data === 'NULL');
134696}
134697
134698function constructYamlNull() {
134699 return null;
134700}
134701
134702function isNull(object) {
134703 return object === null;
134704}
134705
134706module.exports = new Type('tag:yaml.org,2002:null', {
134707 kind: 'scalar',
134708 resolve: resolveYamlNull,
134709 construct: constructYamlNull,
134710 predicate: isNull,
134711 represent: {
134712 canonical: function canonical() {
134713 return '~';
134714 },
134715 lowercase: function lowercase() {
134716 return 'null';
134717 },
134718 uppercase: function uppercase() {
134719 return 'NULL';
134720 },
134721 camelcase: function camelcase() {
134722 return 'Null';
134723 }
134724 },
134725 defaultStyle: 'lowercase'
134726});
134727
134728/***/ }),
6a5a0f88 134729/* 865 */
eb39fafa
DC
134730/***/ (function(module, exports, __webpack_require__) {
134731
134732"use strict";
134733
134734
6a5a0f88 134735var Type = __webpack_require__(857);
eb39fafa
DC
134736
134737function resolveYamlBoolean(data) {
134738 if (data === null) return false;
134739 var max = data.length;
134740 return max === 4 && (data === 'true' || data === 'True' || data === 'TRUE') || max === 5 && (data === 'false' || data === 'False' || data === 'FALSE');
134741}
134742
134743function constructYamlBoolean(data) {
134744 return data === 'true' || data === 'True' || data === 'TRUE';
134745}
134746
134747function isBoolean(object) {
134748 return Object.prototype.toString.call(object) === '[object Boolean]';
134749}
134750
134751module.exports = new Type('tag:yaml.org,2002:bool', {
134752 kind: 'scalar',
134753 resolve: resolveYamlBoolean,
134754 construct: constructYamlBoolean,
134755 predicate: isBoolean,
134756 represent: {
134757 lowercase: function lowercase(object) {
134758 return object ? 'true' : 'false';
134759 },
134760 uppercase: function uppercase(object) {
134761 return object ? 'TRUE' : 'FALSE';
134762 },
134763 camelcase: function camelcase(object) {
134764 return object ? 'True' : 'False';
134765 }
134766 },
134767 defaultStyle: 'lowercase'
134768});
134769
134770/***/ }),
6a5a0f88 134771/* 866 */
eb39fafa
DC
134772/***/ (function(module, exports, __webpack_require__) {
134773
134774"use strict";
134775
134776
6a5a0f88 134777var common = __webpack_require__(852);
eb39fafa 134778
6a5a0f88 134779var Type = __webpack_require__(857);
eb39fafa
DC
134780
134781function isHexCode(c) {
134782 return 0x30
134783 /* 0 */
134784 <= c && c <= 0x39
134785 /* 9 */
134786 || 0x41
134787 /* A */
134788 <= c && c <= 0x46
134789 /* F */
134790 || 0x61
134791 /* a */
134792 <= c && c <= 0x66
134793 /* f */
134794 ;
134795}
134796
134797function isOctCode(c) {
134798 return 0x30
134799 /* 0 */
134800 <= c && c <= 0x37
134801 /* 7 */
134802 ;
134803}
134804
134805function isDecCode(c) {
134806 return 0x30
134807 /* 0 */
134808 <= c && c <= 0x39
134809 /* 9 */
134810 ;
134811}
134812
134813function resolveYamlInteger(data) {
134814 if (data === null) return false;
134815 var max = data.length,
134816 index = 0,
134817 hasDigits = false,
134818 ch;
134819 if (!max) return false;
134820 ch = data[index]; // sign
134821
134822 if (ch === '-' || ch === '+') {
134823 ch = data[++index];
134824 }
134825
134826 if (ch === '0') {
134827 // 0
134828 if (index + 1 === max) return true;
134829 ch = data[++index]; // base 2, base 8, base 16
134830
134831 if (ch === 'b') {
134832 // base 2
134833 index++;
134834
134835 for (; index < max; index++) {
134836 ch = data[index];
134837 if (ch === '_') continue;
134838 if (ch !== '0' && ch !== '1') return false;
134839 hasDigits = true;
134840 }
134841
134842 return hasDigits && ch !== '_';
134843 }
134844
134845 if (ch === 'x') {
134846 // base 16
134847 index++;
134848
134849 for (; index < max; index++) {
134850 ch = data[index];
134851 if (ch === '_') continue;
134852 if (!isHexCode(data.charCodeAt(index))) return false;
134853 hasDigits = true;
134854 }
134855
134856 return hasDigits && ch !== '_';
134857 } // base 8
134858
134859
134860 for (; index < max; index++) {
134861 ch = data[index];
134862 if (ch === '_') continue;
134863 if (!isOctCode(data.charCodeAt(index))) return false;
134864 hasDigits = true;
134865 }
134866
134867 return hasDigits && ch !== '_';
134868 } // base 10 (except 0) or base 60
134869 // value should not start with `_`;
134870
134871
134872 if (ch === '_') return false;
134873
134874 for (; index < max; index++) {
134875 ch = data[index];
134876 if (ch === '_') continue;
134877 if (ch === ':') break;
134878
134879 if (!isDecCode(data.charCodeAt(index))) {
134880 return false;
134881 }
134882
134883 hasDigits = true;
134884 } // Should have digits and should not end with `_`
134885
134886
134887 if (!hasDigits || ch === '_') return false; // if !base60 - done;
134888
134889 if (ch !== ':') return true; // base60 almost not used, no needs to optimize
134890
134891 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
134892}
134893
134894function constructYamlInteger(data) {
134895 var value = data,
134896 sign = 1,
134897 ch,
134898 base,
134899 digits = [];
134900
134901 if (value.indexOf('_') !== -1) {
134902 value = value.replace(/_/g, '');
134903 }
134904
134905 ch = value[0];
134906
134907 if (ch === '-' || ch === '+') {
134908 if (ch === '-') sign = -1;
134909 value = value.slice(1);
134910 ch = value[0];
134911 }
134912
134913 if (value === '0') return 0;
134914
134915 if (ch === '0') {
134916 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
134917 if (value[1] === 'x') return sign * parseInt(value, 16);
134918 return sign * parseInt(value, 8);
134919 }
134920
134921 if (value.indexOf(':') !== -1) {
134922 value.split(':').forEach(function (v) {
134923 digits.unshift(parseInt(v, 10));
134924 });
134925 value = 0;
134926 base = 1;
134927 digits.forEach(function (d) {
134928 value += d * base;
134929 base *= 60;
134930 });
134931 return sign * value;
134932 }
134933
134934 return sign * parseInt(value, 10);
134935}
134936
134937function isInteger(object) {
134938 return Object.prototype.toString.call(object) === '[object Number]' && object % 1 === 0 && !common.isNegativeZero(object);
134939}
134940
134941module.exports = new Type('tag:yaml.org,2002:int', {
134942 kind: 'scalar',
134943 resolve: resolveYamlInteger,
134944 construct: constructYamlInteger,
134945 predicate: isInteger,
134946 represent: {
134947 binary: function binary(obj) {
134948 return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1);
134949 },
134950 octal: function octal(obj) {
134951 return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1);
134952 },
134953 decimal: function decimal(obj) {
134954 return obj.toString(10);
134955 },
134956
134957 /* eslint-disable max-len */
134958 hexadecimal: function hexadecimal(obj) {
134959 return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1);
134960 }
134961 },
134962 defaultStyle: 'decimal',
134963 styleAliases: {
134964 binary: [2, 'bin'],
134965 octal: [8, 'oct'],
134966 decimal: [10, 'dec'],
134967 hexadecimal: [16, 'hex']
134968 }
134969});
134970
134971/***/ }),
6a5a0f88 134972/* 867 */
eb39fafa
DC
134973/***/ (function(module, exports, __webpack_require__) {
134974
134975"use strict";
134976
134977
6a5a0f88 134978var common = __webpack_require__(852);
eb39fafa 134979
6a5a0f88 134980var Type = __webpack_require__(857);
eb39fafa
DC
134981
134982var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers
134983'^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2
134984// special case, seems not from spec
134985'|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // 20:59
134986'|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + // .inf
134987'|[-+]?\\.(?:inf|Inf|INF)' + // .nan
134988'|\\.(?:nan|NaN|NAN))$');
134989
134990function resolveYamlFloat(data) {
134991 if (data === null) return false;
134992
134993 if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
134994 // Probably should update regexp & check speed
134995 data[data.length - 1] === '_') {
134996 return false;
134997 }
134998
134999 return true;
135000}
135001
135002function constructYamlFloat(data) {
135003 var value, sign, base, digits;
135004 value = data.replace(/_/g, '').toLowerCase();
135005 sign = value[0] === '-' ? -1 : 1;
135006 digits = [];
135007
135008 if ('+-'.indexOf(value[0]) >= 0) {
135009 value = value.slice(1);
135010 }
135011
135012 if (value === '.inf') {
135013 return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
135014 } else if (value === '.nan') {
135015 return NaN;
135016 } else if (value.indexOf(':') >= 0) {
135017 value.split(':').forEach(function (v) {
135018 digits.unshift(parseFloat(v, 10));
135019 });
135020 value = 0.0;
135021 base = 1;
135022 digits.forEach(function (d) {
135023 value += d * base;
135024 base *= 60;
135025 });
135026 return sign * value;
135027 }
135028
135029 return sign * parseFloat(value, 10);
135030}
135031
135032var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
135033
135034function representYamlFloat(object, style) {
135035 var res;
135036
135037 if (isNaN(object)) {
135038 switch (style) {
135039 case 'lowercase':
135040 return '.nan';
135041
135042 case 'uppercase':
135043 return '.NAN';
135044
135045 case 'camelcase':
135046 return '.NaN';
135047 }
135048 } else if (Number.POSITIVE_INFINITY === object) {
135049 switch (style) {
135050 case 'lowercase':
135051 return '.inf';
135052
135053 case 'uppercase':
135054 return '.INF';
135055
135056 case 'camelcase':
135057 return '.Inf';
135058 }
135059 } else if (Number.NEGATIVE_INFINITY === object) {
135060 switch (style) {
135061 case 'lowercase':
135062 return '-.inf';
135063
135064 case 'uppercase':
135065 return '-.INF';
135066
135067 case 'camelcase':
135068 return '-.Inf';
135069 }
135070 } else if (common.isNegativeZero(object)) {
135071 return '-0.0';
135072 }
135073
135074 res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100,
135075 // while YAML requres dot: 5.e-100. Fix it with simple hack
135076
135077 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
135078}
135079
135080function isFloat(object) {
135081 return Object.prototype.toString.call(object) === '[object Number]' && (object % 1 !== 0 || common.isNegativeZero(object));
135082}
135083
135084module.exports = new Type('tag:yaml.org,2002:float', {
135085 kind: 'scalar',
135086 resolve: resolveYamlFloat,
135087 construct: constructYamlFloat,
135088 predicate: isFloat,
135089 represent: representYamlFloat,
135090 defaultStyle: 'lowercase'
135091});
135092
135093/***/ }),
6a5a0f88 135094/* 868 */
eb39fafa
DC
135095/***/ (function(module, exports, __webpack_require__) {
135096
135097"use strict";
135098
135099
6a5a0f88 135100var Type = __webpack_require__(857);
eb39fafa
DC
135101
135102var YAML_DATE_REGEXP = new RegExp('^([0-9][0-9][0-9][0-9])' + // [1] year
135103'-([0-9][0-9])' + // [2] month
135104'-([0-9][0-9])$'); // [3] day
135105
135106var YAML_TIMESTAMP_REGEXP = new RegExp('^([0-9][0-9][0-9][0-9])' + // [1] year
135107'-([0-9][0-9]?)' + // [2] month
135108'-([0-9][0-9]?)' + // [3] day
135109'(?:[Tt]|[ \\t]+)' + // ...
135110'([0-9][0-9]?)' + // [4] hour
135111':([0-9][0-9])' + // [5] minute
135112':([0-9][0-9])' + // [6] second
135113'(?:\\.([0-9]*))?' + // [7] fraction
135114'(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
135115'(?::([0-9][0-9]))?))?$'); // [11] tz_minute
135116
135117function resolveYamlTimestamp(data) {
135118 if (data === null) return false;
135119 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
135120 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
135121 return false;
135122}
135123
135124function constructYamlTimestamp(data) {
135125 var match,
135126 year,
135127 month,
135128 day,
135129 hour,
135130 minute,
135131 second,
135132 fraction = 0,
135133 delta = null,
135134 tz_hour,
135135 tz_minute,
135136 date;
135137 match = YAML_DATE_REGEXP.exec(data);
135138 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
135139 if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day
135140
135141 year = +match[1];
135142 month = +match[2] - 1; // JS month starts with 0
135143
135144 day = +match[3];
135145
135146 if (!match[4]) {
135147 // no hour
135148 return new Date(Date.UTC(year, month, day));
135149 } // match: [4] hour [5] minute [6] second [7] fraction
135150
135151
135152 hour = +match[4];
135153 minute = +match[5];
135154 second = +match[6];
135155
135156 if (match[7]) {
135157 fraction = match[7].slice(0, 3);
135158
135159 while (fraction.length < 3) {
135160 // milli-seconds
135161 fraction += '0';
135162 }
135163
135164 fraction = +fraction;
135165 } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
135166
135167
135168 if (match[9]) {
135169 tz_hour = +match[10];
135170 tz_minute = +(match[11] || 0);
135171 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
135172
135173 if (match[9] === '-') delta = -delta;
135174 }
135175
135176 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
135177 if (delta) date.setTime(date.getTime() - delta);
135178 return date;
135179}
135180
135181function representYamlTimestamp(object
135182/*, style*/
135183) {
135184 return object.toISOString();
135185}
135186
135187module.exports = new Type('tag:yaml.org,2002:timestamp', {
135188 kind: 'scalar',
135189 resolve: resolveYamlTimestamp,
135190 construct: constructYamlTimestamp,
135191 instanceOf: Date,
135192 represent: representYamlTimestamp
135193});
135194
135195/***/ }),
6a5a0f88 135196/* 869 */
eb39fafa
DC
135197/***/ (function(module, exports, __webpack_require__) {
135198
135199"use strict";
135200
135201
6a5a0f88 135202var Type = __webpack_require__(857);
eb39fafa
DC
135203
135204function resolveYamlMerge(data) {
135205 return data === '<<' || data === null;
135206}
135207
135208module.exports = new Type('tag:yaml.org,2002:merge', {
135209 kind: 'scalar',
135210 resolve: resolveYamlMerge
135211});
135212
135213/***/ }),
6a5a0f88 135214/* 870 */
eb39fafa
DC
135215/***/ (function(module, exports, __webpack_require__) {
135216
135217"use strict";
135218var require;
135219/*eslint-disable no-bitwise*/
135220
135221var NodeBuffer;
135222
135223try {
135224 // A trick for browserified version, to not include `Buffer` shim
135225 var _require = require;
6a5a0f88 135226 NodeBuffer = __webpack_require__(871).Buffer;
eb39fafa
DC
135227} catch (__) {}
135228
6a5a0f88 135229var Type = __webpack_require__(857); // [ 64, 65, 66 ] -> [ padding, CR, LF ]
eb39fafa
DC
135230
135231
135232var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
135233
135234function resolveYamlBinary(data) {
135235 if (data === null) return false;
135236 var code,
135237 idx,
135238 bitlen = 0,
135239 max = data.length,
135240 map = BASE64_MAP; // Convert one by one.
135241
135242 for (idx = 0; idx < max; idx++) {
135243 code = map.indexOf(data.charAt(idx)); // Skip CR/LF
135244
135245 if (code > 64) continue; // Fail on illegal characters
135246
135247 if (code < 0) return false;
135248 bitlen += 6;
135249 } // If there are any bits left, source was corrupted
135250
135251
135252 return bitlen % 8 === 0;
135253}
135254
135255function constructYamlBinary(data) {
135256 var idx,
135257 tailbits,
135258 input = data.replace(/[\r\n=]/g, ''),
135259 // remove CR/LF & padding to simplify scan
135260 max = input.length,
135261 map = BASE64_MAP,
135262 bits = 0,
135263 result = []; // Collect by 6*4 bits (3 bytes)
135264
135265 for (idx = 0; idx < max; idx++) {
135266 if (idx % 4 === 0 && idx) {
135267 result.push(bits >> 16 & 0xFF);
135268 result.push(bits >> 8 & 0xFF);
135269 result.push(bits & 0xFF);
135270 }
135271
135272 bits = bits << 6 | map.indexOf(input.charAt(idx));
135273 } // Dump tail
135274
135275
135276 tailbits = max % 4 * 6;
135277
135278 if (tailbits === 0) {
135279 result.push(bits >> 16 & 0xFF);
135280 result.push(bits >> 8 & 0xFF);
135281 result.push(bits & 0xFF);
135282 } else if (tailbits === 18) {
135283 result.push(bits >> 10 & 0xFF);
135284 result.push(bits >> 2 & 0xFF);
135285 } else if (tailbits === 12) {
135286 result.push(bits >> 4 & 0xFF);
135287 } // Wrap into Buffer for NodeJS and leave Array for browser
135288
135289
135290 if (NodeBuffer) {
135291 // Support node 6.+ Buffer API when available
135292 return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
135293 }
135294
135295 return result;
135296}
135297
135298function representYamlBinary(object
135299/*, style*/
135300) {
135301 var result = '',
135302 bits = 0,
135303 idx,
135304 tail,
135305 max = object.length,
135306 map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters.
135307
135308 for (idx = 0; idx < max; idx++) {
135309 if (idx % 3 === 0 && idx) {
135310 result += map[bits >> 18 & 0x3F];
135311 result += map[bits >> 12 & 0x3F];
135312 result += map[bits >> 6 & 0x3F];
135313 result += map[bits & 0x3F];
135314 }
135315
135316 bits = (bits << 8) + object[idx];
135317 } // Dump tail
135318
135319
135320 tail = max % 3;
135321
135322 if (tail === 0) {
135323 result += map[bits >> 18 & 0x3F];
135324 result += map[bits >> 12 & 0x3F];
135325 result += map[bits >> 6 & 0x3F];
135326 result += map[bits & 0x3F];
135327 } else if (tail === 2) {
135328 result += map[bits >> 10 & 0x3F];
135329 result += map[bits >> 4 & 0x3F];
135330 result += map[bits << 2 & 0x3F];
135331 result += map[64];
135332 } else if (tail === 1) {
135333 result += map[bits >> 2 & 0x3F];
135334 result += map[bits << 4 & 0x3F];
135335 result += map[64];
135336 result += map[64];
135337 }
135338
135339 return result;
135340}
135341
135342function isBinary(object) {
135343 return NodeBuffer && NodeBuffer.isBuffer(object);
135344}
135345
135346module.exports = new Type('tag:yaml.org,2002:binary', {
135347 kind: 'scalar',
135348 resolve: resolveYamlBinary,
135349 construct: constructYamlBinary,
135350 predicate: isBinary,
135351 represent: representYamlBinary
135352});
135353
135354/***/ }),
6a5a0f88 135355/* 871 */
eb39fafa
DC
135356/***/ (function(module, exports) {
135357
135358module.exports = require("buffer");
135359
135360/***/ }),
6a5a0f88 135361/* 872 */
eb39fafa
DC
135362/***/ (function(module, exports, __webpack_require__) {
135363
135364"use strict";
135365
135366
6a5a0f88 135367var Type = __webpack_require__(857);
eb39fafa
DC
135368
135369var _hasOwnProperty = Object.prototype.hasOwnProperty;
135370var _toString = Object.prototype.toString;
135371
135372function resolveYamlOmap(data) {
135373 if (data === null) return true;
135374 var objectKeys = [],
135375 index,
135376 length,
135377 pair,
135378 pairKey,
135379 pairHasKey,
135380 object = data;
135381
135382 for (index = 0, length = object.length; index < length; index += 1) {
135383 pair = object[index];
135384 pairHasKey = false;
135385 if (_toString.call(pair) !== '[object Object]') return false;
135386
135387 for (pairKey in pair) {
135388 if (_hasOwnProperty.call(pair, pairKey)) {
135389 if (!pairHasKey) pairHasKey = true;else return false;
135390 }
135391 }
135392
135393 if (!pairHasKey) return false;
135394 if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);else return false;
135395 }
135396
135397 return true;
135398}
135399
135400function constructYamlOmap(data) {
135401 return data !== null ? data : [];
135402}
135403
135404module.exports = new Type('tag:yaml.org,2002:omap', {
135405 kind: 'sequence',
135406 resolve: resolveYamlOmap,
135407 construct: constructYamlOmap
135408});
135409
135410/***/ }),
6a5a0f88 135411/* 873 */
eb39fafa
DC
135412/***/ (function(module, exports, __webpack_require__) {
135413
135414"use strict";
135415
135416
6a5a0f88 135417var Type = __webpack_require__(857);
eb39fafa
DC
135418
135419var _toString = Object.prototype.toString;
135420
135421function resolveYamlPairs(data) {
135422 if (data === null) return true;
135423 var index,
135424 length,
135425 pair,
135426 keys,
135427 result,
135428 object = data;
135429 result = new Array(object.length);
135430
135431 for (index = 0, length = object.length; index < length; index += 1) {
135432 pair = object[index];
135433 if (_toString.call(pair) !== '[object Object]') return false;
135434 keys = Object.keys(pair);
135435 if (keys.length !== 1) return false;
135436 result[index] = [keys[0], pair[keys[0]]];
135437 }
135438
135439 return true;
135440}
135441
135442function constructYamlPairs(data) {
135443 if (data === null) return [];
135444 var index,
135445 length,
135446 pair,
135447 keys,
135448 result,
135449 object = data;
135450 result = new Array(object.length);
135451
135452 for (index = 0, length = object.length; index < length; index += 1) {
135453 pair = object[index];
135454 keys = Object.keys(pair);
135455 result[index] = [keys[0], pair[keys[0]]];
135456 }
135457
135458 return result;
135459}
135460
135461module.exports = new Type('tag:yaml.org,2002:pairs', {
135462 kind: 'sequence',
135463 resolve: resolveYamlPairs,
135464 construct: constructYamlPairs
135465});
135466
135467/***/ }),
6a5a0f88 135468/* 874 */
eb39fafa
DC
135469/***/ (function(module, exports, __webpack_require__) {
135470
135471"use strict";
135472
135473
6a5a0f88 135474var Type = __webpack_require__(857);
eb39fafa
DC
135475
135476var _hasOwnProperty = Object.prototype.hasOwnProperty;
135477
135478function resolveYamlSet(data) {
135479 if (data === null) return true;
135480 var key,
135481 object = data;
135482
135483 for (key in object) {
135484 if (_hasOwnProperty.call(object, key)) {
135485 if (object[key] !== null) return false;
135486 }
135487 }
135488
135489 return true;
135490}
135491
135492function constructYamlSet(data) {
135493 return data !== null ? data : {};
135494}
135495
135496module.exports = new Type('tag:yaml.org,2002:set', {
135497 kind: 'mapping',
135498 resolve: resolveYamlSet,
135499 construct: constructYamlSet
135500});
135501
135502/***/ }),
6a5a0f88 135503/* 875 */
eb39fafa
DC
135504/***/ (function(module, exports, __webpack_require__) {
135505
135506"use strict";
135507// JS-YAML's default schema for `load` function.
135508// It is not described in the YAML specification.
135509//
135510// This schema is based on JS-YAML's default safe schema and includes
135511// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
135512//
135513// Also this schema is used as default base schema at `Schema.create` function.
135514
135515
6a5a0f88 135516var Schema = __webpack_require__(856);
eb39fafa
DC
135517
135518module.exports = Schema.DEFAULT = new Schema({
6a5a0f88
TL
135519 include: [__webpack_require__(855)],
135520 explicit: [__webpack_require__(876), __webpack_require__(877), __webpack_require__(878)]
eb39fafa
DC
135521});
135522
135523/***/ }),
6a5a0f88 135524/* 876 */
eb39fafa
DC
135525/***/ (function(module, exports, __webpack_require__) {
135526
135527"use strict";
135528
135529
6a5a0f88 135530var Type = __webpack_require__(857);
eb39fafa
DC
135531
135532function resolveJavascriptUndefined() {
135533 return true;
135534}
135535
135536function constructJavascriptUndefined() {
135537 /*eslint-disable no-undefined*/
135538 return undefined;
135539}
135540
135541function representJavascriptUndefined() {
135542 return '';
135543}
135544
135545function isUndefined(object) {
135546 return typeof object === 'undefined';
135547}
135548
135549module.exports = new Type('tag:yaml.org,2002:js/undefined', {
135550 kind: 'scalar',
135551 resolve: resolveJavascriptUndefined,
135552 construct: constructJavascriptUndefined,
135553 predicate: isUndefined,
135554 represent: representJavascriptUndefined
135555});
135556
135557/***/ }),
6a5a0f88 135558/* 877 */
eb39fafa
DC
135559/***/ (function(module, exports, __webpack_require__) {
135560
135561"use strict";
135562
135563
6a5a0f88 135564var Type = __webpack_require__(857);
eb39fafa
DC
135565
135566function resolveJavascriptRegExp(data) {
135567 if (data === null) return false;
135568 if (data.length === 0) return false;
135569 var regexp = data,
135570 tail = /\/([gim]*)$/.exec(data),
135571 modifiers = ''; // if regexp starts with '/' it can have modifiers and must be properly closed
135572 // `/foo/gim` - modifiers tail can be maximum 3 chars
135573
135574 if (regexp[0] === '/') {
135575 if (tail) modifiers = tail[1];
135576 if (modifiers.length > 3) return false; // if expression starts with /, is should be properly terminated
135577
135578 if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
135579 }
135580
135581 return true;
135582}
135583
135584function constructJavascriptRegExp(data) {
135585 var regexp = data,
135586 tail = /\/([gim]*)$/.exec(data),
135587 modifiers = ''; // `/foo/gim` - tail can be maximum 4 chars
135588
135589 if (regexp[0] === '/') {
135590 if (tail) modifiers = tail[1];
135591 regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
135592 }
135593
135594 return new RegExp(regexp, modifiers);
135595}
135596
135597function representJavascriptRegExp(object
135598/*, style*/
135599) {
135600 var result = '/' + object.source + '/';
135601 if (object.global) result += 'g';
135602 if (object.multiline) result += 'm';
135603 if (object.ignoreCase) result += 'i';
135604 return result;
135605}
135606
135607function isRegExp(object) {
135608 return Object.prototype.toString.call(object) === '[object RegExp]';
135609}
135610
135611module.exports = new Type('tag:yaml.org,2002:js/regexp', {
135612 kind: 'scalar',
135613 resolve: resolveJavascriptRegExp,
135614 construct: constructJavascriptRegExp,
135615 predicate: isRegExp,
135616 represent: representJavascriptRegExp
135617});
135618
135619/***/ }),
6a5a0f88 135620/* 878 */
eb39fafa
DC
135621/***/ (function(module, exports, __webpack_require__) {
135622
135623"use strict";
135624var require;
135625
135626var esprima; // Browserified version does not have esprima
135627//
135628// 1. For node.js just require module as deps
135629// 2. For browser try to require mudule via external AMD system.
135630// If not found - try to fallback to window.esprima. If not
135631// found too - then fail to parse.
135632//
135633
135634try {
135635 // workaround to exclude package from browserify list.
135636 var _require = require;
6a5a0f88 135637 esprima = __webpack_require__(879);
eb39fafa 135638} catch (_) {
6a5a0f88
TL
135639 /* eslint-disable no-redeclare */
135640
135641 /* global window */
eb39fafa
DC
135642 if (typeof window !== 'undefined') esprima = window.esprima;
135643}
135644
6a5a0f88 135645var Type = __webpack_require__(857);
eb39fafa
DC
135646
135647function resolveJavascriptFunction(data) {
135648 if (data === null) return false;
135649
135650 try {
135651 var source = '(' + data + ')',
135652 ast = esprima.parse(source, {
135653 range: true
135654 });
135655
135656 if (ast.type !== 'Program' || ast.body.length !== 1 || ast.body[0].type !== 'ExpressionStatement' || ast.body[0].expression.type !== 'ArrowFunctionExpression' && ast.body[0].expression.type !== 'FunctionExpression') {
135657 return false;
135658 }
135659
135660 return true;
135661 } catch (err) {
135662 return false;
135663 }
135664}
135665
135666function constructJavascriptFunction(data) {
135667 /*jslint evil:true*/
135668 var source = '(' + data + ')',
135669 ast = esprima.parse(source, {
135670 range: true
135671 }),
135672 params = [],
135673 body;
135674
135675 if (ast.type !== 'Program' || ast.body.length !== 1 || ast.body[0].type !== 'ExpressionStatement' || ast.body[0].expression.type !== 'ArrowFunctionExpression' && ast.body[0].expression.type !== 'FunctionExpression') {
135676 throw new Error('Failed to resolve function');
135677 }
135678
135679 ast.body[0].expression.params.forEach(function (param) {
135680 params.push(param.name);
135681 });
135682 body = ast.body[0].expression.body.range; // Esprima's ranges include the first '{' and the last '}' characters on
135683 // function expressions. So cut them out.
135684
135685 if (ast.body[0].expression.body.type === 'BlockStatement') {
135686 /*eslint-disable no-new-func*/
135687 return new Function(params, source.slice(body[0] + 1, body[1] - 1));
135688 } // ES6 arrow functions can omit the BlockStatement. In that case, just return
135689 // the body.
135690
135691 /*eslint-disable no-new-func*/
135692
135693
135694 return new Function(params, 'return ' + source.slice(body[0], body[1]));
135695}
135696
135697function representJavascriptFunction(object
135698/*, style*/
135699) {
135700 return object.toString();
135701}
135702
135703function isFunction(object) {
135704 return Object.prototype.toString.call(object) === '[object Function]';
135705}
135706
135707module.exports = new Type('tag:yaml.org,2002:js/function', {
135708 kind: 'scalar',
135709 resolve: resolveJavascriptFunction,
135710 construct: constructJavascriptFunction,
135711 predicate: isFunction,
135712 represent: representJavascriptFunction
135713});
135714
135715/***/ }),
6a5a0f88 135716/* 879 */
eb39fafa
DC
135717/***/ (function(module, exports, __webpack_require__) {
135718
135719(function webpackUniversalModuleDefinition(root, factory) {
135720 /* istanbul ignore next */
135721 if (true) module.exports = factory();else {}
135722})(this, function () {
135723 return (
135724 /******/
135725 function (modules) {
135726 // webpackBootstrap
135727
135728 /******/
135729 // The module cache
135730
135731 /******/
135732 var installedModules = {};
135733 /******/
135734 // The require function
135735
135736 /******/
135737
135738 function __webpack_require__(moduleId) {
135739 /******/
135740 // Check if module is in cache
135741
135742 /* istanbul ignore if */
135743
135744 /******/
135745 if (installedModules[moduleId])
135746 /******/
135747 return installedModules[moduleId].exports;
135748 /******/
135749 // Create a new module (and put it into the cache)
135750
135751 /******/
135752
135753 var module = installedModules[moduleId] = {
135754 /******/
135755 exports: {},
135756
135757 /******/
135758 id: moduleId,
135759
135760 /******/
135761 loaded: false
135762 /******/
135763
135764 };
135765 /******/
135766 // Execute the module function
135767
135768 /******/
135769
135770 modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
135771 /******/
135772 // Flag the module as loaded
135773
135774 /******/
135775
135776 module.loaded = true;
135777 /******/
135778 // Return the exports of the module
135779
135780 /******/
135781
135782 return module.exports;
135783 /******/
135784 }
135785 /******/
135786 // expose the modules object (__webpack_modules__)
135787
135788 /******/
135789
135790
135791 __webpack_require__.m = modules;
135792 /******/
135793 // expose the module cache
135794
135795 /******/
135796
135797 __webpack_require__.c = installedModules;
135798 /******/
135799 // __webpack_public_path__
135800
135801 /******/
135802
135803 __webpack_require__.p = "";
135804 /******/
135805 // Load entry module and return exports
135806
135807 /******/
135808
135809 return __webpack_require__(0);
135810 /******/
135811 }(
135812 /************************************************************************/
135813
135814 /******/
135815 [
135816 /* 0 */
135817
135818 /***/
135819 function (module, exports, __webpack_require__) {
135820 "use strict";
135821 /*
135822 Copyright JS Foundation and other contributors, https://js.foundation/
135823 Redistribution and use in source and binary forms, with or without
135824 modification, are permitted provided that the following conditions are met:
135825 * Redistributions of source code must retain the above copyright
135826 notice, this list of conditions and the following disclaimer.
135827 * Redistributions in binary form must reproduce the above copyright
135828 notice, this list of conditions and the following disclaimer in the
135829 documentation and/or other materials provided with the distribution.
135830 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
135831 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
135832 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
135833 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
135834 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
135835 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
135836 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
135837 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
135838 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
135839 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
135840 */
135841
135842 Object.defineProperty(exports, "__esModule", {
135843 value: true
135844 });
135845
135846 var comment_handler_1 = __webpack_require__(1);
135847
135848 var jsx_parser_1 = __webpack_require__(3);
135849
135850 var parser_1 = __webpack_require__(8);
135851
135852 var tokenizer_1 = __webpack_require__(15);
135853
135854 function parse(code, options, delegate) {
135855 var commentHandler = null;
135856
135857 var proxyDelegate = function proxyDelegate(node, metadata) {
135858 if (delegate) {
135859 delegate(node, metadata);
135860 }
135861
135862 if (commentHandler) {
135863 commentHandler.visit(node, metadata);
135864 }
135865 };
135866
135867 var parserDelegate = typeof delegate === 'function' ? proxyDelegate : null;
135868 var collectComment = false;
135869
135870 if (options) {
135871 collectComment = typeof options.comment === 'boolean' && options.comment;
135872 var attachComment = typeof options.attachComment === 'boolean' && options.attachComment;
135873
135874 if (collectComment || attachComment) {
135875 commentHandler = new comment_handler_1.CommentHandler();
135876 commentHandler.attach = attachComment;
135877 options.comment = true;
135878 parserDelegate = proxyDelegate;
135879 }
135880 }
135881
135882 var isModule = false;
135883
135884 if (options && typeof options.sourceType === 'string') {
135885 isModule = options.sourceType === 'module';
135886 }
135887
135888 var parser;
135889
135890 if (options && typeof options.jsx === 'boolean' && options.jsx) {
135891 parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
135892 } else {
135893 parser = new parser_1.Parser(code, options, parserDelegate);
135894 }
135895
135896 var program = isModule ? parser.parseModule() : parser.parseScript();
135897 var ast = program;
135898
135899 if (collectComment && commentHandler) {
135900 ast.comments = commentHandler.comments;
135901 }
135902
135903 if (parser.config.tokens) {
135904 ast.tokens = parser.tokens;
135905 }
135906
135907 if (parser.config.tolerant) {
135908 ast.errors = parser.errorHandler.errors;
135909 }
135910
135911 return ast;
135912 }
135913
135914 exports.parse = parse;
135915
135916 function parseModule(code, options, delegate) {
135917 var parsingOptions = options || {};
135918 parsingOptions.sourceType = 'module';
135919 return parse(code, parsingOptions, delegate);
135920 }
135921
135922 exports.parseModule = parseModule;
135923
135924 function parseScript(code, options, delegate) {
135925 var parsingOptions = options || {};
135926 parsingOptions.sourceType = 'script';
135927 return parse(code, parsingOptions, delegate);
135928 }
135929
135930 exports.parseScript = parseScript;
135931
135932 function tokenize(code, options, delegate) {
135933 var tokenizer = new tokenizer_1.Tokenizer(code, options);
135934 var tokens;
135935 tokens = [];
135936
135937 try {
135938 while (true) {
135939 var token = tokenizer.getNextToken();
135940
135941 if (!token) {
135942 break;
135943 }
135944
135945 if (delegate) {
135946 token = delegate(token);
135947 }
135948
135949 tokens.push(token);
135950 }
135951 } catch (e) {
135952 tokenizer.errorHandler.tolerate(e);
135953 }
135954
135955 if (tokenizer.errorHandler.tolerant) {
135956 tokens.errors = tokenizer.errors();
135957 }
135958
135959 return tokens;
135960 }
135961
135962 exports.tokenize = tokenize;
135963
135964 var syntax_1 = __webpack_require__(2);
135965
135966 exports.Syntax = syntax_1.Syntax; // Sync with *.json manifests.
135967
135968 exports.version = '4.0.1';
135969 /***/
135970 },
135971 /* 1 */
135972
135973 /***/
135974 function (module, exports, __webpack_require__) {
135975 "use strict";
135976
135977 Object.defineProperty(exports, "__esModule", {
135978 value: true
135979 });
135980
135981 var syntax_1 = __webpack_require__(2);
135982
135983 var CommentHandler = function () {
135984 function CommentHandler() {
135985 this.attach = false;
135986 this.comments = [];
135987 this.stack = [];
135988 this.leading = [];
135989 this.trailing = [];
135990 }
135991
135992 CommentHandler.prototype.insertInnerComments = function (node, metadata) {
135993 // innnerComments for properties empty block
135994 // `function a() {/** comments **\/}`
135995 if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
135996 var innerComments = [];
135997
135998 for (var i = this.leading.length - 1; i >= 0; --i) {
135999 var entry = this.leading[i];
136000
136001 if (metadata.end.offset >= entry.start) {
136002 innerComments.unshift(entry.comment);
136003 this.leading.splice(i, 1);
136004 this.trailing.splice(i, 1);
136005 }
136006 }
136007
136008 if (innerComments.length) {
136009 node.innerComments = innerComments;
136010 }
136011 }
136012 };
136013
136014 CommentHandler.prototype.findTrailingComments = function (metadata) {
136015 var trailingComments = [];
136016
136017 if (this.trailing.length > 0) {
136018 for (var i = this.trailing.length - 1; i >= 0; --i) {
136019 var entry_1 = this.trailing[i];
136020
136021 if (entry_1.start >= metadata.end.offset) {
136022 trailingComments.unshift(entry_1.comment);
136023 }
136024 }
136025
136026 this.trailing.length = 0;
136027 return trailingComments;
136028 }
136029
136030 var entry = this.stack[this.stack.length - 1];
136031
136032 if (entry && entry.node.trailingComments) {
136033 var firstComment = entry.node.trailingComments[0];
136034
136035 if (firstComment && firstComment.range[0] >= metadata.end.offset) {
136036 trailingComments = entry.node.trailingComments;
136037 delete entry.node.trailingComments;
136038 }
136039 }
136040
136041 return trailingComments;
136042 };
136043
136044 CommentHandler.prototype.findLeadingComments = function (metadata) {
136045 var leadingComments = [];
136046 var target;
136047
136048 while (this.stack.length > 0) {
136049 var entry = this.stack[this.stack.length - 1];
136050
136051 if (entry && entry.start >= metadata.start.offset) {
136052 target = entry.node;
136053 this.stack.pop();
136054 } else {
136055 break;
136056 }
136057 }
136058
136059 if (target) {
136060 var count = target.leadingComments ? target.leadingComments.length : 0;
136061
136062 for (var i = count - 1; i >= 0; --i) {
136063 var comment = target.leadingComments[i];
136064
136065 if (comment.range[1] <= metadata.start.offset) {
136066 leadingComments.unshift(comment);
136067 target.leadingComments.splice(i, 1);
136068 }
136069 }
136070
136071 if (target.leadingComments && target.leadingComments.length === 0) {
136072 delete target.leadingComments;
136073 }
136074
136075 return leadingComments;
136076 }
136077
136078 for (var i = this.leading.length - 1; i >= 0; --i) {
136079 var entry = this.leading[i];
136080
136081 if (entry.start <= metadata.start.offset) {
136082 leadingComments.unshift(entry.comment);
136083 this.leading.splice(i, 1);
136084 }
136085 }
136086
136087 return leadingComments;
136088 };
136089
136090 CommentHandler.prototype.visitNode = function (node, metadata) {
136091 if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
136092 return;
136093 }
136094
136095 this.insertInnerComments(node, metadata);
136096 var trailingComments = this.findTrailingComments(metadata);
136097 var leadingComments = this.findLeadingComments(metadata);
136098
136099 if (leadingComments.length > 0) {
136100 node.leadingComments = leadingComments;
136101 }
136102
136103 if (trailingComments.length > 0) {
136104 node.trailingComments = trailingComments;
136105 }
136106
136107 this.stack.push({
136108 node: node,
136109 start: metadata.start.offset
136110 });
136111 };
136112
136113 CommentHandler.prototype.visitComment = function (node, metadata) {
136114 var type = node.type[0] === 'L' ? 'Line' : 'Block';
136115 var comment = {
136116 type: type,
136117 value: node.value
136118 };
136119
136120 if (node.range) {
136121 comment.range = node.range;
136122 }
136123
136124 if (node.loc) {
136125 comment.loc = node.loc;
136126 }
136127
136128 this.comments.push(comment);
136129
136130 if (this.attach) {
136131 var entry = {
136132 comment: {
136133 type: type,
136134 value: node.value,
136135 range: [metadata.start.offset, metadata.end.offset]
136136 },
136137 start: metadata.start.offset
136138 };
136139
136140 if (node.loc) {
136141 entry.comment.loc = node.loc;
136142 }
136143
136144 node.type = type;
136145 this.leading.push(entry);
136146 this.trailing.push(entry);
136147 }
136148 };
136149
136150 CommentHandler.prototype.visit = function (node, metadata) {
136151 if (node.type === 'LineComment') {
136152 this.visitComment(node, metadata);
136153 } else if (node.type === 'BlockComment') {
136154 this.visitComment(node, metadata);
136155 } else if (this.attach) {
136156 this.visitNode(node, metadata);
136157 }
136158 };
136159
136160 return CommentHandler;
136161 }();
136162
136163 exports.CommentHandler = CommentHandler;
136164 /***/
136165 },
136166 /* 2 */
136167
136168 /***/
136169 function (module, exports) {
136170 "use strict";
136171
136172 Object.defineProperty(exports, "__esModule", {
136173 value: true
136174 });
136175 exports.Syntax = {
136176 AssignmentExpression: 'AssignmentExpression',
136177 AssignmentPattern: 'AssignmentPattern',
136178 ArrayExpression: 'ArrayExpression',
136179 ArrayPattern: 'ArrayPattern',
136180 ArrowFunctionExpression: 'ArrowFunctionExpression',
136181 AwaitExpression: 'AwaitExpression',
136182 BlockStatement: 'BlockStatement',
136183 BinaryExpression: 'BinaryExpression',
136184 BreakStatement: 'BreakStatement',
136185 CallExpression: 'CallExpression',
136186 CatchClause: 'CatchClause',
136187 ClassBody: 'ClassBody',
136188 ClassDeclaration: 'ClassDeclaration',
136189 ClassExpression: 'ClassExpression',
136190 ConditionalExpression: 'ConditionalExpression',
136191 ContinueStatement: 'ContinueStatement',
136192 DoWhileStatement: 'DoWhileStatement',
136193 DebuggerStatement: 'DebuggerStatement',
136194 EmptyStatement: 'EmptyStatement',
136195 ExportAllDeclaration: 'ExportAllDeclaration',
136196 ExportDefaultDeclaration: 'ExportDefaultDeclaration',
136197 ExportNamedDeclaration: 'ExportNamedDeclaration',
136198 ExportSpecifier: 'ExportSpecifier',
136199 ExpressionStatement: 'ExpressionStatement',
136200 ForStatement: 'ForStatement',
136201 ForOfStatement: 'ForOfStatement',
136202 ForInStatement: 'ForInStatement',
136203 FunctionDeclaration: 'FunctionDeclaration',
136204 FunctionExpression: 'FunctionExpression',
136205 Identifier: 'Identifier',
136206 IfStatement: 'IfStatement',
136207 ImportDeclaration: 'ImportDeclaration',
136208 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
136209 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
136210 ImportSpecifier: 'ImportSpecifier',
136211 Literal: 'Literal',
136212 LabeledStatement: 'LabeledStatement',
136213 LogicalExpression: 'LogicalExpression',
136214 MemberExpression: 'MemberExpression',
136215 MetaProperty: 'MetaProperty',
136216 MethodDefinition: 'MethodDefinition',
136217 NewExpression: 'NewExpression',
136218 ObjectExpression: 'ObjectExpression',
136219 ObjectPattern: 'ObjectPattern',
136220 Program: 'Program',
136221 Property: 'Property',
136222 RestElement: 'RestElement',
136223 ReturnStatement: 'ReturnStatement',
136224 SequenceExpression: 'SequenceExpression',
136225 SpreadElement: 'SpreadElement',
136226 Super: 'Super',
136227 SwitchCase: 'SwitchCase',
136228 SwitchStatement: 'SwitchStatement',
136229 TaggedTemplateExpression: 'TaggedTemplateExpression',
136230 TemplateElement: 'TemplateElement',
136231 TemplateLiteral: 'TemplateLiteral',
136232 ThisExpression: 'ThisExpression',
136233 ThrowStatement: 'ThrowStatement',
136234 TryStatement: 'TryStatement',
136235 UnaryExpression: 'UnaryExpression',
136236 UpdateExpression: 'UpdateExpression',
136237 VariableDeclaration: 'VariableDeclaration',
136238 VariableDeclarator: 'VariableDeclarator',
136239 WhileStatement: 'WhileStatement',
136240 WithStatement: 'WithStatement',
136241 YieldExpression: 'YieldExpression'
136242 };
136243 /***/
136244 },
136245 /* 3 */
136246
136247 /***/
136248 function (module, exports, __webpack_require__) {
136249 "use strict";
136250 /* istanbul ignore next */
136251
136252 var __extends = this && this.__extends || function () {
136253 var extendStatics = Object.setPrototypeOf || {
136254 __proto__: []
136255 } instanceof Array && function (d, b) {
136256 d.__proto__ = b;
136257 } || function (d, b) {
136258 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
136259 };
136260
136261 return function (d, b) {
136262 extendStatics(d, b);
136263
136264 function __() {
136265 this.constructor = d;
136266 }
136267
136268 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
136269 };
136270 }();
136271
136272 Object.defineProperty(exports, "__esModule", {
136273 value: true
136274 });
136275
136276 var character_1 = __webpack_require__(4);
136277
136278 var JSXNode = __webpack_require__(5);
136279
136280 var jsx_syntax_1 = __webpack_require__(6);
136281
136282 var Node = __webpack_require__(7);
136283
136284 var parser_1 = __webpack_require__(8);
136285
136286 var token_1 = __webpack_require__(13);
136287
136288 var xhtml_entities_1 = __webpack_require__(14);
136289
136290 token_1.TokenName[100
136291 /* Identifier */
136292 ] = 'JSXIdentifier';
136293 token_1.TokenName[101
136294 /* Text */
136295 ] = 'JSXText'; // Fully qualified element name, e.g. <svg:path> returns "svg:path"
136296
136297 function getQualifiedElementName(elementName) {
136298 var qualifiedName;
136299
136300 switch (elementName.type) {
136301 case jsx_syntax_1.JSXSyntax.JSXIdentifier:
136302 var id = elementName;
136303 qualifiedName = id.name;
136304 break;
136305
136306 case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
136307 var ns = elementName;
136308 qualifiedName = getQualifiedElementName(ns.namespace) + ':' + getQualifiedElementName(ns.name);
136309 break;
136310
136311 case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
136312 var expr = elementName;
136313 qualifiedName = getQualifiedElementName(expr.object) + '.' + getQualifiedElementName(expr.property);
136314 break;
136315
136316 /* istanbul ignore next */
136317
136318 default:
136319 break;
136320 }
136321
136322 return qualifiedName;
136323 }
136324
136325 var JSXParser = function (_super) {
136326 __extends(JSXParser, _super);
136327
136328 function JSXParser(code, options, delegate) {
136329 return _super.call(this, code, options, delegate) || this;
136330 }
136331
136332 JSXParser.prototype.parsePrimaryExpression = function () {
136333 return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
136334 };
136335
136336 JSXParser.prototype.startJSX = function () {
136337 // Unwind the scanner before the lookahead token.
136338 this.scanner.index = this.startMarker.index;
136339 this.scanner.lineNumber = this.startMarker.line;
136340 this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
136341 };
136342
136343 JSXParser.prototype.finishJSX = function () {
136344 // Prime the next lookahead.
136345 this.nextToken();
136346 };
136347
136348 JSXParser.prototype.reenterJSX = function () {
136349 this.startJSX();
136350 this.expectJSX('}'); // Pop the closing '}' added from the lookahead.
136351
136352 if (this.config.tokens) {
136353 this.tokens.pop();
136354 }
136355 };
136356
136357 JSXParser.prototype.createJSXNode = function () {
136358 this.collectComments();
136359 return {
136360 index: this.scanner.index,
136361 line: this.scanner.lineNumber,
136362 column: this.scanner.index - this.scanner.lineStart
136363 };
136364 };
136365
136366 JSXParser.prototype.createJSXChildNode = function () {
136367 return {
136368 index: this.scanner.index,
136369 line: this.scanner.lineNumber,
136370 column: this.scanner.index - this.scanner.lineStart
136371 };
136372 };
136373
136374 JSXParser.prototype.scanXHTMLEntity = function (quote) {
136375 var result = '&';
136376 var valid = true;
136377 var terminated = false;
136378 var numeric = false;
136379 var hex = false;
136380
136381 while (!this.scanner.eof() && valid && !terminated) {
136382 var ch = this.scanner.source[this.scanner.index];
136383
136384 if (ch === quote) {
136385 break;
136386 }
136387
136388 terminated = ch === ';';
136389 result += ch;
136390 ++this.scanner.index;
136391
136392 if (!terminated) {
136393 switch (result.length) {
136394 case 2:
136395 // e.g. '&#123;'
136396 numeric = ch === '#';
136397 break;
136398
136399 case 3:
136400 if (numeric) {
136401 // e.g. '&#x41;'
136402 hex = ch === 'x';
136403 valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
136404 numeric = numeric && !hex;
136405 }
136406
136407 break;
136408
136409 default:
136410 valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
136411 valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
136412 break;
136413 }
136414 }
136415 }
136416
136417 if (valid && terminated && result.length > 2) {
136418 // e.g. '&#x41;' becomes just '#x41'
136419 var str = result.substr(1, result.length - 2);
136420
136421 if (numeric && str.length > 1) {
136422 result = String.fromCharCode(parseInt(str.substr(1), 10));
136423 } else if (hex && str.length > 2) {
136424 result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
136425 } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
136426 result = xhtml_entities_1.XHTMLEntities[str];
136427 }
136428 }
136429
136430 return result;
136431 }; // Scan the next JSX token. This replaces Scanner#lex when in JSX mode.
136432
136433
136434 JSXParser.prototype.lexJSX = function () {
136435 var cp = this.scanner.source.charCodeAt(this.scanner.index); // < > / : = { }
136436
136437 if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
136438 var value = this.scanner.source[this.scanner.index++];
136439 return {
136440 type: 7
136441 /* Punctuator */
136442 ,
136443 value: value,
136444 lineNumber: this.scanner.lineNumber,
136445 lineStart: this.scanner.lineStart,
136446 start: this.scanner.index - 1,
136447 end: this.scanner.index
136448 };
136449 } // " '
136450
136451
136452 if (cp === 34 || cp === 39) {
136453 var start = this.scanner.index;
136454 var quote = this.scanner.source[this.scanner.index++];
136455 var str = '';
136456
136457 while (!this.scanner.eof()) {
136458 var ch = this.scanner.source[this.scanner.index++];
136459
136460 if (ch === quote) {
136461 break;
136462 } else if (ch === '&') {
136463 str += this.scanXHTMLEntity(quote);
136464 } else {
136465 str += ch;
136466 }
136467 }
136468
136469 return {
136470 type: 8
136471 /* StringLiteral */
136472 ,
136473 value: str,
136474 lineNumber: this.scanner.lineNumber,
136475 lineStart: this.scanner.lineStart,
136476 start: start,
136477 end: this.scanner.index
136478 };
136479 } // ... or .
136480
136481
136482 if (cp === 46) {
136483 var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
136484 var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
136485 var value = n1 === 46 && n2 === 46 ? '...' : '.';
136486 var start = this.scanner.index;
136487 this.scanner.index += value.length;
136488 return {
136489 type: 7
136490 /* Punctuator */
136491 ,
136492 value: value,
136493 lineNumber: this.scanner.lineNumber,
136494 lineStart: this.scanner.lineStart,
136495 start: start,
136496 end: this.scanner.index
136497 };
136498 } // `
136499
136500
136501 if (cp === 96) {
136502 // Only placeholder, since it will be rescanned as a real assignment expression.
136503 return {
136504 type: 10
136505 /* Template */
136506 ,
136507 value: '',
136508 lineNumber: this.scanner.lineNumber,
136509 lineStart: this.scanner.lineStart,
136510 start: this.scanner.index,
136511 end: this.scanner.index
136512 };
136513 } // Identifer can not contain backslash (char code 92).
136514
136515
136516 if (character_1.Character.isIdentifierStart(cp) && cp !== 92) {
136517 var start = this.scanner.index;
136518 ++this.scanner.index;
136519
136520 while (!this.scanner.eof()) {
136521 var ch = this.scanner.source.charCodeAt(this.scanner.index);
136522
136523 if (character_1.Character.isIdentifierPart(ch) && ch !== 92) {
136524 ++this.scanner.index;
136525 } else if (ch === 45) {
136526 // Hyphen (char code 45) can be part of an identifier.
136527 ++this.scanner.index;
136528 } else {
136529 break;
136530 }
136531 }
136532
136533 var id = this.scanner.source.slice(start, this.scanner.index);
136534 return {
136535 type: 100
136536 /* Identifier */
136537 ,
136538 value: id,
136539 lineNumber: this.scanner.lineNumber,
136540 lineStart: this.scanner.lineStart,
136541 start: start,
136542 end: this.scanner.index
136543 };
136544 }
136545
136546 return this.scanner.lex();
136547 };
136548
136549 JSXParser.prototype.nextJSXToken = function () {
136550 this.collectComments();
136551 this.startMarker.index = this.scanner.index;
136552 this.startMarker.line = this.scanner.lineNumber;
136553 this.startMarker.column = this.scanner.index - this.scanner.lineStart;
136554 var token = this.lexJSX();
136555 this.lastMarker.index = this.scanner.index;
136556 this.lastMarker.line = this.scanner.lineNumber;
136557 this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
136558
136559 if (this.config.tokens) {
136560 this.tokens.push(this.convertToken(token));
136561 }
136562
136563 return token;
136564 };
136565
136566 JSXParser.prototype.nextJSXText = function () {
136567 this.startMarker.index = this.scanner.index;
136568 this.startMarker.line = this.scanner.lineNumber;
136569 this.startMarker.column = this.scanner.index - this.scanner.lineStart;
136570 var start = this.scanner.index;
136571 var text = '';
136572
136573 while (!this.scanner.eof()) {
136574 var ch = this.scanner.source[this.scanner.index];
136575
136576 if (ch === '{' || ch === '<') {
136577 break;
136578 }
136579
136580 ++this.scanner.index;
136581 text += ch;
136582
136583 if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
136584 ++this.scanner.lineNumber;
136585
136586 if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') {
136587 ++this.scanner.index;
136588 }
136589
136590 this.scanner.lineStart = this.scanner.index;
136591 }
136592 }
136593
136594 this.lastMarker.index = this.scanner.index;
136595 this.lastMarker.line = this.scanner.lineNumber;
136596 this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
136597 var token = {
136598 type: 101
136599 /* Text */
136600 ,
136601 value: text,
136602 lineNumber: this.scanner.lineNumber,
136603 lineStart: this.scanner.lineStart,
136604 start: start,
136605 end: this.scanner.index
136606 };
136607
136608 if (text.length > 0 && this.config.tokens) {
136609 this.tokens.push(this.convertToken(token));
136610 }
136611
136612 return token;
136613 };
136614
136615 JSXParser.prototype.peekJSXToken = function () {
136616 var state = this.scanner.saveState();
136617 this.scanner.scanComments();
136618 var next = this.lexJSX();
136619 this.scanner.restoreState(state);
136620 return next;
136621 }; // Expect the next JSX token to match the specified punctuator.
136622 // If not, an exception will be thrown.
136623
136624
136625 JSXParser.prototype.expectJSX = function (value) {
136626 var token = this.nextJSXToken();
136627
136628 if (token.type !== 7
136629 /* Punctuator */
136630 || token.value !== value) {
136631 this.throwUnexpectedToken(token);
136632 }
136633 }; // Return true if the next JSX token matches the specified punctuator.
136634
136635
136636 JSXParser.prototype.matchJSX = function (value) {
136637 var next = this.peekJSXToken();
136638 return next.type === 7
136639 /* Punctuator */
136640 && next.value === value;
136641 };
136642
136643 JSXParser.prototype.parseJSXIdentifier = function () {
136644 var node = this.createJSXNode();
136645 var token = this.nextJSXToken();
136646
136647 if (token.type !== 100
136648 /* Identifier */
136649 ) {
136650 this.throwUnexpectedToken(token);
136651 }
136652
136653 return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
136654 };
136655
136656 JSXParser.prototype.parseJSXElementName = function () {
136657 var node = this.createJSXNode();
136658 var elementName = this.parseJSXIdentifier();
136659
136660 if (this.matchJSX(':')) {
136661 var namespace = elementName;
136662 this.expectJSX(':');
136663 var name_1 = this.parseJSXIdentifier();
136664 elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
136665 } else if (this.matchJSX('.')) {
136666 while (this.matchJSX('.')) {
136667 var object = elementName;
136668 this.expectJSX('.');
136669 var property = this.parseJSXIdentifier();
136670 elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
136671 }
136672 }
136673
136674 return elementName;
136675 };
136676
136677 JSXParser.prototype.parseJSXAttributeName = function () {
136678 var node = this.createJSXNode();
136679 var attributeName;
136680 var identifier = this.parseJSXIdentifier();
136681
136682 if (this.matchJSX(':')) {
136683 var namespace = identifier;
136684 this.expectJSX(':');
136685 var name_2 = this.parseJSXIdentifier();
136686 attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
136687 } else {
136688 attributeName = identifier;
136689 }
136690
136691 return attributeName;
136692 };
136693
136694 JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
136695 var node = this.createJSXNode();
136696 var token = this.nextJSXToken();
136697
136698 if (token.type !== 8
136699 /* StringLiteral */
136700 ) {
136701 this.throwUnexpectedToken(token);
136702 }
136703
136704 var raw = this.getTokenRaw(token);
136705 return this.finalize(node, new Node.Literal(token.value, raw));
136706 };
136707
136708 JSXParser.prototype.parseJSXExpressionAttribute = function () {
136709 var node = this.createJSXNode();
136710 this.expectJSX('{');
136711 this.finishJSX();
136712
136713 if (this.match('}')) {
136714 this.tolerateError('JSX attributes must only be assigned a non-empty expression');
136715 }
136716
136717 var expression = this.parseAssignmentExpression();
136718 this.reenterJSX();
136719 return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
136720 };
136721
136722 JSXParser.prototype.parseJSXAttributeValue = function () {
136723 return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
136724 };
136725
136726 JSXParser.prototype.parseJSXNameValueAttribute = function () {
136727 var node = this.createJSXNode();
136728 var name = this.parseJSXAttributeName();
136729 var value = null;
136730
136731 if (this.matchJSX('=')) {
136732 this.expectJSX('=');
136733 value = this.parseJSXAttributeValue();
136734 }
136735
136736 return this.finalize(node, new JSXNode.JSXAttribute(name, value));
136737 };
136738
136739 JSXParser.prototype.parseJSXSpreadAttribute = function () {
136740 var node = this.createJSXNode();
136741 this.expectJSX('{');
136742 this.expectJSX('...');
136743 this.finishJSX();
136744 var argument = this.parseAssignmentExpression();
136745 this.reenterJSX();
136746 return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
136747 };
136748
136749 JSXParser.prototype.parseJSXAttributes = function () {
136750 var attributes = [];
136751
136752 while (!this.matchJSX('/') && !this.matchJSX('>')) {
136753 var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute();
136754 attributes.push(attribute);
136755 }
136756
136757 return attributes;
136758 };
136759
136760 JSXParser.prototype.parseJSXOpeningElement = function () {
136761 var node = this.createJSXNode();
136762 this.expectJSX('<');
136763 var name = this.parseJSXElementName();
136764 var attributes = this.parseJSXAttributes();
136765 var selfClosing = this.matchJSX('/');
136766
136767 if (selfClosing) {
136768 this.expectJSX('/');
136769 }
136770
136771 this.expectJSX('>');
136772 return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
136773 };
136774
136775 JSXParser.prototype.parseJSXBoundaryElement = function () {
136776 var node = this.createJSXNode();
136777 this.expectJSX('<');
136778
136779 if (this.matchJSX('/')) {
136780 this.expectJSX('/');
136781 var name_3 = this.parseJSXElementName();
136782 this.expectJSX('>');
136783 return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
136784 }
136785
136786 var name = this.parseJSXElementName();
136787 var attributes = this.parseJSXAttributes();
136788 var selfClosing = this.matchJSX('/');
136789
136790 if (selfClosing) {
136791 this.expectJSX('/');
136792 }
136793
136794 this.expectJSX('>');
136795 return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
136796 };
136797
136798 JSXParser.prototype.parseJSXEmptyExpression = function () {
136799 var node = this.createJSXChildNode();
136800 this.collectComments();
136801 this.lastMarker.index = this.scanner.index;
136802 this.lastMarker.line = this.scanner.lineNumber;
136803 this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
136804 return this.finalize(node, new JSXNode.JSXEmptyExpression());
136805 };
136806
136807 JSXParser.prototype.parseJSXExpressionContainer = function () {
136808 var node = this.createJSXNode();
136809 this.expectJSX('{');
136810 var expression;
136811
136812 if (this.matchJSX('}')) {
136813 expression = this.parseJSXEmptyExpression();
136814 this.expectJSX('}');
136815 } else {
136816 this.finishJSX();
136817 expression = this.parseAssignmentExpression();
136818 this.reenterJSX();
136819 }
136820
136821 return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
136822 };
136823
136824 JSXParser.prototype.parseJSXChildren = function () {
136825 var children = [];
136826
136827 while (!this.scanner.eof()) {
136828 var node = this.createJSXChildNode();
136829 var token = this.nextJSXText();
136830
136831 if (token.start < token.end) {
136832 var raw = this.getTokenRaw(token);
136833 var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
136834 children.push(child);
136835 }
136836
136837 if (this.scanner.source[this.scanner.index] === '{') {
136838 var container = this.parseJSXExpressionContainer();
136839 children.push(container);
136840 } else {
136841 break;
136842 }
136843 }
136844
136845 return children;
136846 };
136847
136848 JSXParser.prototype.parseComplexJSXElement = function (el) {
136849 var stack = [];
136850
136851 while (!this.scanner.eof()) {
136852 el.children = el.children.concat(this.parseJSXChildren());
136853 var node = this.createJSXChildNode();
136854 var element = this.parseJSXBoundaryElement();
136855
136856 if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
136857 var opening = element;
136858
136859 if (opening.selfClosing) {
136860 var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
136861 el.children.push(child);
136862 } else {
136863 stack.push(el);
136864 el = {
136865 node: node,
136866 opening: opening,
136867 closing: null,
136868 children: []
136869 };
136870 }
136871 }
136872
136873 if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
136874 el.closing = element;
136875 var open_1 = getQualifiedElementName(el.opening.name);
136876 var close_1 = getQualifiedElementName(el.closing.name);
136877
136878 if (open_1 !== close_1) {
136879 this.tolerateError('Expected corresponding JSX closing tag for %0', open_1);
136880 }
136881
136882 if (stack.length > 0) {
136883 var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
136884 el = stack[stack.length - 1];
136885 el.children.push(child);
136886 stack.pop();
136887 } else {
136888 break;
136889 }
136890 }
136891 }
136892
136893 return el;
136894 };
136895
136896 JSXParser.prototype.parseJSXElement = function () {
136897 var node = this.createJSXNode();
136898 var opening = this.parseJSXOpeningElement();
136899 var children = [];
136900 var closing = null;
136901
136902 if (!opening.selfClosing) {
136903 var el = this.parseComplexJSXElement({
136904 node: node,
136905 opening: opening,
136906 closing: closing,
136907 children: children
136908 });
136909 children = el.children;
136910 closing = el.closing;
136911 }
136912
136913 return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
136914 };
136915
136916 JSXParser.prototype.parseJSXRoot = function () {
136917 // Pop the opening '<' added from the lookahead.
136918 if (this.config.tokens) {
136919 this.tokens.pop();
136920 }
136921
136922 this.startJSX();
136923 var element = this.parseJSXElement();
136924 this.finishJSX();
136925 return element;
136926 };
136927
136928 JSXParser.prototype.isStartOfExpression = function () {
136929 return _super.prototype.isStartOfExpression.call(this) || this.match('<');
136930 };
136931
136932 return JSXParser;
136933 }(parser_1.Parser);
136934
136935 exports.JSXParser = JSXParser;
136936 /***/
136937 },
136938 /* 4 */
136939
136940 /***/
136941 function (module, exports) {
136942 "use strict";
136943
136944 Object.defineProperty(exports, "__esModule", {
136945 value: true
136946 }); // See also tools/generate-unicode-regex.js.
136947
136948 var Regex = {
136949 // Unicode v8.0.0 NonAsciiIdentifierStart:
136950 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
136951 // Unicode v8.0.0 NonAsciiIdentifierPart:
136952 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
136953 };
136954 exports.Character = {
136955 /* tslint:disable:no-bitwise */
136956 fromCodePoint: function fromCodePoint(cp) {
136957 return cp < 0x10000 ? String.fromCharCode(cp) : String.fromCharCode(0xD800 + (cp - 0x10000 >> 10)) + String.fromCharCode(0xDC00 + (cp - 0x10000 & 1023));
136958 },
136959 // https://tc39.github.io/ecma262/#sec-white-space
136960 isWhiteSpace: function isWhiteSpace(cp) {
136961 return cp === 0x20 || cp === 0x09 || cp === 0x0B || cp === 0x0C || cp === 0xA0 || cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0;
136962 },
136963 // https://tc39.github.io/ecma262/#sec-line-terminators
136964 isLineTerminator: function isLineTerminator(cp) {
136965 return cp === 0x0A || cp === 0x0D || cp === 0x2028 || cp === 0x2029;
136966 },
136967 // https://tc39.github.io/ecma262/#sec-names-and-keywords
136968 isIdentifierStart: function isIdentifierStart(cp) {
136969 return cp === 0x24 || cp === 0x5F || cp >= 0x41 && cp <= 0x5A || cp >= 0x61 && cp <= 0x7A || cp === 0x5C || cp >= 0x80 && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp));
136970 },
136971 isIdentifierPart: function isIdentifierPart(cp) {
136972 return cp === 0x24 || cp === 0x5F || cp >= 0x41 && cp <= 0x5A || cp >= 0x61 && cp <= 0x7A || cp >= 0x30 && cp <= 0x39 || cp === 0x5C || cp >= 0x80 && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp));
136973 },
136974 // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
136975 isDecimalDigit: function isDecimalDigit(cp) {
136976 return cp >= 0x30 && cp <= 0x39; // 0..9
136977 },
136978 isHexDigit: function isHexDigit(cp) {
136979 return cp >= 0x30 && cp <= 0x39 || cp >= 0x41 && cp <= 0x46 || cp >= 0x61 && cp <= 0x66; // a..f
136980 },
136981 isOctalDigit: function isOctalDigit(cp) {
136982 return cp >= 0x30 && cp <= 0x37; // 0..7
136983 }
136984 };
136985 /***/
136986 },
136987 /* 5 */
136988
136989 /***/
136990 function (module, exports, __webpack_require__) {
136991 "use strict";
136992
136993 Object.defineProperty(exports, "__esModule", {
136994 value: true
136995 });
136996
136997 var jsx_syntax_1 = __webpack_require__(6);
136998 /* tslint:disable:max-classes-per-file */
136999
137000
137001 var JSXClosingElement = function () {
137002 function JSXClosingElement(name) {
137003 this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
137004 this.name = name;
137005 }
137006
137007 return JSXClosingElement;
137008 }();
137009
137010 exports.JSXClosingElement = JSXClosingElement;
137011
137012 var JSXElement = function () {
137013 function JSXElement(openingElement, children, closingElement) {
137014 this.type = jsx_syntax_1.JSXSyntax.JSXElement;
137015 this.openingElement = openingElement;
137016 this.children = children;
137017 this.closingElement = closingElement;
137018 }
137019
137020 return JSXElement;
137021 }();
137022
137023 exports.JSXElement = JSXElement;
137024
137025 var JSXEmptyExpression = function () {
137026 function JSXEmptyExpression() {
137027 this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
137028 }
137029
137030 return JSXEmptyExpression;
137031 }();
137032
137033 exports.JSXEmptyExpression = JSXEmptyExpression;
137034
137035 var JSXExpressionContainer = function () {
137036 function JSXExpressionContainer(expression) {
137037 this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
137038 this.expression = expression;
137039 }
137040
137041 return JSXExpressionContainer;
137042 }();
137043
137044 exports.JSXExpressionContainer = JSXExpressionContainer;
137045
137046 var JSXIdentifier = function () {
137047 function JSXIdentifier(name) {
137048 this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
137049 this.name = name;
137050 }
137051
137052 return JSXIdentifier;
137053 }();
137054
137055 exports.JSXIdentifier = JSXIdentifier;
137056
137057 var JSXMemberExpression = function () {
137058 function JSXMemberExpression(object, property) {
137059 this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
137060 this.object = object;
137061 this.property = property;
137062 }
137063
137064 return JSXMemberExpression;
137065 }();
137066
137067 exports.JSXMemberExpression = JSXMemberExpression;
137068
137069 var JSXAttribute = function () {
137070 function JSXAttribute(name, value) {
137071 this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
137072 this.name = name;
137073 this.value = value;
137074 }
137075
137076 return JSXAttribute;
137077 }();
137078
137079 exports.JSXAttribute = JSXAttribute;
137080
137081 var JSXNamespacedName = function () {
137082 function JSXNamespacedName(namespace, name) {
137083 this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
137084 this.namespace = namespace;
137085 this.name = name;
137086 }
137087
137088 return JSXNamespacedName;
137089 }();
137090
137091 exports.JSXNamespacedName = JSXNamespacedName;
137092
137093 var JSXOpeningElement = function () {
137094 function JSXOpeningElement(name, selfClosing, attributes) {
137095 this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
137096 this.name = name;
137097 this.selfClosing = selfClosing;
137098 this.attributes = attributes;
137099 }
137100
137101 return JSXOpeningElement;
137102 }();
137103
137104 exports.JSXOpeningElement = JSXOpeningElement;
137105
137106 var JSXSpreadAttribute = function () {
137107 function JSXSpreadAttribute(argument) {
137108 this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
137109 this.argument = argument;
137110 }
137111
137112 return JSXSpreadAttribute;
137113 }();
137114
137115 exports.JSXSpreadAttribute = JSXSpreadAttribute;
137116
137117 var JSXText = function () {
137118 function JSXText(value, raw) {
137119 this.type = jsx_syntax_1.JSXSyntax.JSXText;
137120 this.value = value;
137121 this.raw = raw;
137122 }
137123
137124 return JSXText;
137125 }();
137126
137127 exports.JSXText = JSXText;
137128 /***/
137129 },
137130 /* 6 */
137131
137132 /***/
137133 function (module, exports) {
137134 "use strict";
137135
137136 Object.defineProperty(exports, "__esModule", {
137137 value: true
137138 });
137139 exports.JSXSyntax = {
137140 JSXAttribute: 'JSXAttribute',
137141 JSXClosingElement: 'JSXClosingElement',
137142 JSXElement: 'JSXElement',
137143 JSXEmptyExpression: 'JSXEmptyExpression',
137144 JSXExpressionContainer: 'JSXExpressionContainer',
137145 JSXIdentifier: 'JSXIdentifier',
137146 JSXMemberExpression: 'JSXMemberExpression',
137147 JSXNamespacedName: 'JSXNamespacedName',
137148 JSXOpeningElement: 'JSXOpeningElement',
137149 JSXSpreadAttribute: 'JSXSpreadAttribute',
137150 JSXText: 'JSXText'
137151 };
137152 /***/
137153 },
137154 /* 7 */
137155
137156 /***/
137157 function (module, exports, __webpack_require__) {
137158 "use strict";
137159
137160 Object.defineProperty(exports, "__esModule", {
137161 value: true
137162 });
137163
137164 var syntax_1 = __webpack_require__(2);
137165 /* tslint:disable:max-classes-per-file */
137166
137167
137168 var ArrayExpression = function () {
137169 function ArrayExpression(elements) {
137170 this.type = syntax_1.Syntax.ArrayExpression;
137171 this.elements = elements;
137172 }
137173
137174 return ArrayExpression;
137175 }();
137176
137177 exports.ArrayExpression = ArrayExpression;
137178
137179 var ArrayPattern = function () {
137180 function ArrayPattern(elements) {
137181 this.type = syntax_1.Syntax.ArrayPattern;
137182 this.elements = elements;
137183 }
137184
137185 return ArrayPattern;
137186 }();
137187
137188 exports.ArrayPattern = ArrayPattern;
137189
137190 var ArrowFunctionExpression = function () {
137191 function ArrowFunctionExpression(params, body, expression) {
137192 this.type = syntax_1.Syntax.ArrowFunctionExpression;
137193 this.id = null;
137194 this.params = params;
137195 this.body = body;
137196 this.generator = false;
137197 this.expression = expression;
137198 this.async = false;
137199 }
137200
137201 return ArrowFunctionExpression;
137202 }();
137203
137204 exports.ArrowFunctionExpression = ArrowFunctionExpression;
137205
137206 var AssignmentExpression = function () {
137207 function AssignmentExpression(operator, left, right) {
137208 this.type = syntax_1.Syntax.AssignmentExpression;
137209 this.operator = operator;
137210 this.left = left;
137211 this.right = right;
137212 }
137213
137214 return AssignmentExpression;
137215 }();
137216
137217 exports.AssignmentExpression = AssignmentExpression;
137218
137219 var AssignmentPattern = function () {
137220 function AssignmentPattern(left, right) {
137221 this.type = syntax_1.Syntax.AssignmentPattern;
137222 this.left = left;
137223 this.right = right;
137224 }
137225
137226 return AssignmentPattern;
137227 }();
137228
137229 exports.AssignmentPattern = AssignmentPattern;
137230
137231 var AsyncArrowFunctionExpression = function () {
137232 function AsyncArrowFunctionExpression(params, body, expression) {
137233 this.type = syntax_1.Syntax.ArrowFunctionExpression;
137234 this.id = null;
137235 this.params = params;
137236 this.body = body;
137237 this.generator = false;
137238 this.expression = expression;
137239 this.async = true;
137240 }
137241
137242 return AsyncArrowFunctionExpression;
137243 }();
137244
137245 exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
137246
137247 var AsyncFunctionDeclaration = function () {
137248 function AsyncFunctionDeclaration(id, params, body) {
137249 this.type = syntax_1.Syntax.FunctionDeclaration;
137250 this.id = id;
137251 this.params = params;
137252 this.body = body;
137253 this.generator = false;
137254 this.expression = false;
137255 this.async = true;
137256 }
137257
137258 return AsyncFunctionDeclaration;
137259 }();
137260
137261 exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
137262
137263 var AsyncFunctionExpression = function () {
137264 function AsyncFunctionExpression(id, params, body) {
137265 this.type = syntax_1.Syntax.FunctionExpression;
137266 this.id = id;
137267 this.params = params;
137268 this.body = body;
137269 this.generator = false;
137270 this.expression = false;
137271 this.async = true;
137272 }
137273
137274 return AsyncFunctionExpression;
137275 }();
137276
137277 exports.AsyncFunctionExpression = AsyncFunctionExpression;
137278
137279 var AwaitExpression = function () {
137280 function AwaitExpression(argument) {
137281 this.type = syntax_1.Syntax.AwaitExpression;
137282 this.argument = argument;
137283 }
137284
137285 return AwaitExpression;
137286 }();
137287
137288 exports.AwaitExpression = AwaitExpression;
137289
137290 var BinaryExpression = function () {
137291 function BinaryExpression(operator, left, right) {
137292 var logical = operator === '||' || operator === '&&';
137293 this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
137294 this.operator = operator;
137295 this.left = left;
137296 this.right = right;
137297 }
137298
137299 return BinaryExpression;
137300 }();
137301
137302 exports.BinaryExpression = BinaryExpression;
137303
137304 var BlockStatement = function () {
137305 function BlockStatement(body) {
137306 this.type = syntax_1.Syntax.BlockStatement;
137307 this.body = body;
137308 }
137309
137310 return BlockStatement;
137311 }();
137312
137313 exports.BlockStatement = BlockStatement;
137314
137315 var BreakStatement = function () {
137316 function BreakStatement(label) {
137317 this.type = syntax_1.Syntax.BreakStatement;
137318 this.label = label;
137319 }
137320
137321 return BreakStatement;
137322 }();
137323
137324 exports.BreakStatement = BreakStatement;
137325
137326 var CallExpression = function () {
137327 function CallExpression(callee, args) {
137328 this.type = syntax_1.Syntax.CallExpression;
137329 this.callee = callee;
137330 this.arguments = args;
137331 }
137332
137333 return CallExpression;
137334 }();
137335
137336 exports.CallExpression = CallExpression;
137337
137338 var CatchClause = function () {
137339 function CatchClause(param, body) {
137340 this.type = syntax_1.Syntax.CatchClause;
137341 this.param = param;
137342 this.body = body;
137343 }
137344
137345 return CatchClause;
137346 }();
137347
137348 exports.CatchClause = CatchClause;
137349
137350 var ClassBody = function () {
137351 function ClassBody(body) {
137352 this.type = syntax_1.Syntax.ClassBody;
137353 this.body = body;
137354 }
137355
137356 return ClassBody;
137357 }();
137358
137359 exports.ClassBody = ClassBody;
137360
137361 var ClassDeclaration = function () {
137362 function ClassDeclaration(id, superClass, body) {
137363 this.type = syntax_1.Syntax.ClassDeclaration;
137364 this.id = id;
137365 this.superClass = superClass;
137366 this.body = body;
137367 }
137368
137369 return ClassDeclaration;
137370 }();
137371
137372 exports.ClassDeclaration = ClassDeclaration;
137373
137374 var ClassExpression = function () {
137375 function ClassExpression(id, superClass, body) {
137376 this.type = syntax_1.Syntax.ClassExpression;
137377 this.id = id;
137378 this.superClass = superClass;
137379 this.body = body;
137380 }
137381
137382 return ClassExpression;
137383 }();
137384
137385 exports.ClassExpression = ClassExpression;
137386
137387 var ComputedMemberExpression = function () {
137388 function ComputedMemberExpression(object, property) {
137389 this.type = syntax_1.Syntax.MemberExpression;
137390 this.computed = true;
137391 this.object = object;
137392 this.property = property;
137393 }
137394
137395 return ComputedMemberExpression;
137396 }();
137397
137398 exports.ComputedMemberExpression = ComputedMemberExpression;
137399
137400 var ConditionalExpression = function () {
137401 function ConditionalExpression(test, consequent, alternate) {
137402 this.type = syntax_1.Syntax.ConditionalExpression;
137403 this.test = test;
137404 this.consequent = consequent;
137405 this.alternate = alternate;
137406 }
137407
137408 return ConditionalExpression;
137409 }();
137410
137411 exports.ConditionalExpression = ConditionalExpression;
137412
137413 var ContinueStatement = function () {
137414 function ContinueStatement(label) {
137415 this.type = syntax_1.Syntax.ContinueStatement;
137416 this.label = label;
137417 }
137418
137419 return ContinueStatement;
137420 }();
137421
137422 exports.ContinueStatement = ContinueStatement;
137423
137424 var DebuggerStatement = function () {
137425 function DebuggerStatement() {
137426 this.type = syntax_1.Syntax.DebuggerStatement;
137427 }
137428
137429 return DebuggerStatement;
137430 }();
137431
137432 exports.DebuggerStatement = DebuggerStatement;
137433
137434 var Directive = function () {
137435 function Directive(expression, directive) {
137436 this.type = syntax_1.Syntax.ExpressionStatement;
137437 this.expression = expression;
137438 this.directive = directive;
137439 }
137440
137441 return Directive;
137442 }();
137443
137444 exports.Directive = Directive;
137445
137446 var DoWhileStatement = function () {
137447 function DoWhileStatement(body, test) {
137448 this.type = syntax_1.Syntax.DoWhileStatement;
137449 this.body = body;
137450 this.test = test;
137451 }
137452
137453 return DoWhileStatement;
137454 }();
137455
137456 exports.DoWhileStatement = DoWhileStatement;
137457
137458 var EmptyStatement = function () {
137459 function EmptyStatement() {
137460 this.type = syntax_1.Syntax.EmptyStatement;
137461 }
137462
137463 return EmptyStatement;
137464 }();
137465
137466 exports.EmptyStatement = EmptyStatement;
137467
137468 var ExportAllDeclaration = function () {
137469 function ExportAllDeclaration(source) {
137470 this.type = syntax_1.Syntax.ExportAllDeclaration;
137471 this.source = source;
137472 }
137473
137474 return ExportAllDeclaration;
137475 }();
137476
137477 exports.ExportAllDeclaration = ExportAllDeclaration;
137478
137479 var ExportDefaultDeclaration = function () {
137480 function ExportDefaultDeclaration(declaration) {
137481 this.type = syntax_1.Syntax.ExportDefaultDeclaration;
137482 this.declaration = declaration;
137483 }
137484
137485 return ExportDefaultDeclaration;
137486 }();
137487
137488 exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
137489
137490 var ExportNamedDeclaration = function () {
137491 function ExportNamedDeclaration(declaration, specifiers, source) {
137492 this.type = syntax_1.Syntax.ExportNamedDeclaration;
137493 this.declaration = declaration;
137494 this.specifiers = specifiers;
137495 this.source = source;
137496 }
137497
137498 return ExportNamedDeclaration;
137499 }();
137500
137501 exports.ExportNamedDeclaration = ExportNamedDeclaration;
137502
137503 var ExportSpecifier = function () {
137504 function ExportSpecifier(local, exported) {
137505 this.type = syntax_1.Syntax.ExportSpecifier;
137506 this.exported = exported;
137507 this.local = local;
137508 }
137509
137510 return ExportSpecifier;
137511 }();
137512
137513 exports.ExportSpecifier = ExportSpecifier;
137514
137515 var ExpressionStatement = function () {
137516 function ExpressionStatement(expression) {
137517 this.type = syntax_1.Syntax.ExpressionStatement;
137518 this.expression = expression;
137519 }
137520
137521 return ExpressionStatement;
137522 }();
137523
137524 exports.ExpressionStatement = ExpressionStatement;
137525
137526 var ForInStatement = function () {
137527 function ForInStatement(left, right, body) {
137528 this.type = syntax_1.Syntax.ForInStatement;
137529 this.left = left;
137530 this.right = right;
137531 this.body = body;
137532 this.each = false;
137533 }
137534
137535 return ForInStatement;
137536 }();
137537
137538 exports.ForInStatement = ForInStatement;
137539
137540 var ForOfStatement = function () {
137541 function ForOfStatement(left, right, body) {
137542 this.type = syntax_1.Syntax.ForOfStatement;
137543 this.left = left;
137544 this.right = right;
137545 this.body = body;
137546 }
137547
137548 return ForOfStatement;
137549 }();
137550
137551 exports.ForOfStatement = ForOfStatement;
137552
137553 var ForStatement = function () {
137554 function ForStatement(init, test, update, body) {
137555 this.type = syntax_1.Syntax.ForStatement;
137556 this.init = init;
137557 this.test = test;
137558 this.update = update;
137559 this.body = body;
137560 }
137561
137562 return ForStatement;
137563 }();
137564
137565 exports.ForStatement = ForStatement;
137566
137567 var FunctionDeclaration = function () {
137568 function FunctionDeclaration(id, params, body, generator) {
137569 this.type = syntax_1.Syntax.FunctionDeclaration;
137570 this.id = id;
137571 this.params = params;
137572 this.body = body;
137573 this.generator = generator;
137574 this.expression = false;
137575 this.async = false;
137576 }
137577
137578 return FunctionDeclaration;
137579 }();
137580
137581 exports.FunctionDeclaration = FunctionDeclaration;
137582
137583 var FunctionExpression = function () {
137584 function FunctionExpression(id, params, body, generator) {
137585 this.type = syntax_1.Syntax.FunctionExpression;
137586 this.id = id;
137587 this.params = params;
137588 this.body = body;
137589 this.generator = generator;
137590 this.expression = false;
137591 this.async = false;
137592 }
137593
137594 return FunctionExpression;
137595 }();
137596
137597 exports.FunctionExpression = FunctionExpression;
137598
137599 var Identifier = function () {
137600 function Identifier(name) {
137601 this.type = syntax_1.Syntax.Identifier;
137602 this.name = name;
137603 }
137604
137605 return Identifier;
137606 }();
137607
137608 exports.Identifier = Identifier;
137609
137610 var IfStatement = function () {
137611 function IfStatement(test, consequent, alternate) {
137612 this.type = syntax_1.Syntax.IfStatement;
137613 this.test = test;
137614 this.consequent = consequent;
137615 this.alternate = alternate;
137616 }
137617
137618 return IfStatement;
137619 }();
137620
137621 exports.IfStatement = IfStatement;
137622
137623 var ImportDeclaration = function () {
137624 function ImportDeclaration(specifiers, source) {
137625 this.type = syntax_1.Syntax.ImportDeclaration;
137626 this.specifiers = specifiers;
137627 this.source = source;
137628 }
137629
137630 return ImportDeclaration;
137631 }();
137632
137633 exports.ImportDeclaration = ImportDeclaration;
137634
137635 var ImportDefaultSpecifier = function () {
137636 function ImportDefaultSpecifier(local) {
137637 this.type = syntax_1.Syntax.ImportDefaultSpecifier;
137638 this.local = local;
137639 }
137640
137641 return ImportDefaultSpecifier;
137642 }();
137643
137644 exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
137645
137646 var ImportNamespaceSpecifier = function () {
137647 function ImportNamespaceSpecifier(local) {
137648 this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
137649 this.local = local;
137650 }
137651
137652 return ImportNamespaceSpecifier;
137653 }();
137654
137655 exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
137656
137657 var ImportSpecifier = function () {
137658 function ImportSpecifier(local, imported) {
137659 this.type = syntax_1.Syntax.ImportSpecifier;
137660 this.local = local;
137661 this.imported = imported;
137662 }
137663
137664 return ImportSpecifier;
137665 }();
137666
137667 exports.ImportSpecifier = ImportSpecifier;
137668
137669 var LabeledStatement = function () {
137670 function LabeledStatement(label, body) {
137671 this.type = syntax_1.Syntax.LabeledStatement;
137672 this.label = label;
137673 this.body = body;
137674 }
137675
137676 return LabeledStatement;
137677 }();
137678
137679 exports.LabeledStatement = LabeledStatement;
137680
137681 var Literal = function () {
137682 function Literal(value, raw) {
137683 this.type = syntax_1.Syntax.Literal;
137684 this.value = value;
137685 this.raw = raw;
137686 }
137687
137688 return Literal;
137689 }();
137690
137691 exports.Literal = Literal;
137692
137693 var MetaProperty = function () {
137694 function MetaProperty(meta, property) {
137695 this.type = syntax_1.Syntax.MetaProperty;
137696 this.meta = meta;
137697 this.property = property;
137698 }
137699
137700 return MetaProperty;
137701 }();
137702
137703 exports.MetaProperty = MetaProperty;
137704
137705 var MethodDefinition = function () {
137706 function MethodDefinition(key, computed, value, kind, isStatic) {
137707 this.type = syntax_1.Syntax.MethodDefinition;
137708 this.key = key;
137709 this.computed = computed;
137710 this.value = value;
137711 this.kind = kind;
137712 this.static = isStatic;
137713 }
137714
137715 return MethodDefinition;
137716 }();
137717
137718 exports.MethodDefinition = MethodDefinition;
137719
137720 var Module = function () {
137721 function Module(body) {
137722 this.type = syntax_1.Syntax.Program;
137723 this.body = body;
137724 this.sourceType = 'module';
137725 }
137726
137727 return Module;
137728 }();
137729
137730 exports.Module = Module;
137731
137732 var NewExpression = function () {
137733 function NewExpression(callee, args) {
137734 this.type = syntax_1.Syntax.NewExpression;
137735 this.callee = callee;
137736 this.arguments = args;
137737 }
137738
137739 return NewExpression;
137740 }();
137741
137742 exports.NewExpression = NewExpression;
137743
137744 var ObjectExpression = function () {
137745 function ObjectExpression(properties) {
137746 this.type = syntax_1.Syntax.ObjectExpression;
137747 this.properties = properties;
137748 }
137749
137750 return ObjectExpression;
137751 }();
137752
137753 exports.ObjectExpression = ObjectExpression;
137754
137755 var ObjectPattern = function () {
137756 function ObjectPattern(properties) {
137757 this.type = syntax_1.Syntax.ObjectPattern;
137758 this.properties = properties;
137759 }
137760
137761 return ObjectPattern;
137762 }();
137763
137764 exports.ObjectPattern = ObjectPattern;
137765
137766 var Property = function () {
137767 function Property(kind, key, computed, value, method, shorthand) {
137768 this.type = syntax_1.Syntax.Property;
137769 this.key = key;
137770 this.computed = computed;
137771 this.value = value;
137772 this.kind = kind;
137773 this.method = method;
137774 this.shorthand = shorthand;
137775 }
137776
137777 return Property;
137778 }();
137779
137780 exports.Property = Property;
137781
137782 var RegexLiteral = function () {
137783 function RegexLiteral(value, raw, pattern, flags) {
137784 this.type = syntax_1.Syntax.Literal;
137785 this.value = value;
137786 this.raw = raw;
137787 this.regex = {
137788 pattern: pattern,
137789 flags: flags
137790 };
137791 }
137792
137793 return RegexLiteral;
137794 }();
137795
137796 exports.RegexLiteral = RegexLiteral;
137797
137798 var RestElement = function () {
137799 function RestElement(argument) {
137800 this.type = syntax_1.Syntax.RestElement;
137801 this.argument = argument;
137802 }
137803
137804 return RestElement;
137805 }();
137806
137807 exports.RestElement = RestElement;
137808
137809 var ReturnStatement = function () {
137810 function ReturnStatement(argument) {
137811 this.type = syntax_1.Syntax.ReturnStatement;
137812 this.argument = argument;
137813 }
137814
137815 return ReturnStatement;
137816 }();
137817
137818 exports.ReturnStatement = ReturnStatement;
137819
137820 var Script = function () {
137821 function Script(body) {
137822 this.type = syntax_1.Syntax.Program;
137823 this.body = body;
137824 this.sourceType = 'script';
137825 }
137826
137827 return Script;
137828 }();
137829
137830 exports.Script = Script;
137831
137832 var SequenceExpression = function () {
137833 function SequenceExpression(expressions) {
137834 this.type = syntax_1.Syntax.SequenceExpression;
137835 this.expressions = expressions;
137836 }
137837
137838 return SequenceExpression;
137839 }();
137840
137841 exports.SequenceExpression = SequenceExpression;
137842
137843 var SpreadElement = function () {
137844 function SpreadElement(argument) {
137845 this.type = syntax_1.Syntax.SpreadElement;
137846 this.argument = argument;
137847 }
137848
137849 return SpreadElement;
137850 }();
137851
137852 exports.SpreadElement = SpreadElement;
137853
137854 var StaticMemberExpression = function () {
137855 function StaticMemberExpression(object, property) {
137856 this.type = syntax_1.Syntax.MemberExpression;
137857 this.computed = false;
137858 this.object = object;
137859 this.property = property;
137860 }
137861
137862 return StaticMemberExpression;
137863 }();
137864
137865 exports.StaticMemberExpression = StaticMemberExpression;
137866
137867 var Super = function () {
137868 function Super() {
137869 this.type = syntax_1.Syntax.Super;
137870 }
137871
137872 return Super;
137873 }();
137874
137875 exports.Super = Super;
137876
137877 var SwitchCase = function () {
137878 function SwitchCase(test, consequent) {
137879 this.type = syntax_1.Syntax.SwitchCase;
137880 this.test = test;
137881 this.consequent = consequent;
137882 }
137883
137884 return SwitchCase;
137885 }();
137886
137887 exports.SwitchCase = SwitchCase;
137888
137889 var SwitchStatement = function () {
137890 function SwitchStatement(discriminant, cases) {
137891 this.type = syntax_1.Syntax.SwitchStatement;
137892 this.discriminant = discriminant;
137893 this.cases = cases;
137894 }
137895
137896 return SwitchStatement;
137897 }();
137898
137899 exports.SwitchStatement = SwitchStatement;
137900
137901 var TaggedTemplateExpression = function () {
137902 function TaggedTemplateExpression(tag, quasi) {
137903 this.type = syntax_1.Syntax.TaggedTemplateExpression;
137904 this.tag = tag;
137905 this.quasi = quasi;
137906 }
137907
137908 return TaggedTemplateExpression;
137909 }();
137910
137911 exports.TaggedTemplateExpression = TaggedTemplateExpression;
137912
137913 var TemplateElement = function () {
137914 function TemplateElement(value, tail) {
137915 this.type = syntax_1.Syntax.TemplateElement;
137916 this.value = value;
137917 this.tail = tail;
137918 }
137919
137920 return TemplateElement;
137921 }();
137922
137923 exports.TemplateElement = TemplateElement;
137924
137925 var TemplateLiteral = function () {
137926 function TemplateLiteral(quasis, expressions) {
137927 this.type = syntax_1.Syntax.TemplateLiteral;
137928 this.quasis = quasis;
137929 this.expressions = expressions;
137930 }
137931
137932 return TemplateLiteral;
137933 }();
137934
137935 exports.TemplateLiteral = TemplateLiteral;
137936
137937 var ThisExpression = function () {
137938 function ThisExpression() {
137939 this.type = syntax_1.Syntax.ThisExpression;
137940 }
137941
137942 return ThisExpression;
137943 }();
137944
137945 exports.ThisExpression = ThisExpression;
137946
137947 var ThrowStatement = function () {
137948 function ThrowStatement(argument) {
137949 this.type = syntax_1.Syntax.ThrowStatement;
137950 this.argument = argument;
137951 }
137952
137953 return ThrowStatement;
137954 }();
137955
137956 exports.ThrowStatement = ThrowStatement;
137957
137958 var TryStatement = function () {
137959 function TryStatement(block, handler, finalizer) {
137960 this.type = syntax_1.Syntax.TryStatement;
137961 this.block = block;
137962 this.handler = handler;
137963 this.finalizer = finalizer;
137964 }
137965
137966 return TryStatement;
137967 }();
137968
137969 exports.TryStatement = TryStatement;
137970
137971 var UnaryExpression = function () {
137972 function UnaryExpression(operator, argument) {
137973 this.type = syntax_1.Syntax.UnaryExpression;
137974 this.operator = operator;
137975 this.argument = argument;
137976 this.prefix = true;
137977 }
137978
137979 return UnaryExpression;
137980 }();
137981
137982 exports.UnaryExpression = UnaryExpression;
137983
137984 var UpdateExpression = function () {
137985 function UpdateExpression(operator, argument, prefix) {
137986 this.type = syntax_1.Syntax.UpdateExpression;
137987 this.operator = operator;
137988 this.argument = argument;
137989 this.prefix = prefix;
137990 }
137991
137992 return UpdateExpression;
137993 }();
137994
137995 exports.UpdateExpression = UpdateExpression;
137996
137997 var VariableDeclaration = function () {
137998 function VariableDeclaration(declarations, kind) {
137999 this.type = syntax_1.Syntax.VariableDeclaration;
138000 this.declarations = declarations;
138001 this.kind = kind;
138002 }
138003
138004 return VariableDeclaration;
138005 }();
138006
138007 exports.VariableDeclaration = VariableDeclaration;
138008
138009 var VariableDeclarator = function () {
138010 function VariableDeclarator(id, init) {
138011 this.type = syntax_1.Syntax.VariableDeclarator;
138012 this.id = id;
138013 this.init = init;
138014 }
138015
138016 return VariableDeclarator;
138017 }();
138018
138019 exports.VariableDeclarator = VariableDeclarator;
138020
138021 var WhileStatement = function () {
138022 function WhileStatement(test, body) {
138023 this.type = syntax_1.Syntax.WhileStatement;
138024 this.test = test;
138025 this.body = body;
138026 }
138027
138028 return WhileStatement;
138029 }();
138030
138031 exports.WhileStatement = WhileStatement;
138032
138033 var WithStatement = function () {
138034 function WithStatement(object, body) {
138035 this.type = syntax_1.Syntax.WithStatement;
138036 this.object = object;
138037 this.body = body;
138038 }
138039
138040 return WithStatement;
138041 }();
138042
138043 exports.WithStatement = WithStatement;
138044
138045 var YieldExpression = function () {
138046 function YieldExpression(argument, delegate) {
138047 this.type = syntax_1.Syntax.YieldExpression;
138048 this.argument = argument;
138049 this.delegate = delegate;
138050 }
138051
138052 return YieldExpression;
138053 }();
138054
138055 exports.YieldExpression = YieldExpression;
138056 /***/
138057 },
138058 /* 8 */
138059
138060 /***/
138061 function (module, exports, __webpack_require__) {
138062 "use strict";
138063
138064 Object.defineProperty(exports, "__esModule", {
138065 value: true
138066 });
138067
138068 var assert_1 = __webpack_require__(9);
138069
138070 var error_handler_1 = __webpack_require__(10);
138071
138072 var messages_1 = __webpack_require__(11);
138073
138074 var Node = __webpack_require__(7);
138075
138076 var scanner_1 = __webpack_require__(12);
138077
138078 var syntax_1 = __webpack_require__(2);
138079
138080 var token_1 = __webpack_require__(13);
138081
138082 var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
138083
138084 var Parser = function () {
138085 function Parser(code, options, delegate) {
138086 if (options === void 0) {
138087 options = {};
138088 }
138089
138090 this.config = {
138091 range: typeof options.range === 'boolean' && options.range,
138092 loc: typeof options.loc === 'boolean' && options.loc,
138093 source: null,
138094 tokens: typeof options.tokens === 'boolean' && options.tokens,
138095 comment: typeof options.comment === 'boolean' && options.comment,
138096 tolerant: typeof options.tolerant === 'boolean' && options.tolerant
138097 };
138098
138099 if (this.config.loc && options.source && options.source !== null) {
138100 this.config.source = String(options.source);
138101 }
138102
138103 this.delegate = delegate;
138104 this.errorHandler = new error_handler_1.ErrorHandler();
138105 this.errorHandler.tolerant = this.config.tolerant;
138106 this.scanner = new scanner_1.Scanner(code, this.errorHandler);
138107 this.scanner.trackComment = this.config.comment;
138108 this.operatorPrecedence = {
138109 ')': 0,
138110 ';': 0,
138111 ',': 0,
138112 '=': 0,
138113 ']': 0,
138114 '||': 1,
138115 '&&': 2,
138116 '|': 3,
138117 '^': 4,
138118 '&': 5,
138119 '==': 6,
138120 '!=': 6,
138121 '===': 6,
138122 '!==': 6,
138123 '<': 7,
138124 '>': 7,
138125 '<=': 7,
138126 '>=': 7,
138127 '<<': 8,
138128 '>>': 8,
138129 '>>>': 8,
138130 '+': 9,
138131 '-': 9,
138132 '*': 11,
138133 '/': 11,
138134 '%': 11
138135 };
138136 this.lookahead = {
138137 type: 2
138138 /* EOF */
138139 ,
138140 value: '',
138141 lineNumber: this.scanner.lineNumber,
138142 lineStart: 0,
138143 start: 0,
138144 end: 0
138145 };
138146 this.hasLineTerminator = false;
138147 this.context = {
138148 isModule: false,
138149 await: false,
138150 allowIn: true,
138151 allowStrictDirective: true,
138152 allowYield: true,
138153 firstCoverInitializedNameError: null,
138154 isAssignmentTarget: false,
138155 isBindingElement: false,
138156 inFunctionBody: false,
138157 inIteration: false,
138158 inSwitch: false,
138159 labelSet: {},
138160 strict: false
138161 };
138162 this.tokens = [];
138163 this.startMarker = {
138164 index: 0,
138165 line: this.scanner.lineNumber,
138166 column: 0
138167 };
138168 this.lastMarker = {
138169 index: 0,
138170 line: this.scanner.lineNumber,
138171 column: 0
138172 };
138173 this.nextToken();
138174 this.lastMarker = {
138175 index: this.scanner.index,
138176 line: this.scanner.lineNumber,
138177 column: this.scanner.index - this.scanner.lineStart
138178 };
138179 }
138180
138181 Parser.prototype.throwError = function (messageFormat) {
138182 var values = [];
138183
138184 for (var _i = 1; _i < arguments.length; _i++) {
138185 values[_i - 1] = arguments[_i];
138186 }
138187
138188 var args = Array.prototype.slice.call(arguments, 1);
138189 var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
138190 assert_1.assert(idx < args.length, 'Message reference must be in range');
138191 return args[idx];
138192 });
138193 var index = this.lastMarker.index;
138194 var line = this.lastMarker.line;
138195 var column = this.lastMarker.column + 1;
138196 throw this.errorHandler.createError(index, line, column, msg);
138197 };
138198
138199 Parser.prototype.tolerateError = function (messageFormat) {
138200 var values = [];
138201
138202 for (var _i = 1; _i < arguments.length; _i++) {
138203 values[_i - 1] = arguments[_i];
138204 }
138205
138206 var args = Array.prototype.slice.call(arguments, 1);
138207 var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
138208 assert_1.assert(idx < args.length, 'Message reference must be in range');
138209 return args[idx];
138210 });
138211 var index = this.lastMarker.index;
138212 var line = this.scanner.lineNumber;
138213 var column = this.lastMarker.column + 1;
138214 this.errorHandler.tolerateError(index, line, column, msg);
138215 }; // Throw an exception because of the token.
138216
138217
138218 Parser.prototype.unexpectedTokenError = function (token, message) {
138219 var msg = message || messages_1.Messages.UnexpectedToken;
138220 var value;
138221
138222 if (token) {
138223 if (!message) {
138224 msg = token.type === 2
138225 /* EOF */
138226 ? messages_1.Messages.UnexpectedEOS : token.type === 3
138227 /* Identifier */
138228 ? messages_1.Messages.UnexpectedIdentifier : token.type === 6
138229 /* NumericLiteral */
138230 ? messages_1.Messages.UnexpectedNumber : token.type === 8
138231 /* StringLiteral */
138232 ? messages_1.Messages.UnexpectedString : token.type === 10
138233 /* Template */
138234 ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken;
138235
138236 if (token.type === 4
138237 /* Keyword */
138238 ) {
138239 if (this.scanner.isFutureReservedWord(token.value)) {
138240 msg = messages_1.Messages.UnexpectedReserved;
138241 } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
138242 msg = messages_1.Messages.StrictReservedWord;
138243 }
138244 }
138245 }
138246
138247 value = token.value;
138248 } else {
138249 value = 'ILLEGAL';
138250 }
138251
138252 msg = msg.replace('%0', value);
138253
138254 if (token && typeof token.lineNumber === 'number') {
138255 var index = token.start;
138256 var line = token.lineNumber;
138257 var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
138258 var column = token.start - lastMarkerLineStart + 1;
138259 return this.errorHandler.createError(index, line, column, msg);
138260 } else {
138261 var index = this.lastMarker.index;
138262 var line = this.lastMarker.line;
138263 var column = this.lastMarker.column + 1;
138264 return this.errorHandler.createError(index, line, column, msg);
138265 }
138266 };
138267
138268 Parser.prototype.throwUnexpectedToken = function (token, message) {
138269 throw this.unexpectedTokenError(token, message);
138270 };
138271
138272 Parser.prototype.tolerateUnexpectedToken = function (token, message) {
138273 this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
138274 };
138275
138276 Parser.prototype.collectComments = function () {
138277 if (!this.config.comment) {
138278 this.scanner.scanComments();
138279 } else {
138280 var comments = this.scanner.scanComments();
138281
138282 if (comments.length > 0 && this.delegate) {
138283 for (var i = 0; i < comments.length; ++i) {
138284 var e = comments[i];
138285 var node = void 0;
138286 node = {
138287 type: e.multiLine ? 'BlockComment' : 'LineComment',
138288 value: this.scanner.source.slice(e.slice[0], e.slice[1])
138289 };
138290
138291 if (this.config.range) {
138292 node.range = e.range;
138293 }
138294
138295 if (this.config.loc) {
138296 node.loc = e.loc;
138297 }
138298
138299 var metadata = {
138300 start: {
138301 line: e.loc.start.line,
138302 column: e.loc.start.column,
138303 offset: e.range[0]
138304 },
138305 end: {
138306 line: e.loc.end.line,
138307 column: e.loc.end.column,
138308 offset: e.range[1]
138309 }
138310 };
138311 this.delegate(node, metadata);
138312 }
138313 }
138314 }
138315 }; // From internal representation to an external structure
138316
138317
138318 Parser.prototype.getTokenRaw = function (token) {
138319 return this.scanner.source.slice(token.start, token.end);
138320 };
138321
138322 Parser.prototype.convertToken = function (token) {
138323 var t = {
138324 type: token_1.TokenName[token.type],
138325 value: this.getTokenRaw(token)
138326 };
138327
138328 if (this.config.range) {
138329 t.range = [token.start, token.end];
138330 }
138331
138332 if (this.config.loc) {
138333 t.loc = {
138334 start: {
138335 line: this.startMarker.line,
138336 column: this.startMarker.column
138337 },
138338 end: {
138339 line: this.scanner.lineNumber,
138340 column: this.scanner.index - this.scanner.lineStart
138341 }
138342 };
138343 }
138344
138345 if (token.type === 9
138346 /* RegularExpression */
138347 ) {
138348 var pattern = token.pattern;
138349 var flags = token.flags;
138350 t.regex = {
138351 pattern: pattern,
138352 flags: flags
138353 };
138354 }
138355
138356 return t;
138357 };
138358
138359 Parser.prototype.nextToken = function () {
138360 var token = this.lookahead;
138361 this.lastMarker.index = this.scanner.index;
138362 this.lastMarker.line = this.scanner.lineNumber;
138363 this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
138364 this.collectComments();
138365
138366 if (this.scanner.index !== this.startMarker.index) {
138367 this.startMarker.index = this.scanner.index;
138368 this.startMarker.line = this.scanner.lineNumber;
138369 this.startMarker.column = this.scanner.index - this.scanner.lineStart;
138370 }
138371
138372 var next = this.scanner.lex();
138373 this.hasLineTerminator = token.lineNumber !== next.lineNumber;
138374
138375 if (next && this.context.strict && next.type === 3
138376 /* Identifier */
138377 ) {
138378 if (this.scanner.isStrictModeReservedWord(next.value)) {
138379 next.type = 4
138380 /* Keyword */
138381 ;
138382 }
138383 }
138384
138385 this.lookahead = next;
138386
138387 if (this.config.tokens && next.type !== 2
138388 /* EOF */
138389 ) {
138390 this.tokens.push(this.convertToken(next));
138391 }
138392
138393 return token;
138394 };
138395
138396 Parser.prototype.nextRegexToken = function () {
138397 this.collectComments();
138398 var token = this.scanner.scanRegExp();
138399
138400 if (this.config.tokens) {
138401 // Pop the previous token, '/' or '/='
138402 // This is added from the lookahead token.
138403 this.tokens.pop();
138404 this.tokens.push(this.convertToken(token));
138405 } // Prime the next lookahead.
138406
138407
138408 this.lookahead = token;
138409 this.nextToken();
138410 return token;
138411 };
138412
138413 Parser.prototype.createNode = function () {
138414 return {
138415 index: this.startMarker.index,
138416 line: this.startMarker.line,
138417 column: this.startMarker.column
138418 };
138419 };
138420
138421 Parser.prototype.startNode = function (token, lastLineStart) {
138422 if (lastLineStart === void 0) {
138423 lastLineStart = 0;
138424 }
138425
138426 var column = token.start - token.lineStart;
138427 var line = token.lineNumber;
138428
138429 if (column < 0) {
138430 column += lastLineStart;
138431 line--;
138432 }
138433
138434 return {
138435 index: token.start,
138436 line: line,
138437 column: column
138438 };
138439 };
138440
138441 Parser.prototype.finalize = function (marker, node) {
138442 if (this.config.range) {
138443 node.range = [marker.index, this.lastMarker.index];
138444 }
138445
138446 if (this.config.loc) {
138447 node.loc = {
138448 start: {
138449 line: marker.line,
138450 column: marker.column
138451 },
138452 end: {
138453 line: this.lastMarker.line,
138454 column: this.lastMarker.column
138455 }
138456 };
138457
138458 if (this.config.source) {
138459 node.loc.source = this.config.source;
138460 }
138461 }
138462
138463 if (this.delegate) {
138464 var metadata = {
138465 start: {
138466 line: marker.line,
138467 column: marker.column,
138468 offset: marker.index
138469 },
138470 end: {
138471 line: this.lastMarker.line,
138472 column: this.lastMarker.column,
138473 offset: this.lastMarker.index
138474 }
138475 };
138476 this.delegate(node, metadata);
138477 }
138478
138479 return node;
138480 }; // Expect the next token to match the specified punctuator.
138481 // If not, an exception will be thrown.
138482
138483
138484 Parser.prototype.expect = function (value) {
138485 var token = this.nextToken();
138486
138487 if (token.type !== 7
138488 /* Punctuator */
138489 || token.value !== value) {
138490 this.throwUnexpectedToken(token);
138491 }
138492 }; // Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
138493
138494
138495 Parser.prototype.expectCommaSeparator = function () {
138496 if (this.config.tolerant) {
138497 var token = this.lookahead;
138498
138499 if (token.type === 7
138500 /* Punctuator */
138501 && token.value === ',') {
138502 this.nextToken();
138503 } else if (token.type === 7
138504 /* Punctuator */
138505 && token.value === ';') {
138506 this.nextToken();
138507 this.tolerateUnexpectedToken(token);
138508 } else {
138509 this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
138510 }
138511 } else {
138512 this.expect(',');
138513 }
138514 }; // Expect the next token to match the specified keyword.
138515 // If not, an exception will be thrown.
138516
138517
138518 Parser.prototype.expectKeyword = function (keyword) {
138519 var token = this.nextToken();
138520
138521 if (token.type !== 4
138522 /* Keyword */
138523 || token.value !== keyword) {
138524 this.throwUnexpectedToken(token);
138525 }
138526 }; // Return true if the next token matches the specified punctuator.
138527
138528
138529 Parser.prototype.match = function (value) {
138530 return this.lookahead.type === 7
138531 /* Punctuator */
138532 && this.lookahead.value === value;
138533 }; // Return true if the next token matches the specified keyword
138534
138535
138536 Parser.prototype.matchKeyword = function (keyword) {
138537 return this.lookahead.type === 4
138538 /* Keyword */
138539 && this.lookahead.value === keyword;
138540 }; // Return true if the next token matches the specified contextual keyword
138541 // (where an identifier is sometimes a keyword depending on the context)
138542
138543
138544 Parser.prototype.matchContextualKeyword = function (keyword) {
138545 return this.lookahead.type === 3
138546 /* Identifier */
138547 && this.lookahead.value === keyword;
138548 }; // Return true if the next token is an assignment operator
138549
138550
138551 Parser.prototype.matchAssign = function () {
138552 if (this.lookahead.type !== 7
138553 /* Punctuator */
138554 ) {
138555 return false;
138556 }
138557
138558 var op = this.lookahead.value;
138559 return op === '=' || op === '*=' || op === '**=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|=';
138560 }; // Cover grammar support.
138561 //
138562 // When an assignment expression position starts with an left parenthesis, the determination of the type
138563 // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
138564 // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
138565 //
138566 // There are three productions that can be parsed in a parentheses pair that needs to be determined
138567 // after the outermost pair is closed. They are:
138568 //
138569 // 1. AssignmentExpression
138570 // 2. BindingElements
138571 // 3. AssignmentTargets
138572 //
138573 // In order to avoid exponential backtracking, we use two flags to denote if the production can be
138574 // binding element or assignment target.
138575 //
138576 // The three productions have the relationship:
138577 //
138578 // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
138579 //
138580 // with a single exception that CoverInitializedName when used directly in an Expression, generates
138581 // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
138582 // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
138583 //
138584 // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
138585 // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
138586 // the CoverInitializedName check is conducted.
138587 //
138588 // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
138589 // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
138590 // pattern. The CoverInitializedName check is deferred.
138591
138592
138593 Parser.prototype.isolateCoverGrammar = function (parseFunction) {
138594 var previousIsBindingElement = this.context.isBindingElement;
138595 var previousIsAssignmentTarget = this.context.isAssignmentTarget;
138596 var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
138597 this.context.isBindingElement = true;
138598 this.context.isAssignmentTarget = true;
138599 this.context.firstCoverInitializedNameError = null;
138600 var result = parseFunction.call(this);
138601
138602 if (this.context.firstCoverInitializedNameError !== null) {
138603 this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
138604 }
138605
138606 this.context.isBindingElement = previousIsBindingElement;
138607 this.context.isAssignmentTarget = previousIsAssignmentTarget;
138608 this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
138609 return result;
138610 };
138611
138612 Parser.prototype.inheritCoverGrammar = function (parseFunction) {
138613 var previousIsBindingElement = this.context.isBindingElement;
138614 var previousIsAssignmentTarget = this.context.isAssignmentTarget;
138615 var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
138616 this.context.isBindingElement = true;
138617 this.context.isAssignmentTarget = true;
138618 this.context.firstCoverInitializedNameError = null;
138619 var result = parseFunction.call(this);
138620 this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
138621 this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
138622 this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
138623 return result;
138624 };
138625
138626 Parser.prototype.consumeSemicolon = function () {
138627 if (this.match(';')) {
138628 this.nextToken();
138629 } else if (!this.hasLineTerminator) {
138630 if (this.lookahead.type !== 2
138631 /* EOF */
138632 && !this.match('}')) {
138633 this.throwUnexpectedToken(this.lookahead);
138634 }
138635
138636 this.lastMarker.index = this.startMarker.index;
138637 this.lastMarker.line = this.startMarker.line;
138638 this.lastMarker.column = this.startMarker.column;
138639 }
138640 }; // https://tc39.github.io/ecma262/#sec-primary-expression
138641
138642
138643 Parser.prototype.parsePrimaryExpression = function () {
138644 var node = this.createNode();
138645 var expr;
138646 var token, raw;
138647
138648 switch (this.lookahead.type) {
138649 case 3
138650 /* Identifier */
138651 :
138652 if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') {
138653 this.tolerateUnexpectedToken(this.lookahead);
138654 }
138655
138656 expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
138657 break;
138658
138659 case 6
138660 /* NumericLiteral */
138661 :
138662 case 8
138663 /* StringLiteral */
138664 :
138665 if (this.context.strict && this.lookahead.octal) {
138666 this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
138667 }
138668
138669 this.context.isAssignmentTarget = false;
138670 this.context.isBindingElement = false;
138671 token = this.nextToken();
138672 raw = this.getTokenRaw(token);
138673 expr = this.finalize(node, new Node.Literal(token.value, raw));
138674 break;
138675
138676 case 1
138677 /* BooleanLiteral */
138678 :
138679 this.context.isAssignmentTarget = false;
138680 this.context.isBindingElement = false;
138681 token = this.nextToken();
138682 raw = this.getTokenRaw(token);
138683 expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
138684 break;
138685
138686 case 5
138687 /* NullLiteral */
138688 :
138689 this.context.isAssignmentTarget = false;
138690 this.context.isBindingElement = false;
138691 token = this.nextToken();
138692 raw = this.getTokenRaw(token);
138693 expr = this.finalize(node, new Node.Literal(null, raw));
138694 break;
138695
138696 case 10
138697 /* Template */
138698 :
138699 expr = this.parseTemplateLiteral();
138700 break;
138701
138702 case 7
138703 /* Punctuator */
138704 :
138705 switch (this.lookahead.value) {
138706 case '(':
138707 this.context.isBindingElement = false;
138708 expr = this.inheritCoverGrammar(this.parseGroupExpression);
138709 break;
138710
138711 case '[':
138712 expr = this.inheritCoverGrammar(this.parseArrayInitializer);
138713 break;
138714
138715 case '{':
138716 expr = this.inheritCoverGrammar(this.parseObjectInitializer);
138717 break;
138718
138719 case '/':
138720 case '/=':
138721 this.context.isAssignmentTarget = false;
138722 this.context.isBindingElement = false;
138723 this.scanner.index = this.startMarker.index;
138724 token = this.nextRegexToken();
138725 raw = this.getTokenRaw(token);
138726 expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
138727 break;
138728
138729 default:
138730 expr = this.throwUnexpectedToken(this.nextToken());
138731 }
138732
138733 break;
138734
138735 case 4
138736 /* Keyword */
138737 :
138738 if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
138739 expr = this.parseIdentifierName();
138740 } else if (!this.context.strict && this.matchKeyword('let')) {
138741 expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
138742 } else {
138743 this.context.isAssignmentTarget = false;
138744 this.context.isBindingElement = false;
138745
138746 if (this.matchKeyword('function')) {
138747 expr = this.parseFunctionExpression();
138748 } else if (this.matchKeyword('this')) {
138749 this.nextToken();
138750 expr = this.finalize(node, new Node.ThisExpression());
138751 } else if (this.matchKeyword('class')) {
138752 expr = this.parseClassExpression();
138753 } else {
138754 expr = this.throwUnexpectedToken(this.nextToken());
138755 }
138756 }
138757
138758 break;
138759
138760 default:
138761 expr = this.throwUnexpectedToken(this.nextToken());
138762 }
138763
138764 return expr;
138765 }; // https://tc39.github.io/ecma262/#sec-array-initializer
138766
138767
138768 Parser.prototype.parseSpreadElement = function () {
138769 var node = this.createNode();
138770 this.expect('...');
138771 var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
138772 return this.finalize(node, new Node.SpreadElement(arg));
138773 };
138774
138775 Parser.prototype.parseArrayInitializer = function () {
138776 var node = this.createNode();
138777 var elements = [];
138778 this.expect('[');
138779
138780 while (!this.match(']')) {
138781 if (this.match(',')) {
138782 this.nextToken();
138783 elements.push(null);
138784 } else if (this.match('...')) {
138785 var element = this.parseSpreadElement();
138786
138787 if (!this.match(']')) {
138788 this.context.isAssignmentTarget = false;
138789 this.context.isBindingElement = false;
138790 this.expect(',');
138791 }
138792
138793 elements.push(element);
138794 } else {
138795 elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
138796
138797 if (!this.match(']')) {
138798 this.expect(',');
138799 }
138800 }
138801 }
138802
138803 this.expect(']');
138804 return this.finalize(node, new Node.ArrayExpression(elements));
138805 }; // https://tc39.github.io/ecma262/#sec-object-initializer
138806
138807
138808 Parser.prototype.parsePropertyMethod = function (params) {
138809 this.context.isAssignmentTarget = false;
138810 this.context.isBindingElement = false;
138811 var previousStrict = this.context.strict;
138812 var previousAllowStrictDirective = this.context.allowStrictDirective;
138813 this.context.allowStrictDirective = params.simple;
138814 var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
138815
138816 if (this.context.strict && params.firstRestricted) {
138817 this.tolerateUnexpectedToken(params.firstRestricted, params.message);
138818 }
138819
138820 if (this.context.strict && params.stricted) {
138821 this.tolerateUnexpectedToken(params.stricted, params.message);
138822 }
138823
138824 this.context.strict = previousStrict;
138825 this.context.allowStrictDirective = previousAllowStrictDirective;
138826 return body;
138827 };
138828
138829 Parser.prototype.parsePropertyMethodFunction = function () {
138830 var isGenerator = false;
138831 var node = this.createNode();
138832 var previousAllowYield = this.context.allowYield;
138833 this.context.allowYield = true;
138834 var params = this.parseFormalParameters();
138835 var method = this.parsePropertyMethod(params);
138836 this.context.allowYield = previousAllowYield;
138837 return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
138838 };
138839
138840 Parser.prototype.parsePropertyMethodAsyncFunction = function () {
138841 var node = this.createNode();
138842 var previousAllowYield = this.context.allowYield;
138843 var previousAwait = this.context.await;
138844 this.context.allowYield = false;
138845 this.context.await = true;
138846 var params = this.parseFormalParameters();
138847 var method = this.parsePropertyMethod(params);
138848 this.context.allowYield = previousAllowYield;
138849 this.context.await = previousAwait;
138850 return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
138851 };
138852
138853 Parser.prototype.parseObjectPropertyKey = function () {
138854 var node = this.createNode();
138855 var token = this.nextToken();
138856 var key;
138857
138858 switch (token.type) {
138859 case 8
138860 /* StringLiteral */
138861 :
138862 case 6
138863 /* NumericLiteral */
138864 :
138865 if (this.context.strict && token.octal) {
138866 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
138867 }
138868
138869 var raw = this.getTokenRaw(token);
138870 key = this.finalize(node, new Node.Literal(token.value, raw));
138871 break;
138872
138873 case 3
138874 /* Identifier */
138875 :
138876 case 1
138877 /* BooleanLiteral */
138878 :
138879 case 5
138880 /* NullLiteral */
138881 :
138882 case 4
138883 /* Keyword */
138884 :
138885 key = this.finalize(node, new Node.Identifier(token.value));
138886 break;
138887
138888 case 7
138889 /* Punctuator */
138890 :
138891 if (token.value === '[') {
138892 key = this.isolateCoverGrammar(this.parseAssignmentExpression);
138893 this.expect(']');
138894 } else {
138895 key = this.throwUnexpectedToken(token);
138896 }
138897
138898 break;
138899
138900 default:
138901 key = this.throwUnexpectedToken(token);
138902 }
138903
138904 return key;
138905 };
138906
138907 Parser.prototype.isPropertyKey = function (key, value) {
138908 return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
138909 };
138910
138911 Parser.prototype.parseObjectProperty = function (hasProto) {
138912 var node = this.createNode();
138913 var token = this.lookahead;
138914 var kind;
138915 var key = null;
138916 var value = null;
138917 var computed = false;
138918 var method = false;
138919 var shorthand = false;
138920 var isAsync = false;
138921
138922 if (token.type === 3
138923 /* Identifier */
138924 ) {
138925 var id = token.value;
138926 this.nextToken();
138927 computed = this.match('[');
138928 isAsync = !this.hasLineTerminator && id === 'async' && !this.match(':') && !this.match('(') && !this.match('*') && !this.match(',');
138929 key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
138930 } else if (this.match('*')) {
138931 this.nextToken();
138932 } else {
138933 computed = this.match('[');
138934 key = this.parseObjectPropertyKey();
138935 }
138936
138937 var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
138938
138939 if (token.type === 3
138940 /* Identifier */
138941 && !isAsync && token.value === 'get' && lookaheadPropertyKey) {
138942 kind = 'get';
138943 computed = this.match('[');
138944 key = this.parseObjectPropertyKey();
138945 this.context.allowYield = false;
138946 value = this.parseGetterMethod();
138947 } else if (token.type === 3
138948 /* Identifier */
138949 && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
138950 kind = 'set';
138951 computed = this.match('[');
138952 key = this.parseObjectPropertyKey();
138953 value = this.parseSetterMethod();
138954 } else if (token.type === 7
138955 /* Punctuator */
138956 && token.value === '*' && lookaheadPropertyKey) {
138957 kind = 'init';
138958 computed = this.match('[');
138959 key = this.parseObjectPropertyKey();
138960 value = this.parseGeneratorMethod();
138961 method = true;
138962 } else {
138963 if (!key) {
138964 this.throwUnexpectedToken(this.lookahead);
138965 }
138966
138967 kind = 'init';
138968
138969 if (this.match(':') && !isAsync) {
138970 if (!computed && this.isPropertyKey(key, '__proto__')) {
138971 if (hasProto.value) {
138972 this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
138973 }
138974
138975 hasProto.value = true;
138976 }
138977
138978 this.nextToken();
138979 value = this.inheritCoverGrammar(this.parseAssignmentExpression);
138980 } else if (this.match('(')) {
138981 value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
138982 method = true;
138983 } else if (token.type === 3
138984 /* Identifier */
138985 ) {
138986 var id = this.finalize(node, new Node.Identifier(token.value));
138987
138988 if (this.match('=')) {
138989 this.context.firstCoverInitializedNameError = this.lookahead;
138990 this.nextToken();
138991 shorthand = true;
138992 var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
138993 value = this.finalize(node, new Node.AssignmentPattern(id, init));
138994 } else {
138995 shorthand = true;
138996 value = id;
138997 }
138998 } else {
138999 this.throwUnexpectedToken(this.nextToken());
139000 }
139001 }
139002
139003 return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
139004 };
139005
139006 Parser.prototype.parseObjectInitializer = function () {
139007 var node = this.createNode();
139008 this.expect('{');
139009 var properties = [];
139010 var hasProto = {
139011 value: false
139012 };
139013
139014 while (!this.match('}')) {
139015 properties.push(this.parseObjectProperty(hasProto));
139016
139017 if (!this.match('}')) {
139018 this.expectCommaSeparator();
139019 }
139020 }
139021
139022 this.expect('}');
139023 return this.finalize(node, new Node.ObjectExpression(properties));
139024 }; // https://tc39.github.io/ecma262/#sec-template-literals
139025
139026
139027 Parser.prototype.parseTemplateHead = function () {
139028 assert_1.assert(this.lookahead.head, 'Template literal must start with a template head');
139029 var node = this.createNode();
139030 var token = this.nextToken();
139031 var raw = token.value;
139032 var cooked = token.cooked;
139033 return this.finalize(node, new Node.TemplateElement({
139034 raw: raw,
139035 cooked: cooked
139036 }, token.tail));
139037 };
139038
139039 Parser.prototype.parseTemplateElement = function () {
139040 if (this.lookahead.type !== 10
139041 /* Template */
139042 ) {
139043 this.throwUnexpectedToken();
139044 }
139045
139046 var node = this.createNode();
139047 var token = this.nextToken();
139048 var raw = token.value;
139049 var cooked = token.cooked;
139050 return this.finalize(node, new Node.TemplateElement({
139051 raw: raw,
139052 cooked: cooked
139053 }, token.tail));
139054 };
139055
139056 Parser.prototype.parseTemplateLiteral = function () {
139057 var node = this.createNode();
139058 var expressions = [];
139059 var quasis = [];
139060 var quasi = this.parseTemplateHead();
139061 quasis.push(quasi);
139062
139063 while (!quasi.tail) {
139064 expressions.push(this.parseExpression());
139065 quasi = this.parseTemplateElement();
139066 quasis.push(quasi);
139067 }
139068
139069 return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
139070 }; // https://tc39.github.io/ecma262/#sec-grouping-operator
139071
139072
139073 Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
139074 switch (expr.type) {
139075 case syntax_1.Syntax.Identifier:
139076 case syntax_1.Syntax.MemberExpression:
139077 case syntax_1.Syntax.RestElement:
139078 case syntax_1.Syntax.AssignmentPattern:
139079 break;
139080
139081 case syntax_1.Syntax.SpreadElement:
139082 expr.type = syntax_1.Syntax.RestElement;
139083 this.reinterpretExpressionAsPattern(expr.argument);
139084 break;
139085
139086 case syntax_1.Syntax.ArrayExpression:
139087 expr.type = syntax_1.Syntax.ArrayPattern;
139088
139089 for (var i = 0; i < expr.elements.length; i++) {
139090 if (expr.elements[i] !== null) {
139091 this.reinterpretExpressionAsPattern(expr.elements[i]);
139092 }
139093 }
139094
139095 break;
139096
139097 case syntax_1.Syntax.ObjectExpression:
139098 expr.type = syntax_1.Syntax.ObjectPattern;
139099
139100 for (var i = 0; i < expr.properties.length; i++) {
139101 this.reinterpretExpressionAsPattern(expr.properties[i].value);
139102 }
139103
139104 break;
139105
139106 case syntax_1.Syntax.AssignmentExpression:
139107 expr.type = syntax_1.Syntax.AssignmentPattern;
139108 delete expr.operator;
139109 this.reinterpretExpressionAsPattern(expr.left);
139110 break;
139111
139112 default:
139113 // Allow other node type for tolerant parsing.
139114 break;
139115 }
139116 };
139117
139118 Parser.prototype.parseGroupExpression = function () {
139119 var expr;
139120 this.expect('(');
139121
139122 if (this.match(')')) {
139123 this.nextToken();
139124
139125 if (!this.match('=>')) {
139126 this.expect('=>');
139127 }
139128
139129 expr = {
139130 type: ArrowParameterPlaceHolder,
139131 params: [],
139132 async: false
139133 };
139134 } else {
139135 var startToken = this.lookahead;
139136 var params = [];
139137
139138 if (this.match('...')) {
139139 expr = this.parseRestElement(params);
139140 this.expect(')');
139141
139142 if (!this.match('=>')) {
139143 this.expect('=>');
139144 }
139145
139146 expr = {
139147 type: ArrowParameterPlaceHolder,
139148 params: [expr],
139149 async: false
139150 };
139151 } else {
139152 var arrow = false;
139153 this.context.isBindingElement = true;
139154 expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
139155
139156 if (this.match(',')) {
139157 var expressions = [];
139158 this.context.isAssignmentTarget = false;
139159 expressions.push(expr);
139160
139161 while (this.lookahead.type !== 2
139162 /* EOF */
139163 ) {
139164 if (!this.match(',')) {
139165 break;
139166 }
139167
139168 this.nextToken();
139169
139170 if (this.match(')')) {
139171 this.nextToken();
139172
139173 for (var i = 0; i < expressions.length; i++) {
139174 this.reinterpretExpressionAsPattern(expressions[i]);
139175 }
139176
139177 arrow = true;
139178 expr = {
139179 type: ArrowParameterPlaceHolder,
139180 params: expressions,
139181 async: false
139182 };
139183 } else if (this.match('...')) {
139184 if (!this.context.isBindingElement) {
139185 this.throwUnexpectedToken(this.lookahead);
139186 }
139187
139188 expressions.push(this.parseRestElement(params));
139189 this.expect(')');
139190
139191 if (!this.match('=>')) {
139192 this.expect('=>');
139193 }
139194
139195 this.context.isBindingElement = false;
139196
139197 for (var i = 0; i < expressions.length; i++) {
139198 this.reinterpretExpressionAsPattern(expressions[i]);
139199 }
139200
139201 arrow = true;
139202 expr = {
139203 type: ArrowParameterPlaceHolder,
139204 params: expressions,
139205 async: false
139206 };
139207 } else {
139208 expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
139209 }
139210
139211 if (arrow) {
139212 break;
139213 }
139214 }
139215
139216 if (!arrow) {
139217 expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
139218 }
139219 }
139220
139221 if (!arrow) {
139222 this.expect(')');
139223
139224 if (this.match('=>')) {
139225 if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') {
139226 arrow = true;
139227 expr = {
139228 type: ArrowParameterPlaceHolder,
139229 params: [expr],
139230 async: false
139231 };
139232 }
139233
139234 if (!arrow) {
139235 if (!this.context.isBindingElement) {
139236 this.throwUnexpectedToken(this.lookahead);
139237 }
139238
139239 if (expr.type === syntax_1.Syntax.SequenceExpression) {
139240 for (var i = 0; i < expr.expressions.length; i++) {
139241 this.reinterpretExpressionAsPattern(expr.expressions[i]);
139242 }
139243 } else {
139244 this.reinterpretExpressionAsPattern(expr);
139245 }
139246
139247 var parameters = expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr];
139248 expr = {
139249 type: ArrowParameterPlaceHolder,
139250 params: parameters,
139251 async: false
139252 };
139253 }
139254 }
139255
139256 this.context.isBindingElement = false;
139257 }
139258 }
139259 }
139260
139261 return expr;
139262 }; // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions
139263
139264
139265 Parser.prototype.parseArguments = function () {
139266 this.expect('(');
139267 var args = [];
139268
139269 if (!this.match(')')) {
139270 while (true) {
139271 var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression);
139272 args.push(expr);
139273
139274 if (this.match(')')) {
139275 break;
139276 }
139277
139278 this.expectCommaSeparator();
139279
139280 if (this.match(')')) {
139281 break;
139282 }
139283 }
139284 }
139285
139286 this.expect(')');
139287 return args;
139288 };
139289
139290 Parser.prototype.isIdentifierName = function (token) {
139291 return token.type === 3
139292 /* Identifier */
139293 || token.type === 4
139294 /* Keyword */
139295 || token.type === 1
139296 /* BooleanLiteral */
139297 || token.type === 5
139298 /* NullLiteral */
139299 ;
139300 };
139301
139302 Parser.prototype.parseIdentifierName = function () {
139303 var node = this.createNode();
139304 var token = this.nextToken();
139305
139306 if (!this.isIdentifierName(token)) {
139307 this.throwUnexpectedToken(token);
139308 }
139309
139310 return this.finalize(node, new Node.Identifier(token.value));
139311 };
139312
139313 Parser.prototype.parseNewExpression = function () {
139314 var node = this.createNode();
139315 var id = this.parseIdentifierName();
139316 assert_1.assert(id.name === 'new', 'New expression must start with `new`');
139317 var expr;
139318
139319 if (this.match('.')) {
139320 this.nextToken();
139321
139322 if (this.lookahead.type === 3
139323 /* Identifier */
139324 && this.context.inFunctionBody && this.lookahead.value === 'target') {
139325 var property = this.parseIdentifierName();
139326 expr = new Node.MetaProperty(id, property);
139327 } else {
139328 this.throwUnexpectedToken(this.lookahead);
139329 }
139330 } else {
139331 var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
139332 var args = this.match('(') ? this.parseArguments() : [];
139333 expr = new Node.NewExpression(callee, args);
139334 this.context.isAssignmentTarget = false;
139335 this.context.isBindingElement = false;
139336 }
139337
139338 return this.finalize(node, expr);
139339 };
139340
139341 Parser.prototype.parseAsyncArgument = function () {
139342 var arg = this.parseAssignmentExpression();
139343 this.context.firstCoverInitializedNameError = null;
139344 return arg;
139345 };
139346
139347 Parser.prototype.parseAsyncArguments = function () {
139348 this.expect('(');
139349 var args = [];
139350
139351 if (!this.match(')')) {
139352 while (true) {
139353 var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument);
139354 args.push(expr);
139355
139356 if (this.match(')')) {
139357 break;
139358 }
139359
139360 this.expectCommaSeparator();
139361
139362 if (this.match(')')) {
139363 break;
139364 }
139365 }
139366 }
139367
139368 this.expect(')');
139369 return args;
139370 };
139371
139372 Parser.prototype.parseLeftHandSideExpressionAllowCall = function () {
139373 var startToken = this.lookahead;
139374 var maybeAsync = this.matchContextualKeyword('async');
139375 var previousAllowIn = this.context.allowIn;
139376 this.context.allowIn = true;
139377 var expr;
139378
139379 if (this.matchKeyword('super') && this.context.inFunctionBody) {
139380 expr = this.createNode();
139381 this.nextToken();
139382 expr = this.finalize(expr, new Node.Super());
139383
139384 if (!this.match('(') && !this.match('.') && !this.match('[')) {
139385 this.throwUnexpectedToken(this.lookahead);
139386 }
139387 } else {
139388 expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
139389 }
139390
139391 while (true) {
139392 if (this.match('.')) {
139393 this.context.isBindingElement = false;
139394 this.context.isAssignmentTarget = true;
139395 this.expect('.');
139396 var property = this.parseIdentifierName();
139397 expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
139398 } else if (this.match('(')) {
139399 var asyncArrow = maybeAsync && startToken.lineNumber === this.lookahead.lineNumber;
139400 this.context.isBindingElement = false;
139401 this.context.isAssignmentTarget = false;
139402 var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
139403 expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
139404
139405 if (asyncArrow && this.match('=>')) {
139406 for (var i = 0; i < args.length; ++i) {
139407 this.reinterpretExpressionAsPattern(args[i]);
139408 }
139409
139410 expr = {
139411 type: ArrowParameterPlaceHolder,
139412 params: args,
139413 async: true
139414 };
139415 }
139416 } else if (this.match('[')) {
139417 this.context.isBindingElement = false;
139418 this.context.isAssignmentTarget = true;
139419 this.expect('[');
139420 var property = this.isolateCoverGrammar(this.parseExpression);
139421 this.expect(']');
139422 expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
139423 } else if (this.lookahead.type === 10
139424 /* Template */
139425 && this.lookahead.head) {
139426 var quasi = this.parseTemplateLiteral();
139427 expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
139428 } else {
139429 break;
139430 }
139431 }
139432
139433 this.context.allowIn = previousAllowIn;
139434 return expr;
139435 };
139436
139437 Parser.prototype.parseSuper = function () {
139438 var node = this.createNode();
139439 this.expectKeyword('super');
139440
139441 if (!this.match('[') && !this.match('.')) {
139442 this.throwUnexpectedToken(this.lookahead);
139443 }
139444
139445 return this.finalize(node, new Node.Super());
139446 };
139447
139448 Parser.prototype.parseLeftHandSideExpression = function () {
139449 assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.');
139450 var node = this.startNode(this.lookahead);
139451 var expr = this.matchKeyword('super') && this.context.inFunctionBody ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
139452
139453 while (true) {
139454 if (this.match('[')) {
139455 this.context.isBindingElement = false;
139456 this.context.isAssignmentTarget = true;
139457 this.expect('[');
139458 var property = this.isolateCoverGrammar(this.parseExpression);
139459 this.expect(']');
139460 expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
139461 } else if (this.match('.')) {
139462 this.context.isBindingElement = false;
139463 this.context.isAssignmentTarget = true;
139464 this.expect('.');
139465 var property = this.parseIdentifierName();
139466 expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
139467 } else if (this.lookahead.type === 10
139468 /* Template */
139469 && this.lookahead.head) {
139470 var quasi = this.parseTemplateLiteral();
139471 expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
139472 } else {
139473 break;
139474 }
139475 }
139476
139477 return expr;
139478 }; // https://tc39.github.io/ecma262/#sec-update-expressions
139479
139480
139481 Parser.prototype.parseUpdateExpression = function () {
139482 var expr;
139483 var startToken = this.lookahead;
139484
139485 if (this.match('++') || this.match('--')) {
139486 var node = this.startNode(startToken);
139487 var token = this.nextToken();
139488 expr = this.inheritCoverGrammar(this.parseUnaryExpression);
139489
139490 if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
139491 this.tolerateError(messages_1.Messages.StrictLHSPrefix);
139492 }
139493
139494 if (!this.context.isAssignmentTarget) {
139495 this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
139496 }
139497
139498 var prefix = true;
139499 expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
139500 this.context.isAssignmentTarget = false;
139501 this.context.isBindingElement = false;
139502 } else {
139503 expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
139504
139505 if (!this.hasLineTerminator && this.lookahead.type === 7
139506 /* Punctuator */
139507 ) {
139508 if (this.match('++') || this.match('--')) {
139509 if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
139510 this.tolerateError(messages_1.Messages.StrictLHSPostfix);
139511 }
139512
139513 if (!this.context.isAssignmentTarget) {
139514 this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
139515 }
139516
139517 this.context.isAssignmentTarget = false;
139518 this.context.isBindingElement = false;
139519 var operator = this.nextToken().value;
139520 var prefix = false;
139521 expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
139522 }
139523 }
139524 }
139525
139526 return expr;
139527 }; // https://tc39.github.io/ecma262/#sec-unary-operators
139528
139529
139530 Parser.prototype.parseAwaitExpression = function () {
139531 var node = this.createNode();
139532 this.nextToken();
139533 var argument = this.parseUnaryExpression();
139534 return this.finalize(node, new Node.AwaitExpression(argument));
139535 };
139536
139537 Parser.prototype.parseUnaryExpression = function () {
139538 var expr;
139539
139540 if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) {
139541 var node = this.startNode(this.lookahead);
139542 var token = this.nextToken();
139543 expr = this.inheritCoverGrammar(this.parseUnaryExpression);
139544 expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
139545
139546 if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) {
139547 this.tolerateError(messages_1.Messages.StrictDelete);
139548 }
139549
139550 this.context.isAssignmentTarget = false;
139551 this.context.isBindingElement = false;
139552 } else if (this.context.await && this.matchContextualKeyword('await')) {
139553 expr = this.parseAwaitExpression();
139554 } else {
139555 expr = this.parseUpdateExpression();
139556 }
139557
139558 return expr;
139559 };
139560
139561 Parser.prototype.parseExponentiationExpression = function () {
139562 var startToken = this.lookahead;
139563 var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
139564
139565 if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) {
139566 this.nextToken();
139567 this.context.isAssignmentTarget = false;
139568 this.context.isBindingElement = false;
139569 var left = expr;
139570 var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
139571 expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right));
139572 }
139573
139574 return expr;
139575 }; // https://tc39.github.io/ecma262/#sec-exp-operator
139576 // https://tc39.github.io/ecma262/#sec-multiplicative-operators
139577 // https://tc39.github.io/ecma262/#sec-additive-operators
139578 // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators
139579 // https://tc39.github.io/ecma262/#sec-relational-operators
139580 // https://tc39.github.io/ecma262/#sec-equality-operators
139581 // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators
139582 // https://tc39.github.io/ecma262/#sec-binary-logical-operators
139583
139584
139585 Parser.prototype.binaryPrecedence = function (token) {
139586 var op = token.value;
139587 var precedence;
139588
139589 if (token.type === 7
139590 /* Punctuator */
139591 ) {
139592 precedence = this.operatorPrecedence[op] || 0;
139593 } else if (token.type === 4
139594 /* Keyword */
139595 ) {
139596 precedence = op === 'instanceof' || this.context.allowIn && op === 'in' ? 7 : 0;
139597 } else {
139598 precedence = 0;
139599 }
139600
139601 return precedence;
139602 };
139603
139604 Parser.prototype.parseBinaryExpression = function () {
139605 var startToken = this.lookahead;
139606 var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
139607 var token = this.lookahead;
139608 var prec = this.binaryPrecedence(token);
139609
139610 if (prec > 0) {
139611 this.nextToken();
139612 this.context.isAssignmentTarget = false;
139613 this.context.isBindingElement = false;
139614 var markers = [startToken, this.lookahead];
139615 var left = expr;
139616 var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
139617 var stack = [left, token.value, right];
139618 var precedences = [prec];
139619
139620 while (true) {
139621 prec = this.binaryPrecedence(this.lookahead);
139622
139623 if (prec <= 0) {
139624 break;
139625 } // Reduce: make a binary expression from the three topmost entries.
139626
139627
139628 while (stack.length > 2 && prec <= precedences[precedences.length - 1]) {
139629 right = stack.pop();
139630 var operator = stack.pop();
139631 precedences.pop();
139632 left = stack.pop();
139633 markers.pop();
139634 var node = this.startNode(markers[markers.length - 1]);
139635 stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
139636 } // Shift.
139637
139638
139639 stack.push(this.nextToken().value);
139640 precedences.push(prec);
139641 markers.push(this.lookahead);
139642 stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
139643 } // Final reduce to clean-up the stack.
139644
139645
139646 var i = stack.length - 1;
139647 expr = stack[i];
139648 var lastMarker = markers.pop();
139649
139650 while (i > 1) {
139651 var marker = markers.pop();
139652 var lastLineStart = lastMarker && lastMarker.lineStart;
139653 var node = this.startNode(marker, lastLineStart);
139654 var operator = stack[i - 1];
139655 expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
139656 i -= 2;
139657 lastMarker = marker;
139658 }
139659 }
139660
139661 return expr;
139662 }; // https://tc39.github.io/ecma262/#sec-conditional-operator
139663
139664
139665 Parser.prototype.parseConditionalExpression = function () {
139666 var startToken = this.lookahead;
139667 var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
139668
139669 if (this.match('?')) {
139670 this.nextToken();
139671 var previousAllowIn = this.context.allowIn;
139672 this.context.allowIn = true;
139673 var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
139674 this.context.allowIn = previousAllowIn;
139675 this.expect(':');
139676 var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
139677 expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
139678 this.context.isAssignmentTarget = false;
139679 this.context.isBindingElement = false;
139680 }
139681
139682 return expr;
139683 }; // https://tc39.github.io/ecma262/#sec-assignment-operators
139684
139685
139686 Parser.prototype.checkPatternParam = function (options, param) {
139687 switch (param.type) {
139688 case syntax_1.Syntax.Identifier:
139689 this.validateParam(options, param, param.name);
139690 break;
139691
139692 case syntax_1.Syntax.RestElement:
139693 this.checkPatternParam(options, param.argument);
139694 break;
139695
139696 case syntax_1.Syntax.AssignmentPattern:
139697 this.checkPatternParam(options, param.left);
139698 break;
139699
139700 case syntax_1.Syntax.ArrayPattern:
139701 for (var i = 0; i < param.elements.length; i++) {
139702 if (param.elements[i] !== null) {
139703 this.checkPatternParam(options, param.elements[i]);
139704 }
139705 }
139706
139707 break;
139708
139709 case syntax_1.Syntax.ObjectPattern:
139710 for (var i = 0; i < param.properties.length; i++) {
139711 this.checkPatternParam(options, param.properties[i].value);
139712 }
139713
139714 break;
139715
139716 default:
139717 break;
139718 }
139719
139720 options.simple = options.simple && param instanceof Node.Identifier;
139721 };
139722
139723 Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
139724 var params = [expr];
139725 var options;
139726 var asyncArrow = false;
139727
139728 switch (expr.type) {
139729 case syntax_1.Syntax.Identifier:
139730 break;
139731
139732 case ArrowParameterPlaceHolder:
139733 params = expr.params;
139734 asyncArrow = expr.async;
139735 break;
139736
139737 default:
139738 return null;
139739 }
139740
139741 options = {
139742 simple: true,
139743 paramSet: {}
139744 };
139745
139746 for (var i = 0; i < params.length; ++i) {
139747 var param = params[i];
139748
139749 if (param.type === syntax_1.Syntax.AssignmentPattern) {
139750 if (param.right.type === syntax_1.Syntax.YieldExpression) {
139751 if (param.right.argument) {
139752 this.throwUnexpectedToken(this.lookahead);
139753 }
139754
139755 param.right.type = syntax_1.Syntax.Identifier;
139756 param.right.name = 'yield';
139757 delete param.right.argument;
139758 delete param.right.delegate;
139759 }
139760 } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') {
139761 this.throwUnexpectedToken(this.lookahead);
139762 }
139763
139764 this.checkPatternParam(options, param);
139765 params[i] = param;
139766 }
139767
139768 if (this.context.strict || !this.context.allowYield) {
139769 for (var i = 0; i < params.length; ++i) {
139770 var param = params[i];
139771
139772 if (param.type === syntax_1.Syntax.YieldExpression) {
139773 this.throwUnexpectedToken(this.lookahead);
139774 }
139775 }
139776 }
139777
139778 if (options.message === messages_1.Messages.StrictParamDupe) {
139779 var token = this.context.strict ? options.stricted : options.firstRestricted;
139780 this.throwUnexpectedToken(token, options.message);
139781 }
139782
139783 return {
139784 simple: options.simple,
139785 params: params,
139786 stricted: options.stricted,
139787 firstRestricted: options.firstRestricted,
139788 message: options.message
139789 };
139790 };
139791
139792 Parser.prototype.parseAssignmentExpression = function () {
139793 var expr;
139794
139795 if (!this.context.allowYield && this.matchKeyword('yield')) {
139796 expr = this.parseYieldExpression();
139797 } else {
139798 var startToken = this.lookahead;
139799 var token = startToken;
139800 expr = this.parseConditionalExpression();
139801
139802 if (token.type === 3
139803 /* Identifier */
139804 && token.lineNumber === this.lookahead.lineNumber && token.value === 'async') {
139805 if (this.lookahead.type === 3
139806 /* Identifier */
139807 || this.matchKeyword('yield')) {
139808 var arg = this.parsePrimaryExpression();
139809 this.reinterpretExpressionAsPattern(arg);
139810 expr = {
139811 type: ArrowParameterPlaceHolder,
139812 params: [arg],
139813 async: true
139814 };
139815 }
139816 }
139817
139818 if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
139819 // https://tc39.github.io/ecma262/#sec-arrow-function-definitions
139820 this.context.isAssignmentTarget = false;
139821 this.context.isBindingElement = false;
139822 var isAsync = expr.async;
139823 var list = this.reinterpretAsCoverFormalsList(expr);
139824
139825 if (list) {
139826 if (this.hasLineTerminator) {
139827 this.tolerateUnexpectedToken(this.lookahead);
139828 }
139829
139830 this.context.firstCoverInitializedNameError = null;
139831 var previousStrict = this.context.strict;
139832 var previousAllowStrictDirective = this.context.allowStrictDirective;
139833 this.context.allowStrictDirective = list.simple;
139834 var previousAllowYield = this.context.allowYield;
139835 var previousAwait = this.context.await;
139836 this.context.allowYield = true;
139837 this.context.await = isAsync;
139838 var node = this.startNode(startToken);
139839 this.expect('=>');
139840 var body = void 0;
139841
139842 if (this.match('{')) {
139843 var previousAllowIn = this.context.allowIn;
139844 this.context.allowIn = true;
139845 body = this.parseFunctionSourceElements();
139846 this.context.allowIn = previousAllowIn;
139847 } else {
139848 body = this.isolateCoverGrammar(this.parseAssignmentExpression);
139849 }
139850
139851 var expression = body.type !== syntax_1.Syntax.BlockStatement;
139852
139853 if (this.context.strict && list.firstRestricted) {
139854 this.throwUnexpectedToken(list.firstRestricted, list.message);
139855 }
139856
139857 if (this.context.strict && list.stricted) {
139858 this.tolerateUnexpectedToken(list.stricted, list.message);
139859 }
139860
139861 expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
139862 this.context.strict = previousStrict;
139863 this.context.allowStrictDirective = previousAllowStrictDirective;
139864 this.context.allowYield = previousAllowYield;
139865 this.context.await = previousAwait;
139866 }
139867 } else {
139868 if (this.matchAssign()) {
139869 if (!this.context.isAssignmentTarget) {
139870 this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
139871 }
139872
139873 if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
139874 var id = expr;
139875
139876 if (this.scanner.isRestrictedWord(id.name)) {
139877 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
139878 }
139879
139880 if (this.scanner.isStrictModeReservedWord(id.name)) {
139881 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
139882 }
139883 }
139884
139885 if (!this.match('=')) {
139886 this.context.isAssignmentTarget = false;
139887 this.context.isBindingElement = false;
139888 } else {
139889 this.reinterpretExpressionAsPattern(expr);
139890 }
139891
139892 token = this.nextToken();
139893 var operator = token.value;
139894 var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
139895 expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
139896 this.context.firstCoverInitializedNameError = null;
139897 }
139898 }
139899 }
139900
139901 return expr;
139902 }; // https://tc39.github.io/ecma262/#sec-comma-operator
139903
139904
139905 Parser.prototype.parseExpression = function () {
139906 var startToken = this.lookahead;
139907 var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
139908
139909 if (this.match(',')) {
139910 var expressions = [];
139911 expressions.push(expr);
139912
139913 while (this.lookahead.type !== 2
139914 /* EOF */
139915 ) {
139916 if (!this.match(',')) {
139917 break;
139918 }
139919
139920 this.nextToken();
139921 expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
139922 }
139923
139924 expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
139925 }
139926
139927 return expr;
139928 }; // https://tc39.github.io/ecma262/#sec-block
139929
139930
139931 Parser.prototype.parseStatementListItem = function () {
139932 var statement;
139933 this.context.isAssignmentTarget = true;
139934 this.context.isBindingElement = true;
139935
139936 if (this.lookahead.type === 4
139937 /* Keyword */
139938 ) {
139939 switch (this.lookahead.value) {
139940 case 'export':
139941 if (!this.context.isModule) {
139942 this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
139943 }
139944
139945 statement = this.parseExportDeclaration();
139946 break;
139947
139948 case 'import':
139949 if (!this.context.isModule) {
139950 this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
139951 }
139952
139953 statement = this.parseImportDeclaration();
139954 break;
139955
139956 case 'const':
139957 statement = this.parseLexicalDeclaration({
139958 inFor: false
139959 });
139960 break;
139961
139962 case 'function':
139963 statement = this.parseFunctionDeclaration();
139964 break;
139965
139966 case 'class':
139967 statement = this.parseClassDeclaration();
139968 break;
139969
139970 case 'let':
139971 statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({
139972 inFor: false
139973 }) : this.parseStatement();
139974 break;
139975
139976 default:
139977 statement = this.parseStatement();
139978 break;
139979 }
139980 } else {
139981 statement = this.parseStatement();
139982 }
139983
139984 return statement;
139985 };
139986
139987 Parser.prototype.parseBlock = function () {
139988 var node = this.createNode();
139989 this.expect('{');
139990 var block = [];
139991
139992 while (true) {
139993 if (this.match('}')) {
139994 break;
139995 }
139996
139997 block.push(this.parseStatementListItem());
139998 }
139999
140000 this.expect('}');
140001 return this.finalize(node, new Node.BlockStatement(block));
140002 }; // https://tc39.github.io/ecma262/#sec-let-and-const-declarations
140003
140004
140005 Parser.prototype.parseLexicalBinding = function (kind, options) {
140006 var node = this.createNode();
140007 var params = [];
140008 var id = this.parsePattern(params, kind);
140009
140010 if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
140011 if (this.scanner.isRestrictedWord(id.name)) {
140012 this.tolerateError(messages_1.Messages.StrictVarName);
140013 }
140014 }
140015
140016 var init = null;
140017
140018 if (kind === 'const') {
140019 if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) {
140020 if (this.match('=')) {
140021 this.nextToken();
140022 init = this.isolateCoverGrammar(this.parseAssignmentExpression);
140023 } else {
140024 this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
140025 }
140026 }
140027 } else if (!options.inFor && id.type !== syntax_1.Syntax.Identifier || this.match('=')) {
140028 this.expect('=');
140029 init = this.isolateCoverGrammar(this.parseAssignmentExpression);
140030 }
140031
140032 return this.finalize(node, new Node.VariableDeclarator(id, init));
140033 };
140034
140035 Parser.prototype.parseBindingList = function (kind, options) {
140036 var list = [this.parseLexicalBinding(kind, options)];
140037
140038 while (this.match(',')) {
140039 this.nextToken();
140040 list.push(this.parseLexicalBinding(kind, options));
140041 }
140042
140043 return list;
140044 };
140045
140046 Parser.prototype.isLexicalDeclaration = function () {
140047 var state = this.scanner.saveState();
140048 this.scanner.scanComments();
140049 var next = this.scanner.lex();
140050 this.scanner.restoreState(state);
140051 return next.type === 3
140052 /* Identifier */
140053 || next.type === 7
140054 /* Punctuator */
140055 && next.value === '[' || next.type === 7
140056 /* Punctuator */
140057 && next.value === '{' || next.type === 4
140058 /* Keyword */
140059 && next.value === 'let' || next.type === 4
140060 /* Keyword */
140061 && next.value === 'yield';
140062 };
140063
140064 Parser.prototype.parseLexicalDeclaration = function (options) {
140065 var node = this.createNode();
140066 var kind = this.nextToken().value;
140067 assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
140068 var declarations = this.parseBindingList(kind, options);
140069 this.consumeSemicolon();
140070 return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
140071 }; // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns
140072
140073
140074 Parser.prototype.parseBindingRestElement = function (params, kind) {
140075 var node = this.createNode();
140076 this.expect('...');
140077 var arg = this.parsePattern(params, kind);
140078 return this.finalize(node, new Node.RestElement(arg));
140079 };
140080
140081 Parser.prototype.parseArrayPattern = function (params, kind) {
140082 var node = this.createNode();
140083 this.expect('[');
140084 var elements = [];
140085
140086 while (!this.match(']')) {
140087 if (this.match(',')) {
140088 this.nextToken();
140089 elements.push(null);
140090 } else {
140091 if (this.match('...')) {
140092 elements.push(this.parseBindingRestElement(params, kind));
140093 break;
140094 } else {
140095 elements.push(this.parsePatternWithDefault(params, kind));
140096 }
140097
140098 if (!this.match(']')) {
140099 this.expect(',');
140100 }
140101 }
140102 }
140103
140104 this.expect(']');
140105 return this.finalize(node, new Node.ArrayPattern(elements));
140106 };
140107
140108 Parser.prototype.parsePropertyPattern = function (params, kind) {
140109 var node = this.createNode();
140110 var computed = false;
140111 var shorthand = false;
140112 var method = false;
140113 var key;
140114 var value;
140115
140116 if (this.lookahead.type === 3
140117 /* Identifier */
140118 ) {
140119 var keyToken = this.lookahead;
140120 key = this.parseVariableIdentifier();
140121 var init = this.finalize(node, new Node.Identifier(keyToken.value));
140122
140123 if (this.match('=')) {
140124 params.push(keyToken);
140125 shorthand = true;
140126 this.nextToken();
140127 var expr = this.parseAssignmentExpression();
140128 value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
140129 } else if (!this.match(':')) {
140130 params.push(keyToken);
140131 shorthand = true;
140132 value = init;
140133 } else {
140134 this.expect(':');
140135 value = this.parsePatternWithDefault(params, kind);
140136 }
140137 } else {
140138 computed = this.match('[');
140139 key = this.parseObjectPropertyKey();
140140 this.expect(':');
140141 value = this.parsePatternWithDefault(params, kind);
140142 }
140143
140144 return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand));
140145 };
140146
140147 Parser.prototype.parseObjectPattern = function (params, kind) {
140148 var node = this.createNode();
140149 var properties = [];
140150 this.expect('{');
140151
140152 while (!this.match('}')) {
140153 properties.push(this.parsePropertyPattern(params, kind));
140154
140155 if (!this.match('}')) {
140156 this.expect(',');
140157 }
140158 }
140159
140160 this.expect('}');
140161 return this.finalize(node, new Node.ObjectPattern(properties));
140162 };
140163
140164 Parser.prototype.parsePattern = function (params, kind) {
140165 var pattern;
140166
140167 if (this.match('[')) {
140168 pattern = this.parseArrayPattern(params, kind);
140169 } else if (this.match('{')) {
140170 pattern = this.parseObjectPattern(params, kind);
140171 } else {
140172 if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) {
140173 this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
140174 }
140175
140176 params.push(this.lookahead);
140177 pattern = this.parseVariableIdentifier(kind);
140178 }
140179
140180 return pattern;
140181 };
140182
140183 Parser.prototype.parsePatternWithDefault = function (params, kind) {
140184 var startToken = this.lookahead;
140185 var pattern = this.parsePattern(params, kind);
140186
140187 if (this.match('=')) {
140188 this.nextToken();
140189 var previousAllowYield = this.context.allowYield;
140190 this.context.allowYield = true;
140191 var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
140192 this.context.allowYield = previousAllowYield;
140193 pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
140194 }
140195
140196 return pattern;
140197 }; // https://tc39.github.io/ecma262/#sec-variable-statement
140198
140199
140200 Parser.prototype.parseVariableIdentifier = function (kind) {
140201 var node = this.createNode();
140202 var token = this.nextToken();
140203
140204 if (token.type === 4
140205 /* Keyword */
140206 && token.value === 'yield') {
140207 if (this.context.strict) {
140208 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
140209 } else if (!this.context.allowYield) {
140210 this.throwUnexpectedToken(token);
140211 }
140212 } else if (token.type !== 3
140213 /* Identifier */
140214 ) {
140215 if (this.context.strict && token.type === 4
140216 /* Keyword */
140217 && this.scanner.isStrictModeReservedWord(token.value)) {
140218 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
140219 } else {
140220 if (this.context.strict || token.value !== 'let' || kind !== 'var') {
140221 this.throwUnexpectedToken(token);
140222 }
140223 }
140224 } else if ((this.context.isModule || this.context.await) && token.type === 3
140225 /* Identifier */
140226 && token.value === 'await') {
140227 this.tolerateUnexpectedToken(token);
140228 }
140229
140230 return this.finalize(node, new Node.Identifier(token.value));
140231 };
140232
140233 Parser.prototype.parseVariableDeclaration = function (options) {
140234 var node = this.createNode();
140235 var params = [];
140236 var id = this.parsePattern(params, 'var');
140237
140238 if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
140239 if (this.scanner.isRestrictedWord(id.name)) {
140240 this.tolerateError(messages_1.Messages.StrictVarName);
140241 }
140242 }
140243
140244 var init = null;
140245
140246 if (this.match('=')) {
140247 this.nextToken();
140248 init = this.isolateCoverGrammar(this.parseAssignmentExpression);
140249 } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
140250 this.expect('=');
140251 }
140252
140253 return this.finalize(node, new Node.VariableDeclarator(id, init));
140254 };
140255
140256 Parser.prototype.parseVariableDeclarationList = function (options) {
140257 var opt = {
140258 inFor: options.inFor
140259 };
140260 var list = [];
140261 list.push(this.parseVariableDeclaration(opt));
140262
140263 while (this.match(',')) {
140264 this.nextToken();
140265 list.push(this.parseVariableDeclaration(opt));
140266 }
140267
140268 return list;
140269 };
140270
140271 Parser.prototype.parseVariableStatement = function () {
140272 var node = this.createNode();
140273 this.expectKeyword('var');
140274 var declarations = this.parseVariableDeclarationList({
140275 inFor: false
140276 });
140277 this.consumeSemicolon();
140278 return this.finalize(node, new Node.VariableDeclaration(declarations, 'var'));
140279 }; // https://tc39.github.io/ecma262/#sec-empty-statement
140280
140281
140282 Parser.prototype.parseEmptyStatement = function () {
140283 var node = this.createNode();
140284 this.expect(';');
140285 return this.finalize(node, new Node.EmptyStatement());
140286 }; // https://tc39.github.io/ecma262/#sec-expression-statement
140287
140288
140289 Parser.prototype.parseExpressionStatement = function () {
140290 var node = this.createNode();
140291 var expr = this.parseExpression();
140292 this.consumeSemicolon();
140293 return this.finalize(node, new Node.ExpressionStatement(expr));
140294 }; // https://tc39.github.io/ecma262/#sec-if-statement
140295
140296
140297 Parser.prototype.parseIfClause = function () {
140298 if (this.context.strict && this.matchKeyword('function')) {
140299 this.tolerateError(messages_1.Messages.StrictFunction);
140300 }
140301
140302 return this.parseStatement();
140303 };
140304
140305 Parser.prototype.parseIfStatement = function () {
140306 var node = this.createNode();
140307 var consequent;
140308 var alternate = null;
140309 this.expectKeyword('if');
140310 this.expect('(');
140311 var test = this.parseExpression();
140312
140313 if (!this.match(')') && this.config.tolerant) {
140314 this.tolerateUnexpectedToken(this.nextToken());
140315 consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
140316 } else {
140317 this.expect(')');
140318 consequent = this.parseIfClause();
140319
140320 if (this.matchKeyword('else')) {
140321 this.nextToken();
140322 alternate = this.parseIfClause();
140323 }
140324 }
140325
140326 return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
140327 }; // https://tc39.github.io/ecma262/#sec-do-while-statement
140328
140329
140330 Parser.prototype.parseDoWhileStatement = function () {
140331 var node = this.createNode();
140332 this.expectKeyword('do');
140333 var previousInIteration = this.context.inIteration;
140334 this.context.inIteration = true;
140335 var body = this.parseStatement();
140336 this.context.inIteration = previousInIteration;
140337 this.expectKeyword('while');
140338 this.expect('(');
140339 var test = this.parseExpression();
140340
140341 if (!this.match(')') && this.config.tolerant) {
140342 this.tolerateUnexpectedToken(this.nextToken());
140343 } else {
140344 this.expect(')');
140345
140346 if (this.match(';')) {
140347 this.nextToken();
140348 }
140349 }
140350
140351 return this.finalize(node, new Node.DoWhileStatement(body, test));
140352 }; // https://tc39.github.io/ecma262/#sec-while-statement
140353
140354
140355 Parser.prototype.parseWhileStatement = function () {
140356 var node = this.createNode();
140357 var body;
140358 this.expectKeyword('while');
140359 this.expect('(');
140360 var test = this.parseExpression();
140361
140362 if (!this.match(')') && this.config.tolerant) {
140363 this.tolerateUnexpectedToken(this.nextToken());
140364 body = this.finalize(this.createNode(), new Node.EmptyStatement());
140365 } else {
140366 this.expect(')');
140367 var previousInIteration = this.context.inIteration;
140368 this.context.inIteration = true;
140369 body = this.parseStatement();
140370 this.context.inIteration = previousInIteration;
140371 }
140372
140373 return this.finalize(node, new Node.WhileStatement(test, body));
140374 }; // https://tc39.github.io/ecma262/#sec-for-statement
140375 // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements
140376
140377
140378 Parser.prototype.parseForStatement = function () {
140379 var init = null;
140380 var test = null;
140381 var update = null;
140382 var forIn = true;
140383 var left, right;
140384 var node = this.createNode();
140385 this.expectKeyword('for');
140386 this.expect('(');
140387
140388 if (this.match(';')) {
140389 this.nextToken();
140390 } else {
140391 if (this.matchKeyword('var')) {
140392 init = this.createNode();
140393 this.nextToken();
140394 var previousAllowIn = this.context.allowIn;
140395 this.context.allowIn = false;
140396 var declarations = this.parseVariableDeclarationList({
140397 inFor: true
140398 });
140399 this.context.allowIn = previousAllowIn;
140400
140401 if (declarations.length === 1 && this.matchKeyword('in')) {
140402 var decl = declarations[0];
140403
140404 if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
140405 this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
140406 }
140407
140408 init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
140409 this.nextToken();
140410 left = init;
140411 right = this.parseExpression();
140412 init = null;
140413 } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
140414 init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
140415 this.nextToken();
140416 left = init;
140417 right = this.parseAssignmentExpression();
140418 init = null;
140419 forIn = false;
140420 } else {
140421 init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
140422 this.expect(';');
140423 }
140424 } else if (this.matchKeyword('const') || this.matchKeyword('let')) {
140425 init = this.createNode();
140426 var kind = this.nextToken().value;
140427
140428 if (!this.context.strict && this.lookahead.value === 'in') {
140429 init = this.finalize(init, new Node.Identifier(kind));
140430 this.nextToken();
140431 left = init;
140432 right = this.parseExpression();
140433 init = null;
140434 } else {
140435 var previousAllowIn = this.context.allowIn;
140436 this.context.allowIn = false;
140437 var declarations = this.parseBindingList(kind, {
140438 inFor: true
140439 });
140440 this.context.allowIn = previousAllowIn;
140441
140442 if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) {
140443 init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
140444 this.nextToken();
140445 left = init;
140446 right = this.parseExpression();
140447 init = null;
140448 } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
140449 init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
140450 this.nextToken();
140451 left = init;
140452 right = this.parseAssignmentExpression();
140453 init = null;
140454 forIn = false;
140455 } else {
140456 this.consumeSemicolon();
140457 init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
140458 }
140459 }
140460 } else {
140461 var initStartToken = this.lookahead;
140462 var previousAllowIn = this.context.allowIn;
140463 this.context.allowIn = false;
140464 init = this.inheritCoverGrammar(this.parseAssignmentExpression);
140465 this.context.allowIn = previousAllowIn;
140466
140467 if (this.matchKeyword('in')) {
140468 if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
140469 this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
140470 }
140471
140472 this.nextToken();
140473 this.reinterpretExpressionAsPattern(init);
140474 left = init;
140475 right = this.parseExpression();
140476 init = null;
140477 } else if (this.matchContextualKeyword('of')) {
140478 if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
140479 this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
140480 }
140481
140482 this.nextToken();
140483 this.reinterpretExpressionAsPattern(init);
140484 left = init;
140485 right = this.parseAssignmentExpression();
140486 init = null;
140487 forIn = false;
140488 } else {
140489 if (this.match(',')) {
140490 var initSeq = [init];
140491
140492 while (this.match(',')) {
140493 this.nextToken();
140494 initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
140495 }
140496
140497 init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
140498 }
140499
140500 this.expect(';');
140501 }
140502 }
140503 }
140504
140505 if (typeof left === 'undefined') {
140506 if (!this.match(';')) {
140507 test = this.parseExpression();
140508 }
140509
140510 this.expect(';');
140511
140512 if (!this.match(')')) {
140513 update = this.parseExpression();
140514 }
140515 }
140516
140517 var body;
140518
140519 if (!this.match(')') && this.config.tolerant) {
140520 this.tolerateUnexpectedToken(this.nextToken());
140521 body = this.finalize(this.createNode(), new Node.EmptyStatement());
140522 } else {
140523 this.expect(')');
140524 var previousInIteration = this.context.inIteration;
140525 this.context.inIteration = true;
140526 body = this.isolateCoverGrammar(this.parseStatement);
140527 this.context.inIteration = previousInIteration;
140528 }
140529
140530 return typeof left === 'undefined' ? this.finalize(node, new Node.ForStatement(init, test, update, body)) : forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : this.finalize(node, new Node.ForOfStatement(left, right, body));
140531 }; // https://tc39.github.io/ecma262/#sec-continue-statement
140532
140533
140534 Parser.prototype.parseContinueStatement = function () {
140535 var node = this.createNode();
140536 this.expectKeyword('continue');
140537 var label = null;
140538
140539 if (this.lookahead.type === 3
140540 /* Identifier */
140541 && !this.hasLineTerminator) {
140542 var id = this.parseVariableIdentifier();
140543 label = id;
140544 var key = '$' + id.name;
140545
140546 if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
140547 this.throwError(messages_1.Messages.UnknownLabel, id.name);
140548 }
140549 }
140550
140551 this.consumeSemicolon();
140552
140553 if (label === null && !this.context.inIteration) {
140554 this.throwError(messages_1.Messages.IllegalContinue);
140555 }
140556
140557 return this.finalize(node, new Node.ContinueStatement(label));
140558 }; // https://tc39.github.io/ecma262/#sec-break-statement
140559
140560
140561 Parser.prototype.parseBreakStatement = function () {
140562 var node = this.createNode();
140563 this.expectKeyword('break');
140564 var label = null;
140565
140566 if (this.lookahead.type === 3
140567 /* Identifier */
140568 && !this.hasLineTerminator) {
140569 var id = this.parseVariableIdentifier();
140570 var key = '$' + id.name;
140571
140572 if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
140573 this.throwError(messages_1.Messages.UnknownLabel, id.name);
140574 }
140575
140576 label = id;
140577 }
140578
140579 this.consumeSemicolon();
140580
140581 if (label === null && !this.context.inIteration && !this.context.inSwitch) {
140582 this.throwError(messages_1.Messages.IllegalBreak);
140583 }
140584
140585 return this.finalize(node, new Node.BreakStatement(label));
140586 }; // https://tc39.github.io/ecma262/#sec-return-statement
140587
140588
140589 Parser.prototype.parseReturnStatement = function () {
140590 if (!this.context.inFunctionBody) {
140591 this.tolerateError(messages_1.Messages.IllegalReturn);
140592 }
140593
140594 var node = this.createNode();
140595 this.expectKeyword('return');
140596 var hasArgument = !this.match(';') && !this.match('}') && !this.hasLineTerminator && this.lookahead.type !== 2
140597 /* EOF */
140598 || this.lookahead.type === 8
140599 /* StringLiteral */
140600 || this.lookahead.type === 10
140601 /* Template */
140602 ;
140603 var argument = hasArgument ? this.parseExpression() : null;
140604 this.consumeSemicolon();
140605 return this.finalize(node, new Node.ReturnStatement(argument));
140606 }; // https://tc39.github.io/ecma262/#sec-with-statement
140607
140608
140609 Parser.prototype.parseWithStatement = function () {
140610 if (this.context.strict) {
140611 this.tolerateError(messages_1.Messages.StrictModeWith);
140612 }
140613
140614 var node = this.createNode();
140615 var body;
140616 this.expectKeyword('with');
140617 this.expect('(');
140618 var object = this.parseExpression();
140619
140620 if (!this.match(')') && this.config.tolerant) {
140621 this.tolerateUnexpectedToken(this.nextToken());
140622 body = this.finalize(this.createNode(), new Node.EmptyStatement());
140623 } else {
140624 this.expect(')');
140625 body = this.parseStatement();
140626 }
140627
140628 return this.finalize(node, new Node.WithStatement(object, body));
140629 }; // https://tc39.github.io/ecma262/#sec-switch-statement
140630
140631
140632 Parser.prototype.parseSwitchCase = function () {
140633 var node = this.createNode();
140634 var test;
140635
140636 if (this.matchKeyword('default')) {
140637 this.nextToken();
140638 test = null;
140639 } else {
140640 this.expectKeyword('case');
140641 test = this.parseExpression();
140642 }
140643
140644 this.expect(':');
140645 var consequent = [];
140646
140647 while (true) {
140648 if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) {
140649 break;
140650 }
140651
140652 consequent.push(this.parseStatementListItem());
140653 }
140654
140655 return this.finalize(node, new Node.SwitchCase(test, consequent));
140656 };
140657
140658 Parser.prototype.parseSwitchStatement = function () {
140659 var node = this.createNode();
140660 this.expectKeyword('switch');
140661 this.expect('(');
140662 var discriminant = this.parseExpression();
140663 this.expect(')');
140664 var previousInSwitch = this.context.inSwitch;
140665 this.context.inSwitch = true;
140666 var cases = [];
140667 var defaultFound = false;
140668 this.expect('{');
140669
140670 while (true) {
140671 if (this.match('}')) {
140672 break;
140673 }
140674
140675 var clause = this.parseSwitchCase();
140676
140677 if (clause.test === null) {
140678 if (defaultFound) {
140679 this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
140680 }
140681
140682 defaultFound = true;
140683 }
140684
140685 cases.push(clause);
140686 }
140687
140688 this.expect('}');
140689 this.context.inSwitch = previousInSwitch;
140690 return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
140691 }; // https://tc39.github.io/ecma262/#sec-labelled-statements
140692
140693
140694 Parser.prototype.parseLabelledStatement = function () {
140695 var node = this.createNode();
140696 var expr = this.parseExpression();
140697 var statement;
140698
140699 if (expr.type === syntax_1.Syntax.Identifier && this.match(':')) {
140700 this.nextToken();
140701 var id = expr;
140702 var key = '$' + id.name;
140703
140704 if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
140705 this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name);
140706 }
140707
140708 this.context.labelSet[key] = true;
140709 var body = void 0;
140710
140711 if (this.matchKeyword('class')) {
140712 this.tolerateUnexpectedToken(this.lookahead);
140713 body = this.parseClassDeclaration();
140714 } else if (this.matchKeyword('function')) {
140715 var token = this.lookahead;
140716 var declaration = this.parseFunctionDeclaration();
140717
140718 if (this.context.strict) {
140719 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
140720 } else if (declaration.generator) {
140721 this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
140722 }
140723
140724 body = declaration;
140725 } else {
140726 body = this.parseStatement();
140727 }
140728
140729 delete this.context.labelSet[key];
140730 statement = new Node.LabeledStatement(id, body);
140731 } else {
140732 this.consumeSemicolon();
140733 statement = new Node.ExpressionStatement(expr);
140734 }
140735
140736 return this.finalize(node, statement);
140737 }; // https://tc39.github.io/ecma262/#sec-throw-statement
140738
140739
140740 Parser.prototype.parseThrowStatement = function () {
140741 var node = this.createNode();
140742 this.expectKeyword('throw');
140743
140744 if (this.hasLineTerminator) {
140745 this.throwError(messages_1.Messages.NewlineAfterThrow);
140746 }
140747
140748 var argument = this.parseExpression();
140749 this.consumeSemicolon();
140750 return this.finalize(node, new Node.ThrowStatement(argument));
140751 }; // https://tc39.github.io/ecma262/#sec-try-statement
140752
140753
140754 Parser.prototype.parseCatchClause = function () {
140755 var node = this.createNode();
140756 this.expectKeyword('catch');
140757 this.expect('(');
140758
140759 if (this.match(')')) {
140760 this.throwUnexpectedToken(this.lookahead);
140761 }
140762
140763 var params = [];
140764 var param = this.parsePattern(params);
140765 var paramMap = {};
140766
140767 for (var i = 0; i < params.length; i++) {
140768 var key = '$' + params[i].value;
140769
140770 if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
140771 this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
140772 }
140773
140774 paramMap[key] = true;
140775 }
140776
140777 if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
140778 if (this.scanner.isRestrictedWord(param.name)) {
140779 this.tolerateError(messages_1.Messages.StrictCatchVariable);
140780 }
140781 }
140782
140783 this.expect(')');
140784 var body = this.parseBlock();
140785 return this.finalize(node, new Node.CatchClause(param, body));
140786 };
140787
140788 Parser.prototype.parseFinallyClause = function () {
140789 this.expectKeyword('finally');
140790 return this.parseBlock();
140791 };
140792
140793 Parser.prototype.parseTryStatement = function () {
140794 var node = this.createNode();
140795 this.expectKeyword('try');
140796 var block = this.parseBlock();
140797 var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null;
140798 var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null;
140799
140800 if (!handler && !finalizer) {
140801 this.throwError(messages_1.Messages.NoCatchOrFinally);
140802 }
140803
140804 return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
140805 }; // https://tc39.github.io/ecma262/#sec-debugger-statement
140806
140807
140808 Parser.prototype.parseDebuggerStatement = function () {
140809 var node = this.createNode();
140810 this.expectKeyword('debugger');
140811 this.consumeSemicolon();
140812 return this.finalize(node, new Node.DebuggerStatement());
140813 }; // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations
140814
140815
140816 Parser.prototype.parseStatement = function () {
140817 var statement;
140818
140819 switch (this.lookahead.type) {
140820 case 1
140821 /* BooleanLiteral */
140822 :
140823 case 5
140824 /* NullLiteral */
140825 :
140826 case 6
140827 /* NumericLiteral */
140828 :
140829 case 8
140830 /* StringLiteral */
140831 :
140832 case 10
140833 /* Template */
140834 :
140835 case 9
140836 /* RegularExpression */
140837 :
140838 statement = this.parseExpressionStatement();
140839 break;
140840
140841 case 7
140842 /* Punctuator */
140843 :
140844 var value = this.lookahead.value;
140845
140846 if (value === '{') {
140847 statement = this.parseBlock();
140848 } else if (value === '(') {
140849 statement = this.parseExpressionStatement();
140850 } else if (value === ';') {
140851 statement = this.parseEmptyStatement();
140852 } else {
140853 statement = this.parseExpressionStatement();
140854 }
140855
140856 break;
140857
140858 case 3
140859 /* Identifier */
140860 :
140861 statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
140862 break;
140863
140864 case 4
140865 /* Keyword */
140866 :
140867 switch (this.lookahead.value) {
140868 case 'break':
140869 statement = this.parseBreakStatement();
140870 break;
140871
140872 case 'continue':
140873 statement = this.parseContinueStatement();
140874 break;
140875
140876 case 'debugger':
140877 statement = this.parseDebuggerStatement();
140878 break;
140879
140880 case 'do':
140881 statement = this.parseDoWhileStatement();
140882 break;
140883
140884 case 'for':
140885 statement = this.parseForStatement();
140886 break;
140887
140888 case 'function':
140889 statement = this.parseFunctionDeclaration();
140890 break;
140891
140892 case 'if':
140893 statement = this.parseIfStatement();
140894 break;
140895
140896 case 'return':
140897 statement = this.parseReturnStatement();
140898 break;
140899
140900 case 'switch':
140901 statement = this.parseSwitchStatement();
140902 break;
140903
140904 case 'throw':
140905 statement = this.parseThrowStatement();
140906 break;
140907
140908 case 'try':
140909 statement = this.parseTryStatement();
140910 break;
140911
140912 case 'var':
140913 statement = this.parseVariableStatement();
140914 break;
140915
140916 case 'while':
140917 statement = this.parseWhileStatement();
140918 break;
140919
140920 case 'with':
140921 statement = this.parseWithStatement();
140922 break;
140923
140924 default:
140925 statement = this.parseExpressionStatement();
140926 break;
140927 }
140928
140929 break;
140930
140931 default:
140932 statement = this.throwUnexpectedToken(this.lookahead);
140933 }
140934
140935 return statement;
140936 }; // https://tc39.github.io/ecma262/#sec-function-definitions
140937
140938
140939 Parser.prototype.parseFunctionSourceElements = function () {
140940 var node = this.createNode();
140941 this.expect('{');
140942 var body = this.parseDirectivePrologues();
140943 var previousLabelSet = this.context.labelSet;
140944 var previousInIteration = this.context.inIteration;
140945 var previousInSwitch = this.context.inSwitch;
140946 var previousInFunctionBody = this.context.inFunctionBody;
140947 this.context.labelSet = {};
140948 this.context.inIteration = false;
140949 this.context.inSwitch = false;
140950 this.context.inFunctionBody = true;
140951
140952 while (this.lookahead.type !== 2
140953 /* EOF */
140954 ) {
140955 if (this.match('}')) {
140956 break;
140957 }
140958
140959 body.push(this.parseStatementListItem());
140960 }
140961
140962 this.expect('}');
140963 this.context.labelSet = previousLabelSet;
140964 this.context.inIteration = previousInIteration;
140965 this.context.inSwitch = previousInSwitch;
140966 this.context.inFunctionBody = previousInFunctionBody;
140967 return this.finalize(node, new Node.BlockStatement(body));
140968 };
140969
140970 Parser.prototype.validateParam = function (options, param, name) {
140971 var key = '$' + name;
140972
140973 if (this.context.strict) {
140974 if (this.scanner.isRestrictedWord(name)) {
140975 options.stricted = param;
140976 options.message = messages_1.Messages.StrictParamName;
140977 }
140978
140979 if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
140980 options.stricted = param;
140981 options.message = messages_1.Messages.StrictParamDupe;
140982 }
140983 } else if (!options.firstRestricted) {
140984 if (this.scanner.isRestrictedWord(name)) {
140985 options.firstRestricted = param;
140986 options.message = messages_1.Messages.StrictParamName;
140987 } else if (this.scanner.isStrictModeReservedWord(name)) {
140988 options.firstRestricted = param;
140989 options.message = messages_1.Messages.StrictReservedWord;
140990 } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
140991 options.stricted = param;
140992 options.message = messages_1.Messages.StrictParamDupe;
140993 }
140994 }
140995 /* istanbul ignore next */
140996
140997
140998 if (typeof Object.defineProperty === 'function') {
140999 Object.defineProperty(options.paramSet, key, {
141000 value: true,
141001 enumerable: true,
141002 writable: true,
141003 configurable: true
141004 });
141005 } else {
141006 options.paramSet[key] = true;
141007 }
141008 };
141009
141010 Parser.prototype.parseRestElement = function (params) {
141011 var node = this.createNode();
141012 this.expect('...');
141013 var arg = this.parsePattern(params);
141014
141015 if (this.match('=')) {
141016 this.throwError(messages_1.Messages.DefaultRestParameter);
141017 }
141018
141019 if (!this.match(')')) {
141020 this.throwError(messages_1.Messages.ParameterAfterRestParameter);
141021 }
141022
141023 return this.finalize(node, new Node.RestElement(arg));
141024 };
141025
141026 Parser.prototype.parseFormalParameter = function (options) {
141027 var params = [];
141028 var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
141029
141030 for (var i = 0; i < params.length; i++) {
141031 this.validateParam(options, params[i], params[i].value);
141032 }
141033
141034 options.simple = options.simple && param instanceof Node.Identifier;
141035 options.params.push(param);
141036 };
141037
141038 Parser.prototype.parseFormalParameters = function (firstRestricted) {
141039 var options;
141040 options = {
141041 simple: true,
141042 params: [],
141043 firstRestricted: firstRestricted
141044 };
141045 this.expect('(');
141046
141047 if (!this.match(')')) {
141048 options.paramSet = {};
141049
141050 while (this.lookahead.type !== 2
141051 /* EOF */
141052 ) {
141053 this.parseFormalParameter(options);
141054
141055 if (this.match(')')) {
141056 break;
141057 }
141058
141059 this.expect(',');
141060
141061 if (this.match(')')) {
141062 break;
141063 }
141064 }
141065 }
141066
141067 this.expect(')');
141068 return {
141069 simple: options.simple,
141070 params: options.params,
141071 stricted: options.stricted,
141072 firstRestricted: options.firstRestricted,
141073 message: options.message
141074 };
141075 };
141076
141077 Parser.prototype.matchAsyncFunction = function () {
141078 var match = this.matchContextualKeyword('async');
141079
141080 if (match) {
141081 var state = this.scanner.saveState();
141082 this.scanner.scanComments();
141083 var next = this.scanner.lex();
141084 this.scanner.restoreState(state);
141085 match = state.lineNumber === next.lineNumber && next.type === 4
141086 /* Keyword */
141087 && next.value === 'function';
141088 }
141089
141090 return match;
141091 };
141092
141093 Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) {
141094 var node = this.createNode();
141095 var isAsync = this.matchContextualKeyword('async');
141096
141097 if (isAsync) {
141098 this.nextToken();
141099 }
141100
141101 this.expectKeyword('function');
141102 var isGenerator = isAsync ? false : this.match('*');
141103
141104 if (isGenerator) {
141105 this.nextToken();
141106 }
141107
141108 var message;
141109 var id = null;
141110 var firstRestricted = null;
141111
141112 if (!identifierIsOptional || !this.match('(')) {
141113 var token = this.lookahead;
141114 id = this.parseVariableIdentifier();
141115
141116 if (this.context.strict) {
141117 if (this.scanner.isRestrictedWord(token.value)) {
141118 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
141119 }
141120 } else {
141121 if (this.scanner.isRestrictedWord(token.value)) {
141122 firstRestricted = token;
141123 message = messages_1.Messages.StrictFunctionName;
141124 } else if (this.scanner.isStrictModeReservedWord(token.value)) {
141125 firstRestricted = token;
141126 message = messages_1.Messages.StrictReservedWord;
141127 }
141128 }
141129 }
141130
141131 var previousAllowAwait = this.context.await;
141132 var previousAllowYield = this.context.allowYield;
141133 this.context.await = isAsync;
141134 this.context.allowYield = !isGenerator;
141135 var formalParameters = this.parseFormalParameters(firstRestricted);
141136 var params = formalParameters.params;
141137 var stricted = formalParameters.stricted;
141138 firstRestricted = formalParameters.firstRestricted;
141139
141140 if (formalParameters.message) {
141141 message = formalParameters.message;
141142 }
141143
141144 var previousStrict = this.context.strict;
141145 var previousAllowStrictDirective = this.context.allowStrictDirective;
141146 this.context.allowStrictDirective = formalParameters.simple;
141147 var body = this.parseFunctionSourceElements();
141148
141149 if (this.context.strict && firstRestricted) {
141150 this.throwUnexpectedToken(firstRestricted, message);
141151 }
141152
141153 if (this.context.strict && stricted) {
141154 this.tolerateUnexpectedToken(stricted, message);
141155 }
141156
141157 this.context.strict = previousStrict;
141158 this.context.allowStrictDirective = previousAllowStrictDirective;
141159 this.context.await = previousAllowAwait;
141160 this.context.allowYield = previousAllowYield;
141161 return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
141162 };
141163
141164 Parser.prototype.parseFunctionExpression = function () {
141165 var node = this.createNode();
141166 var isAsync = this.matchContextualKeyword('async');
141167
141168 if (isAsync) {
141169 this.nextToken();
141170 }
141171
141172 this.expectKeyword('function');
141173 var isGenerator = isAsync ? false : this.match('*');
141174
141175 if (isGenerator) {
141176 this.nextToken();
141177 }
141178
141179 var message;
141180 var id = null;
141181 var firstRestricted;
141182 var previousAllowAwait = this.context.await;
141183 var previousAllowYield = this.context.allowYield;
141184 this.context.await = isAsync;
141185 this.context.allowYield = !isGenerator;
141186
141187 if (!this.match('(')) {
141188 var token = this.lookahead;
141189 id = !this.context.strict && !isGenerator && this.matchKeyword('yield') ? this.parseIdentifierName() : this.parseVariableIdentifier();
141190
141191 if (this.context.strict) {
141192 if (this.scanner.isRestrictedWord(token.value)) {
141193 this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
141194 }
141195 } else {
141196 if (this.scanner.isRestrictedWord(token.value)) {
141197 firstRestricted = token;
141198 message = messages_1.Messages.StrictFunctionName;
141199 } else if (this.scanner.isStrictModeReservedWord(token.value)) {
141200 firstRestricted = token;
141201 message = messages_1.Messages.StrictReservedWord;
141202 }
141203 }
141204 }
141205
141206 var formalParameters = this.parseFormalParameters(firstRestricted);
141207 var params = formalParameters.params;
141208 var stricted = formalParameters.stricted;
141209 firstRestricted = formalParameters.firstRestricted;
141210
141211 if (formalParameters.message) {
141212 message = formalParameters.message;
141213 }
141214
141215 var previousStrict = this.context.strict;
141216 var previousAllowStrictDirective = this.context.allowStrictDirective;
141217 this.context.allowStrictDirective = formalParameters.simple;
141218 var body = this.parseFunctionSourceElements();
141219
141220 if (this.context.strict && firstRestricted) {
141221 this.throwUnexpectedToken(firstRestricted, message);
141222 }
141223
141224 if (this.context.strict && stricted) {
141225 this.tolerateUnexpectedToken(stricted, message);
141226 }
141227
141228 this.context.strict = previousStrict;
141229 this.context.allowStrictDirective = previousAllowStrictDirective;
141230 this.context.await = previousAllowAwait;
141231 this.context.allowYield = previousAllowYield;
141232 return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
141233 }; // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive
141234
141235
141236 Parser.prototype.parseDirective = function () {
141237 var token = this.lookahead;
141238 var node = this.createNode();
141239 var expr = this.parseExpression();
141240 var directive = expr.type === syntax_1.Syntax.Literal ? this.getTokenRaw(token).slice(1, -1) : null;
141241 this.consumeSemicolon();
141242 return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
141243 };
141244
141245 Parser.prototype.parseDirectivePrologues = function () {
141246 var firstRestricted = null;
141247 var body = [];
141248
141249 while (true) {
141250 var token = this.lookahead;
141251
141252 if (token.type !== 8
141253 /* StringLiteral */
141254 ) {
141255 break;
141256 }
141257
141258 var statement = this.parseDirective();
141259 body.push(statement);
141260 var directive = statement.directive;
141261
141262 if (typeof directive !== 'string') {
141263 break;
141264 }
141265
141266 if (directive === 'use strict') {
141267 this.context.strict = true;
141268
141269 if (firstRestricted) {
141270 this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
141271 }
141272
141273 if (!this.context.allowStrictDirective) {
141274 this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
141275 }
141276 } else {
141277 if (!firstRestricted && token.octal) {
141278 firstRestricted = token;
141279 }
141280 }
141281 }
141282
141283 return body;
141284 }; // https://tc39.github.io/ecma262/#sec-method-definitions
141285
141286
141287 Parser.prototype.qualifiedPropertyName = function (token) {
141288 switch (token.type) {
141289 case 3
141290 /* Identifier */
141291 :
141292 case 8
141293 /* StringLiteral */
141294 :
141295 case 1
141296 /* BooleanLiteral */
141297 :
141298 case 5
141299 /* NullLiteral */
141300 :
141301 case 6
141302 /* NumericLiteral */
141303 :
141304 case 4
141305 /* Keyword */
141306 :
141307 return true;
141308
141309 case 7
141310 /* Punctuator */
141311 :
141312 return token.value === '[';
141313
141314 default:
141315 break;
141316 }
141317
141318 return false;
141319 };
141320
141321 Parser.prototype.parseGetterMethod = function () {
141322 var node = this.createNode();
141323 var isGenerator = false;
141324 var previousAllowYield = this.context.allowYield;
141325 this.context.allowYield = !isGenerator;
141326 var formalParameters = this.parseFormalParameters();
141327
141328 if (formalParameters.params.length > 0) {
141329 this.tolerateError(messages_1.Messages.BadGetterArity);
141330 }
141331
141332 var method = this.parsePropertyMethod(formalParameters);
141333 this.context.allowYield = previousAllowYield;
141334 return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
141335 };
141336
141337 Parser.prototype.parseSetterMethod = function () {
141338 var node = this.createNode();
141339 var isGenerator = false;
141340 var previousAllowYield = this.context.allowYield;
141341 this.context.allowYield = !isGenerator;
141342 var formalParameters = this.parseFormalParameters();
141343
141344 if (formalParameters.params.length !== 1) {
141345 this.tolerateError(messages_1.Messages.BadSetterArity);
141346 } else if (formalParameters.params[0] instanceof Node.RestElement) {
141347 this.tolerateError(messages_1.Messages.BadSetterRestParameter);
141348 }
141349
141350 var method = this.parsePropertyMethod(formalParameters);
141351 this.context.allowYield = previousAllowYield;
141352 return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
141353 };
141354
141355 Parser.prototype.parseGeneratorMethod = function () {
141356 var node = this.createNode();
141357 var isGenerator = true;
141358 var previousAllowYield = this.context.allowYield;
141359 this.context.allowYield = true;
141360 var params = this.parseFormalParameters();
141361 this.context.allowYield = false;
141362 var method = this.parsePropertyMethod(params);
141363 this.context.allowYield = previousAllowYield;
141364 return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
141365 }; // https://tc39.github.io/ecma262/#sec-generator-function-definitions
141366
141367
141368 Parser.prototype.isStartOfExpression = function () {
141369 var start = true;
141370 var value = this.lookahead.value;
141371
141372 switch (this.lookahead.type) {
141373 case 7
141374 /* Punctuator */
141375 :
141376 start = value === '[' || value === '(' || value === '{' || value === '+' || value === '-' || value === '!' || value === '~' || value === '++' || value === '--' || value === '/' || value === '/='; // regular expression literal
141377
141378 break;
141379
141380 case 4
141381 /* Keyword */
141382 :
141383 start = value === 'class' || value === 'delete' || value === 'function' || value === 'let' || value === 'new' || value === 'super' || value === 'this' || value === 'typeof' || value === 'void' || value === 'yield';
141384 break;
141385
141386 default:
141387 break;
141388 }
141389
141390 return start;
141391 };
141392
141393 Parser.prototype.parseYieldExpression = function () {
141394 var node = this.createNode();
141395 this.expectKeyword('yield');
141396 var argument = null;
141397 var delegate = false;
141398
141399 if (!this.hasLineTerminator) {
141400 var previousAllowYield = this.context.allowYield;
141401 this.context.allowYield = false;
141402 delegate = this.match('*');
141403
141404 if (delegate) {
141405 this.nextToken();
141406 argument = this.parseAssignmentExpression();
141407 } else if (this.isStartOfExpression()) {
141408 argument = this.parseAssignmentExpression();
141409 }
141410
141411 this.context.allowYield = previousAllowYield;
141412 }
141413
141414 return this.finalize(node, new Node.YieldExpression(argument, delegate));
141415 }; // https://tc39.github.io/ecma262/#sec-class-definitions
141416
141417
141418 Parser.prototype.parseClassElement = function (hasConstructor) {
141419 var token = this.lookahead;
141420 var node = this.createNode();
141421 var kind = '';
141422 var key = null;
141423 var value = null;
141424 var computed = false;
141425 var method = false;
141426 var isStatic = false;
141427 var isAsync = false;
141428
141429 if (this.match('*')) {
141430 this.nextToken();
141431 } else {
141432 computed = this.match('[');
141433 key = this.parseObjectPropertyKey();
141434 var id = key;
141435
141436 if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
141437 token = this.lookahead;
141438 isStatic = true;
141439 computed = this.match('[');
141440
141441 if (this.match('*')) {
141442 this.nextToken();
141443 } else {
141444 key = this.parseObjectPropertyKey();
141445 }
141446 }
141447
141448 if (token.type === 3
141449 /* Identifier */
141450 && !this.hasLineTerminator && token.value === 'async') {
141451 var punctuator = this.lookahead.value;
141452
141453 if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') {
141454 isAsync = true;
141455 token = this.lookahead;
141456 key = this.parseObjectPropertyKey();
141457
141458 if (token.type === 3
141459 /* Identifier */
141460 && token.value === 'constructor') {
141461 this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
141462 }
141463 }
141464 }
141465 }
141466
141467 var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
141468
141469 if (token.type === 3
141470 /* Identifier */
141471 ) {
141472 if (token.value === 'get' && lookaheadPropertyKey) {
141473 kind = 'get';
141474 computed = this.match('[');
141475 key = this.parseObjectPropertyKey();
141476 this.context.allowYield = false;
141477 value = this.parseGetterMethod();
141478 } else if (token.value === 'set' && lookaheadPropertyKey) {
141479 kind = 'set';
141480 computed = this.match('[');
141481 key = this.parseObjectPropertyKey();
141482 value = this.parseSetterMethod();
141483 }
141484 } else if (token.type === 7
141485 /* Punctuator */
141486 && token.value === '*' && lookaheadPropertyKey) {
141487 kind = 'init';
141488 computed = this.match('[');
141489 key = this.parseObjectPropertyKey();
141490 value = this.parseGeneratorMethod();
141491 method = true;
141492 }
141493
141494 if (!kind && key && this.match('(')) {
141495 kind = 'init';
141496 value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
141497 method = true;
141498 }
141499
141500 if (!kind) {
141501 this.throwUnexpectedToken(this.lookahead);
141502 }
141503
141504 if (kind === 'init') {
141505 kind = 'method';
141506 }
141507
141508 if (!computed) {
141509 if (isStatic && this.isPropertyKey(key, 'prototype')) {
141510 this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
141511 }
141512
141513 if (!isStatic && this.isPropertyKey(key, 'constructor')) {
141514 if (kind !== 'method' || !method || value && value.generator) {
141515 this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
141516 }
141517
141518 if (hasConstructor.value) {
141519 this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
141520 } else {
141521 hasConstructor.value = true;
141522 }
141523
141524 kind = 'constructor';
141525 }
141526 }
141527
141528 return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
141529 };
141530
141531 Parser.prototype.parseClassElementList = function () {
141532 var body = [];
141533 var hasConstructor = {
141534 value: false
141535 };
141536 this.expect('{');
141537
141538 while (!this.match('}')) {
141539 if (this.match(';')) {
141540 this.nextToken();
141541 } else {
141542 body.push(this.parseClassElement(hasConstructor));
141543 }
141544 }
141545
141546 this.expect('}');
141547 return body;
141548 };
141549
141550 Parser.prototype.parseClassBody = function () {
141551 var node = this.createNode();
141552 var elementList = this.parseClassElementList();
141553 return this.finalize(node, new Node.ClassBody(elementList));
141554 };
141555
141556 Parser.prototype.parseClassDeclaration = function (identifierIsOptional) {
141557 var node = this.createNode();
141558 var previousStrict = this.context.strict;
141559 this.context.strict = true;
141560 this.expectKeyword('class');
141561 var id = identifierIsOptional && this.lookahead.type !== 3
141562 /* Identifier */
141563 ? null : this.parseVariableIdentifier();
141564 var superClass = null;
141565
141566 if (this.matchKeyword('extends')) {
141567 this.nextToken();
141568 superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
141569 }
141570
141571 var classBody = this.parseClassBody();
141572 this.context.strict = previousStrict;
141573 return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
141574 };
141575
141576 Parser.prototype.parseClassExpression = function () {
141577 var node = this.createNode();
141578 var previousStrict = this.context.strict;
141579 this.context.strict = true;
141580 this.expectKeyword('class');
141581 var id = this.lookahead.type === 3
141582 /* Identifier */
141583 ? this.parseVariableIdentifier() : null;
141584 var superClass = null;
141585
141586 if (this.matchKeyword('extends')) {
141587 this.nextToken();
141588 superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
141589 }
141590
141591 var classBody = this.parseClassBody();
141592 this.context.strict = previousStrict;
141593 return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
141594 }; // https://tc39.github.io/ecma262/#sec-scripts
141595 // https://tc39.github.io/ecma262/#sec-modules
141596
141597
141598 Parser.prototype.parseModule = function () {
141599 this.context.strict = true;
141600 this.context.isModule = true;
141601 this.scanner.isModule = true;
141602 var node = this.createNode();
141603 var body = this.parseDirectivePrologues();
141604
141605 while (this.lookahead.type !== 2
141606 /* EOF */
141607 ) {
141608 body.push(this.parseStatementListItem());
141609 }
141610
141611 return this.finalize(node, new Node.Module(body));
141612 };
141613
141614 Parser.prototype.parseScript = function () {
141615 var node = this.createNode();
141616 var body = this.parseDirectivePrologues();
141617
141618 while (this.lookahead.type !== 2
141619 /* EOF */
141620 ) {
141621 body.push(this.parseStatementListItem());
141622 }
141623
141624 return this.finalize(node, new Node.Script(body));
141625 }; // https://tc39.github.io/ecma262/#sec-imports
141626
141627
141628 Parser.prototype.parseModuleSpecifier = function () {
141629 var node = this.createNode();
141630
141631 if (this.lookahead.type !== 8
141632 /* StringLiteral */
141633 ) {
141634 this.throwError(messages_1.Messages.InvalidModuleSpecifier);
141635 }
141636
141637 var token = this.nextToken();
141638 var raw = this.getTokenRaw(token);
141639 return this.finalize(node, new Node.Literal(token.value, raw));
141640 }; // import {<foo as bar>} ...;
141641
141642
141643 Parser.prototype.parseImportSpecifier = function () {
141644 var node = this.createNode();
141645 var imported;
141646 var local;
141647
141648 if (this.lookahead.type === 3
141649 /* Identifier */
141650 ) {
141651 imported = this.parseVariableIdentifier();
141652 local = imported;
141653
141654 if (this.matchContextualKeyword('as')) {
141655 this.nextToken();
141656 local = this.parseVariableIdentifier();
141657 }
141658 } else {
141659 imported = this.parseIdentifierName();
141660 local = imported;
141661
141662 if (this.matchContextualKeyword('as')) {
141663 this.nextToken();
141664 local = this.parseVariableIdentifier();
141665 } else {
141666 this.throwUnexpectedToken(this.nextToken());
141667 }
141668 }
141669
141670 return this.finalize(node, new Node.ImportSpecifier(local, imported));
141671 }; // {foo, bar as bas}
141672
141673
141674 Parser.prototype.parseNamedImports = function () {
141675 this.expect('{');
141676 var specifiers = [];
141677
141678 while (!this.match('}')) {
141679 specifiers.push(this.parseImportSpecifier());
141680
141681 if (!this.match('}')) {
141682 this.expect(',');
141683 }
141684 }
141685
141686 this.expect('}');
141687 return specifiers;
141688 }; // import <foo> ...;
141689
141690
141691 Parser.prototype.parseImportDefaultSpecifier = function () {
141692 var node = this.createNode();
141693 var local = this.parseIdentifierName();
141694 return this.finalize(node, new Node.ImportDefaultSpecifier(local));
141695 }; // import <* as foo> ...;
141696
141697
141698 Parser.prototype.parseImportNamespaceSpecifier = function () {
141699 var node = this.createNode();
141700 this.expect('*');
141701
141702 if (!this.matchContextualKeyword('as')) {
141703 this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
141704 }
141705
141706 this.nextToken();
141707 var local = this.parseIdentifierName();
141708 return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
141709 };
141710
141711 Parser.prototype.parseImportDeclaration = function () {
141712 if (this.context.inFunctionBody) {
141713 this.throwError(messages_1.Messages.IllegalImportDeclaration);
141714 }
141715
141716 var node = this.createNode();
141717 this.expectKeyword('import');
141718 var src;
141719 var specifiers = [];
141720
141721 if (this.lookahead.type === 8
141722 /* StringLiteral */
141723 ) {
141724 // import 'foo';
141725 src = this.parseModuleSpecifier();
141726 } else {
141727 if (this.match('{')) {
141728 // import {bar}
141729 specifiers = specifiers.concat(this.parseNamedImports());
141730 } else if (this.match('*')) {
141731 // import * as foo
141732 specifiers.push(this.parseImportNamespaceSpecifier());
141733 } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) {
141734 // import foo
141735 specifiers.push(this.parseImportDefaultSpecifier());
141736
141737 if (this.match(',')) {
141738 this.nextToken();
141739
141740 if (this.match('*')) {
141741 // import foo, * as foo
141742 specifiers.push(this.parseImportNamespaceSpecifier());
141743 } else if (this.match('{')) {
141744 // import foo, {bar}
141745 specifiers = specifiers.concat(this.parseNamedImports());
141746 } else {
141747 this.throwUnexpectedToken(this.lookahead);
141748 }
141749 }
141750 } else {
141751 this.throwUnexpectedToken(this.nextToken());
141752 }
141753
141754 if (!this.matchContextualKeyword('from')) {
141755 var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
141756 this.throwError(message, this.lookahead.value);
141757 }
141758
141759 this.nextToken();
141760 src = this.parseModuleSpecifier();
141761 }
141762
141763 this.consumeSemicolon();
141764 return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
141765 }; // https://tc39.github.io/ecma262/#sec-exports
141766
141767
141768 Parser.prototype.parseExportSpecifier = function () {
141769 var node = this.createNode();
141770 var local = this.parseIdentifierName();
141771 var exported = local;
141772
141773 if (this.matchContextualKeyword('as')) {
141774 this.nextToken();
141775 exported = this.parseIdentifierName();
141776 }
141777
141778 return this.finalize(node, new Node.ExportSpecifier(local, exported));
141779 };
141780
141781 Parser.prototype.parseExportDeclaration = function () {
141782 if (this.context.inFunctionBody) {
141783 this.throwError(messages_1.Messages.IllegalExportDeclaration);
141784 }
141785
141786 var node = this.createNode();
141787 this.expectKeyword('export');
141788 var exportDeclaration;
141789
141790 if (this.matchKeyword('default')) {
141791 // export default ...
141792 this.nextToken();
141793
141794 if (this.matchKeyword('function')) {
141795 // export default function foo () {}
141796 // export default function () {}
141797 var declaration = this.parseFunctionDeclaration(true);
141798 exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
141799 } else if (this.matchKeyword('class')) {
141800 // export default class foo {}
141801 var declaration = this.parseClassDeclaration(true);
141802 exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
141803 } else if (this.matchContextualKeyword('async')) {
141804 // export default async function f () {}
141805 // export default async function () {}
141806 // export default async x => x
141807 var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
141808 exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
141809 } else {
141810 if (this.matchContextualKeyword('from')) {
141811 this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
141812 } // export default {};
141813 // export default [];
141814 // export default (1 + 2);
141815
141816
141817 var declaration = this.match('{') ? this.parseObjectInitializer() : this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression();
141818 this.consumeSemicolon();
141819 exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
141820 }
141821 } else if (this.match('*')) {
141822 // export * from 'foo';
141823 this.nextToken();
141824
141825 if (!this.matchContextualKeyword('from')) {
141826 var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
141827 this.throwError(message, this.lookahead.value);
141828 }
141829
141830 this.nextToken();
141831 var src = this.parseModuleSpecifier();
141832 this.consumeSemicolon();
141833 exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
141834 } else if (this.lookahead.type === 4
141835 /* Keyword */
141836 ) {
141837 // export var f = 1;
141838 var declaration = void 0;
141839
141840 switch (this.lookahead.value) {
141841 case 'let':
141842 case 'const':
141843 declaration = this.parseLexicalDeclaration({
141844 inFor: false
141845 });
141846 break;
141847
141848 case 'var':
141849 case 'class':
141850 case 'function':
141851 declaration = this.parseStatementListItem();
141852 break;
141853
141854 default:
141855 this.throwUnexpectedToken(this.lookahead);
141856 }
141857
141858 exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
141859 } else if (this.matchAsyncFunction()) {
141860 var declaration = this.parseFunctionDeclaration();
141861 exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
141862 } else {
141863 var specifiers = [];
141864 var source = null;
141865 var isExportFromIdentifier = false;
141866 this.expect('{');
141867
141868 while (!this.match('}')) {
141869 isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default');
141870 specifiers.push(this.parseExportSpecifier());
141871
141872 if (!this.match('}')) {
141873 this.expect(',');
141874 }
141875 }
141876
141877 this.expect('}');
141878
141879 if (this.matchContextualKeyword('from')) {
141880 // export {default} from 'foo';
141881 // export {foo} from 'foo';
141882 this.nextToken();
141883 source = this.parseModuleSpecifier();
141884 this.consumeSemicolon();
141885 } else if (isExportFromIdentifier) {
141886 // export {default}; // missing fromClause
141887 var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
141888 this.throwError(message, this.lookahead.value);
141889 } else {
141890 // export {foo};
141891 this.consumeSemicolon();
141892 }
141893
141894 exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
141895 }
141896
141897 return exportDeclaration;
141898 };
141899
141900 return Parser;
141901 }();
141902
141903 exports.Parser = Parser;
141904 /***/
141905 },
141906 /* 9 */
141907
141908 /***/
141909 function (module, exports) {
141910 "use strict"; // Ensure the condition is true, otherwise throw an error.
141911 // This is only to have a better contract semantic, i.e. another safety net
141912 // to catch a logic error. The condition shall be fulfilled in normal case.
141913 // Do NOT use this to enforce a certain condition on any user input.
141914
141915 Object.defineProperty(exports, "__esModule", {
141916 value: true
141917 });
141918
141919 function assert(condition, message) {
141920 /* istanbul ignore if */
141921 if (!condition) {
141922 throw new Error('ASSERT: ' + message);
141923 }
141924 }
141925
141926 exports.assert = assert;
141927 /***/
141928 },
141929 /* 10 */
141930
141931 /***/
141932 function (module, exports) {
141933 "use strict";
141934 /* tslint:disable:max-classes-per-file */
141935
141936 Object.defineProperty(exports, "__esModule", {
141937 value: true
141938 });
141939
141940 var ErrorHandler = function () {
141941 function ErrorHandler() {
141942 this.errors = [];
141943 this.tolerant = false;
141944 }
141945
141946 ErrorHandler.prototype.recordError = function (error) {
141947 this.errors.push(error);
141948 };
141949
141950 ErrorHandler.prototype.tolerate = function (error) {
141951 if (this.tolerant) {
141952 this.recordError(error);
141953 } else {
141954 throw error;
141955 }
141956 };
141957
141958 ErrorHandler.prototype.constructError = function (msg, column) {
141959 var error = new Error(msg);
141960
141961 try {
141962 throw error;
141963 } catch (base) {
141964 /* istanbul ignore else */
141965 if (Object.create && Object.defineProperty) {
141966 error = Object.create(base);
141967 Object.defineProperty(error, 'column', {
141968 value: column
141969 });
141970 }
141971 }
141972 /* istanbul ignore next */
141973
141974
141975 return error;
141976 };
141977
141978 ErrorHandler.prototype.createError = function (index, line, col, description) {
141979 var msg = 'Line ' + line + ': ' + description;
141980 var error = this.constructError(msg, col);
141981 error.index = index;
141982 error.lineNumber = line;
141983 error.description = description;
141984 return error;
141985 };
141986
141987 ErrorHandler.prototype.throwError = function (index, line, col, description) {
141988 throw this.createError(index, line, col, description);
141989 };
141990
141991 ErrorHandler.prototype.tolerateError = function (index, line, col, description) {
141992 var error = this.createError(index, line, col, description);
141993
141994 if (this.tolerant) {
141995 this.recordError(error);
141996 } else {
141997 throw error;
141998 }
141999 };
142000
142001 return ErrorHandler;
142002 }();
142003
142004 exports.ErrorHandler = ErrorHandler;
142005 /***/
142006 },
142007 /* 11 */
142008
142009 /***/
142010 function (module, exports) {
142011 "use strict";
142012
142013 Object.defineProperty(exports, "__esModule", {
142014 value: true
142015 }); // Error messages should be identical to V8.
142016
142017 exports.Messages = {
142018 BadGetterArity: 'Getter must not have any formal parameters',
142019 BadSetterArity: 'Setter must have exactly one formal parameter',
142020 BadSetterRestParameter: 'Setter function argument must not be a rest parameter',
142021 ConstructorIsAsync: 'Class constructor may not be an async method',
142022 ConstructorSpecialMethod: 'Class constructor may not be an accessor',
142023 DeclarationMissingInitializer: 'Missing initializer in %0 declaration',
142024 DefaultRestParameter: 'Unexpected token =',
142025 DuplicateBinding: 'Duplicate binding %0',
142026 DuplicateConstructor: 'A class may only have one constructor',
142027 DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
142028 ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer',
142029 GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts',
142030 IllegalBreak: 'Illegal break statement',
142031 IllegalContinue: 'Illegal continue statement',
142032 IllegalExportDeclaration: 'Unexpected token',
142033 IllegalImportDeclaration: 'Unexpected token',
142034 IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list',
142035 IllegalReturn: 'Illegal return statement',
142036 InvalidEscapedReservedWord: 'Keyword must not contain escaped characters',
142037 InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence',
142038 InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
142039 InvalidLHSInForIn: 'Invalid left-hand side in for-in',
142040 InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
142041 InvalidModuleSpecifier: 'Unexpected token',
142042 InvalidRegExp: 'Invalid regular expression',
142043 LetInLexicalBinding: 'let is disallowed as a lexically bound name',
142044 MissingFromClause: 'Unexpected token',
142045 MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
142046 NewlineAfterThrow: 'Illegal newline after throw',
142047 NoAsAfterImportNamespace: 'Unexpected token',
142048 NoCatchOrFinally: 'Missing catch or finally after try',
142049 ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
142050 Redeclaration: '%0 \'%1\' has already been declared',
142051 StaticPrototype: 'Classes may not have static property named prototype',
142052 StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
142053 StrictDelete: 'Delete of an unqualified identifier in strict mode.',
142054 StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block',
142055 StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
142056 StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
142057 StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
142058 StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
142059 StrictModeWith: 'Strict mode code may not include a with statement',
142060 StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
142061 StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
142062 StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
142063 StrictReservedWord: 'Use of future reserved word in strict mode',
142064 StrictVarName: 'Variable name may not be eval or arguments in strict mode',
142065 TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
142066 UnexpectedEOS: 'Unexpected end of input',
142067 UnexpectedIdentifier: 'Unexpected identifier',
142068 UnexpectedNumber: 'Unexpected number',
142069 UnexpectedReserved: 'Unexpected reserved word',
142070 UnexpectedString: 'Unexpected string',
142071 UnexpectedTemplate: 'Unexpected quasi %0',
142072 UnexpectedToken: 'Unexpected token %0',
142073 UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
142074 UnknownLabel: 'Undefined label \'%0\'',
142075 UnterminatedRegExp: 'Invalid regular expression: missing /'
142076 };
142077 /***/
142078 },
142079 /* 12 */
142080
142081 /***/
142082 function (module, exports, __webpack_require__) {
142083 "use strict";
142084
142085 Object.defineProperty(exports, "__esModule", {
142086 value: true
142087 });
142088
142089 var assert_1 = __webpack_require__(9);
142090
142091 var character_1 = __webpack_require__(4);
142092
142093 var messages_1 = __webpack_require__(11);
142094
142095 function hexValue(ch) {
142096 return '0123456789abcdef'.indexOf(ch.toLowerCase());
142097 }
142098
142099 function octalValue(ch) {
142100 return '01234567'.indexOf(ch);
142101 }
142102
142103 var Scanner = function () {
142104 function Scanner(code, handler) {
142105 this.source = code;
142106 this.errorHandler = handler;
142107 this.trackComment = false;
142108 this.isModule = false;
142109 this.length = code.length;
142110 this.index = 0;
142111 this.lineNumber = code.length > 0 ? 1 : 0;
142112 this.lineStart = 0;
142113 this.curlyStack = [];
142114 }
142115
142116 Scanner.prototype.saveState = function () {
142117 return {
142118 index: this.index,
142119 lineNumber: this.lineNumber,
142120 lineStart: this.lineStart
142121 };
142122 };
142123
142124 Scanner.prototype.restoreState = function (state) {
142125 this.index = state.index;
142126 this.lineNumber = state.lineNumber;
142127 this.lineStart = state.lineStart;
142128 };
142129
142130 Scanner.prototype.eof = function () {
142131 return this.index >= this.length;
142132 };
142133
142134 Scanner.prototype.throwUnexpectedToken = function (message) {
142135 if (message === void 0) {
142136 message = messages_1.Messages.UnexpectedTokenIllegal;
142137 }
142138
142139 return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
142140 };
142141
142142 Scanner.prototype.tolerateUnexpectedToken = function (message) {
142143 if (message === void 0) {
142144 message = messages_1.Messages.UnexpectedTokenIllegal;
142145 }
142146
142147 this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
142148 }; // https://tc39.github.io/ecma262/#sec-comments
142149
142150
142151 Scanner.prototype.skipSingleLineComment = function (offset) {
142152 var comments = [];
142153 var start, loc;
142154
142155 if (this.trackComment) {
142156 comments = [];
142157 start = this.index - offset;
142158 loc = {
142159 start: {
142160 line: this.lineNumber,
142161 column: this.index - this.lineStart - offset
142162 },
142163 end: {}
142164 };
142165 }
142166
142167 while (!this.eof()) {
142168 var ch = this.source.charCodeAt(this.index);
142169 ++this.index;
142170
142171 if (character_1.Character.isLineTerminator(ch)) {
142172 if (this.trackComment) {
142173 loc.end = {
142174 line: this.lineNumber,
142175 column: this.index - this.lineStart - 1
142176 };
142177 var entry = {
142178 multiLine: false,
142179 slice: [start + offset, this.index - 1],
142180 range: [start, this.index - 1],
142181 loc: loc
142182 };
142183 comments.push(entry);
142184 }
142185
142186 if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
142187 ++this.index;
142188 }
142189
142190 ++this.lineNumber;
142191 this.lineStart = this.index;
142192 return comments;
142193 }
142194 }
142195
142196 if (this.trackComment) {
142197 loc.end = {
142198 line: this.lineNumber,
142199 column: this.index - this.lineStart
142200 };
142201 var entry = {
142202 multiLine: false,
142203 slice: [start + offset, this.index],
142204 range: [start, this.index],
142205 loc: loc
142206 };
142207 comments.push(entry);
142208 }
142209
142210 return comments;
142211 };
142212
142213 Scanner.prototype.skipMultiLineComment = function () {
142214 var comments = [];
142215 var start, loc;
142216
142217 if (this.trackComment) {
142218 comments = [];
142219 start = this.index - 2;
142220 loc = {
142221 start: {
142222 line: this.lineNumber,
142223 column: this.index - this.lineStart - 2
142224 },
142225 end: {}
142226 };
142227 }
142228
142229 while (!this.eof()) {
142230 var ch = this.source.charCodeAt(this.index);
142231
142232 if (character_1.Character.isLineTerminator(ch)) {
142233 if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) {
142234 ++this.index;
142235 }
142236
142237 ++this.lineNumber;
142238 ++this.index;
142239 this.lineStart = this.index;
142240 } else if (ch === 0x2A) {
142241 // Block comment ends with '*/'.
142242 if (this.source.charCodeAt(this.index + 1) === 0x2F) {
142243 this.index += 2;
142244
142245 if (this.trackComment) {
142246 loc.end = {
142247 line: this.lineNumber,
142248 column: this.index - this.lineStart
142249 };
142250 var entry = {
142251 multiLine: true,
142252 slice: [start + 2, this.index - 2],
142253 range: [start, this.index],
142254 loc: loc
142255 };
142256 comments.push(entry);
142257 }
142258
142259 return comments;
142260 }
142261
142262 ++this.index;
142263 } else {
142264 ++this.index;
142265 }
142266 } // Ran off the end of the file - the whole thing is a comment
142267
142268
142269 if (this.trackComment) {
142270 loc.end = {
142271 line: this.lineNumber,
142272 column: this.index - this.lineStart
142273 };
142274 var entry = {
142275 multiLine: true,
142276 slice: [start + 2, this.index],
142277 range: [start, this.index],
142278 loc: loc
142279 };
142280 comments.push(entry);
142281 }
142282
142283 this.tolerateUnexpectedToken();
142284 return comments;
142285 };
142286
142287 Scanner.prototype.scanComments = function () {
142288 var comments;
142289
142290 if (this.trackComment) {
142291 comments = [];
142292 }
142293
142294 var start = this.index === 0;
142295
142296 while (!this.eof()) {
142297 var ch = this.source.charCodeAt(this.index);
142298
142299 if (character_1.Character.isWhiteSpace(ch)) {
142300 ++this.index;
142301 } else if (character_1.Character.isLineTerminator(ch)) {
142302 ++this.index;
142303
142304 if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) {
142305 ++this.index;
142306 }
142307
142308 ++this.lineNumber;
142309 this.lineStart = this.index;
142310 start = true;
142311 } else if (ch === 0x2F) {
142312 ch = this.source.charCodeAt(this.index + 1);
142313
142314 if (ch === 0x2F) {
142315 this.index += 2;
142316 var comment = this.skipSingleLineComment(2);
142317
142318 if (this.trackComment) {
142319 comments = comments.concat(comment);
142320 }
142321
142322 start = true;
142323 } else if (ch === 0x2A) {
142324 this.index += 2;
142325 var comment = this.skipMultiLineComment();
142326
142327 if (this.trackComment) {
142328 comments = comments.concat(comment);
142329 }
142330 } else {
142331 break;
142332 }
142333 } else if (start && ch === 0x2D) {
142334 // U+003E is '>'
142335 if (this.source.charCodeAt(this.index + 1) === 0x2D && this.source.charCodeAt(this.index + 2) === 0x3E) {
142336 // '-->' is a single-line comment
142337 this.index += 3;
142338 var comment = this.skipSingleLineComment(3);
142339
142340 if (this.trackComment) {
142341 comments = comments.concat(comment);
142342 }
142343 } else {
142344 break;
142345 }
142346 } else if (ch === 0x3C && !this.isModule) {
142347 if (this.source.slice(this.index + 1, this.index + 4) === '!--') {
142348 this.index += 4; // `<!--`
142349
142350 var comment = this.skipSingleLineComment(4);
142351
142352 if (this.trackComment) {
142353 comments = comments.concat(comment);
142354 }
142355 } else {
142356 break;
142357 }
142358 } else {
142359 break;
142360 }
142361 }
142362
142363 return comments;
142364 }; // https://tc39.github.io/ecma262/#sec-future-reserved-words
142365
142366
142367 Scanner.prototype.isFutureReservedWord = function (id) {
142368 switch (id) {
142369 case 'enum':
142370 case 'export':
142371 case 'import':
142372 case 'super':
142373 return true;
142374
142375 default:
142376 return false;
142377 }
142378 };
142379
142380 Scanner.prototype.isStrictModeReservedWord = function (id) {
142381 switch (id) {
142382 case 'implements':
142383 case 'interface':
142384 case 'package':
142385 case 'private':
142386 case 'protected':
142387 case 'public':
142388 case 'static':
142389 case 'yield':
142390 case 'let':
142391 return true;
142392
142393 default:
142394 return false;
142395 }
142396 };
142397
142398 Scanner.prototype.isRestrictedWord = function (id) {
142399 return id === 'eval' || id === 'arguments';
142400 }; // https://tc39.github.io/ecma262/#sec-keywords
142401
142402
142403 Scanner.prototype.isKeyword = function (id) {
142404 switch (id.length) {
142405 case 2:
142406 return id === 'if' || id === 'in' || id === 'do';
142407
142408 case 3:
142409 return id === 'var' || id === 'for' || id === 'new' || id === 'try' || id === 'let';
142410
142411 case 4:
142412 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
142413
142414 case 5:
142415 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
142416
142417 case 6:
142418 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
142419
142420 case 7:
142421 return id === 'default' || id === 'finally' || id === 'extends';
142422
142423 case 8:
142424 return id === 'function' || id === 'continue' || id === 'debugger';
142425
142426 case 10:
142427 return id === 'instanceof';
142428
142429 default:
142430 return false;
142431 }
142432 };
142433
142434 Scanner.prototype.codePointAt = function (i) {
142435 var cp = this.source.charCodeAt(i);
142436
142437 if (cp >= 0xD800 && cp <= 0xDBFF) {
142438 var second = this.source.charCodeAt(i + 1);
142439
142440 if (second >= 0xDC00 && second <= 0xDFFF) {
142441 var first = cp;
142442 cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
142443 }
142444 }
142445
142446 return cp;
142447 };
142448
142449 Scanner.prototype.scanHexEscape = function (prefix) {
142450 var len = prefix === 'u' ? 4 : 2;
142451 var code = 0;
142452
142453 for (var i = 0; i < len; ++i) {
142454 if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
142455 code = code * 16 + hexValue(this.source[this.index++]);
142456 } else {
142457 return null;
142458 }
142459 }
142460
142461 return String.fromCharCode(code);
142462 };
142463
142464 Scanner.prototype.scanUnicodeCodePointEscape = function () {
142465 var ch = this.source[this.index];
142466 var code = 0; // At least, one hex digit is required.
142467
142468 if (ch === '}') {
142469 this.throwUnexpectedToken();
142470 }
142471
142472 while (!this.eof()) {
142473 ch = this.source[this.index++];
142474
142475 if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
142476 break;
142477 }
142478
142479 code = code * 16 + hexValue(ch);
142480 }
142481
142482 if (code > 0x10FFFF || ch !== '}') {
142483 this.throwUnexpectedToken();
142484 }
142485
142486 return character_1.Character.fromCodePoint(code);
142487 };
142488
142489 Scanner.prototype.getIdentifier = function () {
142490 var start = this.index++;
142491
142492 while (!this.eof()) {
142493 var ch = this.source.charCodeAt(this.index);
142494
142495 if (ch === 0x5C) {
142496 // Blackslash (U+005C) marks Unicode escape sequence.
142497 this.index = start;
142498 return this.getComplexIdentifier();
142499 } else if (ch >= 0xD800 && ch < 0xDFFF) {
142500 // Need to handle surrogate pairs.
142501 this.index = start;
142502 return this.getComplexIdentifier();
142503 }
142504
142505 if (character_1.Character.isIdentifierPart(ch)) {
142506 ++this.index;
142507 } else {
142508 break;
142509 }
142510 }
142511
142512 return this.source.slice(start, this.index);
142513 };
142514
142515 Scanner.prototype.getComplexIdentifier = function () {
142516 var cp = this.codePointAt(this.index);
142517 var id = character_1.Character.fromCodePoint(cp);
142518 this.index += id.length; // '\u' (U+005C, U+0075) denotes an escaped character.
142519
142520 var ch;
142521
142522 if (cp === 0x5C) {
142523 if (this.source.charCodeAt(this.index) !== 0x75) {
142524 this.throwUnexpectedToken();
142525 }
142526
142527 ++this.index;
142528
142529 if (this.source[this.index] === '{') {
142530 ++this.index;
142531 ch = this.scanUnicodeCodePointEscape();
142532 } else {
142533 ch = this.scanHexEscape('u');
142534
142535 if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
142536 this.throwUnexpectedToken();
142537 }
142538 }
142539
142540 id = ch;
142541 }
142542
142543 while (!this.eof()) {
142544 cp = this.codePointAt(this.index);
142545
142546 if (!character_1.Character.isIdentifierPart(cp)) {
142547 break;
142548 }
142549
142550 ch = character_1.Character.fromCodePoint(cp);
142551 id += ch;
142552 this.index += ch.length; // '\u' (U+005C, U+0075) denotes an escaped character.
142553
142554 if (cp === 0x5C) {
142555 id = id.substr(0, id.length - 1);
142556
142557 if (this.source.charCodeAt(this.index) !== 0x75) {
142558 this.throwUnexpectedToken();
142559 }
142560
142561 ++this.index;
142562
142563 if (this.source[this.index] === '{') {
142564 ++this.index;
142565 ch = this.scanUnicodeCodePointEscape();
142566 } else {
142567 ch = this.scanHexEscape('u');
142568
142569 if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
142570 this.throwUnexpectedToken();
142571 }
142572 }
142573
142574 id += ch;
142575 }
142576 }
142577
142578 return id;
142579 };
142580
142581 Scanner.prototype.octalToDecimal = function (ch) {
142582 // \0 is not octal escape sequence
142583 var octal = ch !== '0';
142584 var code = octalValue(ch);
142585
142586 if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
142587 octal = true;
142588 code = code * 8 + octalValue(this.source[this.index++]); // 3 digits are only allowed when string starts
142589 // with 0, 1, 2, 3
142590
142591 if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
142592 code = code * 8 + octalValue(this.source[this.index++]);
142593 }
142594 }
142595
142596 return {
142597 code: code,
142598 octal: octal
142599 };
142600 }; // https://tc39.github.io/ecma262/#sec-names-and-keywords
142601
142602
142603 Scanner.prototype.scanIdentifier = function () {
142604 var type;
142605 var start = this.index; // Backslash (U+005C) starts an escaped character.
142606
142607 var id = this.source.charCodeAt(start) === 0x5C ? this.getComplexIdentifier() : this.getIdentifier(); // There is no keyword or literal with only one character.
142608 // Thus, it must be an identifier.
142609
142610 if (id.length === 1) {
142611 type = 3
142612 /* Identifier */
142613 ;
142614 } else if (this.isKeyword(id)) {
142615 type = 4
142616 /* Keyword */
142617 ;
142618 } else if (id === 'null') {
142619 type = 5
142620 /* NullLiteral */
142621 ;
142622 } else if (id === 'true' || id === 'false') {
142623 type = 1
142624 /* BooleanLiteral */
142625 ;
142626 } else {
142627 type = 3
142628 /* Identifier */
142629 ;
142630 }
142631
142632 if (type !== 3
142633 /* Identifier */
142634 && start + id.length !== this.index) {
142635 var restore = this.index;
142636 this.index = start;
142637 this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
142638 this.index = restore;
142639 }
142640
142641 return {
142642 type: type,
142643 value: id,
142644 lineNumber: this.lineNumber,
142645 lineStart: this.lineStart,
142646 start: start,
142647 end: this.index
142648 };
142649 }; // https://tc39.github.io/ecma262/#sec-punctuators
142650
142651
142652 Scanner.prototype.scanPunctuator = function () {
142653 var start = this.index; // Check for most common single-character punctuators.
142654
142655 var str = this.source[this.index];
142656
142657 switch (str) {
142658 case '(':
142659 case '{':
142660 if (str === '{') {
142661 this.curlyStack.push('{');
142662 }
142663
142664 ++this.index;
142665 break;
142666
142667 case '.':
142668 ++this.index;
142669
142670 if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') {
142671 // Spread operator: ...
142672 this.index += 2;
142673 str = '...';
142674 }
142675
142676 break;
142677
142678 case '}':
142679 ++this.index;
142680 this.curlyStack.pop();
142681 break;
142682
142683 case ')':
142684 case ';':
142685 case ',':
142686 case '[':
142687 case ']':
142688 case ':':
142689 case '?':
142690 case '~':
142691 ++this.index;
142692 break;
142693
142694 default:
142695 // 4-character punctuator.
142696 str = this.source.substr(this.index, 4);
142697
142698 if (str === '>>>=') {
142699 this.index += 4;
142700 } else {
142701 // 3-character punctuators.
142702 str = str.substr(0, 3);
142703
142704 if (str === '===' || str === '!==' || str === '>>>' || str === '<<=' || str === '>>=' || str === '**=') {
142705 this.index += 3;
142706 } else {
142707 // 2-character punctuators.
142708 str = str.substr(0, 2);
142709
142710 if (str === '&&' || str === '||' || str === '==' || str === '!=' || str === '+=' || str === '-=' || str === '*=' || str === '/=' || str === '++' || str === '--' || str === '<<' || str === '>>' || str === '&=' || str === '|=' || str === '^=' || str === '%=' || str === '<=' || str === '>=' || str === '=>' || str === '**') {
142711 this.index += 2;
142712 } else {
142713 // 1-character punctuators.
142714 str = this.source[this.index];
142715
142716 if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
142717 ++this.index;
142718 }
142719 }
142720 }
142721 }
142722
142723 }
142724
142725 if (this.index === start) {
142726 this.throwUnexpectedToken();
142727 }
142728
142729 return {
142730 type: 7
142731 /* Punctuator */
142732 ,
142733 value: str,
142734 lineNumber: this.lineNumber,
142735 lineStart: this.lineStart,
142736 start: start,
142737 end: this.index
142738 };
142739 }; // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
142740
142741
142742 Scanner.prototype.scanHexLiteral = function (start) {
142743 var num = '';
142744
142745 while (!this.eof()) {
142746 if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
142747 break;
142748 }
142749
142750 num += this.source[this.index++];
142751 }
142752
142753 if (num.length === 0) {
142754 this.throwUnexpectedToken();
142755 }
142756
142757 if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
142758 this.throwUnexpectedToken();
142759 }
142760
142761 return {
142762 type: 6
142763 /* NumericLiteral */
142764 ,
142765 value: parseInt('0x' + num, 16),
142766 lineNumber: this.lineNumber,
142767 lineStart: this.lineStart,
142768 start: start,
142769 end: this.index
142770 };
142771 };
142772
142773 Scanner.prototype.scanBinaryLiteral = function (start) {
142774 var num = '';
142775 var ch;
142776
142777 while (!this.eof()) {
142778 ch = this.source[this.index];
142779
142780 if (ch !== '0' && ch !== '1') {
142781 break;
142782 }
142783
142784 num += this.source[this.index++];
142785 }
142786
142787 if (num.length === 0) {
142788 // only 0b or 0B
142789 this.throwUnexpectedToken();
142790 }
142791
142792 if (!this.eof()) {
142793 ch = this.source.charCodeAt(this.index);
142794 /* istanbul ignore else */
142795
142796 if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
142797 this.throwUnexpectedToken();
142798 }
142799 }
142800
142801 return {
142802 type: 6
142803 /* NumericLiteral */
142804 ,
142805 value: parseInt(num, 2),
142806 lineNumber: this.lineNumber,
142807 lineStart: this.lineStart,
142808 start: start,
142809 end: this.index
142810 };
142811 };
142812
142813 Scanner.prototype.scanOctalLiteral = function (prefix, start) {
142814 var num = '';
142815 var octal = false;
142816
142817 if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
142818 octal = true;
142819 num = '0' + this.source[this.index++];
142820 } else {
142821 ++this.index;
142822 }
142823
142824 while (!this.eof()) {
142825 if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
142826 break;
142827 }
142828
142829 num += this.source[this.index++];
142830 }
142831
142832 if (!octal && num.length === 0) {
142833 // only 0o or 0O
142834 this.throwUnexpectedToken();
142835 }
142836
142837 if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
142838 this.throwUnexpectedToken();
142839 }
142840
142841 return {
142842 type: 6
142843 /* NumericLiteral */
142844 ,
142845 value: parseInt(num, 8),
142846 octal: octal,
142847 lineNumber: this.lineNumber,
142848 lineStart: this.lineStart,
142849 start: start,
142850 end: this.index
142851 };
142852 };
142853
142854 Scanner.prototype.isImplicitOctalLiteral = function () {
142855 // Implicit octal, unless there is a non-octal digit.
142856 // (Annex B.1.1 on Numeric Literals)
142857 for (var i = this.index + 1; i < this.length; ++i) {
142858 var ch = this.source[i];
142859
142860 if (ch === '8' || ch === '9') {
142861 return false;
142862 }
142863
142864 if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
142865 return true;
142866 }
142867 }
142868
142869 return true;
142870 };
142871
142872 Scanner.prototype.scanNumericLiteral = function () {
142873 var start = this.index;
142874 var ch = this.source[start];
142875 assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || ch === '.', 'Numeric literal must start with a decimal digit or a decimal point');
142876 var num = '';
142877
142878 if (ch !== '.') {
142879 num = this.source[this.index++];
142880 ch = this.source[this.index]; // Hex number starts with '0x'.
142881 // Octal number starts with '0'.
142882 // Octal number in ES6 starts with '0o'.
142883 // Binary number in ES6 starts with '0b'.
142884
142885 if (num === '0') {
142886 if (ch === 'x' || ch === 'X') {
142887 ++this.index;
142888 return this.scanHexLiteral(start);
142889 }
142890
142891 if (ch === 'b' || ch === 'B') {
142892 ++this.index;
142893 return this.scanBinaryLiteral(start);
142894 }
142895
142896 if (ch === 'o' || ch === 'O') {
142897 return this.scanOctalLiteral(ch, start);
142898 }
142899
142900 if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
142901 if (this.isImplicitOctalLiteral()) {
142902 return this.scanOctalLiteral(ch, start);
142903 }
142904 }
142905 }
142906
142907 while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
142908 num += this.source[this.index++];
142909 }
142910
142911 ch = this.source[this.index];
142912 }
142913
142914 if (ch === '.') {
142915 num += this.source[this.index++];
142916
142917 while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
142918 num += this.source[this.index++];
142919 }
142920
142921 ch = this.source[this.index];
142922 }
142923
142924 if (ch === 'e' || ch === 'E') {
142925 num += this.source[this.index++];
142926 ch = this.source[this.index];
142927
142928 if (ch === '+' || ch === '-') {
142929 num += this.source[this.index++];
142930 }
142931
142932 if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
142933 while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
142934 num += this.source[this.index++];
142935 }
142936 } else {
142937 this.throwUnexpectedToken();
142938 }
142939 }
142940
142941 if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
142942 this.throwUnexpectedToken();
142943 }
142944
142945 return {
142946 type: 6
142947 /* NumericLiteral */
142948 ,
142949 value: parseFloat(num),
142950 lineNumber: this.lineNumber,
142951 lineStart: this.lineStart,
142952 start: start,
142953 end: this.index
142954 };
142955 }; // https://tc39.github.io/ecma262/#sec-literals-string-literals
142956
142957
142958 Scanner.prototype.scanStringLiteral = function () {
142959 var start = this.index;
142960 var quote = this.source[start];
142961 assert_1.assert(quote === '\'' || quote === '"', 'String literal must starts with a quote');
142962 ++this.index;
142963 var octal = false;
142964 var str = '';
142965
142966 while (!this.eof()) {
142967 var ch = this.source[this.index++];
142968
142969 if (ch === quote) {
142970 quote = '';
142971 break;
142972 } else if (ch === '\\') {
142973 ch = this.source[this.index++];
142974
142975 if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
142976 switch (ch) {
142977 case 'u':
142978 if (this.source[this.index] === '{') {
142979 ++this.index;
142980 str += this.scanUnicodeCodePointEscape();
142981 } else {
142982 var unescaped_1 = this.scanHexEscape(ch);
142983
142984 if (unescaped_1 === null) {
142985 this.throwUnexpectedToken();
142986 }
142987
142988 str += unescaped_1;
142989 }
142990
142991 break;
142992
142993 case 'x':
142994 var unescaped = this.scanHexEscape(ch);
142995
142996 if (unescaped === null) {
142997 this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
142998 }
142999
143000 str += unescaped;
143001 break;
143002
143003 case 'n':
143004 str += '\n';
143005 break;
143006
143007 case 'r':
143008 str += '\r';
143009 break;
143010
143011 case 't':
143012 str += '\t';
143013 break;
143014
143015 case 'b':
143016 str += '\b';
143017 break;
143018
143019 case 'f':
143020 str += '\f';
143021 break;
143022
143023 case 'v':
143024 str += '\x0B';
143025 break;
143026
143027 case '8':
143028 case '9':
143029 str += ch;
143030 this.tolerateUnexpectedToken();
143031 break;
143032
143033 default:
143034 if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
143035 var octToDec = this.octalToDecimal(ch);
143036 octal = octToDec.octal || octal;
143037 str += String.fromCharCode(octToDec.code);
143038 } else {
143039 str += ch;
143040 }
143041
143042 break;
143043 }
143044 } else {
143045 ++this.lineNumber;
143046
143047 if (ch === '\r' && this.source[this.index] === '\n') {
143048 ++this.index;
143049 }
143050
143051 this.lineStart = this.index;
143052 }
143053 } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
143054 break;
143055 } else {
143056 str += ch;
143057 }
143058 }
143059
143060 if (quote !== '') {
143061 this.index = start;
143062 this.throwUnexpectedToken();
143063 }
143064
143065 return {
143066 type: 8
143067 /* StringLiteral */
143068 ,
143069 value: str,
143070 octal: octal,
143071 lineNumber: this.lineNumber,
143072 lineStart: this.lineStart,
143073 start: start,
143074 end: this.index
143075 };
143076 }; // https://tc39.github.io/ecma262/#sec-template-literal-lexical-components
143077
143078
143079 Scanner.prototype.scanTemplate = function () {
143080 var cooked = '';
143081 var terminated = false;
143082 var start = this.index;
143083 var head = this.source[start] === '`';
143084 var tail = false;
143085 var rawOffset = 2;
143086 ++this.index;
143087
143088 while (!this.eof()) {
143089 var ch = this.source[this.index++];
143090
143091 if (ch === '`') {
143092 rawOffset = 1;
143093 tail = true;
143094 terminated = true;
143095 break;
143096 } else if (ch === '$') {
143097 if (this.source[this.index] === '{') {
143098 this.curlyStack.push('${');
143099 ++this.index;
143100 terminated = true;
143101 break;
143102 }
143103
143104 cooked += ch;
143105 } else if (ch === '\\') {
143106 ch = this.source[this.index++];
143107
143108 if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
143109 switch (ch) {
143110 case 'n':
143111 cooked += '\n';
143112 break;
143113
143114 case 'r':
143115 cooked += '\r';
143116 break;
143117
143118 case 't':
143119 cooked += '\t';
143120 break;
143121
143122 case 'u':
143123 if (this.source[this.index] === '{') {
143124 ++this.index;
143125 cooked += this.scanUnicodeCodePointEscape();
143126 } else {
143127 var restore = this.index;
143128 var unescaped_2 = this.scanHexEscape(ch);
143129
143130 if (unescaped_2 !== null) {
143131 cooked += unescaped_2;
143132 } else {
143133 this.index = restore;
143134 cooked += ch;
143135 }
143136 }
143137
143138 break;
143139
143140 case 'x':
143141 var unescaped = this.scanHexEscape(ch);
143142
143143 if (unescaped === null) {
143144 this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
143145 }
143146
143147 cooked += unescaped;
143148 break;
143149
143150 case 'b':
143151 cooked += '\b';
143152 break;
143153
143154 case 'f':
143155 cooked += '\f';
143156 break;
143157
143158 case 'v':
143159 cooked += '\v';
143160 break;
143161
143162 default:
143163 if (ch === '0') {
143164 if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
143165 // Illegal: \01 \02 and so on
143166 this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
143167 }
143168
143169 cooked += '\0';
143170 } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
143171 // Illegal: \1 \2
143172 this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
143173 } else {
143174 cooked += ch;
143175 }
143176
143177 break;
143178 }
143179 } else {
143180 ++this.lineNumber;
143181
143182 if (ch === '\r' && this.source[this.index] === '\n') {
143183 ++this.index;
143184 }
143185
143186 this.lineStart = this.index;
143187 }
143188 } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
143189 ++this.lineNumber;
143190
143191 if (ch === '\r' && this.source[this.index] === '\n') {
143192 ++this.index;
143193 }
143194
143195 this.lineStart = this.index;
143196 cooked += '\n';
143197 } else {
143198 cooked += ch;
143199 }
143200 }
143201
143202 if (!terminated) {
143203 this.throwUnexpectedToken();
143204 }
143205
143206 if (!head) {
143207 this.curlyStack.pop();
143208 }
143209
143210 return {
143211 type: 10
143212 /* Template */
143213 ,
143214 value: this.source.slice(start + 1, this.index - rawOffset),
143215 cooked: cooked,
143216 head: head,
143217 tail: tail,
143218 lineNumber: this.lineNumber,
143219 lineStart: this.lineStart,
143220 start: start,
143221 end: this.index
143222 };
143223 }; // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
143224
143225
143226 Scanner.prototype.testRegExp = function (pattern, flags) {
143227 // The BMP character to use as a replacement for astral symbols when
143228 // translating an ES6 "u"-flagged pattern to an ES5-compatible
143229 // approximation.
143230 // Note: replacing with '\uFFFF' enables false positives in unlikely
143231 // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
143232 // pattern that would not be detected by this substitution.
143233 var astralSubstitute = '\uFFFF';
143234 var tmp = pattern;
143235 var self = this;
143236
143237 if (flags.indexOf('u') >= 0) {
143238 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
143239 var codePoint = parseInt($1 || $2, 16);
143240
143241 if (codePoint > 0x10FFFF) {
143242 self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
143243 }
143244
143245 if (codePoint <= 0xFFFF) {
143246 return String.fromCharCode(codePoint);
143247 }
143248
143249 return astralSubstitute;
143250 }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
143251 } // First, detect invalid regular expressions.
143252
143253
143254 try {
143255 RegExp(tmp);
143256 } catch (e) {
143257 this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
143258 } // Return a regular expression object for this pattern-flag pair, or
143259 // `null` in case the current environment doesn't support the flags it
143260 // uses.
143261
143262
143263 try {
143264 return new RegExp(pattern, flags);
143265 } catch (exception) {
143266 /* istanbul ignore next */
143267 return null;
143268 }
143269 };
143270
143271 Scanner.prototype.scanRegExpBody = function () {
143272 var ch = this.source[this.index];
143273 assert_1.assert(ch === '/', 'Regular expression literal must start with a slash');
143274 var str = this.source[this.index++];
143275 var classMarker = false;
143276 var terminated = false;
143277
143278 while (!this.eof()) {
143279 ch = this.source[this.index++];
143280 str += ch;
143281
143282 if (ch === '\\') {
143283 ch = this.source[this.index++]; // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
143284
143285 if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
143286 this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
143287 }
143288
143289 str += ch;
143290 } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
143291 this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
143292 } else if (classMarker) {
143293 if (ch === ']') {
143294 classMarker = false;
143295 }
143296 } else {
143297 if (ch === '/') {
143298 terminated = true;
143299 break;
143300 } else if (ch === '[') {
143301 classMarker = true;
143302 }
143303 }
143304 }
143305
143306 if (!terminated) {
143307 this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
143308 } // Exclude leading and trailing slash.
143309
143310
143311 return str.substr(1, str.length - 2);
143312 };
143313
143314 Scanner.prototype.scanRegExpFlags = function () {
143315 var str = '';
143316 var flags = '';
143317
143318 while (!this.eof()) {
143319 var ch = this.source[this.index];
143320
143321 if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
143322 break;
143323 }
143324
143325 ++this.index;
143326
143327 if (ch === '\\' && !this.eof()) {
143328 ch = this.source[this.index];
143329
143330 if (ch === 'u') {
143331 ++this.index;
143332 var restore = this.index;
143333 var char = this.scanHexEscape('u');
143334
143335 if (char !== null) {
143336 flags += char;
143337
143338 for (str += '\\u'; restore < this.index; ++restore) {
143339 str += this.source[restore];
143340 }
143341 } else {
143342 this.index = restore;
143343 flags += 'u';
143344 str += '\\u';
143345 }
143346
143347 this.tolerateUnexpectedToken();
143348 } else {
143349 str += '\\';
143350 this.tolerateUnexpectedToken();
143351 }
143352 } else {
143353 flags += ch;
143354 str += ch;
143355 }
143356 }
143357
143358 return flags;
143359 };
143360
143361 Scanner.prototype.scanRegExp = function () {
143362 var start = this.index;
143363 var pattern = this.scanRegExpBody();
143364 var flags = this.scanRegExpFlags();
143365 var value = this.testRegExp(pattern, flags);
143366 return {
143367 type: 9
143368 /* RegularExpression */
143369 ,
143370 value: '',
143371 pattern: pattern,
143372 flags: flags,
143373 regex: value,
143374 lineNumber: this.lineNumber,
143375 lineStart: this.lineStart,
143376 start: start,
143377 end: this.index
143378 };
143379 };
143380
143381 Scanner.prototype.lex = function () {
143382 if (this.eof()) {
143383 return {
143384 type: 2
143385 /* EOF */
143386 ,
143387 value: '',
143388 lineNumber: this.lineNumber,
143389 lineStart: this.lineStart,
143390 start: this.index,
143391 end: this.index
143392 };
143393 }
143394
143395 var cp = this.source.charCodeAt(this.index);
143396
143397 if (character_1.Character.isIdentifierStart(cp)) {
143398 return this.scanIdentifier();
143399 } // Very common: ( and ) and ;
143400
143401
143402 if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
143403 return this.scanPunctuator();
143404 } // String literal starts with single quote (U+0027) or double quote (U+0022).
143405
143406
143407 if (cp === 0x27 || cp === 0x22) {
143408 return this.scanStringLiteral();
143409 } // Dot (.) U+002E can also start a floating-point number, hence the need
143410 // to check the next character.
143411
143412
143413 if (cp === 0x2E) {
143414 if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
143415 return this.scanNumericLiteral();
143416 }
143417
143418 return this.scanPunctuator();
143419 }
143420
143421 if (character_1.Character.isDecimalDigit(cp)) {
143422 return this.scanNumericLiteral();
143423 } // Template literals start with ` (U+0060) for template head
143424 // or } (U+007D) for template middle or template tail.
143425
143426
143427 if (cp === 0x60 || cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${') {
143428 return this.scanTemplate();
143429 } // Possible identifier start in a surrogate pair.
143430
143431
143432 if (cp >= 0xD800 && cp < 0xDFFF) {
143433 if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
143434 return this.scanIdentifier();
143435 }
143436 }
143437
143438 return this.scanPunctuator();
143439 };
143440
143441 return Scanner;
143442 }();
143443
143444 exports.Scanner = Scanner;
143445 /***/
143446 },
143447 /* 13 */
143448
143449 /***/
143450 function (module, exports) {
143451 "use strict";
143452
143453 Object.defineProperty(exports, "__esModule", {
143454 value: true
143455 });
143456 exports.TokenName = {};
143457 exports.TokenName[1
143458 /* BooleanLiteral */
143459 ] = 'Boolean';
143460 exports.TokenName[2
143461 /* EOF */
143462 ] = '<end>';
143463 exports.TokenName[3
143464 /* Identifier */
143465 ] = 'Identifier';
143466 exports.TokenName[4
143467 /* Keyword */
143468 ] = 'Keyword';
143469 exports.TokenName[5
143470 /* NullLiteral */
143471 ] = 'Null';
143472 exports.TokenName[6
143473 /* NumericLiteral */
143474 ] = 'Numeric';
143475 exports.TokenName[7
143476 /* Punctuator */
143477 ] = 'Punctuator';
143478 exports.TokenName[8
143479 /* StringLiteral */
143480 ] = 'String';
143481 exports.TokenName[9
143482 /* RegularExpression */
143483 ] = 'RegularExpression';
143484 exports.TokenName[10
143485 /* Template */
143486 ] = 'Template';
143487 /***/
143488 },
143489 /* 14 */
143490
143491 /***/
143492 function (module, exports) {
143493 "use strict"; // Generated by generate-xhtml-entities.js. DO NOT MODIFY!
143494
143495 Object.defineProperty(exports, "__esModule", {
143496 value: true
143497 });
143498 exports.XHTMLEntities = {
143499 quot: '\u0022',
143500 amp: '\u0026',
143501 apos: '\u0027',
143502 gt: '\u003E',
143503 nbsp: '\u00A0',
143504 iexcl: '\u00A1',
143505 cent: '\u00A2',
143506 pound: '\u00A3',
143507 curren: '\u00A4',
143508 yen: '\u00A5',
143509 brvbar: '\u00A6',
143510 sect: '\u00A7',
143511 uml: '\u00A8',
143512 copy: '\u00A9',
143513 ordf: '\u00AA',
143514 laquo: '\u00AB',
143515 not: '\u00AC',
143516 shy: '\u00AD',
143517 reg: '\u00AE',
143518 macr: '\u00AF',
143519 deg: '\u00B0',
143520 plusmn: '\u00B1',
143521 sup2: '\u00B2',
143522 sup3: '\u00B3',
143523 acute: '\u00B4',
143524 micro: '\u00B5',
143525 para: '\u00B6',
143526 middot: '\u00B7',
143527 cedil: '\u00B8',
143528 sup1: '\u00B9',
143529 ordm: '\u00BA',
143530 raquo: '\u00BB',
143531 frac14: '\u00BC',
143532 frac12: '\u00BD',
143533 frac34: '\u00BE',
143534 iquest: '\u00BF',
143535 Agrave: '\u00C0',
143536 Aacute: '\u00C1',
143537 Acirc: '\u00C2',
143538 Atilde: '\u00C3',
143539 Auml: '\u00C4',
143540 Aring: '\u00C5',
143541 AElig: '\u00C6',
143542 Ccedil: '\u00C7',
143543 Egrave: '\u00C8',
143544 Eacute: '\u00C9',
143545 Ecirc: '\u00CA',
143546 Euml: '\u00CB',
143547 Igrave: '\u00CC',
143548 Iacute: '\u00CD',
143549 Icirc: '\u00CE',
143550 Iuml: '\u00CF',
143551 ETH: '\u00D0',
143552 Ntilde: '\u00D1',
143553 Ograve: '\u00D2',
143554 Oacute: '\u00D3',
143555 Ocirc: '\u00D4',
143556 Otilde: '\u00D5',
143557 Ouml: '\u00D6',
143558 times: '\u00D7',
143559 Oslash: '\u00D8',
143560 Ugrave: '\u00D9',
143561 Uacute: '\u00DA',
143562 Ucirc: '\u00DB',
143563 Uuml: '\u00DC',
143564 Yacute: '\u00DD',
143565 THORN: '\u00DE',
143566 szlig: '\u00DF',
143567 agrave: '\u00E0',
143568 aacute: '\u00E1',
143569 acirc: '\u00E2',
143570 atilde: '\u00E3',
143571 auml: '\u00E4',
143572 aring: '\u00E5',
143573 aelig: '\u00E6',
143574 ccedil: '\u00E7',
143575 egrave: '\u00E8',
143576 eacute: '\u00E9',
143577 ecirc: '\u00EA',
143578 euml: '\u00EB',
143579 igrave: '\u00EC',
143580 iacute: '\u00ED',
143581 icirc: '\u00EE',
143582 iuml: '\u00EF',
143583 eth: '\u00F0',
143584 ntilde: '\u00F1',
143585 ograve: '\u00F2',
143586 oacute: '\u00F3',
143587 ocirc: '\u00F4',
143588 otilde: '\u00F5',
143589 ouml: '\u00F6',
143590 divide: '\u00F7',
143591 oslash: '\u00F8',
143592 ugrave: '\u00F9',
143593 uacute: '\u00FA',
143594 ucirc: '\u00FB',
143595 uuml: '\u00FC',
143596 yacute: '\u00FD',
143597 thorn: '\u00FE',
143598 yuml: '\u00FF',
143599 OElig: '\u0152',
143600 oelig: '\u0153',
143601 Scaron: '\u0160',
143602 scaron: '\u0161',
143603 Yuml: '\u0178',
143604 fnof: '\u0192',
143605 circ: '\u02C6',
143606 tilde: '\u02DC',
143607 Alpha: '\u0391',
143608 Beta: '\u0392',
143609 Gamma: '\u0393',
143610 Delta: '\u0394',
143611 Epsilon: '\u0395',
143612 Zeta: '\u0396',
143613 Eta: '\u0397',
143614 Theta: '\u0398',
143615 Iota: '\u0399',
143616 Kappa: '\u039A',
143617 Lambda: '\u039B',
143618 Mu: '\u039C',
143619 Nu: '\u039D',
143620 Xi: '\u039E',
143621 Omicron: '\u039F',
143622 Pi: '\u03A0',
143623 Rho: '\u03A1',
143624 Sigma: '\u03A3',
143625 Tau: '\u03A4',
143626 Upsilon: '\u03A5',
143627 Phi: '\u03A6',
143628 Chi: '\u03A7',
143629 Psi: '\u03A8',
143630 Omega: '\u03A9',
143631 alpha: '\u03B1',
143632 beta: '\u03B2',
143633 gamma: '\u03B3',
143634 delta: '\u03B4',
143635 epsilon: '\u03B5',
143636 zeta: '\u03B6',
143637 eta: '\u03B7',
143638 theta: '\u03B8',
143639 iota: '\u03B9',
143640 kappa: '\u03BA',
143641 lambda: '\u03BB',
143642 mu: '\u03BC',
143643 nu: '\u03BD',
143644 xi: '\u03BE',
143645 omicron: '\u03BF',
143646 pi: '\u03C0',
143647 rho: '\u03C1',
143648 sigmaf: '\u03C2',
143649 sigma: '\u03C3',
143650 tau: '\u03C4',
143651 upsilon: '\u03C5',
143652 phi: '\u03C6',
143653 chi: '\u03C7',
143654 psi: '\u03C8',
143655 omega: '\u03C9',
143656 thetasym: '\u03D1',
143657 upsih: '\u03D2',
143658 piv: '\u03D6',
143659 ensp: '\u2002',
143660 emsp: '\u2003',
143661 thinsp: '\u2009',
143662 zwnj: '\u200C',
143663 zwj: '\u200D',
143664 lrm: '\u200E',
143665 rlm: '\u200F',
143666 ndash: '\u2013',
143667 mdash: '\u2014',
143668 lsquo: '\u2018',
143669 rsquo: '\u2019',
143670 sbquo: '\u201A',
143671 ldquo: '\u201C',
143672 rdquo: '\u201D',
143673 bdquo: '\u201E',
143674 dagger: '\u2020',
143675 Dagger: '\u2021',
143676 bull: '\u2022',
143677 hellip: '\u2026',
143678 permil: '\u2030',
143679 prime: '\u2032',
143680 Prime: '\u2033',
143681 lsaquo: '\u2039',
143682 rsaquo: '\u203A',
143683 oline: '\u203E',
143684 frasl: '\u2044',
143685 euro: '\u20AC',
143686 image: '\u2111',
143687 weierp: '\u2118',
143688 real: '\u211C',
143689 trade: '\u2122',
143690 alefsym: '\u2135',
143691 larr: '\u2190',
143692 uarr: '\u2191',
143693 rarr: '\u2192',
143694 darr: '\u2193',
143695 harr: '\u2194',
143696 crarr: '\u21B5',
143697 lArr: '\u21D0',
143698 uArr: '\u21D1',
143699 rArr: '\u21D2',
143700 dArr: '\u21D3',
143701 hArr: '\u21D4',
143702 forall: '\u2200',
143703 part: '\u2202',
143704 exist: '\u2203',
143705 empty: '\u2205',
143706 nabla: '\u2207',
143707 isin: '\u2208',
143708 notin: '\u2209',
143709 ni: '\u220B',
143710 prod: '\u220F',
143711 sum: '\u2211',
143712 minus: '\u2212',
143713 lowast: '\u2217',
143714 radic: '\u221A',
143715 prop: '\u221D',
143716 infin: '\u221E',
143717 ang: '\u2220',
143718 and: '\u2227',
143719 or: '\u2228',
143720 cap: '\u2229',
143721 cup: '\u222A',
143722 int: '\u222B',
143723 there4: '\u2234',
143724 sim: '\u223C',
143725 cong: '\u2245',
143726 asymp: '\u2248',
143727 ne: '\u2260',
143728 equiv: '\u2261',
143729 le: '\u2264',
143730 ge: '\u2265',
143731 sub: '\u2282',
143732 sup: '\u2283',
143733 nsub: '\u2284',
143734 sube: '\u2286',
143735 supe: '\u2287',
143736 oplus: '\u2295',
143737 otimes: '\u2297',
143738 perp: '\u22A5',
143739 sdot: '\u22C5',
143740 lceil: '\u2308',
143741 rceil: '\u2309',
143742 lfloor: '\u230A',
143743 rfloor: '\u230B',
143744 loz: '\u25CA',
143745 spades: '\u2660',
143746 clubs: '\u2663',
143747 hearts: '\u2665',
143748 diams: '\u2666',
143749 lang: '\u27E8',
143750 rang: '\u27E9'
143751 };
143752 /***/
143753 },
143754 /* 15 */
143755
143756 /***/
143757 function (module, exports, __webpack_require__) {
143758 "use strict";
143759
143760 Object.defineProperty(exports, "__esModule", {
143761 value: true
143762 });
143763
143764 var error_handler_1 = __webpack_require__(10);
143765
143766 var scanner_1 = __webpack_require__(12);
143767
143768 var token_1 = __webpack_require__(13);
143769
143770 var Reader = function () {
143771 function Reader() {
143772 this.values = [];
143773 this.curly = this.paren = -1;
143774 } // A function following one of those tokens is an expression.
143775
143776
143777 Reader.prototype.beforeFunctionExpression = function (t) {
143778 return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators
143779 '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators
143780 '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
143781 }; // Determine if forward slash (/) is an operator or part of a regular expression
143782 // https://github.com/mozilla/sweet.js/wiki/design
143783
143784
143785 Reader.prototype.isRegexStart = function () {
143786 var previous = this.values[this.values.length - 1];
143787 var regex = previous !== null;
143788
143789 switch (previous) {
143790 case 'this':
143791 case ']':
143792 regex = false;
143793 break;
143794
143795 case ')':
143796 var keyword = this.values[this.paren - 1];
143797 regex = keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with';
143798 break;
143799
143800 case '}':
143801 // Dividing a function by anything makes little sense,
143802 // but we have to check for that.
143803 regex = false;
143804
143805 if (this.values[this.curly - 3] === 'function') {
143806 // Anonymous function, e.g. function(){} /42
143807 var check = this.values[this.curly - 4];
143808 regex = check ? !this.beforeFunctionExpression(check) : false;
143809 } else if (this.values[this.curly - 4] === 'function') {
143810 // Named function, e.g. function f(){} /42/
143811 var check = this.values[this.curly - 5];
143812 regex = check ? !this.beforeFunctionExpression(check) : true;
143813 }
143814
143815 break;
143816
143817 default:
143818 break;
143819 }
143820
143821 return regex;
143822 };
143823
143824 Reader.prototype.push = function (token) {
143825 if (token.type === 7
143826 /* Punctuator */
143827 || token.type === 4
143828 /* Keyword */
143829 ) {
143830 if (token.value === '{') {
143831 this.curly = this.values.length;
143832 } else if (token.value === '(') {
143833 this.paren = this.values.length;
143834 }
143835
143836 this.values.push(token.value);
143837 } else {
143838 this.values.push(null);
143839 }
143840 };
143841
143842 return Reader;
143843 }();
143844
143845 var Tokenizer = function () {
143846 function Tokenizer(code, config) {
143847 this.errorHandler = new error_handler_1.ErrorHandler();
143848 this.errorHandler.tolerant = config ? typeof config.tolerant === 'boolean' && config.tolerant : false;
143849 this.scanner = new scanner_1.Scanner(code, this.errorHandler);
143850 this.scanner.trackComment = config ? typeof config.comment === 'boolean' && config.comment : false;
143851 this.trackRange = config ? typeof config.range === 'boolean' && config.range : false;
143852 this.trackLoc = config ? typeof config.loc === 'boolean' && config.loc : false;
143853 this.buffer = [];
143854 this.reader = new Reader();
143855 }
143856
143857 Tokenizer.prototype.errors = function () {
143858 return this.errorHandler.errors;
143859 };
143860
143861 Tokenizer.prototype.getNextToken = function () {
143862 if (this.buffer.length === 0) {
143863 var comments = this.scanner.scanComments();
143864
143865 if (this.scanner.trackComment) {
143866 for (var i = 0; i < comments.length; ++i) {
143867 var e = comments[i];
143868 var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
143869 var comment = {
143870 type: e.multiLine ? 'BlockComment' : 'LineComment',
143871 value: value
143872 };
143873
143874 if (this.trackRange) {
143875 comment.range = e.range;
143876 }
143877
143878 if (this.trackLoc) {
143879 comment.loc = e.loc;
143880 }
143881
143882 this.buffer.push(comment);
143883 }
143884 }
143885
143886 if (!this.scanner.eof()) {
143887 var loc = void 0;
143888
143889 if (this.trackLoc) {
143890 loc = {
143891 start: {
143892 line: this.scanner.lineNumber,
143893 column: this.scanner.index - this.scanner.lineStart
143894 },
143895 end: {}
143896 };
143897 }
143898
143899 var startRegex = this.scanner.source[this.scanner.index] === '/' && this.reader.isRegexStart();
143900 var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
143901 this.reader.push(token);
143902 var entry = {
143903 type: token_1.TokenName[token.type],
143904 value: this.scanner.source.slice(token.start, token.end)
143905 };
143906
143907 if (this.trackRange) {
143908 entry.range = [token.start, token.end];
143909 }
143910
143911 if (this.trackLoc) {
143912 loc.end = {
143913 line: this.scanner.lineNumber,
143914 column: this.scanner.index - this.scanner.lineStart
143915 };
143916 entry.loc = loc;
143917 }
143918
143919 if (token.type === 9
143920 /* RegularExpression */
143921 ) {
143922 var pattern = token.pattern;
143923 var flags = token.flags;
143924 entry.regex = {
143925 pattern: pattern,
143926 flags: flags
143927 };
143928 }
143929
143930 this.buffer.push(entry);
143931 }
143932 }
143933
143934 return this.buffer.shift();
143935 };
143936
143937 return Tokenizer;
143938 }();
143939
143940 exports.Tokenizer = Tokenizer;
143941 /***/
143942 }
143943 /******/
143944 ])
143945 );
143946});
143947
143948;
143949
143950/***/ }),
6a5a0f88 143951/* 880 */
eb39fafa
DC
143952/***/ (function(module, exports, __webpack_require__) {
143953
143954"use strict";
143955
143956/*eslint-disable no-use-before-define*/
143957
6a5a0f88 143958var common = __webpack_require__(852);
eb39fafa 143959
6a5a0f88 143960var YAMLException = __webpack_require__(853);
eb39fafa 143961
6a5a0f88 143962var DEFAULT_FULL_SCHEMA = __webpack_require__(875);
eb39fafa 143963
6a5a0f88 143964var DEFAULT_SAFE_SCHEMA = __webpack_require__(855);
eb39fafa
DC
143965
143966var _toString = Object.prototype.toString;
143967var _hasOwnProperty = Object.prototype.hasOwnProperty;
143968var CHAR_TAB = 0x09;
143969/* Tab */
143970
143971var CHAR_LINE_FEED = 0x0A;
143972/* LF */
143973
6a5a0f88
TL
143974var CHAR_CARRIAGE_RETURN = 0x0D;
143975/* CR */
143976
eb39fafa
DC
143977var CHAR_SPACE = 0x20;
143978/* Space */
143979
143980var CHAR_EXCLAMATION = 0x21;
143981/* ! */
143982
143983var CHAR_DOUBLE_QUOTE = 0x22;
143984/* " */
143985
143986var CHAR_SHARP = 0x23;
143987/* # */
143988
143989var CHAR_PERCENT = 0x25;
143990/* % */
143991
143992var CHAR_AMPERSAND = 0x26;
143993/* & */
143994
143995var CHAR_SINGLE_QUOTE = 0x27;
143996/* ' */
143997
143998var CHAR_ASTERISK = 0x2A;
143999/* * */
144000
144001var CHAR_COMMA = 0x2C;
144002/* , */
144003
144004var CHAR_MINUS = 0x2D;
144005/* - */
144006
144007var CHAR_COLON = 0x3A;
144008/* : */
144009
6a5a0f88
TL
144010var CHAR_EQUALS = 0x3D;
144011/* = */
144012
eb39fafa
DC
144013var CHAR_GREATER_THAN = 0x3E;
144014/* > */
144015
144016var CHAR_QUESTION = 0x3F;
144017/* ? */
144018
144019var CHAR_COMMERCIAL_AT = 0x40;
144020/* @ */
144021
144022var CHAR_LEFT_SQUARE_BRACKET = 0x5B;
144023/* [ */
144024
144025var CHAR_RIGHT_SQUARE_BRACKET = 0x5D;
144026/* ] */
144027
144028var CHAR_GRAVE_ACCENT = 0x60;
144029/* ` */
144030
144031var CHAR_LEFT_CURLY_BRACKET = 0x7B;
144032/* { */
144033
144034var CHAR_VERTICAL_LINE = 0x7C;
144035/* | */
144036
144037var CHAR_RIGHT_CURLY_BRACKET = 0x7D;
144038/* } */
144039
144040var ESCAPE_SEQUENCES = {};
144041ESCAPE_SEQUENCES[0x00] = '\\0';
144042ESCAPE_SEQUENCES[0x07] = '\\a';
144043ESCAPE_SEQUENCES[0x08] = '\\b';
144044ESCAPE_SEQUENCES[0x09] = '\\t';
144045ESCAPE_SEQUENCES[0x0A] = '\\n';
144046ESCAPE_SEQUENCES[0x0B] = '\\v';
144047ESCAPE_SEQUENCES[0x0C] = '\\f';
144048ESCAPE_SEQUENCES[0x0D] = '\\r';
144049ESCAPE_SEQUENCES[0x1B] = '\\e';
144050ESCAPE_SEQUENCES[0x22] = '\\"';
144051ESCAPE_SEQUENCES[0x5C] = '\\\\';
144052ESCAPE_SEQUENCES[0x85] = '\\N';
144053ESCAPE_SEQUENCES[0xA0] = '\\_';
144054ESCAPE_SEQUENCES[0x2028] = '\\L';
144055ESCAPE_SEQUENCES[0x2029] = '\\P';
144056var DEPRECATED_BOOLEANS_SYNTAX = ['y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'];
144057
144058function compileStyleMap(schema, map) {
144059 var result, keys, index, length, tag, style, type;
144060 if (map === null) return {};
144061 result = {};
144062 keys = Object.keys(map);
144063
144064 for (index = 0, length = keys.length; index < length; index += 1) {
144065 tag = keys[index];
144066 style = String(map[tag]);
144067
144068 if (tag.slice(0, 2) === '!!') {
144069 tag = 'tag:yaml.org,2002:' + tag.slice(2);
144070 }
144071
144072 type = schema.compiledTypeMap['fallback'][tag];
144073
144074 if (type && _hasOwnProperty.call(type.styleAliases, style)) {
144075 style = type.styleAliases[style];
144076 }
144077
144078 result[tag] = style;
144079 }
144080
144081 return result;
144082}
144083
144084function encodeHex(character) {
144085 var string, handle, length;
144086 string = character.toString(16).toUpperCase();
144087
144088 if (character <= 0xFF) {
144089 handle = 'x';
144090 length = 2;
144091 } else if (character <= 0xFFFF) {
144092 handle = 'u';
144093 length = 4;
144094 } else if (character <= 0xFFFFFFFF) {
144095 handle = 'U';
144096 length = 8;
144097 } else {
144098 throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
144099 }
144100
144101 return '\\' + handle + common.repeat('0', length - string.length) + string;
144102}
144103
144104function State(options) {
144105 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
144106 this.indent = Math.max(1, options['indent'] || 2);
144107 this.noArrayIndent = options['noArrayIndent'] || false;
144108 this.skipInvalid = options['skipInvalid'] || false;
144109 this.flowLevel = common.isNothing(options['flowLevel']) ? -1 : options['flowLevel'];
144110 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
144111 this.sortKeys = options['sortKeys'] || false;
144112 this.lineWidth = options['lineWidth'] || 80;
144113 this.noRefs = options['noRefs'] || false;
144114 this.noCompatMode = options['noCompatMode'] || false;
144115 this.condenseFlow = options['condenseFlow'] || false;
144116 this.implicitTypes = this.schema.compiledImplicit;
144117 this.explicitTypes = this.schema.compiledExplicit;
144118 this.tag = null;
144119 this.result = '';
144120 this.duplicates = [];
144121 this.usedDuplicates = null;
144122} // Indents every line in a string. Empty lines (\n only) are not indented.
144123
144124
144125function indentString(string, spaces) {
144126 var ind = common.repeat(' ', spaces),
144127 position = 0,
144128 next = -1,
144129 result = '',
144130 line,
144131 length = string.length;
144132
144133 while (position < length) {
144134 next = string.indexOf('\n', position);
144135
144136 if (next === -1) {
144137 line = string.slice(position);
144138 position = length;
144139 } else {
144140 line = string.slice(position, next + 1);
144141 position = next + 1;
144142 }
144143
144144 if (line.length && line !== '\n') result += ind;
144145 result += line;
144146 }
144147
144148 return result;
144149}
144150
144151function generateNextLine(state, level) {
144152 return '\n' + common.repeat(' ', state.indent * level);
144153}
144154
144155function testImplicitResolving(state, str) {
144156 var index, length, type;
144157
144158 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
144159 type = state.implicitTypes[index];
144160
144161 if (type.resolve(str)) {
144162 return true;
144163 }
144164 }
144165
144166 return false;
144167} // [33] s-white ::= s-space | s-tab
144168
144169
144170function isWhitespace(c) {
144171 return c === CHAR_SPACE || c === CHAR_TAB;
144172} // Returns true if the character can be printed without escaping.
144173// From YAML 1.2: "any allowed characters known to be non-printable
144174// should also be escaped. [However,] This isn’t mandatory"
144175// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
144176
144177
144178function isPrintable(c) {
144179 return 0x00020 <= c && c <= 0x00007E || 0x000A1 <= c && c <= 0x00D7FF && c !== 0x2028 && c !== 0x2029 || 0x0E000 <= c && c <= 0x00FFFD && c !== 0xFEFF
144180 /* BOM */
144181 || 0x10000 <= c && c <= 0x10FFFF;
6a5a0f88
TL
144182} // [34] ns-char ::= nb-char - s-white
144183// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
144184// [26] b-char ::= b-line-feed | b-carriage-return
144185// [24] b-line-feed ::= #xA /* LF */
144186// [25] b-carriage-return ::= #xD /* CR */
144187// [3] c-byte-order-mark ::= #xFEFF
144188
144189
144190function isNsChar(c) {
144191 return isPrintable(c) && !isWhitespace(c) // byte-order-mark
144192 && c !== 0xFEFF // b-char
144193 && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
eb39fafa
DC
144194} // Simplified test for values allowed after the first character in plain style.
144195
144196
6a5a0f88 144197function isPlainSafe(c, prev) {
eb39fafa
DC
144198 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
144199 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
144200 return isPrintable(c) && c !== 0xFEFF // - c-flow-indicator
144201 && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // - ":" - "#"
6a5a0f88
TL
144202 // /* An ns-char preceding */ "#"
144203 && c !== CHAR_COLON && (c !== CHAR_SHARP || prev && isNsChar(prev));
eb39fafa
DC
144204} // Simplified test for values allowed as the first character in plain style.
144205
144206
144207function isPlainSafeFirst(c) {
144208 // Uses a subset of ns-char - c-indicator
144209 // where ns-char = nb-char - s-white.
144210 return isPrintable(c) && c !== 0xFEFF && !isWhitespace(c) // - s-white
144211 // - (c-indicator ::=
144212 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
6a5a0f88
TL
144213 && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
144214 && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”)
eb39fafa
DC
144215 && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
144216} // Determines whether block indentation indicator is required.
144217
144218
144219function needIndentIndicator(string) {
144220 var leadingSpaceRe = /^\n* /;
144221 return leadingSpaceRe.test(string);
144222}
144223
144224var STYLE_PLAIN = 1,
144225 STYLE_SINGLE = 2,
144226 STYLE_LITERAL = 3,
144227 STYLE_FOLDED = 4,
144228 STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style.
144229// lineWidth = -1 => no limit.
144230// Pre-conditions: str.length > 0.
144231// Post-conditions:
144232// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
144233// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
144234// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
144235
144236function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
144237 var i;
6a5a0f88 144238 var char, prev_char;
eb39fafa
DC
144239 var hasLineBreak = false;
144240 var hasFoldableLine = false; // only checked if shouldTrackWidth
144241
144242 var shouldTrackWidth = lineWidth !== -1;
144243 var previousLineBreak = -1; // count the first line correctly
144244
144245 var plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1));
144246
144247 if (singleLineOnly) {
144248 // Case: no block styles.
144249 // Check for disallowed characters to rule out plain and single.
144250 for (i = 0; i < string.length; i++) {
144251 char = string.charCodeAt(i);
144252
144253 if (!isPrintable(char)) {
144254 return STYLE_DOUBLE;
144255 }
144256
6a5a0f88
TL
144257 prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
144258 plain = plain && isPlainSafe(char, prev_char);
eb39fafa
DC
144259 }
144260 } else {
144261 // Case: block styles permitted.
144262 for (i = 0; i < string.length; i++) {
144263 char = string.charCodeAt(i);
144264
144265 if (char === CHAR_LINE_FEED) {
144266 hasLineBreak = true; // Check if any line can be folded.
144267
144268 if (shouldTrackWidth) {
144269 hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
144270 i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ';
144271 previousLineBreak = i;
144272 }
144273 } else if (!isPrintable(char)) {
144274 return STYLE_DOUBLE;
144275 }
144276
6a5a0f88
TL
144277 prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
144278 plain = plain && isPlainSafe(char, prev_char);
eb39fafa
DC
144279 } // in case the end is missing a \n
144280
144281
144282 hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ';
144283 } // Although every style can represent \n without escaping, prefer block styles
144284 // for multiline, since they're more readable and they don't add empty lines.
144285 // Also prefer folding a super-long line.
144286
144287
144288 if (!hasLineBreak && !hasFoldableLine) {
144289 // Strings interpretable as another type have to be quoted;
144290 // e.g. the string 'true' vs. the boolean true.
144291 return plain && !testAmbiguousType(string) ? STYLE_PLAIN : STYLE_SINGLE;
144292 } // Edge case: block indentation indicator can only have one digit.
144293
144294
144295 if (indentPerLevel > 9 && needIndentIndicator(string)) {
144296 return STYLE_DOUBLE;
144297 } // At this point we know block styles are valid.
144298 // Prefer literal style unless we want to fold.
144299
144300
144301 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
144302} // Note: line breaking/folding is implemented for only the folded style.
144303// NB. We drop the last trailing newline (if any) of a returned block scalar
144304// since the dumper adds its own newline. This always works:
144305// • No ending newline => unaffected; already using strip "-" chomping.
144306// • Ending newline => removed then restored.
144307// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
144308
144309
144310function writeScalar(state, string, level, iskey) {
144311 state.dump = function () {
144312 if (string.length === 0) {
144313 return "''";
144314 }
144315
144316 if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
144317 return "'" + string + "'";
144318 }
144319
144320 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
144321 // As indentation gets deeper, let the width decrease monotonically
144322 // to the lower bound min(state.lineWidth, 40).
144323 // Note that this implies
144324 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
144325 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
144326 // This behaves better than a constant minimum width which disallows narrower options,
144327 // or an indent threshold which causes the width to suddenly increase.
144328
144329 var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety.
144330
144331 var singleLineOnly = iskey // No block styles in flow mode.
144332 || state.flowLevel > -1 && level >= state.flowLevel;
144333
144334 function testAmbiguity(string) {
144335 return testImplicitResolving(state, string);
144336 }
144337
144338 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
144339 case STYLE_PLAIN:
144340 return string;
144341
144342 case STYLE_SINGLE:
144343 return "'" + string.replace(/'/g, "''") + "'";
144344
144345 case STYLE_LITERAL:
144346 return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
144347
144348 case STYLE_FOLDED:
144349 return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
144350
144351 case STYLE_DOUBLE:
144352 return '"' + escapeString(string, lineWidth) + '"';
144353
144354 default:
144355 throw new YAMLException('impossible error: invalid scalar style');
144356 }
144357 }();
144358} // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
144359
144360
144361function blockHeader(string, indentPerLevel) {
144362 var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line.
144363
144364 var clip = string[string.length - 1] === '\n';
144365 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
144366 var chomp = keep ? '+' : clip ? '' : '-';
144367 return indentIndicator + chomp + '\n';
144368} // (See the note for writeScalar.)
144369
144370
144371function dropEndingNewline(string) {
144372 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
144373} // Note: a long line without a suitable break point will exceed the width limit.
144374// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
144375
144376
144377function foldString(string, width) {
144378 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
144379 // unless they're before or after a more-indented line, or at the very
144380 // beginning or end, in which case $k$ maps to $k$.
144381 // Therefore, parse each chunk as newline(s) followed by a content line.
144382 var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line)
144383
144384 var result = function () {
144385 var nextLF = string.indexOf('\n');
144386 nextLF = nextLF !== -1 ? nextLF : string.length;
144387 lineRe.lastIndex = nextLF;
144388 return foldLine(string.slice(0, nextLF), width);
144389 }(); // If we haven't reached the first content line yet, don't add an extra \n.
144390
144391
144392 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
144393 var moreIndented; // rest of the lines
144394
144395 var match;
144396
144397 while (match = lineRe.exec(string)) {
144398 var prefix = match[1],
144399 line = match[2];
144400 moreIndented = line[0] === ' ';
144401 result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width);
144402 prevMoreIndented = moreIndented;
144403 }
144404
144405 return result;
144406} // Greedy line breaking.
144407// Picks the longest line under the limit each time,
144408// otherwise settles for the shortest line over the limit.
144409// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
144410
144411
144412function foldLine(line, width) {
144413 if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space.
144414
144415 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
144416
144417 var match; // start is an inclusive index. end, curr, and next are exclusive.
144418
144419 var start = 0,
144420 end,
144421 curr = 0,
144422 next = 0;
144423 var result = ''; // Invariants: 0 <= start <= length-1.
144424 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
144425 // Inside the loop:
144426 // A match implies length >= 2, so curr and next are <= length-2.
144427
144428 while (match = breakRe.exec(line)) {
144429 next = match.index; // maintain invariant: curr - start <= width
144430
144431 if (next - start > width) {
144432 end = curr > start ? curr : next; // derive end <= length-2
144433
144434 result += '\n' + line.slice(start, end); // skip the space that was output as \n
144435
144436 start = end + 1; // derive start <= length-1
144437 }
144438
144439 curr = next;
144440 } // By the invariants, start <= length-1, so there is something left over.
144441 // It is either the whole string or a part starting from non-whitespace.
144442
144443
144444 result += '\n'; // Insert a break if the remainder is too long and there is a break available.
144445
144446 if (line.length - start > width && curr > start) {
144447 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
144448 } else {
144449 result += line.slice(start);
144450 }
144451
144452 return result.slice(1); // drop extra \n joiner
144453} // Escapes a double-quoted string.
144454
144455
144456function escapeString(string) {
144457 var result = '';
144458 var char, nextChar;
144459 var escapeSeq;
144460
144461 for (var i = 0; i < string.length; i++) {
144462 char = string.charCodeAt(i); // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
144463
144464 if (char >= 0xD800 && char <= 0xDBFF
144465 /* high surrogate */
144466 ) {
144467 nextChar = string.charCodeAt(i + 1);
144468
144469 if (nextChar >= 0xDC00 && nextChar <= 0xDFFF
144470 /* low surrogate */
144471 ) {
144472 // Combine the surrogate pair and store it escaped.
144473 result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); // Advance index one extra since we already used that char here.
144474
144475 i++;
144476 continue;
144477 }
144478 }
144479
144480 escapeSeq = ESCAPE_SEQUENCES[char];
144481 result += !escapeSeq && isPrintable(char) ? string[i] : escapeSeq || encodeHex(char);
144482 }
144483
144484 return result;
144485}
144486
144487function writeFlowSequence(state, level, object) {
144488 var _result = '',
144489 _tag = state.tag,
144490 index,
144491 length;
144492
144493 for (index = 0, length = object.length; index < length; index += 1) {
144494 // Write only valid elements.
144495 if (writeNode(state, level, object[index], false, false)) {
144496 if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
144497 _result += state.dump;
144498 }
144499 }
144500
144501 state.tag = _tag;
144502 state.dump = '[' + _result + ']';
144503}
144504
144505function writeBlockSequence(state, level, object, compact) {
144506 var _result = '',
144507 _tag = state.tag,
144508 index,
144509 length;
144510
144511 for (index = 0, length = object.length; index < length; index += 1) {
144512 // Write only valid elements.
144513 if (writeNode(state, level + 1, object[index], true, true)) {
144514 if (!compact || index !== 0) {
144515 _result += generateNextLine(state, level);
144516 }
144517
144518 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
144519 _result += '-';
144520 } else {
144521 _result += '- ';
144522 }
144523
144524 _result += state.dump;
144525 }
144526 }
144527
144528 state.tag = _tag;
144529 state.dump = _result || '[]'; // Empty sequence if no valid values.
144530}
144531
144532function writeFlowMapping(state, level, object) {
144533 var _result = '',
144534 _tag = state.tag,
144535 objectKeyList = Object.keys(object),
144536 index,
144537 length,
144538 objectKey,
144539 objectValue,
144540 pairBuffer;
144541
144542 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
6a5a0f88 144543 pairBuffer = '';
eb39fafa 144544 if (index !== 0) pairBuffer += ', ';
6a5a0f88 144545 if (state.condenseFlow) pairBuffer += '"';
eb39fafa
DC
144546 objectKey = objectKeyList[index];
144547 objectValue = object[objectKey];
144548
144549 if (!writeNode(state, level, objectKey, false, false)) {
144550 continue; // Skip this pair because of invalid key;
144551 }
144552
144553 if (state.dump.length > 1024) pairBuffer += '? ';
144554 pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
144555
144556 if (!writeNode(state, level, objectValue, false, false)) {
144557 continue; // Skip this pair because of invalid value.
144558 }
144559
144560 pairBuffer += state.dump; // Both key and value are valid.
144561
144562 _result += pairBuffer;
144563 }
144564
144565 state.tag = _tag;
144566 state.dump = '{' + _result + '}';
144567}
144568
144569function writeBlockMapping(state, level, object, compact) {
144570 var _result = '',
144571 _tag = state.tag,
144572 objectKeyList = Object.keys(object),
144573 index,
144574 length,
144575 objectKey,
144576 objectValue,
144577 explicitPair,
144578 pairBuffer; // Allow sorting keys so that the output file is deterministic
144579
144580 if (state.sortKeys === true) {
144581 // Default sorting
144582 objectKeyList.sort();
144583 } else if (typeof state.sortKeys === 'function') {
144584 // Custom sort function
144585 objectKeyList.sort(state.sortKeys);
144586 } else if (state.sortKeys) {
144587 // Something is wrong
144588 throw new YAMLException('sortKeys must be a boolean or a function');
144589 }
144590
144591 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
144592 pairBuffer = '';
144593
144594 if (!compact || index !== 0) {
144595 pairBuffer += generateNextLine(state, level);
144596 }
144597
144598 objectKey = objectKeyList[index];
144599 objectValue = object[objectKey];
144600
144601 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
144602 continue; // Skip this pair because of invalid key.
144603 }
144604
144605 explicitPair = state.tag !== null && state.tag !== '?' || state.dump && state.dump.length > 1024;
144606
144607 if (explicitPair) {
144608 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
144609 pairBuffer += '?';
144610 } else {
144611 pairBuffer += '? ';
144612 }
144613 }
144614
144615 pairBuffer += state.dump;
144616
144617 if (explicitPair) {
144618 pairBuffer += generateNextLine(state, level);
144619 }
144620
144621 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
144622 continue; // Skip this pair because of invalid value.
144623 }
144624
144625 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
144626 pairBuffer += ':';
144627 } else {
144628 pairBuffer += ': ';
144629 }
144630
144631 pairBuffer += state.dump; // Both key and value are valid.
144632
144633 _result += pairBuffer;
144634 }
144635
144636 state.tag = _tag;
144637 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
144638}
144639
144640function detectType(state, object, explicit) {
144641 var _result, typeList, index, length, type, style;
144642
144643 typeList = explicit ? state.explicitTypes : state.implicitTypes;
144644
144645 for (index = 0, length = typeList.length; index < length; index += 1) {
144646 type = typeList[index];
144647
144648 if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === 'object' && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
144649 state.tag = explicit ? type.tag : '?';
144650
144651 if (type.represent) {
144652 style = state.styleMap[type.tag] || type.defaultStyle;
144653
144654 if (_toString.call(type.represent) === '[object Function]') {
144655 _result = type.represent(object, style);
144656 } else if (_hasOwnProperty.call(type.represent, style)) {
144657 _result = type.represent[style](object, style);
144658 } else {
144659 throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
144660 }
144661
144662 state.dump = _result;
144663 }
144664
144665 return true;
144666 }
144667 }
144668
144669 return false;
144670} // Serializes `object` and writes it to global `result`.
144671// Returns true on success, or false on invalid object.
144672//
144673
144674
144675function writeNode(state, level, object, block, compact, iskey) {
144676 state.tag = null;
144677 state.dump = object;
144678
144679 if (!detectType(state, object, false)) {
144680 detectType(state, object, true);
144681 }
144682
144683 var type = _toString.call(state.dump);
144684
144685 if (block) {
144686 block = state.flowLevel < 0 || state.flowLevel > level;
144687 }
144688
144689 var objectOrArray = type === '[object Object]' || type === '[object Array]',
144690 duplicateIndex,
144691 duplicate;
144692
144693 if (objectOrArray) {
144694 duplicateIndex = state.duplicates.indexOf(object);
144695 duplicate = duplicateIndex !== -1;
144696 }
144697
144698 if (state.tag !== null && state.tag !== '?' || duplicate || state.indent !== 2 && level > 0) {
144699 compact = false;
144700 }
144701
144702 if (duplicate && state.usedDuplicates[duplicateIndex]) {
144703 state.dump = '*ref_' + duplicateIndex;
144704 } else {
144705 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
144706 state.usedDuplicates[duplicateIndex] = true;
144707 }
144708
144709 if (type === '[object Object]') {
144710 if (block && Object.keys(state.dump).length !== 0) {
144711 writeBlockMapping(state, level, state.dump, compact);
144712
144713 if (duplicate) {
144714 state.dump = '&ref_' + duplicateIndex + state.dump;
144715 }
144716 } else {
144717 writeFlowMapping(state, level, state.dump);
144718
144719 if (duplicate) {
144720 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
144721 }
144722 }
144723 } else if (type === '[object Array]') {
144724 var arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
144725
144726 if (block && state.dump.length !== 0) {
144727 writeBlockSequence(state, arrayLevel, state.dump, compact);
144728
144729 if (duplicate) {
144730 state.dump = '&ref_' + duplicateIndex + state.dump;
144731 }
144732 } else {
144733 writeFlowSequence(state, arrayLevel, state.dump);
144734
144735 if (duplicate) {
144736 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
144737 }
144738 }
144739 } else if (type === '[object String]') {
144740 if (state.tag !== '?') {
144741 writeScalar(state, state.dump, level, iskey);
144742 }
144743 } else {
144744 if (state.skipInvalid) return false;
144745 throw new YAMLException('unacceptable kind of an object to dump ' + type);
144746 }
144747
144748 if (state.tag !== null && state.tag !== '?') {
144749 state.dump = '!<' + state.tag + '> ' + state.dump;
144750 }
144751 }
144752
144753 return true;
144754}
144755
144756function getDuplicateReferences(object, state) {
144757 var objects = [],
144758 duplicatesIndexes = [],
144759 index,
144760 length;
144761 inspectNode(object, objects, duplicatesIndexes);
144762
144763 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
144764 state.duplicates.push(objects[duplicatesIndexes[index]]);
144765 }
144766
144767 state.usedDuplicates = new Array(length);
144768}
144769
144770function inspectNode(object, objects, duplicatesIndexes) {
144771 var objectKeyList, index, length;
144772
144773 if (object !== null && typeof object === 'object') {
144774 index = objects.indexOf(object);
144775
144776 if (index !== -1) {
144777 if (duplicatesIndexes.indexOf(index) === -1) {
144778 duplicatesIndexes.push(index);
144779 }
144780 } else {
144781 objects.push(object);
144782
144783 if (Array.isArray(object)) {
144784 for (index = 0, length = object.length; index < length; index += 1) {
144785 inspectNode(object[index], objects, duplicatesIndexes);
144786 }
144787 } else {
144788 objectKeyList = Object.keys(object);
144789
144790 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
144791 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
144792 }
144793 }
144794 }
144795 }
144796}
144797
144798function dump(input, options) {
144799 options = options || {};
144800 var state = new State(options);
144801 if (!state.noRefs) getDuplicateReferences(input, state);
144802 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
144803 return '';
144804}
144805
144806function safeDump(input, options) {
144807 return dump(input, common.extend({
144808 schema: DEFAULT_SAFE_SCHEMA
144809 }, options));
144810}
144811
144812module.exports.dump = dump;
144813module.exports.safeDump = safeDump;
144814
144815/***/ }),
6a5a0f88 144816/* 881 */
eb39fafa
DC
144817/***/ (function(module, exports) {
144818
144819function webpackEmptyContext(req) {
144820 var e = new Error("Cannot find module '" + req + "'");
144821 e.code = 'MODULE_NOT_FOUND';
144822 throw e;
144823}
144824webpackEmptyContext.keys = function() { return []; };
144825webpackEmptyContext.resolve = webpackEmptyContext;
144826module.exports = webpackEmptyContext;
6a5a0f88 144827webpackEmptyContext.id = 881;
eb39fafa
DC
144828
144829/***/ }),
6a5a0f88 144830/* 882 */
eb39fafa
DC
144831/***/ (function(module, exports, __webpack_require__) {
144832
144833"use strict";
144834/**
144835 * @fileoverview Module for loading rules from files and directories.
144836 * @author Michael Ficarra
144837 */
144838 //------------------------------------------------------------------------------
144839// Requirements
144840//------------------------------------------------------------------------------
144841
6a5a0f88 144842const fs = __webpack_require__(825),
eb39fafa
DC
144843 path = __webpack_require__(377);
144844
144845const rulesDirCache = {}; //------------------------------------------------------------------------------
144846// Public Interface
144847//------------------------------------------------------------------------------
144848
144849/**
144850 * Load all rule modules from specified directory.
144851 * @param {string} relativeRulesDir Path to rules directory, may be relative.
144852 * @param {string} cwd Current working directory
144853 * @returns {Object} Loaded rule modules.
144854 */
144855
144856module.exports = function (relativeRulesDir, cwd) {
144857 const rulesDir = path.resolve(cwd, relativeRulesDir); // cache will help performance as IO operation are expensive
144858
144859 if (rulesDirCache[rulesDir]) {
144860 return rulesDirCache[rulesDir];
144861 }
144862
144863 const rules = Object.create(null);
144864 fs.readdirSync(rulesDir).forEach(file => {
144865 if (path.extname(file) !== ".js") {
144866 return;
144867 }
144868
6a5a0f88 144869 rules[file.slice(0, -3)] = __webpack_require__(881)(path.join(rulesDir, file));
eb39fafa
DC
144870 });
144871 rulesDirCache[rulesDir] = rules;
144872 return rules;
144873};
144874
144875/***/ }),
6a5a0f88 144876/* 883 */
eb39fafa
DC
144877/***/ (function(module, exports, __webpack_require__) {
144878
144879"use strict";
144880/**
144881 * @fileoverview `FileEnumerator` class.
144882 *
144883 * `FileEnumerator` class has two responsibilities:
144884 *
144885 * 1. Find target files by processing glob patterns.
144886 * 2. Tie each target file and appropriate configuration.
144887 *
144888 * It provides a method:
144889 *
144890 * - `iterateFiles(patterns)`
144891 * Iterate files which are matched by given patterns together with the
144892 * corresponded configuration. This is for `CLIEngine#executeOnFiles()`.
144893 * While iterating files, it loads the configuration file of each directory
144894 * before iterate files on the directory, so we can use the configuration
144895 * files to determine target files.
144896 *
144897 * @example
144898 * const enumerator = new FileEnumerator();
144899 * const linter = new Linter();
144900 *
144901 * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) {
144902 * const code = fs.readFileSync(filePath, "utf8");
144903 * const messages = linter.verify(code, config, filePath);
144904 *
144905 * console.log(messages);
144906 * }
144907 *
144908 * @author Toru Nagashima <https://github.com/mysticatea>
144909 */
144910 //------------------------------------------------------------------------------
144911// Requirements
144912//------------------------------------------------------------------------------
144913
144914function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
144915
144916function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
144917
144918function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
144919
6a5a0f88 144920const fs = __webpack_require__(825);
eb39fafa
DC
144921
144922const path = __webpack_require__(377);
144923
6a5a0f88 144924const getGlobParent = __webpack_require__(884);
eb39fafa 144925
6a5a0f88 144926const isGlob = __webpack_require__(885);
eb39fafa
DC
144927
144928const {
144929 escapeRegExp
144930} = __webpack_require__(403);
144931
144932const {
144933 Minimatch
6a5a0f88 144934} = __webpack_require__(845);
eb39fafa
DC
144935
144936const {
144937 IgnorePattern
6a5a0f88 144938} = __webpack_require__(839);
eb39fafa
DC
144939
144940const {
144941 CascadingConfigArrayFactory
6a5a0f88 144942} = __webpack_require__(831);
eb39fafa
DC
144943
144944const debug = __webpack_require__(416)("eslint:file-enumerator"); //------------------------------------------------------------------------------
144945// Helpers
144946//------------------------------------------------------------------------------
144947
144948
144949const minimatchOpts = {
144950 dot: true,
144951 matchBase: true
144952};
144953const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u;
144954const NONE = 0;
144955const IGNORED_SILENTLY = 1;
144956const IGNORED = 2; // For VSCode intellisense
144957
144958/** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
144959
144960/**
144961 * @typedef {Object} FileEnumeratorOptions
144962 * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays.
144963 * @property {string} [cwd] The base directory to start lookup.
144964 * @property {string[]} [extensions] The extensions to match files for directory patterns.
144965 * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
144966 * @property {boolean} [ignore] The flag to check ignored files.
144967 * @property {string[]} [rulePaths] The value of `--rulesdir` option.
144968 */
144969
144970/**
144971 * @typedef {Object} FileAndConfig
144972 * @property {string} filePath The path to a target file.
144973 * @property {ConfigArray} config The config entries of that file.
144974 * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified.
144975 */
144976
144977/**
144978 * @typedef {Object} FileEntry
144979 * @property {string} filePath The path to a target file.
144980 * @property {ConfigArray} config The config entries of that file.
144981 * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag.
144982 * - `NONE` means the file is a target file.
144983 * - `IGNORED_SILENTLY` means the file should be ignored silently.
144984 * - `IGNORED` means the file should be ignored and warned because it was directly specified.
144985 */
144986
144987/**
144988 * @typedef {Object} FileEnumeratorInternalSlots
144989 * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays.
144990 * @property {string} cwd The base directory to start lookup.
144991 * @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions.
144992 * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
144993 * @property {boolean} ignoreFlag The flag to check ignored files.
144994 * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files.
144995 */
144996
144997/** @type {WeakMap<FileEnumerator, FileEnumeratorInternalSlots>} */
144998
144999const internalSlotsMap = new WeakMap();
145000/**
145001 * Check if a string is a glob pattern or not.
145002 * @param {string} pattern A glob pattern.
145003 * @returns {boolean} `true` if the string is a glob pattern.
145004 */
145005
145006function isGlobPattern(pattern) {
145007 return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern);
145008}
145009/**
145010 * Get stats of a given path.
145011 * @param {string} filePath The path to target file.
145012 * @returns {fs.Stats|null} The stats.
145013 * @private
145014 */
145015
145016
145017function statSafeSync(filePath) {
145018 try {
145019 return fs.statSync(filePath);
145020 } catch (error) {
145021 /* istanbul ignore next */
145022 if (error.code !== "ENOENT") {
145023 throw error;
145024 }
145025
145026 return null;
145027 }
145028}
145029/**
145030 * Get filenames in a given path to a directory.
145031 * @param {string} directoryPath The path to target directory.
145032 * @returns {import("fs").Dirent[]} The filenames.
145033 * @private
145034 */
145035
145036
145037function readdirSafeSync(directoryPath) {
145038 try {
145039 return fs.readdirSync(directoryPath, {
145040 withFileTypes: true
145041 });
145042 } catch (error) {
145043 /* istanbul ignore next */
145044 if (error.code !== "ENOENT") {
145045 throw error;
145046 }
145047
145048 return [];
145049 }
145050}
145051/**
145052 * Create a `RegExp` object to detect extensions.
145053 * @param {string[] | null} extensions The extensions to create.
145054 * @returns {RegExp | null} The created `RegExp` object or null.
145055 */
145056
145057
145058function createExtensionRegExp(extensions) {
145059 if (extensions) {
145060 const normalizedExts = extensions.map(ext => escapeRegExp(ext.startsWith(".") ? ext.slice(1) : ext));
145061 return new RegExp(".\\.(?:".concat(normalizedExts.join("|"), ")$"), "u");
145062 }
145063
145064 return null;
145065}
145066/**
145067 * The error type when no files match a glob.
145068 */
145069
145070
145071class NoFilesFoundError extends Error {
145072 // eslint-disable-next-line jsdoc/require-description
145073
145074 /**
145075 * @param {string} pattern The glob pattern which was not found.
145076 * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled.
145077 */
145078 constructor(pattern, globDisabled) {
145079 super("No files matching '".concat(pattern, "' were found").concat(globDisabled ? " (glob was disabled)" : "", "."));
145080 this.messageTemplate = "file-not-found";
145081 this.messageData = {
145082 pattern,
145083 globDisabled
145084 };
145085 }
145086
145087}
145088/**
145089 * The error type when there are files matched by a glob, but all of them have been ignored.
145090 */
145091
145092
145093class AllFilesIgnoredError extends Error {
145094 // eslint-disable-next-line jsdoc/require-description
145095
145096 /**
145097 * @param {string} pattern The glob pattern which was not found.
145098 */
145099 constructor(pattern) {
145100 super("All files matched by '".concat(pattern, "' are ignored."));
145101 this.messageTemplate = "all-files-ignored";
145102 this.messageData = {
145103 pattern
145104 };
145105 }
145106
145107}
145108/**
145109 * This class provides the functionality that enumerates every file which is
145110 * matched by given glob patterns and that configuration.
145111 */
145112
145113
145114class FileEnumerator {
145115 /**
145116 * Initialize this enumerator.
145117 * @param {FileEnumeratorOptions} options The options.
145118 */
145119 constructor({
145120 cwd = process.cwd(),
145121 configArrayFactory = new CascadingConfigArrayFactory({
145122 cwd
145123 }),
145124 extensions = null,
145125 globInputPaths = true,
145126 errorOnUnmatchedPattern = true,
145127 ignore = true
145128 } = {}) {
145129 internalSlotsMap.set(this, {
145130 configArrayFactory,
145131 cwd,
145132 defaultIgnores: IgnorePattern.createDefaultIgnore(cwd),
145133 extensionRegExp: createExtensionRegExp(extensions),
145134 globInputPaths,
145135 errorOnUnmatchedPattern,
145136 ignoreFlag: ignore
145137 });
145138 }
145139 /**
145140 * Check if a given file is target or not.
145141 * @param {string} filePath The path to a candidate file.
145142 * @param {ConfigArray} [providedConfig] Optional. The configuration for the file.
145143 * @returns {boolean} `true` if the file is a target.
145144 */
145145
145146
145147 isTargetPath(filePath, providedConfig) {
145148 const {
145149 configArrayFactory,
145150 extensionRegExp
145151 } = internalSlotsMap.get(this); // If `--ext` option is present, use it.
145152
145153 if (extensionRegExp) {
145154 return extensionRegExp.test(filePath);
145155 } // `.js` file is target by default.
145156
145157
145158 if (filePath.endsWith(".js")) {
145159 return true;
145160 } // use `overrides[].files` to check additional targets.
145161
145162
145163 const config = providedConfig || configArrayFactory.getConfigArrayForFile(filePath, {
145164 ignoreNotFoundError: true
145165 });
145166 return config.isAdditionalTargetPath(filePath);
145167 }
145168 /**
145169 * Iterate files which are matched by given glob patterns.
145170 * @param {string|string[]} patternOrPatterns The glob patterns to iterate files.
145171 * @returns {IterableIterator<FileAndConfig>} The found files.
145172 */
145173
145174
145175 *iterateFiles(patternOrPatterns) {
145176 const {
145177 globInputPaths,
145178 errorOnUnmatchedPattern
145179 } = internalSlotsMap.get(this);
145180 const patterns = Array.isArray(patternOrPatterns) ? patternOrPatterns : [patternOrPatterns];
145181 debug("Start to iterate files: %o", patterns); // The set of paths to remove duplicate.
145182
145183 const set = new Set();
145184
145185 for (const pattern of patterns) {
145186 let foundRegardlessOfIgnored = false;
145187 let found = false; // Skip empty string.
145188
145189 if (!pattern) {
145190 continue;
145191 } // Iterate files of this pattern.
145192
145193
145194 for (const {
145195 config,
145196 filePath,
145197 flag
145198 } of this._iterateFiles(pattern)) {
145199 foundRegardlessOfIgnored = true;
145200
145201 if (flag === IGNORED_SILENTLY) {
145202 continue;
145203 }
145204
145205 found = true; // Remove duplicate paths while yielding paths.
145206
145207 if (!set.has(filePath)) {
145208 set.add(filePath);
145209 yield {
145210 config,
145211 filePath,
145212 ignored: flag === IGNORED
145213 };
145214 }
145215 } // Raise an error if any files were not found.
145216
145217
145218 if (errorOnUnmatchedPattern) {
145219 if (!foundRegardlessOfIgnored) {
145220 throw new NoFilesFoundError(pattern, !globInputPaths && isGlob(pattern));
145221 }
145222
145223 if (!found) {
145224 throw new AllFilesIgnoredError(pattern);
145225 }
145226 }
145227 }
145228
145229 debug("Complete iterating files: ".concat(JSON.stringify(patterns)));
145230 }
145231 /**
145232 * Iterate files which are matched by a given glob pattern.
145233 * @param {string} pattern The glob pattern to iterate files.
145234 * @returns {IterableIterator<FileEntry>} The found files.
145235 */
145236
145237
145238 _iterateFiles(pattern) {
145239 const {
145240 cwd,
145241 globInputPaths
145242 } = internalSlotsMap.get(this);
145243 const absolutePath = path.resolve(cwd, pattern);
145244 const isDot = dotfilesPattern.test(pattern);
145245 const stat = statSafeSync(absolutePath);
145246
145247 if (stat && stat.isDirectory()) {
145248 return this._iterateFilesWithDirectory(absolutePath, isDot);
145249 }
145250
145251 if (stat && stat.isFile()) {
145252 return this._iterateFilesWithFile(absolutePath);
145253 }
145254
145255 if (globInputPaths && isGlobPattern(pattern)) {
145256 return this._iterateFilesWithGlob(absolutePath, isDot);
145257 }
145258
145259 return [];
145260 }
145261 /**
145262 * Iterate a file which is matched by a given path.
145263 * @param {string} filePath The path to the target file.
145264 * @returns {IterableIterator<FileEntry>} The found files.
145265 * @private
145266 */
145267
145268
145269 _iterateFilesWithFile(filePath) {
145270 debug("File: ".concat(filePath));
145271 const {
145272 configArrayFactory
145273 } = internalSlotsMap.get(this);
145274 const config = configArrayFactory.getConfigArrayForFile(filePath);
145275
145276 const ignored = this._isIgnoredFile(filePath, {
145277 config,
145278 direct: true
145279 });
145280
145281 const flag = ignored ? IGNORED : NONE;
145282 return [{
145283 config,
145284 filePath,
145285 flag
145286 }];
145287 }
145288 /**
145289 * Iterate files in a given path.
145290 * @param {string} directoryPath The path to the target directory.
145291 * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
145292 * @returns {IterableIterator<FileEntry>} The found files.
145293 * @private
145294 */
145295
145296
145297 _iterateFilesWithDirectory(directoryPath, dotfiles) {
145298 debug("Directory: ".concat(directoryPath));
145299 return this._iterateFilesRecursive(directoryPath, {
145300 dotfiles,
145301 recursive: true,
145302 selector: null
145303 });
145304 }
145305 /**
145306 * Iterate files which are matched by a given glob pattern.
145307 * @param {string} pattern The glob pattern to iterate files.
145308 * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
145309 * @returns {IterableIterator<FileEntry>} The found files.
145310 * @private
145311 */
145312
145313
145314 _iterateFilesWithGlob(pattern, dotfiles) {
145315 debug("Glob: ".concat(pattern));
145316 const directoryPath = path.resolve(getGlobParent(pattern));
145317 const globPart = pattern.slice(directoryPath.length + 1);
145318 /*
145319 * recursive if there are `**` or path separators in the glob part.
145320 * Otherwise, patterns such as `src/*.js`, it doesn't need recursive.
145321 */
145322
145323 const recursive = /\*\*|\/|\\/u.test(globPart);
145324 const selector = new Minimatch(pattern, minimatchOpts);
145325 debug("recursive? ".concat(recursive));
145326 return this._iterateFilesRecursive(directoryPath, {
145327 dotfiles,
145328 recursive,
145329 selector
145330 });
145331 }
145332 /**
145333 * Iterate files in a given path.
145334 * @param {string} directoryPath The path to the target directory.
145335 * @param {Object} options The options to iterate files.
145336 * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default.
145337 * @param {boolean} [options.recursive] If `true` then it dives into sub directories.
145338 * @param {InstanceType<Minimatch>} [options.selector] The matcher to choose files.
145339 * @returns {IterableIterator<FileEntry>} The found files.
145340 * @private
145341 */
145342
145343
145344 *_iterateFilesRecursive(directoryPath, options) {
145345 debug("Enter the directory: ".concat(directoryPath));
145346 const {
145347 configArrayFactory
145348 } = internalSlotsMap.get(this);
145349 /** @type {ConfigArray|null} */
145350
145351 let config = null; // Enumerate the files of this directory.
145352
145353 for (const entry of readdirSafeSync(directoryPath)) {
145354 const filePath = path.join(directoryPath, entry.name); // Check if the file is matched.
145355
145356 if (entry.isFile()) {
145357 if (!config) {
145358 config = configArrayFactory.getConfigArrayForFile(filePath,
145359 /*
145360 * We must ignore `ConfigurationNotFoundError` at this
145361 * point because we don't know if target files exist in
145362 * this directory.
145363 */
145364 {
145365 ignoreNotFoundError: true
145366 });
145367 }
145368
145369 const matched = options.selector // Started with a glob pattern; choose by the pattern.
145370 ? options.selector.match(filePath) // Started with a directory path; choose by file extensions.
145371 : this.isTargetPath(filePath, config);
145372
145373 if (matched) {
56c4a2cb 145374 const ignored = this._isIgnoredFile(filePath, _objectSpread(_objectSpread({}, options), {}, {
eb39fafa
DC
145375 config
145376 }));
145377
145378 const flag = ignored ? IGNORED_SILENTLY : NONE;
145379 debug("Yield: ".concat(entry.name).concat(ignored ? " but ignored" : ""));
145380 yield {
145381 config: configArrayFactory.getConfigArrayForFile(filePath),
145382 filePath,
145383 flag
145384 };
145385 } else {
145386 debug("Didn't match: ".concat(entry.name));
145387 } // Dive into the sub directory.
145388
145389 } else if (options.recursive && entry.isDirectory()) {
145390 if (!config) {
145391 config = configArrayFactory.getConfigArrayForFile(filePath, {
145392 ignoreNotFoundError: true
145393 });
145394 }
145395
56c4a2cb 145396 const ignored = this._isIgnoredFile(filePath + path.sep, _objectSpread(_objectSpread({}, options), {}, {
eb39fafa
DC
145397 config
145398 }));
145399
145400 if (!ignored) {
145401 yield* this._iterateFilesRecursive(filePath, options);
145402 }
145403 }
145404 }
145405
145406 debug("Leave the directory: ".concat(directoryPath));
145407 }
145408 /**
145409 * Check if a given file should be ignored.
145410 * @param {string} filePath The path to a file to check.
145411 * @param {Object} options Options
145412 * @param {ConfigArray} [options.config] The config for this file.
145413 * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default.
145414 * @param {boolean} [options.direct] If `true` then this is a direct specified file.
145415 * @returns {boolean} `true` if the file should be ignored.
145416 * @private
145417 */
145418
145419
145420 _isIgnoredFile(filePath, {
145421 config: providedConfig,
145422 dotfiles = false,
145423 direct = false
145424 }) {
145425 const {
145426 configArrayFactory,
145427 defaultIgnores,
145428 ignoreFlag
145429 } = internalSlotsMap.get(this);
145430
145431 if (ignoreFlag) {
145432 const config = providedConfig || configArrayFactory.getConfigArrayForFile(filePath, {
145433 ignoreNotFoundError: true
145434 });
145435 const ignores = config.extractConfig(filePath).ignores || defaultIgnores;
145436 return ignores(filePath, dotfiles);
145437 }
145438
145439 return !direct && defaultIgnores(filePath, dotfiles);
145440 }
145441
145442} //------------------------------------------------------------------------------
145443// Public Interface
145444//------------------------------------------------------------------------------
145445
145446
145447module.exports = {
145448 FileEnumerator
145449};
145450
145451/***/ }),
6a5a0f88 145452/* 884 */
eb39fafa
DC
145453/***/ (function(module, exports, __webpack_require__) {
145454
145455"use strict";
145456
145457
6a5a0f88 145458var isGlob = __webpack_require__(885);
eb39fafa
DC
145459
145460var pathPosixDirname = __webpack_require__(377).posix.dirname;
145461
145462var isWin32 = __webpack_require__(423).platform() === 'win32';
145463var slash = '/';
145464var backslash = /\\/g;
145465var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
145466var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
145467var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
145468/**
145469 * @param {string} str
145470 * @param {Object} opts
145471 * @param {boolean} [opts.flipBackslashes=true]
145472 */
145473
145474module.exports = function globParent(str, opts) {
145475 var options = Object.assign({
145476 flipBackslashes: true
145477 }, opts); // flip windows path separators
145478
145479 if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
145480 str = str.replace(backslash, slash);
145481 } // special case for strings ending in enclosure containing path separator
145482
145483
145484 if (enclosure.test(str)) {
145485 str += slash;
145486 } // preserves full path in case of trailing path separator
145487
145488
145489 str += 'a'; // remove path parts that are globby
145490
145491 do {
145492 str = pathPosixDirname(str);
145493 } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
145494
145495
145496 return str.replace(escaped, '$1');
145497};
145498
145499/***/ }),
6a5a0f88 145500/* 885 */
eb39fafa
DC
145501/***/ (function(module, exports, __webpack_require__) {
145502
145503/*!
145504 * is-glob <https://github.com/jonschlinkert/is-glob>
145505 *
145506 * Copyright (c) 2014-2017, Jon Schlinkert.
145507 * Released under the MIT License.
145508 */
6a5a0f88 145509var isExtglob = __webpack_require__(886);
eb39fafa
DC
145510
145511var chars = {
145512 '{': '}',
145513 '(': ')',
145514 '[': ']'
145515};
145516var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
145517var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
145518
145519module.exports = function isGlob(str, options) {
145520 if (typeof str !== 'string' || str === '') {
145521 return false;
145522 }
145523
145524 if (isExtglob(str)) {
145525 return true;
145526 }
145527
145528 var regex = strictRegex;
145529 var match; // optionally relax regex
145530
145531 if (options && options.strict === false) {
145532 regex = relaxedRegex;
145533 }
145534
145535 while (match = regex.exec(str)) {
145536 if (match[2]) return true;
145537 var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
145538 // set the index to the next closing character
145539
145540 var open = match[1];
145541 var close = open ? chars[open] : null;
145542
145543 if (open && close) {
145544 var n = str.indexOf(close, idx);
145545
145546 if (n !== -1) {
145547 idx = n + 1;
145548 }
145549 }
145550
145551 str = str.slice(idx);
145552 }
145553
145554 return false;
145555};
145556
145557/***/ }),
6a5a0f88 145558/* 886 */
eb39fafa
DC
145559/***/ (function(module, exports) {
145560
145561/*!
145562 * is-extglob <https://github.com/jonschlinkert/is-extglob>
145563 *
145564 * Copyright (c) 2014-2016, Jon Schlinkert.
145565 * Licensed under the MIT License.
145566 */
145567module.exports = function isExtglob(str) {
145568 if (typeof str !== 'string' || str === '') {
145569 return false;
145570 }
145571
145572 var match;
145573
145574 while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
145575 if (match[2]) return true;
145576 str = str.slice(match.index + match[0].length);
145577 }
145578
145579 return false;
145580};
145581
145582/***/ }),
6a5a0f88 145583/* 887 */
eb39fafa
DC
145584/***/ (function(module, exports, __webpack_require__) {
145585
145586"use strict";
145587/**
145588 * @fileoverview Defining the hashing function in one place.
145589 * @author Michael Ficarra
145590 */
145591 //------------------------------------------------------------------------------
145592// Requirements
145593//------------------------------------------------------------------------------
145594
6a5a0f88 145595const murmur = __webpack_require__(888); //------------------------------------------------------------------------------
eb39fafa
DC
145596// Helpers
145597//------------------------------------------------------------------------------
145598//------------------------------------------------------------------------------
145599// Private
145600//------------------------------------------------------------------------------
145601
145602/**
145603 * hash the given string
145604 * @param {string} str the string to hash
145605 * @returns {string} the hash
145606 */
145607
145608
145609function hash(str) {
145610 return murmur(str).result().toString(36);
145611} //------------------------------------------------------------------------------
145612// Public Interface
145613//------------------------------------------------------------------------------
145614
145615
145616module.exports = hash;
145617
145618/***/ }),
6a5a0f88 145619/* 888 */
eb39fafa
DC
145620/***/ (function(module, exports, __webpack_require__) {
145621
145622/**
145623 * @preserve
145624 * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013)
145625 *
145626 * @author <a href="mailto:jensyt@gmail.com">Jens Taylor</a>
145627 * @see http://github.com/homebrewing/brauhaus-diff
145628 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
145629 * @see http://github.com/garycourt/murmurhash-js
145630 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
145631 * @see http://sites.google.com/site/murmurhash/
145632 */
145633(function () {
145634 var cache; // Call this function without `new` to use the cached object (good for
145635 // single-threaded environments), or with `new` to create a new object.
145636 //
145637 // @param {string} key A UTF-16 or ASCII string
145638 // @param {number} seed An optional positive integer
145639 // @return {object} A MurmurHash3 object for incremental hashing
145640
145641 function MurmurHash3(key, seed) {
145642 var m = this instanceof MurmurHash3 ? this : cache;
145643 m.reset(seed);
145644
145645 if (typeof key === 'string' && key.length > 0) {
145646 m.hash(key);
145647 }
145648
145649 if (m !== this) {
145650 return m;
145651 }
145652 }
145653
145654 ; // Incrementally add a string to this hash
145655 //
145656 // @param {string} key A UTF-16 or ASCII string
145657 // @return {object} this
145658
145659 MurmurHash3.prototype.hash = function (key) {
145660 var h1, k1, i, top, len;
145661 len = key.length;
145662 this.len += len;
145663 k1 = this.k1;
145664 i = 0;
145665
145666 switch (this.rem) {
145667 case 0:
145668 k1 ^= len > i ? key.charCodeAt(i++) & 0xffff : 0;
145669
145670 case 1:
145671 k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0;
145672
145673 case 2:
145674 k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0;
145675
145676 case 3:
145677 k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0;
145678 k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0;
145679 }
145680
145681 this.rem = len + this.rem & 3; // & 3 is same as % 4
145682
145683 len -= this.rem;
145684
145685 if (len > 0) {
145686 h1 = this.h1;
145687
145688 while (1) {
145689 k1 = k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000 & 0xffffffff;
145690 k1 = k1 << 15 | k1 >>> 17;
145691 k1 = k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000 & 0xffffffff;
145692 h1 ^= k1;
145693 h1 = h1 << 13 | h1 >>> 19;
145694 h1 = h1 * 5 + 0xe6546b64 & 0xffffffff;
145695
145696 if (i >= len) {
145697 break;
145698 }
145699
145700 k1 = key.charCodeAt(i++) & 0xffff ^ (key.charCodeAt(i++) & 0xffff) << 8 ^ (key.charCodeAt(i++) & 0xffff) << 16;
145701 top = key.charCodeAt(i++);
145702 k1 ^= (top & 0xff) << 24 ^ (top & 0xff00) >> 8;
145703 }
145704
145705 k1 = 0;
145706
145707 switch (this.rem) {
145708 case 3:
145709 k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16;
145710
145711 case 2:
145712 k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8;
145713
145714 case 1:
145715 k1 ^= key.charCodeAt(i) & 0xffff;
145716 }
145717
145718 this.h1 = h1;
145719 }
145720
145721 this.k1 = k1;
145722 return this;
145723 }; // Get the result of this hash
145724 //
145725 // @return {number} The 32-bit hash
145726
145727
145728 MurmurHash3.prototype.result = function () {
145729 var k1, h1;
145730 k1 = this.k1;
145731 h1 = this.h1;
145732
145733 if (k1 > 0) {
145734 k1 = k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000 & 0xffffffff;
145735 k1 = k1 << 15 | k1 >>> 17;
145736 k1 = k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000 & 0xffffffff;
145737 h1 ^= k1;
145738 }
145739
145740 h1 ^= this.len;
145741 h1 ^= h1 >>> 16;
145742 h1 = h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000 & 0xffffffff;
145743 h1 ^= h1 >>> 13;
145744 h1 = h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000 & 0xffffffff;
145745 h1 ^= h1 >>> 16;
145746 return h1 >>> 0;
145747 }; // Reset the hash object for reuse
145748 //
145749 // @param {number} seed An optional positive integer
145750
145751
145752 MurmurHash3.prototype.reset = function (seed) {
145753 this.h1 = typeof seed === 'number' ? seed : 0;
145754 this.rem = this.k1 = this.len = 0;
145755 return this;
145756 }; // A cached object to use. This can be safely used if you're in a single-
145757 // threaded environment, otherwise you need to create new hashes to use.
145758
145759
145760 cache = new MurmurHash3();
145761
145762 if (true) {
145763 module.exports = MurmurHash3;
145764 } else {}
145765})();
145766
145767/***/ }),
6a5a0f88 145768/* 889 */
eb39fafa
DC
145769/***/ (function(module, exports, __webpack_require__) {
145770
145771"use strict";
145772/**
145773 * @fileoverview Utility for caching lint results.
145774 * @author Kevin Partington
145775 */
145776 //-----------------------------------------------------------------------------
145777// Requirements
145778//-----------------------------------------------------------------------------
145779
145780const assert = __webpack_require__(379);
145781
6a5a0f88 145782const fs = __webpack_require__(825);
eb39fafa 145783
6a5a0f88 145784const fileEntryCache = __webpack_require__(890);
eb39fafa 145785
6a5a0f88 145786const stringify = __webpack_require__(911);
eb39fafa
DC
145787
145788const pkg = __webpack_require__(408);
145789
6a5a0f88 145790const hash = __webpack_require__(887); //-----------------------------------------------------------------------------
eb39fafa
DC
145791// Helpers
145792//-----------------------------------------------------------------------------
145793
145794
145795const configHashCache = new WeakMap();
145796const nodeVersion = process && process.version;
145797/**
145798 * Calculates the hash of the config
145799 * @param {ConfigArray} config The config.
145800 * @returns {string} The hash of the config
145801 */
145802
145803function hashOfConfigFor(config) {
145804 if (!configHashCache.has(config)) {
145805 configHashCache.set(config, hash("".concat(pkg.version, "_").concat(nodeVersion, "_").concat(stringify(config))));
145806 }
145807
145808 return configHashCache.get(config);
145809} //-----------------------------------------------------------------------------
145810// Public Interface
145811//-----------------------------------------------------------------------------
145812
145813/**
145814 * Lint result cache. This wraps around the file-entry-cache module,
145815 * transparently removing properties that are difficult or expensive to
145816 * serialize and adding them back in on retrieval.
145817 */
145818
145819
145820class LintResultCache {
145821 /**
145822 * Creates a new LintResultCache instance.
145823 * @param {string} cacheFileLocation The cache file location.
145824 * configuration lookup by file path).
145825 */
145826 constructor(cacheFileLocation) {
145827 assert(cacheFileLocation, "Cache file location is required");
145828 this.fileEntryCache = fileEntryCache.create(cacheFileLocation);
145829 }
145830 /**
145831 * Retrieve cached lint results for a given file path, if present in the
145832 * cache. If the file is present and has not been changed, rebuild any
145833 * missing result information.
145834 * @param {string} filePath The file for which to retrieve lint results.
145835 * @param {ConfigArray} config The config of the file.
145836 * @returns {Object|null} The rebuilt lint results, or null if the file is
145837 * changed or not in the filesystem.
145838 */
145839
145840
145841 getCachedLintResults(filePath, config) {
145842 /*
145843 * Cached lint results are valid if and only if:
145844 * 1. The file is present in the filesystem
145845 * 2. The file has not changed since the time it was previously linted
145846 * 3. The ESLint configuration has not changed since the time the file
145847 * was previously linted
145848 * If any of these are not true, we will not reuse the lint results.
145849 */
145850 const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath);
145851 const hashOfConfig = hashOfConfigFor(config);
145852 const changed = fileDescriptor.changed || fileDescriptor.meta.hashOfConfig !== hashOfConfig;
145853
145854 if (fileDescriptor.notFound || changed) {
145855 return null;
145856 } // If source is present but null, need to reread the file from the filesystem.
145857
145858
145859 if (fileDescriptor.meta.results && fileDescriptor.meta.results.source === null) {
145860 fileDescriptor.meta.results.source = fs.readFileSync(filePath, "utf-8");
145861 }
145862
145863 return fileDescriptor.meta.results;
145864 }
145865 /**
145866 * Set the cached lint results for a given file path, after removing any
145867 * information that will be both unnecessary and difficult to serialize.
145868 * Avoids caching results with an "output" property (meaning fixes were
145869 * applied), to prevent potentially incorrect results if fixes are not
145870 * written to disk.
145871 * @param {string} filePath The file for which to set lint results.
145872 * @param {ConfigArray} config The config of the file.
145873 * @param {Object} result The lint result to be set for the file.
145874 * @returns {void}
145875 */
145876
145877
145878 setCachedLintResults(filePath, config, result) {
145879 if (result && Object.prototype.hasOwnProperty.call(result, "output")) {
145880 return;
145881 }
145882
145883 const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath);
145884
145885 if (fileDescriptor && !fileDescriptor.notFound) {
145886 // Serialize the result, except that we want to remove the file source if present.
145887 const resultToSerialize = Object.assign({}, result);
145888 /*
145889 * Set result.source to null.
145890 * In `getCachedLintResults`, if source is explicitly null, we will
145891 * read the file from the filesystem to set the value again.
145892 */
145893
145894 if (Object.prototype.hasOwnProperty.call(resultToSerialize, "source")) {
145895 resultToSerialize.source = null;
145896 }
145897
145898 fileDescriptor.meta.results = resultToSerialize;
145899 fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config);
145900 }
145901 }
145902 /**
145903 * Persists the in-memory cache to disk.
145904 * @returns {void}
145905 */
145906
145907
145908 reconcile() {
145909 this.fileEntryCache.reconcile();
145910 }
145911
145912}
145913
145914module.exports = LintResultCache;
145915
145916/***/ }),
6a5a0f88 145917/* 890 */
eb39fafa
DC
145918/***/ (function(module, exports, __webpack_require__) {
145919
145920var path = __webpack_require__(377);
145921
6a5a0f88 145922var crypto = __webpack_require__(891);
eb39fafa
DC
145923
145924module.exports = {
145925 createFromFile: function createFromFile(filePath, useChecksum) {
145926 var fname = path.basename(filePath);
145927 var dir = path.dirname(filePath);
145928 return this.create(fname, dir, useChecksum);
145929 },
145930 create: function create(cacheId, _path, useChecksum) {
6a5a0f88 145931 var fs = __webpack_require__(825);
eb39fafa 145932
6a5a0f88 145933 var flatCache = __webpack_require__(892);
eb39fafa
DC
145934
145935 var cache = flatCache.load(cacheId, _path);
145936 var normalizedEntries = {};
145937
145938 var removeNotFoundFiles = function removeNotFoundFiles() {
145939 const cachedEntries = cache.keys(); // remove not found entries
145940
145941 cachedEntries.forEach(function remover(fPath) {
145942 try {
145943 fs.statSync(fPath);
145944 } catch (err) {
145945 if (err.code === 'ENOENT') {
145946 cache.removeKey(fPath);
145947 }
145948 }
145949 });
145950 };
145951
145952 removeNotFoundFiles();
145953 return {
145954 /**
145955 * the flat cache storage used to persist the metadata of the `files
145956 * @type {Object}
145957 */
145958 cache: cache,
145959
145960 /**
145961 * Given a buffer, calculate md5 hash of its content.
145962 * @method getHash
145963 * @param {Buffer} buffer buffer to calculate hash on
145964 * @return {String} content hash digest
145965 */
145966 getHash: function getHash(buffer) {
145967 return crypto.createHash('md5').update(buffer).digest('hex');
145968 },
145969
145970 /**
145971 * Return whether or not a file has changed since last time reconcile was called.
145972 * @method hasFileChanged
145973 * @param {String} file the filepath to check
145974 * @return {Boolean} wheter or not the file has changed
145975 */
145976 hasFileChanged: function hasFileChanged(file) {
145977 return this.getFileDescriptor(file).changed;
145978 },
145979
145980 /**
145981 * given an array of file paths it return and object with three arrays:
145982 * - changedFiles: Files that changed since previous run
145983 * - notChangedFiles: Files that haven't change
145984 * - notFoundFiles: Files that were not found, probably deleted
145985 *
145986 * @param {Array} files the files to analyze and compare to the previous seen files
145987 * @return {[type]} [description]
145988 */
145989 analyzeFiles: function analyzeFiles(files) {
145990 var me = this;
145991 files = files || [];
145992 var res = {
145993 changedFiles: [],
145994 notFoundFiles: [],
145995 notChangedFiles: []
145996 };
145997 me.normalizeEntries(files).forEach(function (entry) {
145998 if (entry.changed) {
145999 res.changedFiles.push(entry.key);
146000 return;
146001 }
146002
146003 if (entry.notFound) {
146004 res.notFoundFiles.push(entry.key);
146005 return;
146006 }
146007
146008 res.notChangedFiles.push(entry.key);
146009 });
146010 return res;
146011 },
146012 getFileDescriptor: function getFileDescriptor(file) {
146013 var fstat;
146014
146015 try {
146016 fstat = fs.statSync(file);
146017 } catch (ex) {
146018 this.removeEntry(file);
146019 return {
146020 key: file,
146021 notFound: true,
146022 err: ex
146023 };
146024 }
146025
146026 if (useChecksum) {
146027 return this._getFileDescriptorUsingChecksum(file);
146028 }
146029
146030 return this._getFileDescriptorUsingMtimeAndSize(file, fstat);
146031 },
146032 _getFileDescriptorUsingMtimeAndSize: function _getFileDescriptorUsingMtimeAndSize(file, fstat) {
146033 var meta = cache.getKey(file);
146034 var cacheExists = !!meta;
146035 var cSize = fstat.size;
146036 var cTime = fstat.mtime.getTime();
146037 var isDifferentDate;
146038 var isDifferentSize;
146039
146040 if (!meta) {
146041 meta = {
146042 size: cSize,
146043 mtime: cTime
146044 };
146045 } else {
146046 isDifferentDate = cTime !== meta.mtime;
146047 isDifferentSize = cSize !== meta.size;
146048 }
146049
146050 var nEntry = normalizedEntries[file] = {
146051 key: file,
146052 changed: !cacheExists || isDifferentDate || isDifferentSize,
146053 meta: meta
146054 };
146055 return nEntry;
146056 },
146057 _getFileDescriptorUsingChecksum: function _getFileDescriptorUsingChecksum(file) {
146058 var meta = cache.getKey(file);
146059 var cacheExists = !!meta;
146060 var contentBuffer;
146061
146062 try {
146063 contentBuffer = fs.readFileSync(file);
146064 } catch (ex) {
146065 contentBuffer = '';
146066 }
146067
146068 var isDifferent = true;
146069 var hash = this.getHash(contentBuffer);
146070
146071 if (!meta) {
146072 meta = {
146073 hash: hash
146074 };
146075 } else {
146076 isDifferent = hash !== meta.hash;
146077 }
146078
146079 var nEntry = normalizedEntries[file] = {
146080 key: file,
146081 changed: !cacheExists || isDifferent,
146082 meta: meta
146083 };
146084 return nEntry;
146085 },
146086
146087 /**
146088 * Return the list o the files that changed compared
146089 * against the ones stored in the cache
146090 *
146091 * @method getUpdated
146092 * @param files {Array} the array of files to compare against the ones in the cache
146093 * @returns {Array}
146094 */
146095 getUpdatedFiles: function getUpdatedFiles(files) {
146096 var me = this;
146097 files = files || [];
146098 return me.normalizeEntries(files).filter(function (entry) {
146099 return entry.changed;
146100 }).map(function (entry) {
146101 return entry.key;
146102 });
146103 },
146104
146105 /**
146106 * return the list of files
146107 * @method normalizeEntries
146108 * @param files
146109 * @returns {*}
146110 */
146111 normalizeEntries: function normalizeEntries(files) {
146112 files = files || [];
146113 var me = this;
146114 var nEntries = files.map(function (file) {
146115 return me.getFileDescriptor(file);
146116 }); //normalizeEntries = nEntries;
146117
146118 return nEntries;
146119 },
146120
146121 /**
146122 * Remove an entry from the file-entry-cache. Useful to force the file to still be considered
146123 * modified the next time the process is run
146124 *
146125 * @method removeEntry
146126 * @param entryName
146127 */
146128 removeEntry: function removeEntry(entryName) {
146129 delete normalizedEntries[entryName];
146130 cache.removeKey(entryName);
146131 },
146132
146133 /**
146134 * Delete the cache file from the disk
146135 * @method deleteCacheFile
146136 */
146137 deleteCacheFile: function deleteCacheFile() {
146138 cache.removeCacheFile();
146139 },
146140
146141 /**
146142 * remove the cache from the file and clear the memory cache
146143 */
146144 destroy: function destroy() {
146145 normalizedEntries = {};
146146 cache.destroy();
146147 },
146148 _getMetaForFileUsingCheckSum: function _getMetaForFileUsingCheckSum(cacheEntry) {
146149 var contentBuffer = fs.readFileSync(cacheEntry.key);
146150 var hash = this.getHash(contentBuffer);
146151 var meta = Object.assign(cacheEntry.meta, {
146152 hash: hash
146153 });
146154 return meta;
146155 },
146156 _getMetaForFileUsingMtimeAndSize: function _getMetaForFileUsingMtimeAndSize(cacheEntry) {
146157 var stat = fs.statSync(cacheEntry.key);
146158 var meta = Object.assign(cacheEntry.meta, {
146159 size: stat.size,
146160 mtime: stat.mtime.getTime()
146161 });
146162 return meta;
146163 },
146164
146165 /**
146166 * Sync the files and persist them to the cache
146167 * @method reconcile
146168 */
146169 reconcile: function reconcile(noPrune) {
146170 removeNotFoundFiles();
146171 noPrune = typeof noPrune === 'undefined' ? true : noPrune;
146172 var entries = normalizedEntries;
146173 var keys = Object.keys(entries);
146174
146175 if (keys.length === 0) {
146176 return;
146177 }
146178
146179 var me = this;
146180 keys.forEach(function (entryName) {
146181 var cacheEntry = entries[entryName];
146182
146183 try {
146184 var meta = useChecksum ? me._getMetaForFileUsingCheckSum(cacheEntry) : me._getMetaForFileUsingMtimeAndSize(cacheEntry);
146185 cache.setKey(entryName, meta);
146186 } catch (err) {
146187 // if the file does not exists we don't save it
146188 // other errors are just thrown
146189 if (err.code !== 'ENOENT') {
146190 throw err;
146191 }
146192 }
146193 });
146194 cache.save(noPrune);
146195 }
146196 };
146197 }
146198};
146199
146200/***/ }),
6a5a0f88 146201/* 891 */
eb39fafa
DC
146202/***/ (function(module, exports) {
146203
146204module.exports = require("crypto");
146205
146206/***/ }),
6a5a0f88 146207/* 892 */
eb39fafa
DC
146208/***/ (function(module, exports, __webpack_require__) {
146209
146210/* WEBPACK VAR INJECTION */(function(__dirname) {var path = __webpack_require__(377);
146211
6a5a0f88 146212var fs = __webpack_require__(825);
eb39fafa 146213
6a5a0f88 146214var utils = __webpack_require__(893);
eb39fafa 146215
6a5a0f88 146216var del = __webpack_require__(897);
eb39fafa
DC
146217
146218var writeJSON = utils.writeJSON;
146219var cache = {
146220 /**
146221 * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
146222 * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
146223 * then the cache module directory `./cache` will be used instead
146224 *
146225 * @method load
146226 * @param docId {String} the id of the cache, would also be used as the name of the file cache
146227 * @param [cacheDir] {String} directory for the cache entry
146228 */
146229 load: function load(docId, cacheDir) {
146230 var me = this;
146231 me._visited = {};
146232 me._persisted = {};
146233 me._pathToFile = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, './.cache/', docId);
146234
146235 if (fs.existsSync(me._pathToFile)) {
146236 me._persisted = utils.tryParse(me._pathToFile, {});
146237 }
146238 },
146239
146240 /**
146241 * Load the cache from the provided file
146242 * @method loadFile
146243 * @param {String} pathToFile the path to the file containing the info for the cache
146244 */
146245 loadFile: function loadFile(pathToFile) {
146246 var me = this;
146247 var dir = path.dirname(pathToFile);
146248 var fName = path.basename(pathToFile);
146249 me.load(fName, dir);
146250 },
146251
146252 /**
146253 * Returns the entire persisted object
146254 * @method all
146255 * @returns {*}
146256 */
146257 all: function all() {
146258 return this._persisted;
146259 },
146260 keys: function keys() {
146261 return Object.keys(this._persisted);
146262 },
146263
146264 /**
146265 * sets a key to a given value
146266 * @method setKey
146267 * @param key {string} the key to set
146268 * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
146269 */
146270 setKey: function setKey(key, value) {
146271 this._visited[key] = true;
146272 this._persisted[key] = value;
146273 },
146274
146275 /**
146276 * remove a given key from the cache
146277 * @method removeKey
146278 * @param key {String} the key to remove from the object
146279 */
146280 removeKey: function removeKey(key) {
146281 delete this._visited[key]; // esfmt-ignore-line
146282
146283 delete this._persisted[key]; // esfmt-ignore-line
146284 },
146285
146286 /**
146287 * Return the value of the provided key
146288 * @method getKey
146289 * @param key {String} the name of the key to retrieve
146290 * @returns {*} the value from the key
146291 */
146292 getKey: function getKey(key) {
146293 this._visited[key] = true;
146294 return this._persisted[key];
146295 },
146296
146297 /**
146298 * Remove keys that were not accessed/set since the
146299 * last time the `prune` method was called.
146300 * @method _prune
146301 * @private
146302 */
146303 _prune: function _prune() {
146304 var me = this;
146305 var obj = {};
146306 var keys = Object.keys(me._visited); // no keys visited for either get or set value
146307
146308 if (keys.length === 0) {
146309 return;
146310 }
146311
146312 keys.forEach(function (key) {
146313 obj[key] = me._persisted[key];
146314 });
146315 me._visited = {};
146316 me._persisted = obj;
146317 },
146318
146319 /**
146320 * Save the state of the cache identified by the docId to disk
146321 * as a JSON structure
146322 * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files
146323 * @method save
146324 */
146325 save: function save(noPrune) {
146326 var me = this;
146327 !noPrune && me._prune();
146328 writeJSON(me._pathToFile, me._persisted);
146329 },
146330
146331 /**
146332 * remove the file where the cache is persisted
146333 * @method removeCacheFile
146334 * @return {Boolean} true or false if the file was successfully deleted
146335 */
146336 removeCacheFile: function removeCacheFile() {
146337 return del(this._pathToFile);
146338 },
146339
146340 /**
146341 * Destroy the file cache and cache content.
146342 * @method destroy
146343 */
146344 destroy: function destroy() {
146345 var me = this;
146346 me._visited = {};
146347 me._persisted = {};
146348 me.removeCacheFile();
146349 }
146350};
146351module.exports = {
146352 /**
146353 * Alias for create. Should be considered depreacted. Will be removed in next releases
146354 *
146355 * @method load
146356 * @param docId {String} the id of the cache, would also be used as the name of the file cache
146357 * @param [cacheDir] {String} directory for the cache entry
146358 * @returns {cache} cache instance
146359 */
146360 load: function load(docId, cacheDir) {
146361 return this.create(docId, cacheDir);
146362 },
146363
146364 /**
146365 * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
146366 * cache storage.
146367 *
146368 * @method create
146369 * @param docId {String} the id of the cache, would also be used as the name of the file cache
146370 * @param [cacheDir] {String} directory for the cache entry
146371 * @returns {cache} cache instance
146372 */
146373 create: function create(docId, cacheDir) {
146374 var obj = Object.create(cache);
146375 obj.load(docId, cacheDir);
146376 return obj;
146377 },
146378 createFromFile: function createFromFile(filePath) {
146379 var obj = Object.create(cache);
146380 obj.loadFile(filePath);
146381 return obj;
146382 },
146383
146384 /**
146385 * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly
146386 *
146387 * @method clearCache
146388 * @param docId {String} the id of the cache, would also be used as the name of the file cache
146389 * @param cacheDir {String} the directory where the cache file was written
146390 * @returns {Boolean} true if the cache folder was deleted. False otherwise
146391 */
146392 clearCacheById: function clearCacheById(docId, cacheDir) {
146393 var filePath = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, './.cache/', docId);
146394 return del(filePath);
146395 },
146396
146397 /**
146398 * Remove all cache stored in the cache directory
146399 * @method clearAll
146400 * @returns {Boolean} true if the cache folder was deleted. False otherwise
146401 */
146402 clearAll: function clearAll(cacheDir) {
146403 var filePath = cacheDir ? path.resolve(cacheDir) : path.resolve(__dirname, './.cache/');
146404 return del(filePath);
146405 }
146406};
146407/* WEBPACK VAR INJECTION */}.call(this, "/"))
146408
146409/***/ }),
6a5a0f88 146410/* 893 */
eb39fafa
DC
146411/***/ (function(module, exports, __webpack_require__) {
146412
6a5a0f88 146413var fs = __webpack_require__(825);
eb39fafa 146414
6a5a0f88 146415var write = __webpack_require__(894);
eb39fafa 146416
6a5a0f88 146417var flatted = __webpack_require__(896);
eb39fafa
DC
146418
146419module.exports = {
146420 tryParse: function tryParse(filePath, defaultValue) {
146421 var result;
146422
146423 try {
146424 result = this.readJSON(filePath);
146425 } catch (ex) {
146426 result = defaultValue;
146427 }
146428
146429 return result;
146430 },
146431
146432 /**
146433 * Read json file synchronously using flatted
146434 *
146435 * @method readJSON
146436 * @param {String} filePath Json filepath
146437 * @returns {*} parse result
146438 */
146439 readJSON: function readJSON(filePath) {
146440 return flatted.parse(fs.readFileSync(filePath, {
146441 encoding: 'utf8'
146442 }));
146443 },
146444
146445 /**
146446 * Write json file synchronously using circular-json
146447 *
146448 * @method writeJSON
146449 * @param {String} filePath Json filepath
146450 * @param {*} data Object to serialize
146451 */
146452 writeJSON: function writeJSON(filePath, data) {
146453 write.sync(filePath, flatted.stringify(data));
146454 }
146455};
146456
146457/***/ }),
6a5a0f88 146458/* 894 */
eb39fafa
DC
146459/***/ (function(module, exports, __webpack_require__) {
146460
146461"use strict";
146462/*!
146463 * write <https://github.com/jonschlinkert/write>
146464 *
146465 * Copyright (c) 2014-2017, Jon Schlinkert.
146466 * Released under the MIT License.
146467 */
146468
146469
6a5a0f88 146470var fs = __webpack_require__(825);
eb39fafa
DC
146471
146472var path = __webpack_require__(377);
146473
6a5a0f88 146474var mkdirp = __webpack_require__(895);
eb39fafa
DC
146475/**
146476 * Asynchronously writes data to a file, replacing the file if it already
146477 * exists and creating any intermediate directories if they don't already
146478 * exist. Data can be a string or a buffer. Returns a promise if a callback
146479 * function is not passed.
146480 *
146481 * ```js
146482 * var writeFile = require('write');
146483 * writeFile('foo.txt', 'This is content...', function(err) {
146484 * if (err) console.log(err);
146485 * });
146486 *
146487 * // promise
146488 * writeFile('foo.txt', 'This is content...')
146489 * .then(function() {
146490 * // do stuff
146491 * });
146492 * ```
146493 * @name writeFile
146494 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.
146495 * @param {string|Buffer|Uint8Array} `data` String to write to disk.
146496 * @param {object} `options` Options to pass to [fs.writeFile][fs]{#fs_fs_writefile_file_data_options_callback} and/or [mkdirp][]
146497 * @param {Function} `callback` (optional) If no callback is provided, a promise is returned.
146498 * @api public
146499 */
146500
146501
146502function writeFile(filepath, data, options, cb) {
146503 if (typeof options === 'function') {
146504 cb = options;
146505 options = {};
146506 }
146507
146508 if (typeof cb !== 'function') {
146509 return writeFile.promise.apply(null, arguments);
146510 }
146511
146512 if (typeof filepath !== 'string') {
146513 cb(new TypeError('expected filepath to be a string'));
146514 return;
146515 }
146516
146517 mkdirp(path.dirname(filepath), options, function (err) {
146518 if (err) {
146519 cb(err);
146520 return;
146521 }
146522
146523 fs.writeFile(filepath, data, options, cb);
146524 });
146525}
146526
146527;
146528/**
146529 * The promise version of [writeFile](#writefile). Returns a promise.
146530 *
146531 * ```js
146532 * var writeFile = require('write');
146533 * writeFile.promise('foo.txt', 'This is content...')
146534 * .then(function() {
146535 * // do stuff
146536 * });
146537 * ```
146538 * @name .promise
146539 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.
146540 * @param {string|Buffer|Uint8Array} `val` String or buffer to write to disk.
146541 * @param {object} `options` Options to pass to [fs.writeFile][fs]{#fs_fs_writefile_file_data_options_callback} and/or [mkdirp][]
146542 * @return {Promise}
146543 * @api public
146544 */
146545
146546writeFile.promise = function (filepath, val, options) {
146547 if (typeof filepath !== 'string') {
146548 return Promise.reject(new TypeError('expected filepath to be a string'));
146549 }
146550
146551 return new Promise(function (resolve, reject) {
146552 mkdirp(path.dirname(filepath), options, function (err) {
146553 if (err) {
146554 reject(err);
146555 return;
146556 }
146557
146558 fs.writeFile(filepath, val, options, function (err) {
146559 if (err) {
146560 reject(err);
146561 return;
146562 }
146563
146564 resolve(val);
146565 });
146566 });
146567 });
146568};
146569/**
146570 * The synchronous version of [writeFile](#writefile). Returns undefined.
146571 *
146572 * ```js
146573 * var writeFile = require('write');
146574 * writeFile.sync('foo.txt', 'This is content...');
146575 * ```
146576 * @name .sync
146577 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.
146578 * @param {string|Buffer|Uint8Array} `data` String or buffer to write to disk.
146579 * @param {object} `options` Options to pass to [fs.writeFileSync][fs]{#fs_fs_writefilesync_file_data_options} and/or [mkdirp][]
146580 * @return {undefined}
146581 * @api public
146582 */
146583
146584
146585writeFile.sync = function (filepath, data, options) {
146586 if (typeof filepath !== 'string') {
146587 throw new TypeError('expected filepath to be a string');
146588 }
146589
146590 mkdirp.sync(path.dirname(filepath), options);
146591 fs.writeFileSync(filepath, data, options);
146592};
146593/**
146594 * Uses `fs.createWriteStream` to write data to a file, replacing the
146595 * file if it already exists and creating any intermediate directories
146596 * if they don't already exist. Data can be a string or a buffer. Returns
146597 * a new [WriteStream](https://nodejs.org/api/fs.html#fs_class_fs_writestream)
146598 * object.
146599 *
146600 * ```js
146601 * var fs = require('fs');
146602 * var writeFile = require('write');
146603 * fs.createReadStream('README.md')
146604 * .pipe(writeFile.stream('a/b/c/other-file.md'))
146605 * .on('close', function() {
146606 * // do stuff
146607 * });
146608 * ```
146609 * @name .stream
146610 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.
146611 * @param {object} `options` Options to pass to [mkdirp][] and [fs.createWriteStream][fs]{#fs_fs_createwritestream_path_options}
146612 * @return {Stream} Returns a new [WriteStream](https://nodejs.org/api/fs.html#fs_class_fs_writestream) object. (See [Writable Stream](https://nodejs.org/api/stream.html#stream_class_stream_writable)).
146613 * @api public
146614 */
146615
146616
146617writeFile.stream = function (filepath, options) {
146618 mkdirp.sync(path.dirname(filepath), options);
146619 return fs.createWriteStream(filepath, options);
146620};
146621/**
146622 * Expose `writeFile`
146623 */
146624
146625
146626module.exports = writeFile;
146627
146628/***/ }),
6a5a0f88 146629/* 895 */
eb39fafa
DC
146630/***/ (function(module, exports, __webpack_require__) {
146631
146632var path = __webpack_require__(377);
146633
6a5a0f88 146634var fs = __webpack_require__(825);
eb39fafa
DC
146635
146636var _0777 = parseInt('0777', 8);
146637
146638module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
146639
146640function mkdirP(p, opts, f, made) {
146641 if (typeof opts === 'function') {
146642 f = opts;
146643 opts = {};
146644 } else if (!opts || typeof opts !== 'object') {
146645 opts = {
146646 mode: opts
146647 };
146648 }
146649
146650 var mode = opts.mode;
146651 var xfs = opts.fs || fs;
146652
146653 if (mode === undefined) {
56c4a2cb 146654 mode = _0777;
eb39fafa
DC
146655 }
146656
146657 if (!made) made = null;
146658
146659 var cb = f || function () {};
146660
146661 p = path.resolve(p);
146662 xfs.mkdir(p, mode, function (er) {
146663 if (!er) {
146664 made = made || p;
146665 return cb(null, made);
146666 }
146667
146668 switch (er.code) {
146669 case 'ENOENT':
146670 if (path.dirname(p) === p) return cb(er);
146671 mkdirP(path.dirname(p), opts, function (er, made) {
146672 if (er) cb(er, made);else mkdirP(p, opts, cb, made);
146673 });
146674 break;
146675 // In the case of any other error, just see if there's a dir
146676 // there already. If so, then hooray! If not, then something
146677 // is borked.
146678
146679 default:
146680 xfs.stat(p, function (er2, stat) {
146681 // if the stat fails, then that's super weird.
146682 // let the original error be the failure reason.
146683 if (er2 || !stat.isDirectory()) cb(er, made);else cb(null, made);
146684 });
146685 break;
146686 }
146687 });
146688}
146689
146690mkdirP.sync = function sync(p, opts, made) {
146691 if (!opts || typeof opts !== 'object') {
146692 opts = {
146693 mode: opts
146694 };
146695 }
146696
146697 var mode = opts.mode;
146698 var xfs = opts.fs || fs;
146699
146700 if (mode === undefined) {
56c4a2cb 146701 mode = _0777;
eb39fafa
DC
146702 }
146703
146704 if (!made) made = null;
146705 p = path.resolve(p);
146706
146707 try {
146708 xfs.mkdirSync(p, mode);
146709 made = made || p;
146710 } catch (err0) {
146711 switch (err0.code) {
146712 case 'ENOENT':
146713 made = sync(path.dirname(p), opts, made);
146714 sync(p, opts, made);
146715 break;
146716 // In the case of any other error, just see if there's a dir
146717 // there already. If so, then hooray! If not, then something
146718 // is borked.
146719
146720 default:
146721 var stat;
146722
146723 try {
146724 stat = xfs.statSync(p);
146725 } catch (err1) {
146726 throw err0;
146727 }
146728
146729 if (!stat.isDirectory()) throw err0;
146730 break;
146731 }
146732 }
146733
146734 return made;
146735};
146736
146737/***/ }),
6a5a0f88 146738/* 896 */
eb39fafa
DC
146739/***/ (function(module, exports) {
146740
146741var Flatted = function (Primitive, primitive) {
146742 /*!
146743 * ISC License
146744 *
146745 * Copyright (c) 2018, Andrea Giammarchi, @WebReflection
146746 *
146747 * Permission to use, copy, modify, and/or distribute this software for any
146748 * purpose with or without fee is hereby granted, provided that the above
146749 * copyright notice and this permission notice appear in all copies.
146750 *
146751 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
146752 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
146753 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
146754 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
146755 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
146756 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
146757 * PERFORMANCE OF THIS SOFTWARE.
146758 */
146759 var Flatted = {
146760 parse: function parse(text, reviver) {
146761 var input = JSON.parse(text, Primitives).map(primitives);
146762 var value = input[0];
146763 var $ = reviver || noop;
146764 var tmp = typeof value === 'object' && value ? revive(input, new Set(), value, $) : value;
146765 return $.call({
146766 '': tmp
146767 }, '', tmp);
146768 },
146769 stringify: function stringify(value, replacer, space) {
146770 for (var firstRun, known = new Map(), input = [], output = [], $ = replacer && typeof replacer === typeof input ? function (k, v) {
146771 if (k === '' || -1 < replacer.indexOf(k)) return v;
146772 } : replacer || noop, i = +set(known, input, $.call({
146773 '': value
146774 }, '', value)), replace = function replace(key, value) {
146775 if (firstRun) {
146776 firstRun = !firstRun;
146777 return value;
146778 }
146779
146780 var after = $.call(this, key, value);
146781
146782 switch (typeof after) {
146783 case 'object':
146784 if (after === null) return after;
146785
146786 case primitive:
146787 return known.get(after) || set(known, input, after);
146788 }
146789
146790 return after;
146791 }; i < input.length; i++) {
146792 firstRun = true;
146793 output[i] = JSON.stringify(input[i], replace, space);
146794 }
146795
146796 return '[' + output.join(',') + ']';
146797 }
146798 };
146799 return Flatted;
146800
146801 function noop(key, value) {
146802 return value;
146803 }
146804
146805 function revive(input, parsed, output, $) {
146806 return Object.keys(output).reduce(function (output, key) {
146807 var value = output[key];
146808
146809 if (value instanceof Primitive) {
146810 var tmp = input[value];
146811
146812 if (typeof tmp === 'object' && !parsed.has(tmp)) {
146813 parsed.add(tmp);
146814 output[key] = $.call(output, key, revive(input, parsed, tmp, $));
146815 } else {
146816 output[key] = $.call(output, key, tmp);
146817 }
146818 } else output[key] = $.call(output, key, value);
146819
146820 return output;
146821 }, output);
146822 }
146823
146824 function set(known, input, value) {
146825 var index = Primitive(input.push(value) - 1);
146826 known.set(value, index);
146827 return index;
146828 } // the two kinds of primitives
146829 // 1. the real one
146830 // 2. the wrapped one
146831
146832
146833 function primitives(value) {
146834 return value instanceof Primitive ? Primitive(value) : value;
146835 }
146836
146837 function Primitives(key, value) {
146838 return typeof value === primitive ? new Primitive(value) : value;
146839 }
146840}(String, 'string');
146841
146842module.exports = Flatted;
146843
146844/***/ }),
6a5a0f88 146845/* 897 */
eb39fafa
DC
146846/***/ (function(module, exports, __webpack_require__) {
146847
6a5a0f88 146848var rimraf = __webpack_require__(898).sync;
eb39fafa 146849
6a5a0f88 146850var fs = __webpack_require__(825);
eb39fafa
DC
146851
146852module.exports = function del(file) {
146853 if (fs.existsSync(file)) {
146854 //if rimraf doesn't throw then the file has been deleted or didn't exist
146855 rimraf(file, {
146856 glob: false
146857 });
146858 return true;
146859 }
146860
146861 return false;
146862};
146863
146864/***/ }),
6a5a0f88 146865/* 898 */
eb39fafa
DC
146866/***/ (function(module, exports, __webpack_require__) {
146867
146868module.exports = rimraf;
146869rimraf.sync = rimrafSync;
146870
146871var assert = __webpack_require__(379);
146872
146873var path = __webpack_require__(377);
146874
6a5a0f88 146875var fs = __webpack_require__(825);
eb39fafa 146876
6a5a0f88 146877var glob = __webpack_require__(899);
eb39fafa
DC
146878
146879var _0666 = parseInt('666', 8);
146880
146881var defaultGlobOpts = {
146882 nosort: true,
146883 silent: true
146884}; // for EMFILE handling
146885
146886var timeout = 0;
146887var isWindows = process.platform === "win32";
146888
146889function defaults(options) {
146890 var methods = ['unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir'];
146891 methods.forEach(function (m) {
146892 options[m] = options[m] || fs[m];
146893 m = m + 'Sync';
146894 options[m] = options[m] || fs[m];
146895 });
146896 options.maxBusyTries = options.maxBusyTries || 3;
146897 options.emfileWait = options.emfileWait || 1000;
146898
146899 if (options.glob === false) {
146900 options.disableGlob = true;
146901 }
146902
146903 options.disableGlob = options.disableGlob || false;
146904 options.glob = options.glob || defaultGlobOpts;
146905}
146906
146907function rimraf(p, options, cb) {
146908 if (typeof options === 'function') {
146909 cb = options;
146910 options = {};
146911 }
146912
146913 assert(p, 'rimraf: missing path');
146914 assert.equal(typeof p, 'string', 'rimraf: path should be a string');
146915 assert.equal(typeof cb, 'function', 'rimraf: callback function required');
146916 assert(options, 'rimraf: invalid options argument provided');
146917 assert.equal(typeof options, 'object', 'rimraf: options should be object');
146918 defaults(options);
146919 var busyTries = 0;
146920 var errState = null;
146921 var n = 0;
146922 if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]);
146923 options.lstat(p, function (er, stat) {
146924 if (!er) return afterGlob(null, [p]);
146925 glob(p, options.glob, afterGlob);
146926 });
146927
146928 function next(er) {
146929 errState = errState || er;
146930 if (--n === 0) cb(errState);
146931 }
146932
146933 function afterGlob(er, results) {
146934 if (er) return cb(er);
146935 n = results.length;
146936 if (n === 0) return cb();
146937 results.forEach(function (p) {
146938 rimraf_(p, options, function CB(er) {
146939 if (er) {
146940 if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) {
146941 busyTries++;
146942 var time = busyTries * 100; // try again, with the same exact callback as this one.
146943
146944 return setTimeout(function () {
146945 rimraf_(p, options, CB);
146946 }, time);
146947 } // this one won't happen if graceful-fs is used.
146948
146949
146950 if (er.code === "EMFILE" && timeout < options.emfileWait) {
146951 return setTimeout(function () {
146952 rimraf_(p, options, CB);
146953 }, timeout++);
146954 } // already gone
146955
146956
146957 if (er.code === "ENOENT") er = null;
146958 }
146959
146960 timeout = 0;
146961 next(er);
146962 });
146963 });
146964 }
146965} // Two possible strategies.
146966// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
146967// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
146968//
146969// Both result in an extra syscall when you guess wrong. However, there
146970// are likely far more normal files in the world than directories. This
146971// is based on the assumption that a the average number of files per
146972// directory is >= 1.
146973//
146974// If anyone ever complains about this, then I guess the strategy could
146975// be made configurable somehow. But until then, YAGNI.
146976
146977
146978function rimraf_(p, options, cb) {
146979 assert(p);
146980 assert(options);
146981 assert(typeof cb === 'function'); // sunos lets the root user unlink directories, which is... weird.
146982 // so we have to lstat here and make sure it's not a dir.
146983
146984 options.lstat(p, function (er, st) {
146985 if (er && er.code === "ENOENT") return cb(null); // Windows can EPERM on stat. Life is suffering.
146986
146987 if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb);
146988 if (st && st.isDirectory()) return rmdir(p, options, er, cb);
146989 options.unlink(p, function (er) {
146990 if (er) {
146991 if (er.code === "ENOENT") return cb(null);
146992 if (er.code === "EPERM") return isWindows ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb);
146993 if (er.code === "EISDIR") return rmdir(p, options, er, cb);
146994 }
146995
146996 return cb(er);
146997 });
146998 });
146999}
147000
147001function fixWinEPERM(p, options, er, cb) {
147002 assert(p);
147003 assert(options);
147004 assert(typeof cb === 'function');
147005 if (er) assert(er instanceof Error);
147006 options.chmod(p, _0666, function (er2) {
147007 if (er2) cb(er2.code === "ENOENT" ? null : er);else options.stat(p, function (er3, stats) {
147008 if (er3) cb(er3.code === "ENOENT" ? null : er);else if (stats.isDirectory()) rmdir(p, options, er, cb);else options.unlink(p, cb);
147009 });
147010 });
147011}
147012
147013function fixWinEPERMSync(p, options, er) {
147014 assert(p);
147015 assert(options);
147016 if (er) assert(er instanceof Error);
147017
147018 try {
147019 options.chmodSync(p, _0666);
147020 } catch (er2) {
147021 if (er2.code === "ENOENT") return;else throw er;
147022 }
147023
147024 try {
147025 var stats = options.statSync(p);
147026 } catch (er3) {
147027 if (er3.code === "ENOENT") return;else throw er;
147028 }
147029
147030 if (stats.isDirectory()) rmdirSync(p, options, er);else options.unlinkSync(p);
147031}
147032
147033function rmdir(p, options, originalEr, cb) {
147034 assert(p);
147035 assert(options);
147036 if (originalEr) assert(originalEr instanceof Error);
147037 assert(typeof cb === 'function'); // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
147038 // if we guessed wrong, and it's not a directory, then
147039 // raise the original error.
147040
147041 options.rmdir(p, function (er) {
147042 if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb);else if (er && er.code === "ENOTDIR") cb(originalEr);else cb(er);
147043 });
147044}
147045
147046function rmkids(p, options, cb) {
147047 assert(p);
147048 assert(options);
147049 assert(typeof cb === 'function');
147050 options.readdir(p, function (er, files) {
147051 if (er) return cb(er);
147052 var n = files.length;
147053 if (n === 0) return options.rmdir(p, cb);
147054 var errState;
147055 files.forEach(function (f) {
147056 rimraf(path.join(p, f), options, function (er) {
147057 if (errState) return;
147058 if (er) return cb(errState = er);
147059 if (--n === 0) options.rmdir(p, cb);
147060 });
147061 });
147062 });
147063} // this looks simpler, and is strictly *faster*, but will
147064// tie up the JavaScript thread and fail on excessively
147065// deep directory trees.
147066
147067
147068function rimrafSync(p, options) {
147069 options = options || {};
147070 defaults(options);
147071 assert(p, 'rimraf: missing path');
147072 assert.equal(typeof p, 'string', 'rimraf: path should be a string');
147073 assert(options, 'rimraf: missing options');
147074 assert.equal(typeof options, 'object', 'rimraf: options should be object');
147075 var results;
147076
147077 if (options.disableGlob || !glob.hasMagic(p)) {
147078 results = [p];
147079 } else {
147080 try {
147081 options.lstatSync(p);
147082 results = [p];
147083 } catch (er) {
147084 results = glob.sync(p, options.glob);
147085 }
147086 }
147087
147088 if (!results.length) return;
147089
147090 for (var i = 0; i < results.length; i++) {
147091 var p = results[i];
147092
147093 try {
147094 var st = options.lstatSync(p);
147095 } catch (er) {
147096 if (er.code === "ENOENT") return; // Windows can EPERM on stat. Life is suffering.
147097
147098 if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er);
147099 }
147100
147101 try {
147102 // sunos lets the root user unlink directories, which is... weird.
147103 if (st && st.isDirectory()) rmdirSync(p, options, null);else options.unlinkSync(p);
147104 } catch (er) {
147105 if (er.code === "ENOENT") return;
147106 if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er);
147107 if (er.code !== "EISDIR") throw er;
147108 rmdirSync(p, options, er);
147109 }
147110 }
147111}
147112
147113function rmdirSync(p, options, originalEr) {
147114 assert(p);
147115 assert(options);
147116 if (originalEr) assert(originalEr instanceof Error);
147117
147118 try {
147119 options.rmdirSync(p);
147120 } catch (er) {
147121 if (er.code === "ENOENT") return;
147122 if (er.code === "ENOTDIR") throw originalEr;
147123 if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options);
147124 }
147125}
147126
147127function rmkidsSync(p, options) {
147128 assert(p);
147129 assert(options);
147130 options.readdirSync(p).forEach(function (f) {
147131 rimrafSync(path.join(p, f), options);
147132 }); // We only end up here once we got ENOTEMPTY at least once, and
147133 // at this point, we are guaranteed to have removed all the kids.
147134 // So, we know that it won't be ENOENT or ENOTDIR or anything else.
147135 // try really hard to delete stuff on windows, because it has a
147136 // PROFOUNDLY annoying habit of not closing handles promptly when
147137 // files are deleted, resulting in spurious ENOTEMPTY errors.
147138
147139 var retries = isWindows ? 100 : 1;
147140 var i = 0;
147141
147142 do {
147143 var threw = true;
147144
147145 try {
147146 var ret = options.rmdirSync(p, options);
147147 threw = false;
147148 return ret;
147149 } finally {
147150 if (++i < retries && threw) continue;
147151 }
147152 } while (true);
147153}
147154
147155/***/ }),
6a5a0f88 147156/* 899 */
eb39fafa
DC
147157/***/ (function(module, exports, __webpack_require__) {
147158
147159// Approach:
147160//
147161// 1. Get the minimatch set
147162// 2. For each pattern in the set, PROCESS(pattern, false)
147163// 3. Store matches per-set, then uniq them
147164//
147165// PROCESS(pattern, inGlobStar)
147166// Get the first [n] items from pattern that are all strings
147167// Join these together. This is PREFIX.
147168// If there is no more remaining, then stat(PREFIX) and
147169// add to matches if it succeeds. END.
147170//
147171// If inGlobStar and PREFIX is symlink and points to dir
147172// set ENTRIES = []
147173// else readdir(PREFIX) as ENTRIES
147174// If fail, END
147175//
147176// with ENTRIES
147177// If pattern[n] is GLOBSTAR
147178// // handle the case where the globstar match is empty
147179// // by pruning it out, and testing the resulting pattern
147180// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
147181// // handle other cases.
147182// for ENTRY in ENTRIES (not dotfiles)
147183// // attach globstar + tail onto the entry
147184// // Mark that this entry is a globstar match
147185// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
147186//
147187// else // not globstar
147188// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
147189// Test ENTRY against pattern[n]
147190// If fails, continue
147191// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
147192//
147193// Caveat:
147194// Cache all stats and readdirs results to minimize syscall. Since all
147195// we ever care about is existence and directory-ness, we can just keep
147196// `true` for files, and [children,...] for directories, or `false` for
147197// things that don't exist.
147198module.exports = glob;
147199
6a5a0f88 147200var fs = __webpack_require__(825);
eb39fafa 147201
6a5a0f88 147202var rp = __webpack_require__(900);
eb39fafa 147203
6a5a0f88 147204var minimatch = __webpack_require__(845);
eb39fafa
DC
147205
147206var Minimatch = minimatch.Minimatch;
147207
6a5a0f88 147208var inherits = __webpack_require__(902);
eb39fafa 147209
6a5a0f88 147210var EE = __webpack_require__(904).EventEmitter;
eb39fafa
DC
147211
147212var path = __webpack_require__(377);
147213
147214var assert = __webpack_require__(379);
147215
6a5a0f88 147216var isAbsolute = __webpack_require__(905);
eb39fafa 147217
6a5a0f88 147218var globSync = __webpack_require__(906);
eb39fafa 147219
6a5a0f88 147220var common = __webpack_require__(907);
eb39fafa
DC
147221
147222var alphasort = common.alphasort;
147223var alphasorti = common.alphasorti;
147224var setopts = common.setopts;
147225var ownProp = common.ownProp;
147226
6a5a0f88 147227var inflight = __webpack_require__(908);
eb39fafa
DC
147228
147229var util = __webpack_require__(412);
147230
147231var childrenIgnored = common.childrenIgnored;
147232var isIgnored = common.isIgnored;
147233
6a5a0f88 147234var once = __webpack_require__(910);
eb39fafa
DC
147235
147236function glob(pattern, options, cb) {
147237 if (typeof options === 'function') cb = options, options = {};
147238 if (!options) options = {};
147239
147240 if (options.sync) {
147241 if (cb) throw new TypeError('callback provided to sync glob');
147242 return globSync(pattern, options);
147243 }
147244
147245 return new Glob(pattern, options, cb);
147246}
147247
147248glob.sync = globSync;
147249var GlobSync = glob.GlobSync = globSync.GlobSync; // old api surface
147250
147251glob.glob = glob;
147252
147253function extend(origin, add) {
147254 if (add === null || typeof add !== 'object') {
147255 return origin;
147256 }
147257
147258 var keys = Object.keys(add);
147259 var i = keys.length;
147260
147261 while (i--) {
147262 origin[keys[i]] = add[keys[i]];
147263 }
147264
147265 return origin;
147266}
147267
147268glob.hasMagic = function (pattern, options_) {
147269 var options = extend({}, options_);
147270 options.noprocess = true;
147271 var g = new Glob(pattern, options);
147272 var set = g.minimatch.set;
147273 if (!pattern) return false;
147274 if (set.length > 1) return true;
147275
147276 for (var j = 0; j < set[0].length; j++) {
147277 if (typeof set[0][j] !== 'string') return true;
147278 }
147279
147280 return false;
147281};
147282
147283glob.Glob = Glob;
147284inherits(Glob, EE);
147285
147286function Glob(pattern, options, cb) {
147287 if (typeof options === 'function') {
147288 cb = options;
147289 options = null;
147290 }
147291
147292 if (options && options.sync) {
147293 if (cb) throw new TypeError('callback provided to sync glob');
147294 return new GlobSync(pattern, options);
147295 }
147296
147297 if (!(this instanceof Glob)) return new Glob(pattern, options, cb);
147298 setopts(this, pattern, options);
147299 this._didRealPath = false; // process each pattern in the minimatch set
147300
147301 var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that
147302 // duplicates are automagically pruned.
147303 // Later, we do an Object.keys() on these.
147304 // Keep them as a list so we can fill in when nonull is set.
147305
147306 this.matches = new Array(n);
147307
147308 if (typeof cb === 'function') {
147309 cb = once(cb);
147310 this.on('error', cb);
147311 this.on('end', function (matches) {
147312 cb(null, matches);
147313 });
147314 }
147315
147316 var self = this;
147317 this._processing = 0;
147318 this._emitQueue = [];
147319 this._processQueue = [];
147320 this.paused = false;
147321 if (this.noprocess) return this;
147322 if (n === 0) return done();
147323 var sync = true;
147324
147325 for (var i = 0; i < n; i++) {
147326 this._process(this.minimatch.set[i], i, false, done);
147327 }
147328
147329 sync = false;
147330
147331 function done() {
147332 --self._processing;
147333
147334 if (self._processing <= 0) {
147335 if (sync) {
147336 process.nextTick(function () {
147337 self._finish();
147338 });
147339 } else {
147340 self._finish();
147341 }
147342 }
147343 }
147344}
147345
147346Glob.prototype._finish = function () {
147347 assert(this instanceof Glob);
147348 if (this.aborted) return;
147349 if (this.realpath && !this._didRealpath) return this._realpath();
147350 common.finish(this);
147351 this.emit('end', this.found);
147352};
147353
147354Glob.prototype._realpath = function () {
147355 if (this._didRealpath) return;
147356 this._didRealpath = true;
147357 var n = this.matches.length;
147358 if (n === 0) return this._finish();
147359 var self = this;
147360
147361 for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next);
147362
147363 function next() {
147364 if (--n === 0) self._finish();
147365 }
147366};
147367
147368Glob.prototype._realpathSet = function (index, cb) {
147369 var matchset = this.matches[index];
147370 if (!matchset) return cb();
147371 var found = Object.keys(matchset);
147372 var self = this;
147373 var n = found.length;
147374 if (n === 0) return cb();
147375 var set = this.matches[index] = Object.create(null);
147376 found.forEach(function (p, i) {
147377 // If there's a problem with the stat, then it means that
147378 // one or more of the links in the realpath couldn't be
147379 // resolved. just return the abs value in that case.
147380 p = self._makeAbs(p);
147381 rp.realpath(p, self.realpathCache, function (er, real) {
147382 if (!er) set[real] = true;else if (er.syscall === 'stat') set[p] = true;else self.emit('error', er); // srsly wtf right here
147383
147384 if (--n === 0) {
147385 self.matches[index] = set;
147386 cb();
147387 }
147388 });
147389 });
147390};
147391
147392Glob.prototype._mark = function (p) {
147393 return common.mark(this, p);
147394};
147395
147396Glob.prototype._makeAbs = function (f) {
147397 return common.makeAbs(this, f);
147398};
147399
147400Glob.prototype.abort = function () {
147401 this.aborted = true;
147402 this.emit('abort');
147403};
147404
147405Glob.prototype.pause = function () {
147406 if (!this.paused) {
147407 this.paused = true;
147408 this.emit('pause');
147409 }
147410};
147411
147412Glob.prototype.resume = function () {
147413 if (this.paused) {
147414 this.emit('resume');
147415 this.paused = false;
147416
147417 if (this._emitQueue.length) {
147418 var eq = this._emitQueue.slice(0);
147419
147420 this._emitQueue.length = 0;
147421
147422 for (var i = 0; i < eq.length; i++) {
147423 var e = eq[i];
147424
147425 this._emitMatch(e[0], e[1]);
147426 }
147427 }
147428
147429 if (this._processQueue.length) {
147430 var pq = this._processQueue.slice(0);
147431
147432 this._processQueue.length = 0;
147433
147434 for (var i = 0; i < pq.length; i++) {
147435 var p = pq[i];
147436 this._processing--;
147437
147438 this._process(p[0], p[1], p[2], p[3]);
147439 }
147440 }
147441 }
147442};
147443
147444Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
147445 assert(this instanceof Glob);
147446 assert(typeof cb === 'function');
147447 if (this.aborted) return;
147448 this._processing++;
147449
147450 if (this.paused) {
147451 this._processQueue.push([pattern, index, inGlobStar, cb]);
147452
147453 return;
147454 } //console.error('PROCESS %d', this._processing, pattern)
147455 // Get the first [n] parts of pattern that are all strings.
147456
147457
147458 var n = 0;
147459
147460 while (typeof pattern[n] === 'string') {
147461 n++;
147462 } // now n is the index of the first one that is *not* a string.
147463 // see if there's anything else
147464
147465
147466 var prefix;
147467
147468 switch (n) {
147469 // if not, then this is rather simple
147470 case pattern.length:
147471 this._processSimple(pattern.join('/'), index, cb);
147472
147473 return;
147474
147475 case 0:
147476 // pattern *starts* with some non-trivial item.
147477 // going to readdir(cwd), but not include the prefix in matches.
147478 prefix = null;
147479 break;
147480
147481 default:
147482 // pattern has some string bits in the front.
147483 // whatever it starts with, whether that's 'absolute' like /foo/bar,
147484 // or 'relative' like '../baz'
147485 prefix = pattern.slice(0, n).join('/');
147486 break;
147487 }
147488
147489 var remain = pattern.slice(n); // get the list of entries.
147490
147491 var read;
147492 if (prefix === null) read = '.';else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
147493 if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix;
147494 read = prefix;
147495 } else read = prefix;
147496
147497 var abs = this._makeAbs(read); //if ignored, skip _processing
147498
147499
147500 if (childrenIgnored(this, read)) return cb();
147501 var isGlobStar = remain[0] === minimatch.GLOBSTAR;
147502 if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
147503};
147504
147505Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
147506 var self = this;
147507
147508 this._readdir(abs, inGlobStar, function (er, entries) {
147509 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
147510 });
147511};
147512
147513Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
147514 // if the abs isn't a dir, then nothing can match!
147515 if (!entries) return cb(); // It will only match dot entries if it starts with a dot, or if
147516 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
147517
147518 var pn = remain[0];
147519 var negate = !!this.minimatch.negate;
147520 var rawGlob = pn._glob;
147521 var dotOk = this.dot || rawGlob.charAt(0) === '.';
147522 var matchedEntries = [];
147523
147524 for (var i = 0; i < entries.length; i++) {
147525 var e = entries[i];
147526
147527 if (e.charAt(0) !== '.' || dotOk) {
147528 var m;
147529
147530 if (negate && !prefix) {
147531 m = !e.match(pn);
147532 } else {
147533 m = e.match(pn);
147534 }
147535
147536 if (m) matchedEntries.push(e);
147537 }
147538 } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
147539
147540
147541 var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
147542
147543 if (len === 0) return cb(); // if this is the last remaining pattern bit, then no need for
147544 // an additional stat *unless* the user has specified mark or
147545 // stat explicitly. We know they exist, since readdir returned
147546 // them.
147547
147548 if (remain.length === 1 && !this.mark && !this.stat) {
147549 if (!this.matches[index]) this.matches[index] = Object.create(null);
147550
147551 for (var i = 0; i < len; i++) {
147552 var e = matchedEntries[i];
147553
147554 if (prefix) {
147555 if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
147556 }
147557
147558 if (e.charAt(0) === '/' && !this.nomount) {
147559 e = path.join(this.root, e);
147560 }
147561
147562 this._emitMatch(index, e);
147563 } // This was the last one, and no stats were needed
147564
147565
147566 return cb();
147567 } // now test all matched entries as stand-ins for that part
147568 // of the pattern.
147569
147570
147571 remain.shift();
147572
147573 for (var i = 0; i < len; i++) {
147574 var e = matchedEntries[i];
147575 var newPattern;
147576
147577 if (prefix) {
147578 if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
147579 }
147580
147581 this._process([e].concat(remain), index, inGlobStar, cb);
147582 }
147583
147584 cb();
147585};
147586
147587Glob.prototype._emitMatch = function (index, e) {
147588 if (this.aborted) return;
147589 if (isIgnored(this, e)) return;
147590
147591 if (this.paused) {
147592 this._emitQueue.push([index, e]);
147593
147594 return;
147595 }
147596
147597 var abs = isAbsolute(e) ? e : this._makeAbs(e);
147598 if (this.mark) e = this._mark(e);
147599 if (this.absolute) e = abs;
147600 if (this.matches[index][e]) return;
147601
147602 if (this.nodir) {
147603 var c = this.cache[abs];
147604 if (c === 'DIR' || Array.isArray(c)) return;
147605 }
147606
147607 this.matches[index][e] = true;
147608 var st = this.statCache[abs];
147609 if (st) this.emit('stat', e, st);
147610 this.emit('match', e);
147611};
147612
147613Glob.prototype._readdirInGlobStar = function (abs, cb) {
147614 if (this.aborted) return; // follow all symlinked directories forever
147615 // just proceed as if this is a non-globstar situation
147616
147617 if (this.follow) return this._readdir(abs, false, cb);
147618 var lstatkey = 'lstat\0' + abs;
147619 var self = this;
147620 var lstatcb = inflight(lstatkey, lstatcb_);
147621 if (lstatcb) fs.lstat(abs, lstatcb);
147622
147623 function lstatcb_(er, lstat) {
147624 if (er && er.code === 'ENOENT') return cb();
147625 var isSym = lstat && lstat.isSymbolicLink();
147626 self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
147627 // don't bother doing a readdir in that case.
147628
147629 if (!isSym && lstat && !lstat.isDirectory()) {
147630 self.cache[abs] = 'FILE';
147631 cb();
147632 } else self._readdir(abs, false, cb);
147633 }
147634};
147635
147636Glob.prototype._readdir = function (abs, inGlobStar, cb) {
147637 if (this.aborted) return;
147638 cb = inflight('readdir\0' + abs + '\0' + inGlobStar, cb);
147639 if (!cb) return; //console.error('RD %j %j', +inGlobStar, abs)
147640
147641 if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb);
147642
147643 if (ownProp(this.cache, abs)) {
147644 var c = this.cache[abs];
147645 if (!c || c === 'FILE') return cb();
147646 if (Array.isArray(c)) return cb(null, c);
147647 }
147648
147649 var self = this;
147650 fs.readdir(abs, readdirCb(this, abs, cb));
147651};
147652
147653function readdirCb(self, abs, cb) {
147654 return function (er, entries) {
147655 if (er) self._readdirError(abs, er, cb);else self._readdirEntries(abs, entries, cb);
147656 };
147657}
147658
147659Glob.prototype._readdirEntries = function (abs, entries, cb) {
147660 if (this.aborted) return; // if we haven't asked to stat everything, then just
147661 // assume that everything in there exists, so we can avoid
147662 // having to stat it a second time.
147663
147664 if (!this.mark && !this.stat) {
147665 for (var i = 0; i < entries.length; i++) {
147666 var e = entries[i];
147667 if (abs === '/') e = abs + e;else e = abs + '/' + e;
147668 this.cache[e] = true;
147669 }
147670 }
147671
147672 this.cache[abs] = entries;
147673 return cb(null, entries);
147674};
147675
147676Glob.prototype._readdirError = function (f, er, cb) {
147677 if (this.aborted) return; // handle errors, and cache the information
147678
147679 switch (er.code) {
147680 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
147681
147682 case 'ENOTDIR':
147683 // totally normal. means it *does* exist.
147684 var abs = this._makeAbs(f);
147685
147686 this.cache[abs] = 'FILE';
147687
147688 if (abs === this.cwdAbs) {
147689 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
147690 error.path = this.cwd;
147691 error.code = er.code;
147692 this.emit('error', error);
147693 this.abort();
147694 }
147695
147696 break;
147697
147698 case 'ENOENT': // not terribly unusual
147699
147700 case 'ELOOP':
147701 case 'ENAMETOOLONG':
147702 case 'UNKNOWN':
147703 this.cache[this._makeAbs(f)] = false;
147704 break;
147705
147706 default:
147707 // some unusual error. Treat as failure.
147708 this.cache[this._makeAbs(f)] = false;
147709
147710 if (this.strict) {
147711 this.emit('error', er); // If the error is handled, then we abort
147712 // if not, we threw out of here
147713
147714 this.abort();
147715 }
147716
147717 if (!this.silent) console.error('glob error', er);
147718 break;
147719 }
147720
147721 return cb();
147722};
147723
147724Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
147725 var self = this;
147726
147727 this._readdir(abs, inGlobStar, function (er, entries) {
147728 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
147729 });
147730};
147731
147732Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
147733 //console.error('pgs2', prefix, remain[0], entries)
147734 // no entries means not a dir, so it can never have matches
147735 // foo.txt/** doesn't match foo.txt
147736 if (!entries) return cb(); // test without the globstar, and with every child both below
147737 // and replacing the globstar.
147738
147739 var remainWithoutGlobStar = remain.slice(1);
147740 var gspref = prefix ? [prefix] : [];
147741 var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
147742
147743 this._process(noGlobStar, index, false, cb);
147744
147745 var isSym = this.symlinks[abs];
147746 var len = entries.length; // If it's a symlink, and we're in a globstar, then stop
147747
147748 if (isSym && inGlobStar) return cb();
147749
147750 for (var i = 0; i < len; i++) {
147751 var e = entries[i];
147752 if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
147753
147754 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
147755
147756 this._process(instead, index, true, cb);
147757
147758 var below = gspref.concat(entries[i], remain);
147759
147760 this._process(below, index, true, cb);
147761 }
147762
147763 cb();
147764};
147765
147766Glob.prototype._processSimple = function (prefix, index, cb) {
147767 // XXX review this. Shouldn't it be doing the mounting etc
147768 // before doing stat? kinda weird?
147769 var self = this;
147770
147771 this._stat(prefix, function (er, exists) {
147772 self._processSimple2(prefix, index, er, exists, cb);
147773 });
147774};
147775
147776Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
147777 //console.error('ps2', prefix, exists)
147778 if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
147779
147780 if (!exists) return cb();
147781
147782 if (prefix && isAbsolute(prefix) && !this.nomount) {
147783 var trail = /[\/\\]$/.test(prefix);
147784
147785 if (prefix.charAt(0) === '/') {
147786 prefix = path.join(this.root, prefix);
147787 } else {
147788 prefix = path.resolve(this.root, prefix);
147789 if (trail) prefix += '/';
147790 }
147791 }
147792
147793 if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
147794
147795 this._emitMatch(index, prefix);
147796
147797 cb();
147798}; // Returns either 'DIR', 'FILE', or false
147799
147800
147801Glob.prototype._stat = function (f, cb) {
147802 var abs = this._makeAbs(f);
147803
147804 var needDir = f.slice(-1) === '/';
147805 if (f.length > this.maxLength) return cb();
147806
147807 if (!this.stat && ownProp(this.cache, abs)) {
147808 var c = this.cache[abs];
147809 if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
147810
147811 if (!needDir || c === 'DIR') return cb(null, c);
147812 if (needDir && c === 'FILE') return cb(); // otherwise we have to stat, because maybe c=true
147813 // if we know it exists, but not what it is.
147814 }
147815
147816 var exists;
147817 var stat = this.statCache[abs];
147818
147819 if (stat !== undefined) {
147820 if (stat === false) return cb(null, stat);else {
147821 var type = stat.isDirectory() ? 'DIR' : 'FILE';
147822 if (needDir && type === 'FILE') return cb();else return cb(null, type, stat);
147823 }
147824 }
147825
147826 var self = this;
147827 var statcb = inflight('stat\0' + abs, lstatcb_);
147828 if (statcb) fs.lstat(abs, statcb);
147829
147830 function lstatcb_(er, lstat) {
147831 if (lstat && lstat.isSymbolicLink()) {
147832 // If it's a symlink, then treat it as the target, unless
147833 // the target does not exist, then treat it as a file.
147834 return fs.stat(abs, function (er, stat) {
147835 if (er) self._stat2(f, abs, null, lstat, cb);else self._stat2(f, abs, er, stat, cb);
147836 });
147837 } else {
147838 self._stat2(f, abs, er, lstat, cb);
147839 }
147840 }
147841};
147842
147843Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
147844 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
147845 this.statCache[abs] = false;
147846 return cb();
147847 }
147848
147849 var needDir = f.slice(-1) === '/';
147850 this.statCache[abs] = stat;
147851 if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat);
147852 var c = true;
147853 if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
147854 this.cache[abs] = this.cache[abs] || c;
147855 if (needDir && c === 'FILE') return cb();
147856 return cb(null, c, stat);
147857};
147858
147859/***/ }),
6a5a0f88 147860/* 900 */
eb39fafa
DC
147861/***/ (function(module, exports, __webpack_require__) {
147862
147863module.exports = realpath;
147864realpath.realpath = realpath;
147865realpath.sync = realpathSync;
147866realpath.realpathSync = realpathSync;
147867realpath.monkeypatch = monkeypatch;
147868realpath.unmonkeypatch = unmonkeypatch;
147869
6a5a0f88 147870var fs = __webpack_require__(825);
eb39fafa
DC
147871
147872var origRealpath = fs.realpath;
147873var origRealpathSync = fs.realpathSync;
147874var version = process.version;
147875var ok = /^v[0-5]\./.test(version);
147876
6a5a0f88 147877var old = __webpack_require__(901);
eb39fafa
DC
147878
147879function newError(er) {
147880 return er && er.syscall === 'realpath' && (er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG');
147881}
147882
147883function realpath(p, cache, cb) {
147884 if (ok) {
147885 return origRealpath(p, cache, cb);
147886 }
147887
147888 if (typeof cache === 'function') {
147889 cb = cache;
147890 cache = null;
147891 }
147892
147893 origRealpath(p, cache, function (er, result) {
147894 if (newError(er)) {
147895 old.realpath(p, cache, cb);
147896 } else {
147897 cb(er, result);
147898 }
147899 });
147900}
147901
147902function realpathSync(p, cache) {
147903 if (ok) {
147904 return origRealpathSync(p, cache);
147905 }
147906
147907 try {
147908 return origRealpathSync(p, cache);
147909 } catch (er) {
147910 if (newError(er)) {
147911 return old.realpathSync(p, cache);
147912 } else {
147913 throw er;
147914 }
147915 }
147916}
147917
147918function monkeypatch() {
147919 fs.realpath = realpath;
147920 fs.realpathSync = realpathSync;
147921}
147922
147923function unmonkeypatch() {
147924 fs.realpath = origRealpath;
147925 fs.realpathSync = origRealpathSync;
147926}
147927
147928/***/ }),
6a5a0f88 147929/* 901 */
eb39fafa
DC
147930/***/ (function(module, exports, __webpack_require__) {
147931
147932// Copyright Joyent, Inc. and other Node contributors.
147933//
147934// Permission is hereby granted, free of charge, to any person obtaining a
147935// copy of this software and associated documentation files (the
147936// "Software"), to deal in the Software without restriction, including
147937// without limitation the rights to use, copy, modify, merge, publish,
147938// distribute, sublicense, and/or sell copies of the Software, and to permit
147939// persons to whom the Software is furnished to do so, subject to the
147940// following conditions:
147941//
147942// The above copyright notice and this permission notice shall be included
147943// in all copies or substantial portions of the Software.
147944//
147945// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
147946// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
147947// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
147948// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
147949// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
147950// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
147951// USE OR OTHER DEALINGS IN THE SOFTWARE.
147952var pathModule = __webpack_require__(377);
147953
147954var isWindows = process.platform === 'win32';
147955
6a5a0f88 147956var fs = __webpack_require__(825); // JavaScript implementation of realpath, ported from node pre-v6
eb39fafa
DC
147957
147958
147959var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
147960
147961function rethrow() {
147962 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
147963 // is fairly slow to generate.
147964 var callback;
147965
147966 if (DEBUG) {
147967 var backtrace = new Error();
147968 callback = debugCallback;
147969 } else callback = missingCallback;
147970
147971 return callback;
147972
147973 function debugCallback(err) {
147974 if (err) {
147975 backtrace.message = err.message;
147976 err = backtrace;
147977 missingCallback(err);
147978 }
147979 }
147980
147981 function missingCallback(err) {
147982 if (err) {
147983 if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
147984 else if (!process.noDeprecation) {
147985 var msg = 'fs: missing callback ' + (err.stack || err.message);
147986 if (process.traceDeprecation) console.trace(msg);else console.error(msg);
147987 }
147988 }
147989 }
147990}
147991
147992function maybeCallback(cb) {
147993 return typeof cb === 'function' ? cb : rethrow();
147994}
147995
147996var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path
147997// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
147998
147999if (isWindows) {
148000 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
148001} else {
148002 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
148003} // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
148004
148005
148006if (isWindows) {
148007 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
148008} else {
148009 var splitRootRe = /^[\/]*/;
148010}
148011
148012exports.realpathSync = function realpathSync(p, cache) {
148013 // make p is absolute
148014 p = pathModule.resolve(p);
148015
148016 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
148017 return cache[p];
148018 }
148019
148020 var original = p,
148021 seenLinks = {},
148022 knownHard = {}; // current character position in p
148023
148024 var pos; // the partial path so far, including a trailing slash if any
148025
148026 var current; // the partial path without a trailing slash (except when pointing at a root)
148027
148028 var base; // the partial path scanned in the previous round, with slash
148029
148030 var previous;
148031 start();
148032
148033 function start() {
148034 // Skip over roots
148035 var m = splitRootRe.exec(p);
148036 pos = m[0].length;
148037 current = m[0];
148038 base = m[0];
148039 previous = ''; // On windows, check that the root exists. On unix there is no need.
148040
148041 if (isWindows && !knownHard[base]) {
148042 fs.lstatSync(base);
148043 knownHard[base] = true;
148044 }
148045 } // walk down the path, swapping out linked pathparts for their real
148046 // values
148047 // NB: p.length changes.
148048
148049
148050 while (pos < p.length) {
148051 // find the next part
148052 nextPartRe.lastIndex = pos;
148053 var result = nextPartRe.exec(p);
148054 previous = current;
148055 current += result[0];
148056 base = previous + result[1];
148057 pos = nextPartRe.lastIndex; // continue if not a symlink
148058
148059 if (knownHard[base] || cache && cache[base] === base) {
148060 continue;
148061 }
148062
148063 var resolvedLink;
148064
148065 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
148066 // some known symbolic link. no need to stat again.
148067 resolvedLink = cache[base];
148068 } else {
148069 var stat = fs.lstatSync(base);
148070
148071 if (!stat.isSymbolicLink()) {
148072 knownHard[base] = true;
148073 if (cache) cache[base] = base;
148074 continue;
148075 } // read the link if it wasn't read before
148076 // dev/ino always return 0 on windows, so skip the check.
148077
148078
148079 var linkTarget = null;
148080
148081 if (!isWindows) {
148082 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
148083
148084 if (seenLinks.hasOwnProperty(id)) {
148085 linkTarget = seenLinks[id];
148086 }
148087 }
148088
148089 if (linkTarget === null) {
148090 fs.statSync(base);
148091 linkTarget = fs.readlinkSync(base);
148092 }
148093
148094 resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache.
148095
148096 if (cache) cache[base] = resolvedLink;
148097 if (!isWindows) seenLinks[id] = linkTarget;
148098 } // resolve the link, then start over
148099
148100
148101 p = pathModule.resolve(resolvedLink, p.slice(pos));
148102 start();
148103 }
148104
148105 if (cache) cache[original] = p;
148106 return p;
148107};
148108
148109exports.realpath = function realpath(p, cache, cb) {
148110 if (typeof cb !== 'function') {
148111 cb = maybeCallback(cache);
148112 cache = null;
148113 } // make p is absolute
148114
148115
148116 p = pathModule.resolve(p);
148117
148118 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
148119 return process.nextTick(cb.bind(null, null, cache[p]));
148120 }
148121
148122 var original = p,
148123 seenLinks = {},
148124 knownHard = {}; // current character position in p
148125
148126 var pos; // the partial path so far, including a trailing slash if any
148127
148128 var current; // the partial path without a trailing slash (except when pointing at a root)
148129
148130 var base; // the partial path scanned in the previous round, with slash
148131
148132 var previous;
148133 start();
148134
148135 function start() {
148136 // Skip over roots
148137 var m = splitRootRe.exec(p);
148138 pos = m[0].length;
148139 current = m[0];
148140 base = m[0];
148141 previous = ''; // On windows, check that the root exists. On unix there is no need.
148142
148143 if (isWindows && !knownHard[base]) {
148144 fs.lstat(base, function (err) {
148145 if (err) return cb(err);
148146 knownHard[base] = true;
148147 LOOP();
148148 });
148149 } else {
148150 process.nextTick(LOOP);
148151 }
148152 } // walk down the path, swapping out linked pathparts for their real
148153 // values
148154
148155
148156 function LOOP() {
148157 // stop if scanned past end of path
148158 if (pos >= p.length) {
148159 if (cache) cache[original] = p;
148160 return cb(null, p);
148161 } // find the next part
148162
148163
148164 nextPartRe.lastIndex = pos;
148165 var result = nextPartRe.exec(p);
148166 previous = current;
148167 current += result[0];
148168 base = previous + result[1];
148169 pos = nextPartRe.lastIndex; // continue if not a symlink
148170
148171 if (knownHard[base] || cache && cache[base] === base) {
148172 return process.nextTick(LOOP);
148173 }
148174
148175 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
148176 // known symbolic link. no need to stat again.
148177 return gotResolvedLink(cache[base]);
148178 }
148179
148180 return fs.lstat(base, gotStat);
148181 }
148182
148183 function gotStat(err, stat) {
148184 if (err) return cb(err); // if not a symlink, skip to the next path part
148185
148186 if (!stat.isSymbolicLink()) {
148187 knownHard[base] = true;
148188 if (cache) cache[base] = base;
148189 return process.nextTick(LOOP);
148190 } // stat & read the link if not read before
148191 // call gotTarget as soon as the link target is known
148192 // dev/ino always return 0 on windows, so skip the check.
148193
148194
148195 if (!isWindows) {
148196 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
148197
148198 if (seenLinks.hasOwnProperty(id)) {
148199 return gotTarget(null, seenLinks[id], base);
148200 }
148201 }
148202
148203 fs.stat(base, function (err) {
148204 if (err) return cb(err);
148205 fs.readlink(base, function (err, target) {
148206 if (!isWindows) seenLinks[id] = target;
148207 gotTarget(err, target);
148208 });
148209 });
148210 }
148211
148212 function gotTarget(err, target, base) {
148213 if (err) return cb(err);
148214 var resolvedLink = pathModule.resolve(previous, target);
148215 if (cache) cache[base] = resolvedLink;
148216 gotResolvedLink(resolvedLink);
148217 }
148218
148219 function gotResolvedLink(resolvedLink) {
148220 // resolve the link, then start over
148221 p = pathModule.resolve(resolvedLink, p.slice(pos));
148222 start();
148223 }
148224};
148225
148226/***/ }),
6a5a0f88 148227/* 902 */
eb39fafa
DC
148228/***/ (function(module, exports, __webpack_require__) {
148229
148230try {
148231 var util = __webpack_require__(412);
148232 /* istanbul ignore next */
148233
148234
148235 if (typeof util.inherits !== 'function') throw '';
148236 module.exports = util.inherits;
148237} catch (e) {
148238 /* istanbul ignore next */
6a5a0f88 148239 module.exports = __webpack_require__(903);
eb39fafa
DC
148240}
148241
148242/***/ }),
6a5a0f88 148243/* 903 */
eb39fafa
DC
148244/***/ (function(module, exports) {
148245
148246if (typeof Object.create === 'function') {
148247 // implementation from standard node.js 'util' module
148248 module.exports = function inherits(ctor, superCtor) {
148249 if (superCtor) {
148250 ctor.super_ = superCtor;
148251 ctor.prototype = Object.create(superCtor.prototype, {
148252 constructor: {
148253 value: ctor,
148254 enumerable: false,
148255 writable: true,
148256 configurable: true
148257 }
148258 });
148259 }
148260 };
148261} else {
148262 // old school shim for old browsers
148263 module.exports = function inherits(ctor, superCtor) {
148264 if (superCtor) {
148265 ctor.super_ = superCtor;
148266
148267 var TempCtor = function TempCtor() {};
148268
148269 TempCtor.prototype = superCtor.prototype;
148270 ctor.prototype = new TempCtor();
148271 ctor.prototype.constructor = ctor;
148272 }
148273 };
148274}
148275
148276/***/ }),
6a5a0f88 148277/* 904 */
eb39fafa
DC
148278/***/ (function(module, exports) {
148279
148280module.exports = require("events");
148281
148282/***/ }),
6a5a0f88 148283/* 905 */
eb39fafa
DC
148284/***/ (function(module, exports, __webpack_require__) {
148285
148286"use strict";
148287
148288
148289function posix(path) {
148290 return path.charAt(0) === '/';
148291}
148292
148293function win32(path) {
148294 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
148295 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
148296 var result = splitDeviceRe.exec(path);
148297 var device = result[1] || '';
148298 var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute
148299
148300 return Boolean(result[2] || isUnc);
148301}
148302
148303module.exports = process.platform === 'win32' ? win32 : posix;
148304module.exports.posix = posix;
148305module.exports.win32 = win32;
148306
148307/***/ }),
6a5a0f88 148308/* 906 */
eb39fafa
DC
148309/***/ (function(module, exports, __webpack_require__) {
148310
148311module.exports = globSync;
148312globSync.GlobSync = GlobSync;
148313
6a5a0f88 148314var fs = __webpack_require__(825);
eb39fafa 148315
6a5a0f88 148316var rp = __webpack_require__(900);
eb39fafa 148317
6a5a0f88 148318var minimatch = __webpack_require__(845);
eb39fafa
DC
148319
148320var Minimatch = minimatch.Minimatch;
148321
6a5a0f88 148322var Glob = __webpack_require__(899).Glob;
eb39fafa
DC
148323
148324var util = __webpack_require__(412);
148325
148326var path = __webpack_require__(377);
148327
148328var assert = __webpack_require__(379);
148329
6a5a0f88 148330var isAbsolute = __webpack_require__(905);
eb39fafa 148331
6a5a0f88 148332var common = __webpack_require__(907);
eb39fafa
DC
148333
148334var alphasort = common.alphasort;
148335var alphasorti = common.alphasorti;
148336var setopts = common.setopts;
148337var ownProp = common.ownProp;
148338var childrenIgnored = common.childrenIgnored;
148339var isIgnored = common.isIgnored;
148340
148341function globSync(pattern, options) {
148342 if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
148343 return new GlobSync(pattern, options).found;
148344}
148345
148346function GlobSync(pattern, options) {
148347 if (!pattern) throw new Error('must provide pattern');
148348 if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
148349 if (!(this instanceof GlobSync)) return new GlobSync(pattern, options);
148350 setopts(this, pattern, options);
148351 if (this.noprocess) return this;
148352 var n = this.minimatch.set.length;
148353 this.matches = new Array(n);
148354
148355 for (var i = 0; i < n; i++) {
148356 this._process(this.minimatch.set[i], i, false);
148357 }
148358
148359 this._finish();
148360}
148361
148362GlobSync.prototype._finish = function () {
148363 assert(this instanceof GlobSync);
148364
148365 if (this.realpath) {
148366 var self = this;
148367 this.matches.forEach(function (matchset, index) {
148368 var set = self.matches[index] = Object.create(null);
148369
148370 for (var p in matchset) {
148371 try {
148372 p = self._makeAbs(p);
148373 var real = rp.realpathSync(p, self.realpathCache);
148374 set[real] = true;
148375 } catch (er) {
148376 if (er.syscall === 'stat') set[self._makeAbs(p)] = true;else throw er;
148377 }
148378 }
148379 });
148380 }
148381
148382 common.finish(this);
148383};
148384
148385GlobSync.prototype._process = function (pattern, index, inGlobStar) {
148386 assert(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings.
148387
148388 var n = 0;
148389
148390 while (typeof pattern[n] === 'string') {
148391 n++;
148392 } // now n is the index of the first one that is *not* a string.
148393 // See if there's anything else
148394
148395
148396 var prefix;
148397
148398 switch (n) {
148399 // if not, then this is rather simple
148400 case pattern.length:
148401 this._processSimple(pattern.join('/'), index);
148402
148403 return;
148404
148405 case 0:
148406 // pattern *starts* with some non-trivial item.
148407 // going to readdir(cwd), but not include the prefix in matches.
148408 prefix = null;
148409 break;
148410
148411 default:
148412 // pattern has some string bits in the front.
148413 // whatever it starts with, whether that's 'absolute' like /foo/bar,
148414 // or 'relative' like '../baz'
148415 prefix = pattern.slice(0, n).join('/');
148416 break;
148417 }
148418
148419 var remain = pattern.slice(n); // get the list of entries.
148420
148421 var read;
148422 if (prefix === null) read = '.';else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
148423 if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix;
148424 read = prefix;
148425 } else read = prefix;
148426
148427 var abs = this._makeAbs(read); //if ignored, skip processing
148428
148429
148430 if (childrenIgnored(this, read)) return;
148431 var isGlobStar = remain[0] === minimatch.GLOBSTAR;
148432 if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
148433};
148434
148435GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
148436 var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match!
148437
148438
148439 if (!entries) return; // It will only match dot entries if it starts with a dot, or if
148440 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
148441
148442 var pn = remain[0];
148443 var negate = !!this.minimatch.negate;
148444 var rawGlob = pn._glob;
148445 var dotOk = this.dot || rawGlob.charAt(0) === '.';
148446 var matchedEntries = [];
148447
148448 for (var i = 0; i < entries.length; i++) {
148449 var e = entries[i];
148450
148451 if (e.charAt(0) !== '.' || dotOk) {
148452 var m;
148453
148454 if (negate && !prefix) {
148455 m = !e.match(pn);
148456 } else {
148457 m = e.match(pn);
148458 }
148459
148460 if (m) matchedEntries.push(e);
148461 }
148462 }
148463
148464 var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
148465
148466 if (len === 0) return; // if this is the last remaining pattern bit, then no need for
148467 // an additional stat *unless* the user has specified mark or
148468 // stat explicitly. We know they exist, since readdir returned
148469 // them.
148470
148471 if (remain.length === 1 && !this.mark && !this.stat) {
148472 if (!this.matches[index]) this.matches[index] = Object.create(null);
148473
148474 for (var i = 0; i < len; i++) {
148475 var e = matchedEntries[i];
148476
148477 if (prefix) {
148478 if (prefix.slice(-1) !== '/') e = prefix + '/' + e;else e = prefix + e;
148479 }
148480
148481 if (e.charAt(0) === '/' && !this.nomount) {
148482 e = path.join(this.root, e);
148483 }
148484
148485 this._emitMatch(index, e);
148486 } // This was the last one, and no stats were needed
148487
148488
148489 return;
148490 } // now test all matched entries as stand-ins for that part
148491 // of the pattern.
148492
148493
148494 remain.shift();
148495
148496 for (var i = 0; i < len; i++) {
148497 var e = matchedEntries[i];
148498 var newPattern;
148499 if (prefix) newPattern = [prefix, e];else newPattern = [e];
148500
148501 this._process(newPattern.concat(remain), index, inGlobStar);
148502 }
148503};
148504
148505GlobSync.prototype._emitMatch = function (index, e) {
148506 if (isIgnored(this, e)) return;
148507
148508 var abs = this._makeAbs(e);
148509
148510 if (this.mark) e = this._mark(e);
148511
148512 if (this.absolute) {
148513 e = abs;
148514 }
148515
148516 if (this.matches[index][e]) return;
148517
148518 if (this.nodir) {
148519 var c = this.cache[abs];
148520 if (c === 'DIR' || Array.isArray(c)) return;
148521 }
148522
148523 this.matches[index][e] = true;
148524 if (this.stat) this._stat(e);
148525};
148526
148527GlobSync.prototype._readdirInGlobStar = function (abs) {
148528 // follow all symlinked directories forever
148529 // just proceed as if this is a non-globstar situation
148530 if (this.follow) return this._readdir(abs, false);
148531 var entries;
148532 var lstat;
148533 var stat;
148534
148535 try {
148536 lstat = fs.lstatSync(abs);
148537 } catch (er) {
148538 if (er.code === 'ENOENT') {
148539 // lstat failed, doesn't exist
148540 return null;
148541 }
148542 }
148543
148544 var isSym = lstat && lstat.isSymbolicLink();
148545 this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
148546 // don't bother doing a readdir in that case.
148547
148548 if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE';else entries = this._readdir(abs, false);
148549 return entries;
148550};
148551
148552GlobSync.prototype._readdir = function (abs, inGlobStar) {
148553 var entries;
148554 if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs);
148555
148556 if (ownProp(this.cache, abs)) {
148557 var c = this.cache[abs];
148558 if (!c || c === 'FILE') return null;
148559 if (Array.isArray(c)) return c;
148560 }
148561
148562 try {
148563 return this._readdirEntries(abs, fs.readdirSync(abs));
148564 } catch (er) {
148565 this._readdirError(abs, er);
148566
148567 return null;
148568 }
148569};
148570
148571GlobSync.prototype._readdirEntries = function (abs, entries) {
148572 // if we haven't asked to stat everything, then just
148573 // assume that everything in there exists, so we can avoid
148574 // having to stat it a second time.
148575 if (!this.mark && !this.stat) {
148576 for (var i = 0; i < entries.length; i++) {
148577 var e = entries[i];
148578 if (abs === '/') e = abs + e;else e = abs + '/' + e;
148579 this.cache[e] = true;
148580 }
148581 }
148582
148583 this.cache[abs] = entries; // mark and cache dir-ness
148584
148585 return entries;
148586};
148587
148588GlobSync.prototype._readdirError = function (f, er) {
148589 // handle errors, and cache the information
148590 switch (er.code) {
148591 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
148592
148593 case 'ENOTDIR':
148594 // totally normal. means it *does* exist.
148595 var abs = this._makeAbs(f);
148596
148597 this.cache[abs] = 'FILE';
148598
148599 if (abs === this.cwdAbs) {
148600 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
148601 error.path = this.cwd;
148602 error.code = er.code;
148603 throw error;
148604 }
148605
148606 break;
148607
148608 case 'ENOENT': // not terribly unusual
148609
148610 case 'ELOOP':
148611 case 'ENAMETOOLONG':
148612 case 'UNKNOWN':
148613 this.cache[this._makeAbs(f)] = false;
148614 break;
148615
148616 default:
148617 // some unusual error. Treat as failure.
148618 this.cache[this._makeAbs(f)] = false;
148619 if (this.strict) throw er;
148620 if (!this.silent) console.error('glob error', er);
148621 break;
148622 }
148623};
148624
148625GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
148626 var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches
148627 // foo.txt/** doesn't match foo.txt
148628
148629
148630 if (!entries) return; // test without the globstar, and with every child both below
148631 // and replacing the globstar.
148632
148633 var remainWithoutGlobStar = remain.slice(1);
148634 var gspref = prefix ? [prefix] : [];
148635 var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
148636
148637 this._process(noGlobStar, index, false);
148638
148639 var len = entries.length;
148640 var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop
148641
148642 if (isSym && inGlobStar) return;
148643
148644 for (var i = 0; i < len; i++) {
148645 var e = entries[i];
148646 if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
148647
148648 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
148649
148650 this._process(instead, index, true);
148651
148652 var below = gspref.concat(entries[i], remain);
148653
148654 this._process(below, index, true);
148655 }
148656};
148657
148658GlobSync.prototype._processSimple = function (prefix, index) {
148659 // XXX review this. Shouldn't it be doing the mounting etc
148660 // before doing stat? kinda weird?
148661 var exists = this._stat(prefix);
148662
148663 if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
148664
148665 if (!exists) return;
148666
148667 if (prefix && isAbsolute(prefix) && !this.nomount) {
148668 var trail = /[\/\\]$/.test(prefix);
148669
148670 if (prefix.charAt(0) === '/') {
148671 prefix = path.join(this.root, prefix);
148672 } else {
148673 prefix = path.resolve(this.root, prefix);
148674 if (trail) prefix += '/';
148675 }
148676 }
148677
148678 if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
148679
148680 this._emitMatch(index, prefix);
148681}; // Returns either 'DIR', 'FILE', or false
148682
148683
148684GlobSync.prototype._stat = function (f) {
148685 var abs = this._makeAbs(f);
148686
148687 var needDir = f.slice(-1) === '/';
148688 if (f.length > this.maxLength) return false;
148689
148690 if (!this.stat && ownProp(this.cache, abs)) {
148691 var c = this.cache[abs];
148692 if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
148693
148694 if (!needDir || c === 'DIR') return c;
148695 if (needDir && c === 'FILE') return false; // otherwise we have to stat, because maybe c=true
148696 // if we know it exists, but not what it is.
148697 }
148698
148699 var exists;
148700 var stat = this.statCache[abs];
148701
148702 if (!stat) {
148703 var lstat;
148704
148705 try {
148706 lstat = fs.lstatSync(abs);
148707 } catch (er) {
148708 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
148709 this.statCache[abs] = false;
148710 return false;
148711 }
148712 }
148713
148714 if (lstat && lstat.isSymbolicLink()) {
148715 try {
148716 stat = fs.statSync(abs);
148717 } catch (er) {
148718 stat = lstat;
148719 }
148720 } else {
148721 stat = lstat;
148722 }
148723 }
148724
148725 this.statCache[abs] = stat;
148726 var c = true;
148727 if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
148728 this.cache[abs] = this.cache[abs] || c;
148729 if (needDir && c === 'FILE') return false;
148730 return c;
148731};
148732
148733GlobSync.prototype._mark = function (p) {
148734 return common.mark(this, p);
148735};
148736
148737GlobSync.prototype._makeAbs = function (f) {
148738 return common.makeAbs(this, f);
148739};
148740
148741/***/ }),
6a5a0f88 148742/* 907 */
eb39fafa
DC
148743/***/ (function(module, exports, __webpack_require__) {
148744
148745exports.alphasort = alphasort;
148746exports.alphasorti = alphasorti;
148747exports.setopts = setopts;
148748exports.ownProp = ownProp;
148749exports.makeAbs = makeAbs;
148750exports.finish = finish;
148751exports.mark = mark;
148752exports.isIgnored = isIgnored;
148753exports.childrenIgnored = childrenIgnored;
148754
148755function ownProp(obj, field) {
148756 return Object.prototype.hasOwnProperty.call(obj, field);
148757}
148758
148759var path = __webpack_require__(377);
148760
6a5a0f88 148761var minimatch = __webpack_require__(845);
eb39fafa 148762
6a5a0f88 148763var isAbsolute = __webpack_require__(905);
eb39fafa
DC
148764
148765var Minimatch = minimatch.Minimatch;
148766
148767function alphasorti(a, b) {
148768 return a.toLowerCase().localeCompare(b.toLowerCase());
148769}
148770
148771function alphasort(a, b) {
148772 return a.localeCompare(b);
148773}
148774
148775function setupIgnores(self, options) {
148776 self.ignore = options.ignore || [];
148777 if (!Array.isArray(self.ignore)) self.ignore = [self.ignore];
148778
148779 if (self.ignore.length) {
148780 self.ignore = self.ignore.map(ignoreMap);
148781 }
148782} // ignore patterns are always in dot:true mode.
148783
148784
148785function ignoreMap(pattern) {
148786 var gmatcher = null;
148787
148788 if (pattern.slice(-3) === '/**') {
148789 var gpattern = pattern.replace(/(\/\*\*)+$/, '');
148790 gmatcher = new Minimatch(gpattern, {
148791 dot: true
148792 });
148793 }
148794
148795 return {
148796 matcher: new Minimatch(pattern, {
148797 dot: true
148798 }),
148799 gmatcher: gmatcher
148800 };
148801}
148802
148803function setopts(self, pattern, options) {
148804 if (!options) options = {}; // base-matching: just use globstar for that.
148805
148806 if (options.matchBase && -1 === pattern.indexOf("/")) {
148807 if (options.noglobstar) {
148808 throw new Error("base matching requires globstar");
148809 }
148810
148811 pattern = "**/" + pattern;
148812 }
148813
148814 self.silent = !!options.silent;
148815 self.pattern = pattern;
148816 self.strict = options.strict !== false;
148817 self.realpath = !!options.realpath;
148818 self.realpathCache = options.realpathCache || Object.create(null);
148819 self.follow = !!options.follow;
148820 self.dot = !!options.dot;
148821 self.mark = !!options.mark;
148822 self.nodir = !!options.nodir;
148823 if (self.nodir) self.mark = true;
148824 self.sync = !!options.sync;
148825 self.nounique = !!options.nounique;
148826 self.nonull = !!options.nonull;
148827 self.nosort = !!options.nosort;
148828 self.nocase = !!options.nocase;
148829 self.stat = !!options.stat;
148830 self.noprocess = !!options.noprocess;
148831 self.absolute = !!options.absolute;
148832 self.maxLength = options.maxLength || Infinity;
148833 self.cache = options.cache || Object.create(null);
148834 self.statCache = options.statCache || Object.create(null);
148835 self.symlinks = options.symlinks || Object.create(null);
148836 setupIgnores(self, options);
148837 self.changedCwd = false;
148838 var cwd = process.cwd();
148839 if (!ownProp(options, "cwd")) self.cwd = cwd;else {
148840 self.cwd = path.resolve(options.cwd);
148841 self.changedCwd = self.cwd !== cwd;
148842 }
148843 self.root = options.root || path.resolve(self.cwd, "/");
148844 self.root = path.resolve(self.root);
148845 if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`?
148846 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
148847
148848 self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
148849 if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
148850 self.nomount = !!options.nomount; // disable comments and negation in Minimatch.
148851 // Note that they are not supported in Glob itself anyway.
148852
148853 options.nonegate = true;
148854 options.nocomment = true;
148855 self.minimatch = new Minimatch(pattern, options);
148856 self.options = self.minimatch.options;
148857}
148858
148859function finish(self) {
148860 var nou = self.nounique;
148861 var all = nou ? [] : Object.create(null);
148862
148863 for (var i = 0, l = self.matches.length; i < l; i++) {
148864 var matches = self.matches[i];
148865
148866 if (!matches || Object.keys(matches).length === 0) {
148867 if (self.nonull) {
148868 // do like the shell, and spit out the literal glob
148869 var literal = self.minimatch.globSet[i];
148870 if (nou) all.push(literal);else all[literal] = true;
148871 }
148872 } else {
148873 // had matches
148874 var m = Object.keys(matches);
148875 if (nou) all.push.apply(all, m);else m.forEach(function (m) {
148876 all[m] = true;
148877 });
148878 }
148879 }
148880
148881 if (!nou) all = Object.keys(all);
148882 if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort); // at *some* point we statted all of these
148883
148884 if (self.mark) {
148885 for (var i = 0; i < all.length; i++) {
148886 all[i] = self._mark(all[i]);
148887 }
148888
148889 if (self.nodir) {
148890 all = all.filter(function (e) {
148891 var notDir = !/\/$/.test(e);
148892 var c = self.cache[e] || self.cache[makeAbs(self, e)];
148893 if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c);
148894 return notDir;
148895 });
148896 }
148897 }
148898
148899 if (self.ignore.length) all = all.filter(function (m) {
148900 return !isIgnored(self, m);
148901 });
148902 self.found = all;
148903}
148904
148905function mark(self, p) {
148906 var abs = makeAbs(self, p);
148907 var c = self.cache[abs];
148908 var m = p;
148909
148910 if (c) {
148911 var isDir = c === 'DIR' || Array.isArray(c);
148912 var slash = p.slice(-1) === '/';
148913 if (isDir && !slash) m += '/';else if (!isDir && slash) m = m.slice(0, -1);
148914
148915 if (m !== p) {
148916 var mabs = makeAbs(self, m);
148917 self.statCache[mabs] = self.statCache[abs];
148918 self.cache[mabs] = self.cache[abs];
148919 }
148920 }
148921
148922 return m;
148923} // lotta situps...
148924
148925
148926function makeAbs(self, f) {
148927 var abs = f;
148928
148929 if (f.charAt(0) === '/') {
148930 abs = path.join(self.root, f);
148931 } else if (isAbsolute(f) || f === '') {
148932 abs = f;
148933 } else if (self.changedCwd) {
148934 abs = path.resolve(self.cwd, f);
148935 } else {
148936 abs = path.resolve(f);
148937 }
148938
148939 if (process.platform === 'win32') abs = abs.replace(/\\/g, '/');
148940 return abs;
148941} // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
148942// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
148943
148944
148945function isIgnored(self, path) {
148946 if (!self.ignore.length) return false;
148947 return self.ignore.some(function (item) {
148948 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path));
148949 });
148950}
148951
148952function childrenIgnored(self, path) {
148953 if (!self.ignore.length) return false;
148954 return self.ignore.some(function (item) {
148955 return !!(item.gmatcher && item.gmatcher.match(path));
148956 });
148957}
148958
148959/***/ }),
6a5a0f88 148960/* 908 */
eb39fafa
DC
148961/***/ (function(module, exports, __webpack_require__) {
148962
6a5a0f88 148963var wrappy = __webpack_require__(909);
eb39fafa
DC
148964
148965var reqs = Object.create(null);
148966
6a5a0f88 148967var once = __webpack_require__(910);
eb39fafa
DC
148968
148969module.exports = wrappy(inflight);
148970
148971function inflight(key, cb) {
148972 if (reqs[key]) {
148973 reqs[key].push(cb);
148974 return null;
148975 } else {
148976 reqs[key] = [cb];
148977 return makeres(key);
148978 }
148979}
148980
148981function makeres(key) {
148982 return once(function RES() {
148983 var cbs = reqs[key];
148984 var len = cbs.length;
148985 var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this
148986 // pass should be queued for later execution if something in the
148987 // list of callbacks throws, or if it should just be discarded.
148988 // However, it's such an edge case that it hardly matters, and either
148989 // choice is likely as surprising as the other.
148990 // As it happens, we do go ahead and schedule it for later execution.
148991
148992 try {
148993 for (var i = 0; i < len; i++) {
148994 cbs[i].apply(null, args);
148995 }
148996 } finally {
148997 if (cbs.length > len) {
148998 // added more in the interim.
148999 // de-zalgo, just in case, but don't call again.
149000 cbs.splice(0, len);
149001 process.nextTick(function () {
149002 RES.apply(null, args);
149003 });
149004 } else {
149005 delete reqs[key];
149006 }
149007 }
149008 });
149009}
149010
149011function slice(args) {
149012 var length = args.length;
149013 var array = [];
149014
149015 for (var i = 0; i < length; i++) array[i] = args[i];
149016
149017 return array;
149018}
149019
149020/***/ }),
6a5a0f88 149021/* 909 */
eb39fafa
DC
149022/***/ (function(module, exports) {
149023
149024// Returns a wrapper function that returns a wrapped callback
149025// The wrapper function should do some stuff, and return a
149026// presumably different callback function.
149027// This makes sure that own properties are retained, so that
149028// decorations and such are not lost along the way.
149029module.exports = wrappy;
149030
149031function wrappy(fn, cb) {
149032 if (fn && cb) return wrappy(fn)(cb);
149033 if (typeof fn !== 'function') throw new TypeError('need wrapper function');
149034 Object.keys(fn).forEach(function (k) {
149035 wrapper[k] = fn[k];
149036 });
149037 return wrapper;
149038
149039 function wrapper() {
149040 var args = new Array(arguments.length);
149041
149042 for (var i = 0; i < args.length; i++) {
149043 args[i] = arguments[i];
149044 }
149045
149046 var ret = fn.apply(this, args);
149047 var cb = args[args.length - 1];
149048
149049 if (typeof ret === 'function' && ret !== cb) {
149050 Object.keys(cb).forEach(function (k) {
149051 ret[k] = cb[k];
149052 });
149053 }
149054
149055 return ret;
149056 }
149057}
149058
149059/***/ }),
6a5a0f88 149060/* 910 */
eb39fafa
DC
149061/***/ (function(module, exports, __webpack_require__) {
149062
6a5a0f88 149063var wrappy = __webpack_require__(909);
eb39fafa
DC
149064
149065module.exports = wrappy(once);
149066module.exports.strict = wrappy(onceStrict);
149067once.proto = once(function () {
149068 Object.defineProperty(Function.prototype, 'once', {
149069 value: function value() {
149070 return once(this);
149071 },
149072 configurable: true
149073 });
149074 Object.defineProperty(Function.prototype, 'onceStrict', {
149075 value: function value() {
149076 return onceStrict(this);
149077 },
149078 configurable: true
149079 });
149080});
149081
149082function once(fn) {
149083 var f = function f() {
149084 if (f.called) return f.value;
149085 f.called = true;
149086 return f.value = fn.apply(this, arguments);
149087 };
149088
149089 f.called = false;
149090 return f;
149091}
149092
149093function onceStrict(fn) {
149094 var f = function f() {
149095 if (f.called) throw new Error(f.onceError);
149096 f.called = true;
149097 return f.value = fn.apply(this, arguments);
149098 };
149099
149100 var name = fn.name || 'Function wrapped with `once`';
149101 f.onceError = name + " shouldn't be called more than once";
149102 f.called = false;
149103 return f;
149104}
149105
149106/***/ }),
6a5a0f88 149107/* 911 */
eb39fafa
DC
149108/***/ (function(module, exports) {
149109
149110module.exports = function (obj, opts) {
149111 if (!opts) opts = {};
149112 if (typeof opts === 'function') opts = {
149113 cmp: opts
149114 };
149115 var space = opts.space || '';
149116 if (typeof space === 'number') space = Array(space + 1).join(' ');
149117 var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
149118
149119 var replacer = opts.replacer || function (key, value) {
149120 return value;
149121 };
149122
149123 var cmp = opts.cmp && function (f) {
149124 return function (node) {
149125 return function (a, b) {
149126 var aobj = {
149127 key: a,
149128 value: node[a]
149129 };
149130 var bobj = {
149131 key: b,
149132 value: node[b]
149133 };
149134 return f(aobj, bobj);
149135 };
149136 };
149137 }(opts.cmp);
149138
149139 var seen = [];
149140 return function stringify(parent, key, node, level) {
149141 var indent = space ? '\n' + new Array(level + 1).join(space) : '';
149142 var colonSeparator = space ? ': ' : ':';
149143
149144 if (node && node.toJSON && typeof node.toJSON === 'function') {
149145 node = node.toJSON();
149146 }
149147
149148 node = replacer.call(parent, key, node);
149149
149150 if (node === undefined) {
149151 return;
149152 }
149153
149154 if (typeof node !== 'object' || node === null) {
149155 return JSON.stringify(node);
149156 }
149157
149158 if (isArray(node)) {
149159 var out = [];
149160
149161 for (var i = 0; i < node.length; i++) {
149162 var item = stringify(node, i, node[i], level + 1) || JSON.stringify(null);
149163 out.push(indent + space + item);
149164 }
149165
149166 return '[' + out.join(',') + indent + ']';
149167 } else {
149168 if (seen.indexOf(node) !== -1) {
149169 if (cycles) return JSON.stringify('__cycle__');
149170 throw new TypeError('Converting circular structure to JSON');
149171 } else seen.push(node);
149172
149173 var keys = objectKeys(node).sort(cmp && cmp(node));
149174 var out = [];
149175
149176 for (var i = 0; i < keys.length; i++) {
149177 var key = keys[i];
149178 var value = stringify(node, key, node[key], level + 1);
149179 if (!value) continue;
149180 var keyValue = JSON.stringify(key) + colonSeparator + value;
149181 ;
149182 out.push(indent + space + keyValue);
149183 }
149184
149185 seen.splice(seen.indexOf(node), 1);
149186 return '{' + out.join(',') + indent + '}';
149187 }
149188 }({
149189 '': obj
149190 }, '', obj, 0);
149191};
149192
149193var isArray = Array.isArray || function (x) {
149194 return {}.toString.call(x) === '[object Array]';
149195};
149196
149197var objectKeys = Object.keys || function (obj) {
149198 var has = Object.prototype.hasOwnProperty || function () {
149199 return true;
149200 };
149201
149202 var keys = [];
149203
149204 for (var key in obj) {
149205 if (has.call(obj, key)) keys.push(key);
149206 }
149207
149208 return keys;
149209};
149210
149211/***/ })
756e2b86 149212/******/ ]);