UNPKG

1.16 MBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v1.9.3
4 Wed, 10 Apr 2019 07:08:17 GMT - commit 516a06db40da5552910ff95a16aef13e2d3eca19
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11import util$2 from 'util';
12import path, { relative, basename, extname, dirname, resolve as resolve$1, sep } from 'path';
13import * as acorn__default from 'acorn';
14import { tokTypes, Parser as Parser$1 } from 'acorn';
15import fs__default, { writeFile as writeFile$1, readdirSync, mkdirSync, readFileSync, lstatSync, realpathSync, statSync, watch as watch$1 } from 'fs';
16import { EventEmitter } from 'events';
17import tty from 'tty';
18import net from 'net';
19import url from 'url';
20import module$1 from 'module';
21
22/*! *****************************************************************************
23Copyright (c) Microsoft Corporation. All rights reserved.
24Licensed under the Apache License, Version 2.0 (the "License"); you may not use
25this file except in compliance with the License. You may obtain a copy of the
26License at http://www.apache.org/licenses/LICENSE-2.0
27
28THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
29KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
30WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
31MERCHANTABLITY OR NON-INFRINGEMENT.
32
33See the Apache Version 2.0 License for specific language governing permissions
34and limitations under the License.
35***************************************************************************** */
36/* global Reflect, Promise */
37
38var extendStatics = function(d, b) {
39 extendStatics = Object.setPrototypeOf ||
40 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42 return extendStatics(d, b);
43};
44
45function __extends(d, b) {
46 extendStatics(d, b);
47 function __() { this.constructor = d; }
48 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
49}
50
51var __assign = function() {
52 __assign = Object.assign || function __assign(t) {
53 for (var s, i = 1, n = arguments.length; i < n; i++) {
54 s = arguments[i];
55 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
56 }
57 return t;
58 };
59 return __assign.apply(this, arguments);
60};
61
62function __rest(s, e) {
63 var t = {};
64 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
65 t[p] = s[p];
66 if (s != null && typeof Object.getOwnPropertySymbols === "function")
67 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
68 t[p[i]] = s[p[i]];
69 return t;
70}
71
72function __decorate(decorators, target, key, desc) {
73 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
74 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
75 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
76 return c > 3 && r && Object.defineProperty(target, key, r), r;
77}
78
79function __param(paramIndex, decorator) {
80 return function (target, key) { decorator(target, key, paramIndex); }
81}
82
83function __metadata(metadataKey, metadataValue) {
84 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
85}
86
87function __awaiter(thisArg, _arguments, P, generator) {
88 return new (P || (P = Promise))(function (resolve, reject) {
89 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
90 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
91 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
92 step((generator = generator.apply(thisArg, _arguments || [])).next());
93 });
94}
95
96function __generator(thisArg, body) {
97 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
98 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
99 function verb(n) { return function (v) { return step([n, v]); }; }
100 function step(op) {
101 if (f) throw new TypeError("Generator is already executing.");
102 while (_) try {
103 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
104 if (y = 0, t) op = [op[0] & 2, t.value];
105 switch (op[0]) {
106 case 0: case 1: t = op; break;
107 case 4: _.label++; return { value: op[1], done: false };
108 case 5: _.label++; y = op[1]; op = [0]; continue;
109 case 7: op = _.ops.pop(); _.trys.pop(); continue;
110 default:
111 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
112 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
113 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
114 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
115 if (t[2]) _.ops.pop();
116 _.trys.pop(); continue;
117 }
118 op = body.call(thisArg, _);
119 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
120 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
121 }
122}
123
124function __exportStar(m, exports) {
125 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
126}
127
128function __values(o) {
129 var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
130 if (m) return m.call(o);
131 return {
132 next: function () {
133 if (o && i >= o.length) o = void 0;
134 return { value: o && o[i++], done: !o };
135 }
136 };
137}
138
139function __read(o, n) {
140 var m = typeof Symbol === "function" && o[Symbol.iterator];
141 if (!m) return o;
142 var i = m.call(o), r, ar = [], e;
143 try {
144 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
145 }
146 catch (error) { e = { error: error }; }
147 finally {
148 try {
149 if (r && !r.done && (m = i["return"])) m.call(i);
150 }
151 finally { if (e) throw e.error; }
152 }
153 return ar;
154}
155
156function __spread() {
157 for (var ar = [], i = 0; i < arguments.length; i++)
158 ar = ar.concat(__read(arguments[i]));
159 return ar;
160}
161
162function __await(v) {
163 return this instanceof __await ? (this.v = v, this) : new __await(v);
164}
165
166function __asyncGenerator(thisArg, _arguments, generator) {
167 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
168 var g = generator.apply(thisArg, _arguments || []), i, q = [];
169 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
170 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
171 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
172 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
173 function fulfill(value) { resume("next", value); }
174 function reject(value) { resume("throw", value); }
175 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
176}
177
178function __asyncDelegator(o) {
179 var i, p;
180 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
181 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
182}
183
184function __asyncValues(o) {
185 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
186 var m = o[Symbol.asyncIterator], i;
187 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
188 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
189 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
190}
191
192function __makeTemplateObject(cooked, raw) {
193 if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
194 return cooked;
195}
196function __importStar(mod) {
197 if (mod && mod.__esModule) return mod;
198 var result = {};
199 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
200 result.default = mod;
201 return result;
202}
203
204function __importDefault(mod) {
205 return (mod && mod.__esModule) ? mod : { default: mod };
206}
207
208var tslib_1 = /*#__PURE__*/Object.freeze({
209 __extends: __extends,
210 get __assign () { return __assign; },
211 __rest: __rest,
212 __decorate: __decorate,
213 __param: __param,
214 __metadata: __metadata,
215 __awaiter: __awaiter,
216 __generator: __generator,
217 __exportStar: __exportStar,
218 __values: __values,
219 __read: __read,
220 __spread: __spread,
221 __await: __await,
222 __asyncGenerator: __asyncGenerator,
223 __asyncDelegator: __asyncDelegator,
224 __asyncValues: __asyncValues,
225 __makeTemplateObject: __makeTemplateObject,
226 __importStar: __importStar,
227 __importDefault: __importDefault
228});
229
230var version = "1.9.3";
231
232var minimalisticAssert = assert;
233
234function assert(val, msg) {
235 if (!val)
236 throw new Error(msg || 'Assertion failed');
237}
238
239assert.equal = function assertEqual(l, r, msg) {
240 if (l != r)
241 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
242};
243
244var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
245
246function createCommonjsModule(fn, module) {
247 return module = { exports: {} }, fn(module, module.exports), module.exports;
248}
249
250var inherits_browser = createCommonjsModule(function (module) {
251if (typeof Object.create === 'function') {
252 // implementation from standard node.js 'util' module
253 module.exports = function inherits(ctor, superCtor) {
254 ctor.super_ = superCtor;
255 ctor.prototype = Object.create(superCtor.prototype, {
256 constructor: {
257 value: ctor,
258 enumerable: false,
259 writable: true,
260 configurable: true
261 }
262 });
263 };
264} else {
265 // old school shim for old browsers
266 module.exports = function inherits(ctor, superCtor) {
267 ctor.super_ = superCtor;
268 var TempCtor = function () {};
269 TempCtor.prototype = superCtor.prototype;
270 ctor.prototype = new TempCtor();
271 ctor.prototype.constructor = ctor;
272 };
273}
274});
275
276var inherits = createCommonjsModule(function (module) {
277try {
278 var util = util$2;
279 if (typeof util.inherits !== 'function') throw '';
280 module.exports = util.inherits;
281} catch (e) {
282 module.exports = inherits_browser;
283}
284});
285
286var inherits_1 = inherits;
287
288function isSurrogatePair(msg, i) {
289 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
290 return false;
291 }
292 if (i < 0 || i + 1 >= msg.length) {
293 return false;
294 }
295 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
296}
297
298function toArray(msg, enc) {
299 if (Array.isArray(msg))
300 return msg.slice();
301 if (!msg)
302 return [];
303 var res = [];
304 if (typeof msg === 'string') {
305 if (!enc) {
306 // Inspired by stringToUtf8ByteArray() in closure-library by Google
307 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
308 // Apache License 2.0
309 // https://github.com/google/closure-library/blob/master/LICENSE
310 var p = 0;
311 for (var i = 0; i < msg.length; i++) {
312 var c = msg.charCodeAt(i);
313 if (c < 128) {
314 res[p++] = c;
315 } else if (c < 2048) {
316 res[p++] = (c >> 6) | 192;
317 res[p++] = (c & 63) | 128;
318 } else if (isSurrogatePair(msg, i)) {
319 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
320 res[p++] = (c >> 18) | 240;
321 res[p++] = ((c >> 12) & 63) | 128;
322 res[p++] = ((c >> 6) & 63) | 128;
323 res[p++] = (c & 63) | 128;
324 } else {
325 res[p++] = (c >> 12) | 224;
326 res[p++] = ((c >> 6) & 63) | 128;
327 res[p++] = (c & 63) | 128;
328 }
329 }
330 } else if (enc === 'hex') {
331 msg = msg.replace(/[^a-z0-9]+/ig, '');
332 if (msg.length % 2 !== 0)
333 msg = '0' + msg;
334 for (i = 0; i < msg.length; i += 2)
335 res.push(parseInt(msg[i] + msg[i + 1], 16));
336 }
337 } else {
338 for (i = 0; i < msg.length; i++)
339 res[i] = msg[i] | 0;
340 }
341 return res;
342}
343var toArray_1 = toArray;
344
345function toHex(msg) {
346 var res = '';
347 for (var i = 0; i < msg.length; i++)
348 res += zero2(msg[i].toString(16));
349 return res;
350}
351var toHex_1 = toHex;
352
353function htonl(w) {
354 var res = (w >>> 24) |
355 ((w >>> 8) & 0xff00) |
356 ((w << 8) & 0xff0000) |
357 ((w & 0xff) << 24);
358 return res >>> 0;
359}
360var htonl_1 = htonl;
361
362function toHex32(msg, endian) {
363 var res = '';
364 for (var i = 0; i < msg.length; i++) {
365 var w = msg[i];
366 if (endian === 'little')
367 w = htonl(w);
368 res += zero8(w.toString(16));
369 }
370 return res;
371}
372var toHex32_1 = toHex32;
373
374function zero2(word) {
375 if (word.length === 1)
376 return '0' + word;
377 else
378 return word;
379}
380var zero2_1 = zero2;
381
382function zero8(word) {
383 if (word.length === 7)
384 return '0' + word;
385 else if (word.length === 6)
386 return '00' + word;
387 else if (word.length === 5)
388 return '000' + word;
389 else if (word.length === 4)
390 return '0000' + word;
391 else if (word.length === 3)
392 return '00000' + word;
393 else if (word.length === 2)
394 return '000000' + word;
395 else if (word.length === 1)
396 return '0000000' + word;
397 else
398 return word;
399}
400var zero8_1 = zero8;
401
402function join32(msg, start, end, endian) {
403 var len = end - start;
404 minimalisticAssert(len % 4 === 0);
405 var res = new Array(len / 4);
406 for (var i = 0, k = start; i < res.length; i++, k += 4) {
407 var w;
408 if (endian === 'big')
409 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
410 else
411 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
412 res[i] = w >>> 0;
413 }
414 return res;
415}
416var join32_1 = join32;
417
418function split32(msg, endian) {
419 var res = new Array(msg.length * 4);
420 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
421 var m = msg[i];
422 if (endian === 'big') {
423 res[k] = m >>> 24;
424 res[k + 1] = (m >>> 16) & 0xff;
425 res[k + 2] = (m >>> 8) & 0xff;
426 res[k + 3] = m & 0xff;
427 } else {
428 res[k + 3] = m >>> 24;
429 res[k + 2] = (m >>> 16) & 0xff;
430 res[k + 1] = (m >>> 8) & 0xff;
431 res[k] = m & 0xff;
432 }
433 }
434 return res;
435}
436var split32_1 = split32;
437
438function rotr32(w, b) {
439 return (w >>> b) | (w << (32 - b));
440}
441var rotr32_1 = rotr32;
442
443function rotl32(w, b) {
444 return (w << b) | (w >>> (32 - b));
445}
446var rotl32_1 = rotl32;
447
448function sum32(a, b) {
449 return (a + b) >>> 0;
450}
451var sum32_1 = sum32;
452
453function sum32_3(a, b, c) {
454 return (a + b + c) >>> 0;
455}
456var sum32_3_1 = sum32_3;
457
458function sum32_4(a, b, c, d) {
459 return (a + b + c + d) >>> 0;
460}
461var sum32_4_1 = sum32_4;
462
463function sum32_5(a, b, c, d, e) {
464 return (a + b + c + d + e) >>> 0;
465}
466var sum32_5_1 = sum32_5;
467
468function sum64(buf, pos, ah, al) {
469 var bh = buf[pos];
470 var bl = buf[pos + 1];
471
472 var lo = (al + bl) >>> 0;
473 var hi = (lo < al ? 1 : 0) + ah + bh;
474 buf[pos] = hi >>> 0;
475 buf[pos + 1] = lo;
476}
477var sum64_1 = sum64;
478
479function sum64_hi(ah, al, bh, bl) {
480 var lo = (al + bl) >>> 0;
481 var hi = (lo < al ? 1 : 0) + ah + bh;
482 return hi >>> 0;
483}
484var sum64_hi_1 = sum64_hi;
485
486function sum64_lo(ah, al, bh, bl) {
487 var lo = al + bl;
488 return lo >>> 0;
489}
490var sum64_lo_1 = sum64_lo;
491
492function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
493 var carry = 0;
494 var lo = al;
495 lo = (lo + bl) >>> 0;
496 carry += lo < al ? 1 : 0;
497 lo = (lo + cl) >>> 0;
498 carry += lo < cl ? 1 : 0;
499 lo = (lo + dl) >>> 0;
500 carry += lo < dl ? 1 : 0;
501
502 var hi = ah + bh + ch + dh + carry;
503 return hi >>> 0;
504}
505var sum64_4_hi_1 = sum64_4_hi;
506
507function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
508 var lo = al + bl + cl + dl;
509 return lo >>> 0;
510}
511var sum64_4_lo_1 = sum64_4_lo;
512
513function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
514 var carry = 0;
515 var lo = al;
516 lo = (lo + bl) >>> 0;
517 carry += lo < al ? 1 : 0;
518 lo = (lo + cl) >>> 0;
519 carry += lo < cl ? 1 : 0;
520 lo = (lo + dl) >>> 0;
521 carry += lo < dl ? 1 : 0;
522 lo = (lo + el) >>> 0;
523 carry += lo < el ? 1 : 0;
524
525 var hi = ah + bh + ch + dh + eh + carry;
526 return hi >>> 0;
527}
528var sum64_5_hi_1 = sum64_5_hi;
529
530function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
531 var lo = al + bl + cl + dl + el;
532
533 return lo >>> 0;
534}
535var sum64_5_lo_1 = sum64_5_lo;
536
537function rotr64_hi(ah, al, num) {
538 var r = (al << (32 - num)) | (ah >>> num);
539 return r >>> 0;
540}
541var rotr64_hi_1 = rotr64_hi;
542
543function rotr64_lo(ah, al, num) {
544 var r = (ah << (32 - num)) | (al >>> num);
545 return r >>> 0;
546}
547var rotr64_lo_1 = rotr64_lo;
548
549function shr64_hi(ah, al, num) {
550 return ah >>> num;
551}
552var shr64_hi_1 = shr64_hi;
553
554function shr64_lo(ah, al, num) {
555 var r = (ah << (32 - num)) | (al >>> num);
556 return r >>> 0;
557}
558var shr64_lo_1 = shr64_lo;
559
560var utils = {
561 inherits: inherits_1,
562 toArray: toArray_1,
563 toHex: toHex_1,
564 htonl: htonl_1,
565 toHex32: toHex32_1,
566 zero2: zero2_1,
567 zero8: zero8_1,
568 join32: join32_1,
569 split32: split32_1,
570 rotr32: rotr32_1,
571 rotl32: rotl32_1,
572 sum32: sum32_1,
573 sum32_3: sum32_3_1,
574 sum32_4: sum32_4_1,
575 sum32_5: sum32_5_1,
576 sum64: sum64_1,
577 sum64_hi: sum64_hi_1,
578 sum64_lo: sum64_lo_1,
579 sum64_4_hi: sum64_4_hi_1,
580 sum64_4_lo: sum64_4_lo_1,
581 sum64_5_hi: sum64_5_hi_1,
582 sum64_5_lo: sum64_5_lo_1,
583 rotr64_hi: rotr64_hi_1,
584 rotr64_lo: rotr64_lo_1,
585 shr64_hi: shr64_hi_1,
586 shr64_lo: shr64_lo_1
587};
588
589function BlockHash() {
590 this.pending = null;
591 this.pendingTotal = 0;
592 this.blockSize = this.constructor.blockSize;
593 this.outSize = this.constructor.outSize;
594 this.hmacStrength = this.constructor.hmacStrength;
595 this.padLength = this.constructor.padLength / 8;
596 this.endian = 'big';
597
598 this._delta8 = this.blockSize / 8;
599 this._delta32 = this.blockSize / 32;
600}
601var BlockHash_1 = BlockHash;
602
603BlockHash.prototype.update = function update(msg, enc) {
604 // Convert message to array, pad it, and join into 32bit blocks
605 msg = utils.toArray(msg, enc);
606 if (!this.pending)
607 this.pending = msg;
608 else
609 this.pending = this.pending.concat(msg);
610 this.pendingTotal += msg.length;
611
612 // Enough data, try updating
613 if (this.pending.length >= this._delta8) {
614 msg = this.pending;
615
616 // Process pending data in blocks
617 var r = msg.length % this._delta8;
618 this.pending = msg.slice(msg.length - r, msg.length);
619 if (this.pending.length === 0)
620 this.pending = null;
621
622 msg = utils.join32(msg, 0, msg.length - r, this.endian);
623 for (var i = 0; i < msg.length; i += this._delta32)
624 this._update(msg, i, i + this._delta32);
625 }
626
627 return this;
628};
629
630BlockHash.prototype.digest = function digest(enc) {
631 this.update(this._pad());
632 minimalisticAssert(this.pending === null);
633
634 return this._digest(enc);
635};
636
637BlockHash.prototype._pad = function pad() {
638 var len = this.pendingTotal;
639 var bytes = this._delta8;
640 var k = bytes - ((len + this.padLength) % bytes);
641 var res = new Array(k + this.padLength);
642 res[0] = 0x80;
643 for (var i = 1; i < k; i++)
644 res[i] = 0;
645
646 // Append length
647 len <<= 3;
648 if (this.endian === 'big') {
649 for (var t = 8; t < this.padLength; t++)
650 res[i++] = 0;
651
652 res[i++] = 0;
653 res[i++] = 0;
654 res[i++] = 0;
655 res[i++] = 0;
656 res[i++] = (len >>> 24) & 0xff;
657 res[i++] = (len >>> 16) & 0xff;
658 res[i++] = (len >>> 8) & 0xff;
659 res[i++] = len & 0xff;
660 } else {
661 res[i++] = len & 0xff;
662 res[i++] = (len >>> 8) & 0xff;
663 res[i++] = (len >>> 16) & 0xff;
664 res[i++] = (len >>> 24) & 0xff;
665 res[i++] = 0;
666 res[i++] = 0;
667 res[i++] = 0;
668 res[i++] = 0;
669
670 for (t = 8; t < this.padLength; t++)
671 res[i++] = 0;
672 }
673
674 return res;
675};
676
677var common = {
678 BlockHash: BlockHash_1
679};
680
681var rotr32$1 = utils.rotr32;
682
683function ft_1(s, x, y, z) {
684 if (s === 0)
685 return ch32(x, y, z);
686 if (s === 1 || s === 3)
687 return p32(x, y, z);
688 if (s === 2)
689 return maj32(x, y, z);
690}
691var ft_1_1 = ft_1;
692
693function ch32(x, y, z) {
694 return (x & y) ^ ((~x) & z);
695}
696var ch32_1 = ch32;
697
698function maj32(x, y, z) {
699 return (x & y) ^ (x & z) ^ (y & z);
700}
701var maj32_1 = maj32;
702
703function p32(x, y, z) {
704 return x ^ y ^ z;
705}
706var p32_1 = p32;
707
708function s0_256(x) {
709 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
710}
711var s0_256_1 = s0_256;
712
713function s1_256(x) {
714 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
715}
716var s1_256_1 = s1_256;
717
718function g0_256(x) {
719 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
720}
721var g0_256_1 = g0_256;
722
723function g1_256(x) {
724 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
725}
726var g1_256_1 = g1_256;
727
728var common$1 = {
729 ft_1: ft_1_1,
730 ch32: ch32_1,
731 maj32: maj32_1,
732 p32: p32_1,
733 s0_256: s0_256_1,
734 s1_256: s1_256_1,
735 g0_256: g0_256_1,
736 g1_256: g1_256_1
737};
738
739var sum32$1 = utils.sum32;
740var sum32_4$1 = utils.sum32_4;
741var sum32_5$1 = utils.sum32_5;
742var ch32$1 = common$1.ch32;
743var maj32$1 = common$1.maj32;
744var s0_256$1 = common$1.s0_256;
745var s1_256$1 = common$1.s1_256;
746var g0_256$1 = common$1.g0_256;
747var g1_256$1 = common$1.g1_256;
748
749var BlockHash$1 = common.BlockHash;
750
751var sha256_K = [
752 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
753 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
754 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
755 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
756 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
757 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
758 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
759 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
760 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
761 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
762 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
763 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
764 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
765 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
766 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
767 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
768];
769
770function SHA256() {
771 if (!(this instanceof SHA256))
772 return new SHA256();
773
774 BlockHash$1.call(this);
775 this.h = [
776 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
777 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
778 ];
779 this.k = sha256_K;
780 this.W = new Array(64);
781}
782utils.inherits(SHA256, BlockHash$1);
783var _256 = SHA256;
784
785SHA256.blockSize = 512;
786SHA256.outSize = 256;
787SHA256.hmacStrength = 192;
788SHA256.padLength = 64;
789
790SHA256.prototype._update = function _update(msg, start) {
791 var W = this.W;
792
793 for (var i = 0; i < 16; i++)
794 W[i] = msg[start + i];
795 for (; i < W.length; i++)
796 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
797
798 var a = this.h[0];
799 var b = this.h[1];
800 var c = this.h[2];
801 var d = this.h[3];
802 var e = this.h[4];
803 var f = this.h[5];
804 var g = this.h[6];
805 var h = this.h[7];
806
807 minimalisticAssert(this.k.length === W.length);
808 for (i = 0; i < W.length; i++) {
809 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
810 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
811 h = g;
812 g = f;
813 f = e;
814 e = sum32$1(d, T1);
815 d = c;
816 c = b;
817 b = a;
818 a = sum32$1(T1, T2);
819 }
820
821 this.h[0] = sum32$1(this.h[0], a);
822 this.h[1] = sum32$1(this.h[1], b);
823 this.h[2] = sum32$1(this.h[2], c);
824 this.h[3] = sum32$1(this.h[3], d);
825 this.h[4] = sum32$1(this.h[4], e);
826 this.h[5] = sum32$1(this.h[5], f);
827 this.h[6] = sum32$1(this.h[6], g);
828 this.h[7] = sum32$1(this.h[7], h);
829};
830
831SHA256.prototype._digest = function digest(enc) {
832 if (enc === 'hex')
833 return utils.toHex32(this.h, 'big');
834 else
835 return utils.split32(this.h, 'big');
836};
837
838var charToInteger = {};
839var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
840for (var i = 0; i < chars.length; i++) {
841 charToInteger[chars.charCodeAt(i)] = i;
842}
843function decode(mappings) {
844 var generatedCodeColumn = 0; // first field
845 var sourceFileIndex = 0; // second field
846 var sourceCodeLine = 0; // third field
847 var sourceCodeColumn = 0; // fourth field
848 var nameIndex = 0; // fifth field
849 var decoded = [];
850 var line = [];
851 var segment = [];
852 for (var i = 0, j = 0, shift = 0, value = 0, len = mappings.length; i < len; i++) {
853 var c = mappings.charCodeAt(i);
854 if (c === 44) { // ","
855 if (segment.length)
856 line.push(new Int32Array(segment));
857 segment = [];
858 j = 0;
859 }
860 else if (c === 59) { // ";"
861 if (segment.length)
862 line.push(new Int32Array(segment));
863 segment = [];
864 j = 0;
865 decoded.push(line);
866 line = [];
867 generatedCodeColumn = 0;
868 }
869 else {
870 var integer = charToInteger[c];
871 if (integer === undefined) {
872 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
873 }
874 var hasContinuationBit = integer & 32;
875 integer &= 31;
876 value += integer << shift;
877 if (hasContinuationBit) {
878 shift += 5;
879 }
880 else {
881 var shouldNegate = value & 1;
882 value >>= 1;
883 var num = shouldNegate ? -value : value;
884 if (j == 0) {
885 generatedCodeColumn += num;
886 segment.push(generatedCodeColumn);
887 }
888 else if (j === 1) {
889 sourceFileIndex += num;
890 segment.push(sourceFileIndex);
891 }
892 else if (j === 2) {
893 sourceCodeLine += num;
894 segment.push(sourceCodeLine);
895 }
896 else if (j === 3) {
897 sourceCodeColumn += num;
898 segment.push(sourceCodeColumn);
899 }
900 else if (j === 4) {
901 nameIndex += num;
902 segment.push(nameIndex);
903 }
904 j++;
905 value = shift = 0; // reset
906 }
907 }
908 }
909 if (segment.length)
910 line.push(new Int32Array(segment));
911 decoded.push(line);
912 return decoded;
913}
914function encode(decoded) {
915 var sourceFileIndex = 0; // second field
916 var sourceCodeLine = 0; // third field
917 var sourceCodeColumn = 0; // fourth field
918 var nameIndex = 0; // fifth field
919 var mappings = '';
920 for (var i = 0; i < decoded.length; i++) {
921 var line = decoded[i];
922 if (i > 0)
923 mappings += ';';
924 if (line.length === 0)
925 continue;
926 var generatedCodeColumn = 0; // first field
927 var lineMappings = [];
928 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
929 var segment = line_1[_i];
930 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
931 generatedCodeColumn = segment[0];
932 if (segment.length > 1) {
933 segmentMappings +=
934 encodeInteger(segment[1] - sourceFileIndex) +
935 encodeInteger(segment[2] - sourceCodeLine) +
936 encodeInteger(segment[3] - sourceCodeColumn);
937 sourceFileIndex = segment[1];
938 sourceCodeLine = segment[2];
939 sourceCodeColumn = segment[3];
940 }
941 if (segment.length === 5) {
942 segmentMappings += encodeInteger(segment[4] - nameIndex);
943 nameIndex = segment[4];
944 }
945 lineMappings.push(segmentMappings);
946 }
947 mappings += lineMappings.join(',');
948 }
949 return mappings;
950}
951function encodeInteger(num) {
952 var result = '';
953 num = num < 0 ? (-num << 1) | 1 : num << 1;
954 do {
955 var clamped = num & 31;
956 num >>= 5;
957 if (num > 0) {
958 clamped |= 32;
959 }
960 result += chars[clamped];
961 } while (num > 0);
962 return result;
963}
964
965var Chunk = function Chunk(start, end, content) {
966 this.start = start;
967 this.end = end;
968 this.original = content;
969
970 this.intro = '';
971 this.outro = '';
972
973 this.content = content;
974 this.storeName = false;
975 this.edited = false;
976
977 // we make these non-enumerable, for sanity while debugging
978 Object.defineProperties(this, {
979 previous: { writable: true, value: null },
980 next: { writable: true, value: null }
981 });
982};
983
984Chunk.prototype.appendLeft = function appendLeft (content) {
985 this.outro += content;
986};
987
988Chunk.prototype.appendRight = function appendRight (content) {
989 this.intro = this.intro + content;
990};
991
992Chunk.prototype.clone = function clone () {
993 var chunk = new Chunk(this.start, this.end, this.original);
994
995 chunk.intro = this.intro;
996 chunk.outro = this.outro;
997 chunk.content = this.content;
998 chunk.storeName = this.storeName;
999 chunk.edited = this.edited;
1000
1001 return chunk;
1002};
1003
1004Chunk.prototype.contains = function contains (index) {
1005 return this.start < index && index < this.end;
1006};
1007
1008Chunk.prototype.eachNext = function eachNext (fn) {
1009 var chunk = this;
1010 while (chunk) {
1011 fn(chunk);
1012 chunk = chunk.next;
1013 }
1014};
1015
1016Chunk.prototype.eachPrevious = function eachPrevious (fn) {
1017 var chunk = this;
1018 while (chunk) {
1019 fn(chunk);
1020 chunk = chunk.previous;
1021 }
1022};
1023
1024Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
1025 this.content = content;
1026 if (!contentOnly) {
1027 this.intro = '';
1028 this.outro = '';
1029 }
1030 this.storeName = storeName;
1031
1032 this.edited = true;
1033
1034 return this;
1035};
1036
1037Chunk.prototype.prependLeft = function prependLeft (content) {
1038 this.outro = content + this.outro;
1039};
1040
1041Chunk.prototype.prependRight = function prependRight (content) {
1042 this.intro = content + this.intro;
1043};
1044
1045Chunk.prototype.split = function split (index) {
1046 var sliceIndex = index - this.start;
1047
1048 var originalBefore = this.original.slice(0, sliceIndex);
1049 var originalAfter = this.original.slice(sliceIndex);
1050
1051 this.original = originalBefore;
1052
1053 var newChunk = new Chunk(index, this.end, originalAfter);
1054 newChunk.outro = this.outro;
1055 this.outro = '';
1056
1057 this.end = index;
1058
1059 if (this.edited) {
1060 // TODO is this block necessary?...
1061 newChunk.edit('', false);
1062 this.content = '';
1063 } else {
1064 this.content = originalBefore;
1065 }
1066
1067 newChunk.next = this.next;
1068 if (newChunk.next) { newChunk.next.previous = newChunk; }
1069 newChunk.previous = this;
1070 this.next = newChunk;
1071
1072 return newChunk;
1073};
1074
1075Chunk.prototype.toString = function toString () {
1076 return this.intro + this.content + this.outro;
1077};
1078
1079Chunk.prototype.trimEnd = function trimEnd (rx) {
1080 this.outro = this.outro.replace(rx, '');
1081 if (this.outro.length) { return true; }
1082
1083 var trimmed = this.content.replace(rx, '');
1084
1085 if (trimmed.length) {
1086 if (trimmed !== this.content) {
1087 this.split(this.start + trimmed.length).edit('', undefined, true);
1088 }
1089 return true;
1090
1091 } else {
1092 this.edit('', undefined, true);
1093
1094 this.intro = this.intro.replace(rx, '');
1095 if (this.intro.length) { return true; }
1096 }
1097};
1098
1099Chunk.prototype.trimStart = function trimStart (rx) {
1100 this.intro = this.intro.replace(rx, '');
1101 if (this.intro.length) { return true; }
1102
1103 var trimmed = this.content.replace(rx, '');
1104
1105 if (trimmed.length) {
1106 if (trimmed !== this.content) {
1107 this.split(this.end - trimmed.length);
1108 this.edit('', undefined, true);
1109 }
1110 return true;
1111
1112 } else {
1113 this.edit('', undefined, true);
1114
1115 this.outro = this.outro.replace(rx, '');
1116 if (this.outro.length) { return true; }
1117 }
1118};
1119
1120var btoa = function () {
1121 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
1122};
1123if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
1124 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
1125} else if (typeof Buffer === 'function') {
1126 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
1127}
1128
1129var SourceMap = function SourceMap(properties) {
1130 this.version = 3;
1131 this.file = properties.file;
1132 this.sources = properties.sources;
1133 this.sourcesContent = properties.sourcesContent;
1134 this.names = properties.names;
1135 this.mappings = encode(properties.mappings);
1136};
1137
1138SourceMap.prototype.toString = function toString () {
1139 return JSON.stringify(this);
1140};
1141
1142SourceMap.prototype.toUrl = function toUrl () {
1143 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
1144};
1145
1146function guessIndent(code) {
1147 var lines = code.split('\n');
1148
1149 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
1150 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
1151
1152 if (tabbed.length === 0 && spaced.length === 0) {
1153 return null;
1154 }
1155
1156 // More lines tabbed than spaced? Assume tabs, and
1157 // default to tabs in the case of a tie (or nothing
1158 // to go on)
1159 if (tabbed.length >= spaced.length) {
1160 return '\t';
1161 }
1162
1163 // Otherwise, we need to guess the multiple
1164 var min = spaced.reduce(function (previous, current) {
1165 var numSpaces = /^ +/.exec(current)[0].length;
1166 return Math.min(numSpaces, previous);
1167 }, Infinity);
1168
1169 return new Array(min + 1).join(' ');
1170}
1171
1172function getRelativePath(from, to) {
1173 var fromParts = from.split(/[/\\]/);
1174 var toParts = to.split(/[/\\]/);
1175
1176 fromParts.pop(); // get dirname
1177
1178 while (fromParts[0] === toParts[0]) {
1179 fromParts.shift();
1180 toParts.shift();
1181 }
1182
1183 if (fromParts.length) {
1184 var i = fromParts.length;
1185 while (i--) { fromParts[i] = '..'; }
1186 }
1187
1188 return fromParts.concat(toParts).join('/');
1189}
1190
1191var toString = Object.prototype.toString;
1192
1193function isObject(thing) {
1194 return toString.call(thing) === '[object Object]';
1195}
1196
1197function getLocator(source) {
1198 var originalLines = source.split('\n');
1199 var lineOffsets = [];
1200
1201 for (var i = 0, pos = 0; i < originalLines.length; i++) {
1202 lineOffsets.push(pos);
1203 pos += originalLines[i].length + 1;
1204 }
1205
1206 return function locate(index) {
1207 var i = 0;
1208 var j = lineOffsets.length;
1209 while (i < j) {
1210 var m = (i + j) >> 1;
1211 if (index < lineOffsets[m]) {
1212 j = m;
1213 } else {
1214 i = m + 1;
1215 }
1216 }
1217 var line = i - 1;
1218 var column = index - lineOffsets[line];
1219 return { line: line, column: column };
1220 };
1221}
1222
1223var Mappings = function Mappings(hires) {
1224 this.hires = hires;
1225 this.generatedCodeLine = 0;
1226 this.generatedCodeColumn = 0;
1227 this.raw = [];
1228 this.rawSegments = this.raw[this.generatedCodeLine] = [];
1229 this.pending = null;
1230};
1231
1232Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
1233 if (content.length) {
1234 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1235 if (nameIndex >= 0) {
1236 segment.push(nameIndex);
1237 }
1238 this.rawSegments.push(segment);
1239 } else if (this.pending) {
1240 this.rawSegments.push(this.pending);
1241 }
1242
1243 this.advance(content);
1244 this.pending = null;
1245};
1246
1247Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
1248 var originalCharIndex = chunk.start;
1249 var first = true;
1250
1251 while (originalCharIndex < chunk.end) {
1252 if (this.hires || first || sourcemapLocations[originalCharIndex]) {
1253 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
1254 }
1255
1256 if (original[originalCharIndex] === '\n') {
1257 loc.line += 1;
1258 loc.column = 0;
1259 this.generatedCodeLine += 1;
1260 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1261 this.generatedCodeColumn = 0;
1262 } else {
1263 loc.column += 1;
1264 this.generatedCodeColumn += 1;
1265 }
1266
1267 originalCharIndex += 1;
1268 first = false;
1269 }
1270
1271 this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1272};
1273
1274Mappings.prototype.advance = function advance (str) {
1275 if (!str) { return; }
1276
1277 var lines = str.split('\n');
1278
1279 if (lines.length > 1) {
1280 for (var i = 0; i < lines.length - 1; i++) {
1281 this.generatedCodeLine++;
1282 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1283 }
1284 this.generatedCodeColumn = 0;
1285 }
1286
1287 this.generatedCodeColumn += lines[lines.length - 1].length;
1288};
1289
1290var n = '\n';
1291
1292var warned = {
1293 insertLeft: false,
1294 insertRight: false,
1295 storeName: false
1296};
1297
1298var MagicString = function MagicString(string, options) {
1299 if ( options === void 0 ) options = {};
1300
1301 var chunk = new Chunk(0, string.length, string);
1302
1303 Object.defineProperties(this, {
1304 original: { writable: true, value: string },
1305 outro: { writable: true, value: '' },
1306 intro: { writable: true, value: '' },
1307 firstChunk: { writable: true, value: chunk },
1308 lastChunk: { writable: true, value: chunk },
1309 lastSearchedChunk: { writable: true, value: chunk },
1310 byStart: { writable: true, value: {} },
1311 byEnd: { writable: true, value: {} },
1312 filename: { writable: true, value: options.filename },
1313 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1314 sourcemapLocations: { writable: true, value: {} },
1315 storedNames: { writable: true, value: {} },
1316 indentStr: { writable: true, value: guessIndent(string) }
1317 });
1318
1319 this.byStart[0] = chunk;
1320 this.byEnd[string.length] = chunk;
1321};
1322
1323MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
1324 this.sourcemapLocations[char] = true;
1325};
1326
1327MagicString.prototype.append = function append (content) {
1328 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
1329
1330 this.outro += content;
1331 return this;
1332};
1333
1334MagicString.prototype.appendLeft = function appendLeft (index, content) {
1335 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1336
1337 this._split(index);
1338
1339 var chunk = this.byEnd[index];
1340
1341 if (chunk) {
1342 chunk.appendLeft(content);
1343 } else {
1344 this.intro += content;
1345 }
1346 return this;
1347};
1348
1349MagicString.prototype.appendRight = function appendRight (index, content) {
1350 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1351
1352 this._split(index);
1353
1354 var chunk = this.byStart[index];
1355
1356 if (chunk) {
1357 chunk.appendRight(content);
1358 } else {
1359 this.outro += content;
1360 }
1361 return this;
1362};
1363
1364MagicString.prototype.clone = function clone () {
1365 var cloned = new MagicString(this.original, { filename: this.filename });
1366
1367 var originalChunk = this.firstChunk;
1368 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1369
1370 while (originalChunk) {
1371 cloned.byStart[clonedChunk.start] = clonedChunk;
1372 cloned.byEnd[clonedChunk.end] = clonedChunk;
1373
1374 var nextOriginalChunk = originalChunk.next;
1375 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1376
1377 if (nextClonedChunk) {
1378 clonedChunk.next = nextClonedChunk;
1379 nextClonedChunk.previous = clonedChunk;
1380
1381 clonedChunk = nextClonedChunk;
1382 }
1383
1384 originalChunk = nextOriginalChunk;
1385 }
1386
1387 cloned.lastChunk = clonedChunk;
1388
1389 if (this.indentExclusionRanges) {
1390 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1391 }
1392
1393 Object.keys(this.sourcemapLocations).forEach(function (loc) {
1394 cloned.sourcemapLocations[loc] = true;
1395 });
1396
1397 return cloned;
1398};
1399
1400MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
1401 var this$1 = this;
1402
1403 options = options || {};
1404
1405 var sourceIndex = 0;
1406 var names = Object.keys(this.storedNames);
1407 var mappings = new Mappings(options.hires);
1408
1409 var locate = getLocator(this.original);
1410
1411 if (this.intro) {
1412 mappings.advance(this.intro);
1413 }
1414
1415 this.firstChunk.eachNext(function (chunk) {
1416 var loc = locate(chunk.start);
1417
1418 if (chunk.intro.length) { mappings.advance(chunk.intro); }
1419
1420 if (chunk.edited) {
1421 mappings.addEdit(
1422 sourceIndex,
1423 chunk.content,
1424 loc,
1425 chunk.storeName ? names.indexOf(chunk.original) : -1
1426 );
1427 } else {
1428 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
1429 }
1430
1431 if (chunk.outro.length) { mappings.advance(chunk.outro); }
1432 });
1433
1434 return {
1435 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1436 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1437 sourcesContent: options.includeContent ? [this.original] : [null],
1438 names: names,
1439 mappings: mappings.raw
1440 };
1441};
1442
1443MagicString.prototype.generateMap = function generateMap (options) {
1444 return new SourceMap(this.generateDecodedMap(options));
1445};
1446
1447MagicString.prototype.getIndentString = function getIndentString () {
1448 return this.indentStr === null ? '\t' : this.indentStr;
1449};
1450
1451MagicString.prototype.indent = function indent (indentStr, options) {
1452 var pattern = /^[^\r\n]/gm;
1453
1454 if (isObject(indentStr)) {
1455 options = indentStr;
1456 indentStr = undefined;
1457 }
1458
1459 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1460
1461 if (indentStr === '') { return this; } // noop
1462
1463 options = options || {};
1464
1465 // Process exclusion ranges
1466 var isExcluded = {};
1467
1468 if (options.exclude) {
1469 var exclusions =
1470 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1471 exclusions.forEach(function (exclusion) {
1472 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
1473 isExcluded[i] = true;
1474 }
1475 });
1476 }
1477
1478 var shouldIndentNextCharacter = options.indentStart !== false;
1479 var replacer = function (match) {
1480 if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
1481 shouldIndentNextCharacter = true;
1482 return match;
1483 };
1484
1485 this.intro = this.intro.replace(pattern, replacer);
1486
1487 var charIndex = 0;
1488 var chunk = this.firstChunk;
1489
1490 while (chunk) {
1491 var end = chunk.end;
1492
1493 if (chunk.edited) {
1494 if (!isExcluded[charIndex]) {
1495 chunk.content = chunk.content.replace(pattern, replacer);
1496
1497 if (chunk.content.length) {
1498 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1499 }
1500 }
1501 } else {
1502 charIndex = chunk.start;
1503
1504 while (charIndex < end) {
1505 if (!isExcluded[charIndex]) {
1506 var char = this.original[charIndex];
1507
1508 if (char === '\n') {
1509 shouldIndentNextCharacter = true;
1510 } else if (char !== '\r' && shouldIndentNextCharacter) {
1511 shouldIndentNextCharacter = false;
1512
1513 if (charIndex === chunk.start) {
1514 chunk.prependRight(indentStr);
1515 } else {
1516 this._splitChunk(chunk, charIndex);
1517 chunk = chunk.next;
1518 chunk.prependRight(indentStr);
1519 }
1520 }
1521 }
1522
1523 charIndex += 1;
1524 }
1525 }
1526
1527 charIndex = chunk.end;
1528 chunk = chunk.next;
1529 }
1530
1531 this.outro = this.outro.replace(pattern, replacer);
1532
1533 return this;
1534};
1535
1536MagicString.prototype.insert = function insert () {
1537 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1538};
1539
1540MagicString.prototype.insertLeft = function insertLeft (index, content) {
1541 if (!warned.insertLeft) {
1542 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
1543 warned.insertLeft = true;
1544 }
1545
1546 return this.appendLeft(index, content);
1547};
1548
1549MagicString.prototype.insertRight = function insertRight (index, content) {
1550 if (!warned.insertRight) {
1551 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
1552 warned.insertRight = true;
1553 }
1554
1555 return this.prependRight(index, content);
1556};
1557
1558MagicString.prototype.move = function move (start, end, index) {
1559 if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
1560
1561 this._split(start);
1562 this._split(end);
1563 this._split(index);
1564
1565 var first = this.byStart[start];
1566 var last = this.byEnd[end];
1567
1568 var oldLeft = first.previous;
1569 var oldRight = last.next;
1570
1571 var newRight = this.byStart[index];
1572 if (!newRight && last === this.lastChunk) { return this; }
1573 var newLeft = newRight ? newRight.previous : this.lastChunk;
1574
1575 if (oldLeft) { oldLeft.next = oldRight; }
1576 if (oldRight) { oldRight.previous = oldLeft; }
1577
1578 if (newLeft) { newLeft.next = first; }
1579 if (newRight) { newRight.previous = last; }
1580
1581 if (!first.previous) { this.firstChunk = last.next; }
1582 if (!last.next) {
1583 this.lastChunk = first.previous;
1584 this.lastChunk.next = null;
1585 }
1586
1587 first.previous = newLeft;
1588 last.next = newRight || null;
1589
1590 if (!newLeft) { this.firstChunk = first; }
1591 if (!newRight) { this.lastChunk = last; }
1592 return this;
1593};
1594
1595MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
1596 if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
1597
1598 while (start < 0) { start += this.original.length; }
1599 while (end < 0) { end += this.original.length; }
1600
1601 if (end > this.original.length) { throw new Error('end is out of bounds'); }
1602 if (start === end)
1603 { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
1604
1605 this._split(start);
1606 this._split(end);
1607
1608 if (options === true) {
1609 if (!warned.storeName) {
1610 console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
1611 warned.storeName = true;
1612 }
1613
1614 options = { storeName: true };
1615 }
1616 var storeName = options !== undefined ? options.storeName : false;
1617 var contentOnly = options !== undefined ? options.contentOnly : false;
1618
1619 if (storeName) {
1620 var original = this.original.slice(start, end);
1621 this.storedNames[original] = true;
1622 }
1623
1624 var first = this.byStart[start];
1625 var last = this.byEnd[end];
1626
1627 if (first) {
1628 if (end > first.end && first.next !== this.byStart[first.end]) {
1629 throw new Error('Cannot overwrite across a split point');
1630 }
1631
1632 first.edit(content, storeName, contentOnly);
1633
1634 if (first !== last) {
1635 var chunk = first.next;
1636 while (chunk !== last) {
1637 chunk.edit('', false);
1638 chunk = chunk.next;
1639 }
1640
1641 chunk.edit('', false);
1642 }
1643 } else {
1644 // must be inserting at the end
1645 var newChunk = new Chunk(start, end, '').edit(content, storeName);
1646
1647 // TODO last chunk in the array may not be the last chunk, if it's moved...
1648 last.next = newChunk;
1649 newChunk.previous = last;
1650 }
1651 return this;
1652};
1653
1654MagicString.prototype.prepend = function prepend (content) {
1655 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
1656
1657 this.intro = content + this.intro;
1658 return this;
1659};
1660
1661MagicString.prototype.prependLeft = function prependLeft (index, content) {
1662 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1663
1664 this._split(index);
1665
1666 var chunk = this.byEnd[index];
1667
1668 if (chunk) {
1669 chunk.prependLeft(content);
1670 } else {
1671 this.intro = content + this.intro;
1672 }
1673 return this;
1674};
1675
1676MagicString.prototype.prependRight = function prependRight (index, content) {
1677 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1678
1679 this._split(index);
1680
1681 var chunk = this.byStart[index];
1682
1683 if (chunk) {
1684 chunk.prependRight(content);
1685 } else {
1686 this.outro = content + this.outro;
1687 }
1688 return this;
1689};
1690
1691MagicString.prototype.remove = function remove (start, end) {
1692 while (start < 0) { start += this.original.length; }
1693 while (end < 0) { end += this.original.length; }
1694
1695 if (start === end) { return this; }
1696
1697 if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
1698 if (start > end) { throw new Error('end must be greater than start'); }
1699
1700 this._split(start);
1701 this._split(end);
1702
1703 var chunk = this.byStart[start];
1704
1705 while (chunk) {
1706 chunk.intro = '';
1707 chunk.outro = '';
1708 chunk.edit('');
1709
1710 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1711 }
1712 return this;
1713};
1714
1715MagicString.prototype.lastChar = function lastChar () {
1716 if (this.outro.length)
1717 { return this.outro[this.outro.length - 1]; }
1718 var chunk = this.lastChunk;
1719 do {
1720 if (chunk.outro.length)
1721 { return chunk.outro[chunk.outro.length - 1]; }
1722 if (chunk.content.length)
1723 { return chunk.content[chunk.content.length - 1]; }
1724 if (chunk.intro.length)
1725 { return chunk.intro[chunk.intro.length - 1]; }
1726 } while (chunk = chunk.previous);
1727 if (this.intro.length)
1728 { return this.intro[this.intro.length - 1]; }
1729 return '';
1730};
1731
1732MagicString.prototype.lastLine = function lastLine () {
1733 var lineIndex = this.outro.lastIndexOf(n);
1734 if (lineIndex !== -1)
1735 { return this.outro.substr(lineIndex + 1); }
1736 var lineStr = this.outro;
1737 var chunk = this.lastChunk;
1738 do {
1739 if (chunk.outro.length > 0) {
1740 lineIndex = chunk.outro.lastIndexOf(n);
1741 if (lineIndex !== -1)
1742 { return chunk.outro.substr(lineIndex + 1) + lineStr; }
1743 lineStr = chunk.outro + lineStr;
1744 }
1745
1746 if (chunk.content.length > 0) {
1747 lineIndex = chunk.content.lastIndexOf(n);
1748 if (lineIndex !== -1)
1749 { return chunk.content.substr(lineIndex + 1) + lineStr; }
1750 lineStr = chunk.content + lineStr;
1751 }
1752
1753 if (chunk.intro.length > 0) {
1754 lineIndex = chunk.intro.lastIndexOf(n);
1755 if (lineIndex !== -1)
1756 { return chunk.intro.substr(lineIndex + 1) + lineStr; }
1757 lineStr = chunk.intro + lineStr;
1758 }
1759 } while (chunk = chunk.previous);
1760 lineIndex = this.intro.lastIndexOf(n);
1761 if (lineIndex !== -1)
1762 { return this.intro.substr(lineIndex + 1) + lineStr; }
1763 return this.intro + lineStr;
1764};
1765
1766MagicString.prototype.slice = function slice (start, end) {
1767 if ( start === void 0 ) start = 0;
1768 if ( end === void 0 ) end = this.original.length;
1769
1770 while (start < 0) { start += this.original.length; }
1771 while (end < 0) { end += this.original.length; }
1772
1773 var result = '';
1774
1775 // find start chunk
1776 var chunk = this.firstChunk;
1777 while (chunk && (chunk.start > start || chunk.end <= start)) {
1778 // found end chunk before start
1779 if (chunk.start < end && chunk.end >= end) {
1780 return result;
1781 }
1782
1783 chunk = chunk.next;
1784 }
1785
1786 if (chunk && chunk.edited && chunk.start !== start)
1787 { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
1788
1789 var startChunk = chunk;
1790 while (chunk) {
1791 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1792 result += chunk.intro;
1793 }
1794
1795 var containsEnd = chunk.start < end && chunk.end >= end;
1796 if (containsEnd && chunk.edited && chunk.end !== end)
1797 { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
1798
1799 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1800 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1801
1802 result += chunk.content.slice(sliceStart, sliceEnd);
1803
1804 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1805 result += chunk.outro;
1806 }
1807
1808 if (containsEnd) {
1809 break;
1810 }
1811
1812 chunk = chunk.next;
1813 }
1814
1815 return result;
1816};
1817
1818// TODO deprecate this? not really very useful
1819MagicString.prototype.snip = function snip (start, end) {
1820 var clone = this.clone();
1821 clone.remove(0, start);
1822 clone.remove(end, clone.original.length);
1823
1824 return clone;
1825};
1826
1827MagicString.prototype._split = function _split (index) {
1828 if (this.byStart[index] || this.byEnd[index]) { return; }
1829
1830 var chunk = this.lastSearchedChunk;
1831 var searchForward = index > chunk.end;
1832
1833 while (chunk) {
1834 if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
1835
1836 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1837 }
1838};
1839
1840MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
1841 if (chunk.edited && chunk.content.length) {
1842 // zero-length edited chunks are a special case (overlapping replacements)
1843 var loc = getLocator(this.original)(index);
1844 throw new Error(
1845 ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
1846 );
1847 }
1848
1849 var newChunk = chunk.split(index);
1850
1851 this.byEnd[index] = chunk;
1852 this.byStart[index] = newChunk;
1853 this.byEnd[newChunk.end] = newChunk;
1854
1855 if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
1856
1857 this.lastSearchedChunk = chunk;
1858 return true;
1859};
1860
1861MagicString.prototype.toString = function toString () {
1862 var str = this.intro;
1863
1864 var chunk = this.firstChunk;
1865 while (chunk) {
1866 str += chunk.toString();
1867 chunk = chunk.next;
1868 }
1869
1870 return str + this.outro;
1871};
1872
1873MagicString.prototype.isEmpty = function isEmpty () {
1874 var chunk = this.firstChunk;
1875 do {
1876 if (chunk.intro.length && chunk.intro.trim() ||
1877 chunk.content.length && chunk.content.trim() ||
1878 chunk.outro.length && chunk.outro.trim())
1879 { return false; }
1880 } while (chunk = chunk.next);
1881 return true;
1882};
1883
1884MagicString.prototype.length = function length () {
1885 var chunk = this.firstChunk;
1886 var length = 0;
1887 do {
1888 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1889 } while (chunk = chunk.next);
1890 return length;
1891};
1892
1893MagicString.prototype.trimLines = function trimLines () {
1894 return this.trim('[\\r\\n]');
1895};
1896
1897MagicString.prototype.trim = function trim (charType) {
1898 return this.trimStart(charType).trimEnd(charType);
1899};
1900
1901MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
1902 var rx = new RegExp((charType || '\\s') + '+$');
1903
1904 this.outro = this.outro.replace(rx, '');
1905 if (this.outro.length) { return true; }
1906
1907 var chunk = this.lastChunk;
1908
1909 do {
1910 var end = chunk.end;
1911 var aborted = chunk.trimEnd(rx);
1912
1913 // if chunk was trimmed, we have a new lastChunk
1914 if (chunk.end !== end) {
1915 if (this.lastChunk === chunk) {
1916 this.lastChunk = chunk.next;
1917 }
1918
1919 this.byEnd[chunk.end] = chunk;
1920 this.byStart[chunk.next.start] = chunk.next;
1921 this.byEnd[chunk.next.end] = chunk.next;
1922 }
1923
1924 if (aborted) { return true; }
1925 chunk = chunk.previous;
1926 } while (chunk);
1927
1928 return false;
1929};
1930
1931MagicString.prototype.trimEnd = function trimEnd (charType) {
1932 this.trimEndAborted(charType);
1933 return this;
1934};
1935MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
1936 var rx = new RegExp('^' + (charType || '\\s') + '+');
1937
1938 this.intro = this.intro.replace(rx, '');
1939 if (this.intro.length) { return true; }
1940
1941 var chunk = this.firstChunk;
1942
1943 do {
1944 var end = chunk.end;
1945 var aborted = chunk.trimStart(rx);
1946
1947 if (chunk.end !== end) {
1948 // special case...
1949 if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
1950
1951 this.byEnd[chunk.end] = chunk;
1952 this.byStart[chunk.next.start] = chunk.next;
1953 this.byEnd[chunk.next.end] = chunk.next;
1954 }
1955
1956 if (aborted) { return true; }
1957 chunk = chunk.next;
1958 } while (chunk);
1959
1960 return false;
1961};
1962
1963MagicString.prototype.trimStart = function trimStart (charType) {
1964 this.trimStartAborted(charType);
1965 return this;
1966};
1967
1968var hasOwnProp = Object.prototype.hasOwnProperty;
1969
1970var Bundle = function Bundle(options) {
1971 if ( options === void 0 ) options = {};
1972
1973 this.intro = options.intro || '';
1974 this.separator = options.separator !== undefined ? options.separator : '\n';
1975 this.sources = [];
1976 this.uniqueSources = [];
1977 this.uniqueSourceIndexByFilename = {};
1978};
1979
1980Bundle.prototype.addSource = function addSource (source) {
1981 if (source instanceof MagicString) {
1982 return this.addSource({
1983 content: source,
1984 filename: source.filename,
1985 separator: this.separator
1986 });
1987 }
1988
1989 if (!isObject(source) || !source.content) {
1990 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1991 }
1992
1993 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1994 if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
1995 });
1996
1997 if (source.separator === undefined) {
1998 // TODO there's a bunch of this sort of thing, needs cleaning up
1999 source.separator = this.separator;
2000 }
2001
2002 if (source.filename) {
2003 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
2004 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
2005 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
2006 } else {
2007 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
2008 if (source.content.original !== uniqueSource.content) {
2009 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
2010 }
2011 }
2012 }
2013
2014 this.sources.push(source);
2015 return this;
2016};
2017
2018Bundle.prototype.append = function append (str, options) {
2019 this.addSource({
2020 content: new MagicString(str),
2021 separator: (options && options.separator) || ''
2022 });
2023
2024 return this;
2025};
2026
2027Bundle.prototype.clone = function clone () {
2028 var bundle = new Bundle({
2029 intro: this.intro,
2030 separator: this.separator
2031 });
2032
2033 this.sources.forEach(function (source) {
2034 bundle.addSource({
2035 filename: source.filename,
2036 content: source.content.clone(),
2037 separator: source.separator
2038 });
2039 });
2040
2041 return bundle;
2042};
2043
2044Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
2045 var this$1 = this;
2046 if ( options === void 0 ) options = {};
2047
2048 var names = [];
2049 this.sources.forEach(function (source) {
2050 Object.keys(source.content.storedNames).forEach(function (name) {
2051 if (!~names.indexOf(name)) { names.push(name); }
2052 });
2053 });
2054
2055 var mappings = new Mappings(options.hires);
2056
2057 if (this.intro) {
2058 mappings.advance(this.intro);
2059 }
2060
2061 this.sources.forEach(function (source, i) {
2062 if (i > 0) {
2063 mappings.advance(this$1.separator);
2064 }
2065
2066 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
2067 var magicString = source.content;
2068 var locate = getLocator(magicString.original);
2069
2070 if (magicString.intro) {
2071 mappings.advance(magicString.intro);
2072 }
2073
2074 magicString.firstChunk.eachNext(function (chunk) {
2075 var loc = locate(chunk.start);
2076
2077 if (chunk.intro.length) { mappings.advance(chunk.intro); }
2078
2079 if (source.filename) {
2080 if (chunk.edited) {
2081 mappings.addEdit(
2082 sourceIndex,
2083 chunk.content,
2084 loc,
2085 chunk.storeName ? names.indexOf(chunk.original) : -1
2086 );
2087 } else {
2088 mappings.addUneditedChunk(
2089 sourceIndex,
2090 chunk,
2091 magicString.original,
2092 loc,
2093 magicString.sourcemapLocations
2094 );
2095 }
2096 } else {
2097 mappings.advance(chunk.content);
2098 }
2099
2100 if (chunk.outro.length) { mappings.advance(chunk.outro); }
2101 });
2102
2103 if (magicString.outro) {
2104 mappings.advance(magicString.outro);
2105 }
2106 });
2107
2108 return {
2109 file: options.file ? options.file.split(/[/\\]/).pop() : null,
2110 sources: this.uniqueSources.map(function (source) {
2111 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
2112 }),
2113 sourcesContent: this.uniqueSources.map(function (source) {
2114 return options.includeContent ? source.content : null;
2115 }),
2116 names: names,
2117 mappings: mappings.raw
2118 };
2119};
2120
2121Bundle.prototype.generateMap = function generateMap (options) {
2122 return new SourceMap(this.generateDecodedMap(options));
2123};
2124
2125Bundle.prototype.getIndentString = function getIndentString () {
2126 var indentStringCounts = {};
2127
2128 this.sources.forEach(function (source) {
2129 var indentStr = source.content.indentStr;
2130
2131 if (indentStr === null) { return; }
2132
2133 if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
2134 indentStringCounts[indentStr] += 1;
2135 });
2136
2137 return (
2138 Object.keys(indentStringCounts).sort(function (a, b) {
2139 return indentStringCounts[a] - indentStringCounts[b];
2140 })[0] || '\t'
2141 );
2142};
2143
2144Bundle.prototype.indent = function indent (indentStr) {
2145 var this$1 = this;
2146
2147 if (!arguments.length) {
2148 indentStr = this.getIndentString();
2149 }
2150
2151 if (indentStr === '') { return this; } // noop
2152
2153 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
2154
2155 this.sources.forEach(function (source, i) {
2156 var separator = source.separator !== undefined ? source.separator : this$1.separator;
2157 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
2158
2159 source.content.indent(indentStr, {
2160 exclude: source.indentExclusionRanges,
2161 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
2162 });
2163
2164 trailingNewline = source.content.lastChar() === '\n';
2165 });
2166
2167 if (this.intro) {
2168 this.intro =
2169 indentStr +
2170 this.intro.replace(/^[^\n]/gm, function (match, index) {
2171 return index > 0 ? indentStr + match : match;
2172 });
2173 }
2174
2175 return this;
2176};
2177
2178Bundle.prototype.prepend = function prepend (str) {
2179 this.intro = str + this.intro;
2180 return this;
2181};
2182
2183Bundle.prototype.toString = function toString () {
2184 var this$1 = this;
2185
2186 var body = this.sources
2187 .map(function (source, i) {
2188 var separator = source.separator !== undefined ? source.separator : this$1.separator;
2189 var str = (i > 0 ? separator : '') + source.content.toString();
2190
2191 return str;
2192 })
2193 .join('');
2194
2195 return this.intro + body;
2196};
2197
2198Bundle.prototype.isEmpty = function isEmpty () {
2199 if (this.intro.length && this.intro.trim())
2200 { return false; }
2201 if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
2202 { return false; }
2203 return true;
2204};
2205
2206Bundle.prototype.length = function length () {
2207 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
2208};
2209
2210Bundle.prototype.trimLines = function trimLines () {
2211 return this.trim('[\\r\\n]');
2212};
2213
2214Bundle.prototype.trim = function trim (charType) {
2215 return this.trimStart(charType).trimEnd(charType);
2216};
2217
2218Bundle.prototype.trimStart = function trimStart (charType) {
2219 var rx = new RegExp('^' + (charType || '\\s') + '+');
2220 this.intro = this.intro.replace(rx, '');
2221
2222 if (!this.intro) {
2223 var source;
2224 var i = 0;
2225
2226 do {
2227 source = this.sources[i++];
2228 if (!source) {
2229 break;
2230 }
2231 } while (!source.content.trimStartAborted(charType));
2232 }
2233
2234 return this;
2235};
2236
2237Bundle.prototype.trimEnd = function trimEnd (charType) {
2238 var rx = new RegExp((charType || '\\s') + '+$');
2239
2240 var source;
2241 var i = this.sources.length - 1;
2242
2243 do {
2244 source = this.sources[i--];
2245 if (!source) {
2246 this.intro = this.intro.replace(rx, '');
2247 break;
2248 }
2249 } while (!source.content.trimEndAborted(charType));
2250
2251 return this;
2252};
2253
2254var BlockStatement = 'BlockStatement';
2255var CallExpression = 'CallExpression';
2256var ClassDeclaration = 'ClassDeclaration';
2257var ExportAllDeclaration = 'ExportAllDeclaration';
2258var ExportDefaultDeclaration = 'ExportDefaultDeclaration';
2259var ExpressionStatement = 'ExpressionStatement';
2260var FunctionDeclaration = 'FunctionDeclaration';
2261var FunctionExpression = 'FunctionExpression';
2262var Identifier = 'Identifier';
2263var ImportDefaultSpecifier = 'ImportDefaultSpecifier';
2264var ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
2265var Literal = 'Literal';
2266var MemberExpression = 'MemberExpression';
2267var Program = 'Program';
2268var Property = 'Property';
2269var ReturnStatement = 'ReturnStatement';
2270var TemplateLiteral = 'TemplateLiteral';
2271var VariableDeclaration = 'VariableDeclaration';
2272
2273var CallOptions = /** @class */ (function () {
2274 function CallOptions(_a) {
2275 var _b = _a === void 0 ? {} : _a, _c = _b.withNew, withNew = _c === void 0 ? false : _c, _d = _b.args, args = _d === void 0 ? [] : _d, _e = _b.callIdentifier, callIdentifier = _e === void 0 ? undefined : _e;
2276 this.withNew = withNew;
2277 this.args = args;
2278 this.callIdentifier = callIdentifier;
2279 }
2280 CallOptions.create = function (callOptions) {
2281 return new this(callOptions);
2282 };
2283 CallOptions.prototype.equals = function (callOptions) {
2284 return callOptions && this.callIdentifier === callOptions.callIdentifier;
2285 };
2286 return CallOptions;
2287}());
2288
2289var UNKNOWN_KEY = { UNKNOWN_KEY: true };
2290var EMPTY_PATH = [];
2291var UNKNOWN_PATH = [UNKNOWN_KEY];
2292function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions) {
2293 if (inheritedDescriptions === void 0) { inheritedDescriptions = null; }
2294 return Object.create(inheritedDescriptions, memberDescriptions);
2295}
2296var UNKNOWN_VALUE = { UNKNOWN_VALUE: true };
2297var UNKNOWN_EXPRESSION = {
2298 deoptimizePath: function () { },
2299 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2300 getReturnExpressionWhenCalledAtPath: function () { return UNKNOWN_EXPRESSION; },
2301 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 0; },
2302 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2303 hasEffectsWhenCalledAtPath: function () { return true; },
2304 include: function () { },
2305 included: true,
2306 toString: function () { return '[[UNKNOWN]]'; }
2307};
2308var UNDEFINED_EXPRESSION = {
2309 deoptimizePath: function () { },
2310 getLiteralValueAtPath: function () { return undefined; },
2311 getReturnExpressionWhenCalledAtPath: function () { return UNKNOWN_EXPRESSION; },
2312 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 0; },
2313 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2314 hasEffectsWhenCalledAtPath: function () { return true; },
2315 include: function () { },
2316 included: true,
2317 toString: function () { return 'undefined'; }
2318};
2319var returnsUnknown = {
2320 value: {
2321 callsArgs: null,
2322 mutatesSelf: false,
2323 returns: null,
2324 returnsPrimitive: UNKNOWN_EXPRESSION
2325 }
2326};
2327var mutatesSelfReturnsUnknown = {
2328 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
2329};
2330var callsArgReturnsUnknown = {
2331 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
2332};
2333var UnknownArrayExpression = /** @class */ (function () {
2334 function UnknownArrayExpression() {
2335 this.included = false;
2336 }
2337 UnknownArrayExpression.prototype.deoptimizePath = function () { };
2338 UnknownArrayExpression.prototype.getLiteralValueAtPath = function () {
2339 return UNKNOWN_VALUE;
2340 };
2341 UnknownArrayExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
2342 if (path.length === 1) {
2343 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
2344 }
2345 return UNKNOWN_EXPRESSION;
2346 };
2347 UnknownArrayExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
2348 return path.length > 1;
2349 };
2350 UnknownArrayExpression.prototype.hasEffectsWhenAssignedAtPath = function (path) {
2351 return path.length > 1;
2352 };
2353 UnknownArrayExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
2354 if (path.length === 1) {
2355 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
2356 }
2357 return true;
2358 };
2359 UnknownArrayExpression.prototype.include = function () {
2360 this.included = true;
2361 };
2362 UnknownArrayExpression.prototype.toString = function () {
2363 return '[[UNKNOWN ARRAY]]';
2364 };
2365 return UnknownArrayExpression;
2366}());
2367var returnsArray = {
2368 value: {
2369 callsArgs: null,
2370 mutatesSelf: false,
2371 returns: UnknownArrayExpression,
2372 returnsPrimitive: null
2373 }
2374};
2375var mutatesSelfReturnsArray = {
2376 value: {
2377 callsArgs: null,
2378 mutatesSelf: true,
2379 returns: UnknownArrayExpression,
2380 returnsPrimitive: null
2381 }
2382};
2383var callsArgReturnsArray = {
2384 value: {
2385 callsArgs: [0],
2386 mutatesSelf: false,
2387 returns: UnknownArrayExpression,
2388 returnsPrimitive: null
2389 }
2390};
2391var callsArgMutatesSelfReturnsArray = {
2392 value: {
2393 callsArgs: [0],
2394 mutatesSelf: true,
2395 returns: UnknownArrayExpression,
2396 returnsPrimitive: null
2397 }
2398};
2399var UNKNOWN_LITERAL_BOOLEAN = {
2400 deoptimizePath: function () { },
2401 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2402 getReturnExpressionWhenCalledAtPath: function (path) {
2403 if (path.length === 1) {
2404 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2405 }
2406 return UNKNOWN_EXPRESSION;
2407 },
2408 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
2409 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2410 hasEffectsWhenCalledAtPath: function (path) {
2411 if (path.length === 1) {
2412 var subPath = path[0];
2413 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
2414 }
2415 return true;
2416 },
2417 include: function () { },
2418 included: true,
2419 toString: function () { return '[[UNKNOWN BOOLEAN]]'; }
2420};
2421var returnsBoolean = {
2422 value: {
2423 callsArgs: null,
2424 mutatesSelf: false,
2425 returns: null,
2426 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2427 }
2428};
2429var callsArgReturnsBoolean = {
2430 value: {
2431 callsArgs: [0],
2432 mutatesSelf: false,
2433 returns: null,
2434 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2435 }
2436};
2437var UNKNOWN_LITERAL_NUMBER = {
2438 deoptimizePath: function () { },
2439 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2440 getReturnExpressionWhenCalledAtPath: function (path) {
2441 if (path.length === 1) {
2442 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2443 }
2444 return UNKNOWN_EXPRESSION;
2445 },
2446 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
2447 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2448 hasEffectsWhenCalledAtPath: function (path) {
2449 if (path.length === 1) {
2450 var subPath = path[0];
2451 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
2452 }
2453 return true;
2454 },
2455 include: function () { },
2456 included: true,
2457 toString: function () { return '[[UNKNOWN NUMBER]]'; }
2458};
2459var returnsNumber = {
2460 value: {
2461 callsArgs: null,
2462 mutatesSelf: false,
2463 returns: null,
2464 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2465 }
2466};
2467var mutatesSelfReturnsNumber = {
2468 value: {
2469 callsArgs: null,
2470 mutatesSelf: true,
2471 returns: null,
2472 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2473 }
2474};
2475var callsArgReturnsNumber = {
2476 value: {
2477 callsArgs: [0],
2478 mutatesSelf: false,
2479 returns: null,
2480 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2481 }
2482};
2483var UNKNOWN_LITERAL_STRING = {
2484 deoptimizePath: function () { },
2485 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2486 getReturnExpressionWhenCalledAtPath: function (path) {
2487 if (path.length === 1) {
2488 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2489 }
2490 return UNKNOWN_EXPRESSION;
2491 },
2492 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
2493 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2494 hasEffectsWhenCalledAtPath: function (path, callOptions, options) {
2495 if (path.length === 1) {
2496 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, options);
2497 }
2498 return true;
2499 },
2500 include: function () { },
2501 included: true,
2502 toString: function () { return '[[UNKNOWN STRING]]'; }
2503};
2504var returnsString = {
2505 value: {
2506 callsArgs: null,
2507 mutatesSelf: false,
2508 returns: null,
2509 returnsPrimitive: UNKNOWN_LITERAL_STRING
2510 }
2511};
2512var UnknownObjectExpression = /** @class */ (function () {
2513 function UnknownObjectExpression() {
2514 this.included = false;
2515 }
2516 UnknownObjectExpression.prototype.deoptimizePath = function () { };
2517 UnknownObjectExpression.prototype.getLiteralValueAtPath = function () {
2518 return UNKNOWN_VALUE;
2519 };
2520 UnknownObjectExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
2521 if (path.length === 1) {
2522 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2523 }
2524 return UNKNOWN_EXPRESSION;
2525 };
2526 UnknownObjectExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
2527 return path.length > 1;
2528 };
2529 UnknownObjectExpression.prototype.hasEffectsWhenAssignedAtPath = function (path) {
2530 return path.length > 1;
2531 };
2532 UnknownObjectExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
2533 if (path.length === 1) {
2534 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, options);
2535 }
2536 return true;
2537 };
2538 UnknownObjectExpression.prototype.include = function () {
2539 this.included = true;
2540 };
2541 UnknownObjectExpression.prototype.toString = function () {
2542 return '[[UNKNOWN OBJECT]]';
2543 };
2544 return UnknownObjectExpression;
2545}());
2546var objectMembers = assembleMemberDescriptions({
2547 hasOwnProperty: returnsBoolean,
2548 isPrototypeOf: returnsBoolean,
2549 propertyIsEnumerable: returnsBoolean,
2550 toLocaleString: returnsString,
2551 toString: returnsString,
2552 valueOf: returnsUnknown
2553});
2554var arrayMembers = assembleMemberDescriptions({
2555 concat: returnsArray,
2556 copyWithin: mutatesSelfReturnsArray,
2557 every: callsArgReturnsBoolean,
2558 fill: mutatesSelfReturnsArray,
2559 filter: callsArgReturnsArray,
2560 find: callsArgReturnsUnknown,
2561 findIndex: callsArgReturnsNumber,
2562 forEach: callsArgReturnsUnknown,
2563 includes: returnsBoolean,
2564 indexOf: returnsNumber,
2565 join: returnsString,
2566 lastIndexOf: returnsNumber,
2567 map: callsArgReturnsArray,
2568 pop: mutatesSelfReturnsUnknown,
2569 push: mutatesSelfReturnsNumber,
2570 reduce: callsArgReturnsUnknown,
2571 reduceRight: callsArgReturnsUnknown,
2572 reverse: mutatesSelfReturnsArray,
2573 shift: mutatesSelfReturnsUnknown,
2574 slice: returnsArray,
2575 some: callsArgReturnsBoolean,
2576 sort: callsArgMutatesSelfReturnsArray,
2577 splice: mutatesSelfReturnsArray,
2578 unshift: mutatesSelfReturnsNumber
2579}, objectMembers);
2580var literalBooleanMembers = assembleMemberDescriptions({
2581 valueOf: returnsBoolean
2582}, objectMembers);
2583var literalNumberMembers = assembleMemberDescriptions({
2584 toExponential: returnsString,
2585 toFixed: returnsString,
2586 toLocaleString: returnsString,
2587 toPrecision: returnsString,
2588 valueOf: returnsNumber
2589}, objectMembers);
2590var literalStringMembers = assembleMemberDescriptions({
2591 charAt: returnsString,
2592 charCodeAt: returnsNumber,
2593 codePointAt: returnsNumber,
2594 concat: returnsString,
2595 endsWith: returnsBoolean,
2596 includes: returnsBoolean,
2597 indexOf: returnsNumber,
2598 lastIndexOf: returnsNumber,
2599 localeCompare: returnsNumber,
2600 match: returnsBoolean,
2601 normalize: returnsString,
2602 padEnd: returnsString,
2603 padStart: returnsString,
2604 repeat: returnsString,
2605 replace: {
2606 value: {
2607 callsArgs: [1],
2608 mutatesSelf: false,
2609 returns: null,
2610 returnsPrimitive: UNKNOWN_LITERAL_STRING
2611 }
2612 },
2613 search: returnsNumber,
2614 slice: returnsString,
2615 split: returnsArray,
2616 startsWith: returnsBoolean,
2617 substr: returnsString,
2618 substring: returnsString,
2619 toLocaleLowerCase: returnsString,
2620 toLocaleUpperCase: returnsString,
2621 toLowerCase: returnsString,
2622 toUpperCase: returnsString,
2623 trim: returnsString,
2624 valueOf: returnsString
2625}, objectMembers);
2626function getLiteralMembersForValue(value) {
2627 switch (typeof value) {
2628 case 'boolean':
2629 return literalBooleanMembers;
2630 case 'number':
2631 return literalNumberMembers;
2632 case 'string':
2633 return literalStringMembers;
2634 default:
2635 return Object.create(null);
2636 }
2637}
2638function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, options) {
2639 if (typeof memberName !== 'string' || !members[memberName])
2640 return true;
2641 if (members[memberName].mutatesSelf && parentIncluded)
2642 return true;
2643 if (!members[memberName].callsArgs)
2644 return false;
2645 for (var _i = 0, _a = members[memberName].callsArgs; _i < _a.length; _i++) {
2646 var argIndex = _a[_i];
2647 if (callOptions.args[argIndex] &&
2648 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, CallOptions.create({
2649 args: [],
2650 callIdentifier: {},
2651 withNew: false
2652 }), options.getHasEffectsWhenCalledOptions()))
2653 return true;
2654 }
2655 return false;
2656}
2657function getMemberReturnExpressionWhenCalled(members, memberName) {
2658 if (typeof memberName !== 'string' || !members[memberName])
2659 return UNKNOWN_EXPRESSION;
2660 return members[memberName].returnsPrimitive !== null
2661 ? members[memberName].returnsPrimitive
2662 : new members[memberName].returns();
2663}
2664
2665var Variable = /** @class */ (function () {
2666 function Variable(name) {
2667 this.exportName = null;
2668 this.included = false;
2669 this.isId = false;
2670 this.isReassigned = false;
2671 this.reexported = false;
2672 this.renderBaseName = null;
2673 this.renderName = null;
2674 this.safeExportName = null;
2675 this.name = name;
2676 }
2677 /**
2678 * Binds identifiers that reference this variable to this variable.
2679 * Necessary to be able to change variable names.
2680 */
2681 Variable.prototype.addReference = function (_identifier) { };
2682 Variable.prototype.deoptimizePath = function (_path) { };
2683 Variable.prototype.getBaseVariableName = function () {
2684 return this.renderBaseName || this.renderName || this.name;
2685 };
2686 Variable.prototype.getLiteralValueAtPath = function (_path, _recursionTracker, _origin) {
2687 return UNKNOWN_VALUE;
2688 };
2689 Variable.prototype.getName = function () {
2690 var name = this.renderName || this.name;
2691 return this.renderBaseName ? this.renderBaseName + "." + name : name;
2692 };
2693 Variable.prototype.getReturnExpressionWhenCalledAtPath = function (_path, _recursionTracker, _origin) {
2694 return UNKNOWN_EXPRESSION;
2695 };
2696 Variable.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
2697 return path.length > 0;
2698 };
2699 Variable.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
2700 return true;
2701 };
2702 Variable.prototype.hasEffectsWhenCalledAtPath = function (_path, _callOptions, _options) {
2703 return true;
2704 };
2705 /**
2706 * Marks this variable as being part of the bundle, which is usually the case when one of
2707 * its identifiers becomes part of the bundle. Returns true if it has not been included
2708 * previously.
2709 * Once a variable is included, it should take care all its declarations are included.
2710 */
2711 Variable.prototype.include = function () {
2712 this.included = true;
2713 };
2714 Variable.prototype.setRenderNames = function (baseName, name) {
2715 this.renderBaseName = baseName;
2716 this.renderName = name;
2717 };
2718 Variable.prototype.setSafeName = function (name) {
2719 this.renderName = name;
2720 };
2721 Variable.prototype.toString = function () {
2722 return this.name;
2723 };
2724 return Variable;
2725}());
2726
2727// To avoid infinite recursions
2728var MAX_PATH_DEPTH = 7;
2729var LocalVariable = /** @class */ (function (_super) {
2730 __extends(LocalVariable, _super);
2731 function LocalVariable(name, declarator, init, context) {
2732 var _this = _super.call(this, name) || this;
2733 _this.additionalInitializers = null;
2734 _this.expressionsToBeDeoptimized = [];
2735 _this.declarations = declarator ? [declarator] : [];
2736 _this.init = init;
2737 _this.deoptimizationTracker = context.deoptimizationTracker;
2738 _this.module = context.module;
2739 return _this;
2740 }
2741 LocalVariable.prototype.addDeclaration = function (identifier, init) {
2742 this.declarations.push(identifier);
2743 if (this.additionalInitializers === null) {
2744 this.additionalInitializers = this.init === null ? [] : [this.init];
2745 this.init = UNKNOWN_EXPRESSION;
2746 this.isReassigned = true;
2747 }
2748 if (init !== null) {
2749 this.additionalInitializers.push(init);
2750 }
2751 };
2752 LocalVariable.prototype.consolidateInitializers = function () {
2753 if (this.additionalInitializers !== null) {
2754 for (var _i = 0, _a = this.additionalInitializers; _i < _a.length; _i++) {
2755 var initializer = _a[_i];
2756 initializer.deoptimizePath(UNKNOWN_PATH);
2757 }
2758 this.additionalInitializers = null;
2759 }
2760 };
2761 LocalVariable.prototype.deoptimizePath = function (path) {
2762 if (path.length > MAX_PATH_DEPTH)
2763 return;
2764 if (!(this.isReassigned || this.deoptimizationTracker.track(this, path))) {
2765 if (path.length === 0) {
2766 if (!this.isReassigned) {
2767 this.isReassigned = true;
2768 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
2769 var expression = _a[_i];
2770 expression.deoptimizeCache();
2771 }
2772 if (this.init) {
2773 this.init.deoptimizePath(UNKNOWN_PATH);
2774 }
2775 }
2776 }
2777 else if (this.init) {
2778 this.init.deoptimizePath(path);
2779 }
2780 }
2781 };
2782 LocalVariable.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
2783 if (this.isReassigned ||
2784 !this.init ||
2785 path.length > MAX_PATH_DEPTH ||
2786 recursionTracker.isTracked(this.init, path)) {
2787 return UNKNOWN_VALUE;
2788 }
2789 this.expressionsToBeDeoptimized.push(origin);
2790 return this.init.getLiteralValueAtPath(path, recursionTracker.track(this.init, path), origin);
2791 };
2792 LocalVariable.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
2793 if (this.isReassigned ||
2794 !this.init ||
2795 path.length > MAX_PATH_DEPTH ||
2796 recursionTracker.isTracked(this.init, path)) {
2797 return UNKNOWN_EXPRESSION;
2798 }
2799 this.expressionsToBeDeoptimized.push(origin);
2800 return this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.init, path), origin);
2801 };
2802 LocalVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
2803 if (path.length === 0)
2804 return false;
2805 return (this.isReassigned ||
2806 path.length > MAX_PATH_DEPTH ||
2807 (this.init &&
2808 !options.hasNodeBeenAccessedAtPath(path, this.init) &&
2809 this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init))));
2810 };
2811 LocalVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
2812 if (this.included || path.length > MAX_PATH_DEPTH)
2813 return true;
2814 if (path.length === 0)
2815 return false;
2816 return (this.isReassigned ||
2817 (this.init &&
2818 !options.hasNodeBeenAssignedAtPath(path, this.init) &&
2819 this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init))));
2820 };
2821 LocalVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
2822 if (path.length > MAX_PATH_DEPTH)
2823 return true;
2824 return (this.isReassigned ||
2825 (this.init &&
2826 !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) &&
2827 this.init.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions))));
2828 };
2829 LocalVariable.prototype.include = function () {
2830 if (!this.included) {
2831 this.included = true;
2832 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
2833 var declaration = _a[_i];
2834 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2835 if (!declaration.included)
2836 declaration.include(false);
2837 var node = declaration.parent;
2838 while (!node.included) {
2839 // We do not want to properly include parents in case they are part of a dead branch
2840 // in which case .include() might pull in more dead code
2841 node.included = true;
2842 if (node.type === Program)
2843 break;
2844 node = node.parent;
2845 }
2846 }
2847 }
2848 };
2849 return LocalVariable;
2850}(Variable));
2851LocalVariable.prototype.isLocal = true;
2852
2853function isExportDefaultVariable(variable) {
2854 return variable.isDefault;
2855}
2856var ExportDefaultVariable = /** @class */ (function (_super) {
2857 __extends(ExportDefaultVariable, _super);
2858 function ExportDefaultVariable(name, exportDefaultDeclaration, context) {
2859 var _this = _super.call(this, name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context) || this;
2860 // Not initialised during construction
2861 _this.originalId = null;
2862 var declaration = exportDefaultDeclaration.declaration;
2863 if ((declaration.type === FunctionDeclaration ||
2864 declaration.type === ClassDeclaration) &&
2865 declaration.id) {
2866 _this.hasId = true;
2867 _this.originalId = declaration.id;
2868 }
2869 else if (declaration.type === Identifier) {
2870 _this.originalId = declaration;
2871 }
2872 return _this;
2873 }
2874 ExportDefaultVariable.prototype.addReference = function (identifier) {
2875 if (!this.hasId) {
2876 this.name = identifier.name;
2877 }
2878 };
2879 ExportDefaultVariable.prototype.getName = function () {
2880 return this.referencesOriginal() ? this.originalId.variable.getName() : _super.prototype.getName.call(this);
2881 };
2882 ExportDefaultVariable.prototype.getOriginalVariable = function () {
2883 return (this.originalId && this.originalId.variable) || null;
2884 };
2885 ExportDefaultVariable.prototype.getOriginalVariableName = function () {
2886 return (this.originalId && this.originalId.name) || null;
2887 };
2888 ExportDefaultVariable.prototype.referencesOriginal = function () {
2889 return this.originalId && (this.hasId || !this.originalId.variable.isReassigned);
2890 };
2891 ExportDefaultVariable.prototype.setRenderNames = function (baseName, name) {
2892 if (this.referencesOriginal()) {
2893 this.originalId.variable.setRenderNames(baseName, name);
2894 }
2895 else {
2896 _super.prototype.setRenderNames.call(this, baseName, name);
2897 }
2898 };
2899 ExportDefaultVariable.prototype.setSafeName = function (name) {
2900 if (this.referencesOriginal()) {
2901 this.originalId.variable.setSafeName(name);
2902 }
2903 else {
2904 _super.prototype.setSafeName.call(this, name);
2905 }
2906 };
2907 return ExportDefaultVariable;
2908}(LocalVariable));
2909ExportDefaultVariable.prototype.getBaseVariableName = ExportDefaultVariable.prototype.getName;
2910ExportDefaultVariable.prototype.isDefault = true;
2911
2912var MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
2913var INTEROP_DEFAULT_VARIABLE = '_interopDefault';
2914
2915var ExportShimVariable = /** @class */ (function (_super) {
2916 __extends(ExportShimVariable, _super);
2917 function ExportShimVariable(module) {
2918 var _this = _super.call(this, MISSING_EXPORT_SHIM_VARIABLE) || this;
2919 _this.module = module;
2920 return _this;
2921 }
2922 return ExportShimVariable;
2923}(Variable));
2924
2925var pureFunctions = {};
2926var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' ');
2927var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' ');
2928var simdMethods = 'abs add and bool check div equal extractLane fromFloat32x4 fromFloat32x4Bits fromFloat64x2 fromFloat64x2Bits fromInt16x8Bits fromInt32x4 fromInt32x4Bits fromInt8x16Bits greaterThan greaterThanOrEqual lessThan lessThanOrEqual load max maxNum min minNum mul neg not notEqual or reciprocalApproximation reciprocalSqrtApproximation replaceLane select selectBits shiftLeftByScalar shiftRightArithmeticByScalar shiftRightLogicalByScalar shuffle splat sqrt store sub swizzle xor'.split(' ');
2929var allSimdMethods = [];
2930simdTypes.forEach(function (t) {
2931 simdMethods.forEach(function (m) {
2932 allSimdMethods.push("SIMD." + t + "." + m);
2933 });
2934});
2935[
2936 'Array.isArray',
2937 'Error',
2938 'EvalError',
2939 'InternalError',
2940 'RangeError',
2941 'ReferenceError',
2942 'SyntaxError',
2943 'TypeError',
2944 'URIError',
2945 'isFinite',
2946 'isNaN',
2947 'parseFloat',
2948 'parseInt',
2949 'decodeURI',
2950 'decodeURIComponent',
2951 'encodeURI',
2952 'encodeURIComponent',
2953 'escape',
2954 'unescape',
2955 'Object',
2956 'Object.create',
2957 'Object.getNotifier',
2958 'Object.getOwn',
2959 'Object.getOwnPropertyDescriptor',
2960 'Object.getOwnPropertyNames',
2961 'Object.getOwnPropertySymbols',
2962 'Object.getPrototypeOf',
2963 'Object.is',
2964 'Object.isExtensible',
2965 'Object.isFrozen',
2966 'Object.isSealed',
2967 'Object.keys',
2968 'Boolean',
2969 'Number',
2970 'Number.isFinite',
2971 'Number.isInteger',
2972 'Number.isNaN',
2973 'Number.isSafeInteger',
2974 'Number.parseFloat',
2975 'Number.parseInt',
2976 'Symbol',
2977 'Symbol.for',
2978 'Symbol.keyFor',
2979 'Math.abs',
2980 'Math.acos',
2981 'Math.acosh',
2982 'Math.asin',
2983 'Math.asinh',
2984 'Math.atan',
2985 'Math.atan2',
2986 'Math.atanh',
2987 'Math.cbrt',
2988 'Math.ceil',
2989 'Math.clz32',
2990 'Math.cos',
2991 'Math.cosh',
2992 'Math.exp',
2993 'Math.expm1',
2994 'Math.floor',
2995 'Math.fround',
2996 'Math.hypot',
2997 'Math.imul',
2998 'Math.log',
2999 'Math.log10',
3000 'Math.log1p',
3001 'Math.log2',
3002 'Math.max',
3003 'Math.min',
3004 'Math.pow',
3005 'Math.random',
3006 'Math.round',
3007 'Math.sign',
3008 'Math.sin',
3009 'Math.sinh',
3010 'Math.sqrt',
3011 'Math.tan',
3012 'Math.tanh',
3013 'Math.trunc',
3014 'Date',
3015 'Date.UTC',
3016 'Date.now',
3017 'Date.parse',
3018 'String',
3019 'String.fromCharCode',
3020 'String.fromCodePoint',
3021 'String.raw',
3022 'RegExp',
3023 'Map',
3024 'Set',
3025 'WeakMap',
3026 'WeakSet',
3027 'ArrayBuffer',
3028 'ArrayBuffer.isView',
3029 'DataView',
3030 'Promise.all',
3031 'Promise.race',
3032 'Promise.resolve',
3033 'Intl.Collator',
3034 'Intl.Collator.supportedLocalesOf',
3035 'Intl.DateTimeFormat',
3036 'Intl.DateTimeFormat.supportedLocalesOf',
3037 'Intl.NumberFormat',
3038 'Intl.NumberFormat.supportedLocalesOf'
3039 // TODO properties of e.g. window...
3040]
3041 .concat(arrayTypes, arrayTypes.map(function (t) { return t + ".from"; }), arrayTypes.map(function (t) { return t + ".of"; }), simdTypes.map(function (t) { return "SIMD." + t; }), allSimdMethods)
3042 .forEach(function (name) { return (pureFunctions[name] = true); });
3043
3044var GlobalVariable = /** @class */ (function (_super) {
3045 __extends(GlobalVariable, _super);
3046 function GlobalVariable() {
3047 return _super !== null && _super.apply(this, arguments) || this;
3048 }
3049 GlobalVariable.prototype.hasEffectsWhenAccessedAtPath = function (path) {
3050 // path.length == 0 can also have an effect but we postpone this for now
3051 return (path.length > 0 &&
3052 !this.isPureFunctionMember(path) &&
3053 !(this.name === 'Reflect' && path.length === 1));
3054 };
3055 GlobalVariable.prototype.hasEffectsWhenCalledAtPath = function (path) {
3056 return !pureFunctions[[this.name].concat(path).join('.')];
3057 };
3058 GlobalVariable.prototype.isPureFunctionMember = function (path) {
3059 return (pureFunctions[[this.name].concat(path).join('.')] ||
3060 (path.length >= 1 && pureFunctions[[this.name].concat(path.slice(0, -1)).join('.')]) ||
3061 (path.length >= 2 &&
3062 pureFunctions[[this.name].concat(path.slice(0, -2)).join('.')] &&
3063 path[path.length - 2] === 'prototype'));
3064 };
3065 return GlobalVariable;
3066}(Variable));
3067
3068var NamespaceVariable = /** @class */ (function (_super) {
3069 __extends(NamespaceVariable, _super);
3070 function NamespaceVariable(context) {
3071 var _this = _super.call(this, context.getModuleName()) || this;
3072 _this.memberVariables = Object.create(null);
3073 _this.containsExternalNamespace = false;
3074 _this.referencedEarly = false;
3075 _this.references = [];
3076 _this.context = context;
3077 _this.module = context.module;
3078 for (var _i = 0, _a = _this.context.getExports().concat(_this.context.getReexports()); _i < _a.length; _i++) {
3079 var name = _a[_i];
3080 if (name[0] === '*' && name.length > 1)
3081 _this.containsExternalNamespace = true;
3082 _this.memberVariables[name] = _this.context.traceExport(name);
3083 }
3084 return _this;
3085 }
3086 NamespaceVariable.prototype.addReference = function (identifier) {
3087 this.references.push(identifier);
3088 this.name = identifier.name;
3089 };
3090 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
3091 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
3092 // the reassignment to the right variable. This means we lost track of this variable and thus
3093 // need to reassign all exports.
3094 NamespaceVariable.prototype.deoptimizePath = function () {
3095 for (var key in this.memberVariables) {
3096 this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
3097 }
3098 };
3099 NamespaceVariable.prototype.include = function () {
3100 if (!this.included) {
3101 if (this.containsExternalNamespace) {
3102 this.context.error({
3103 code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
3104 id: this.module.id,
3105 message: "Cannot create an explicit namespace object for module \"" + this.context.getModuleName() + "\" because it contains a reexported external namespace"
3106 }, undefined);
3107 }
3108 this.included = true;
3109 for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
3110 var identifier = _a[_i];
3111 if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
3112 this.referencedEarly = true;
3113 break;
3114 }
3115 }
3116 if (this.context.preserveModules) {
3117 for (var _b = 0, _c = Object.keys(this.memberVariables); _b < _c.length; _b++) {
3118 var memberName = _c[_b];
3119 this.memberVariables[memberName].include();
3120 }
3121 }
3122 else {
3123 for (var _d = 0, _e = Object.keys(this.memberVariables); _d < _e.length; _d++) {
3124 var memberName = _e[_d];
3125 this.context.includeVariable(this.memberVariables[memberName]);
3126 }
3127 }
3128 }
3129 };
3130 NamespaceVariable.prototype.renderBlock = function (options) {
3131 var _this = this;
3132 var _ = options.compact ? '' : ' ';
3133 var n = options.compact ? '' : '\n';
3134 var t = options.indent;
3135 var members = Object.keys(this.memberVariables).map(function (name) {
3136 var original = _this.memberVariables[name];
3137 if (_this.referencedEarly || original.isReassigned) {
3138 return t + "get " + name + _ + "()" + _ + "{" + _ + "return " + original.getName() + (options.compact ? '' : ';') + _ + "}";
3139 }
3140 return "" + t + name + ": " + original.getName();
3141 });
3142 var name = this.getName();
3143 var callee = options.freeze ? "/*#__PURE__*/Object.freeze" : '';
3144 var output = options.varOrConst + " " + name + " = " + (options.namespaceToStringTag
3145 ? "{" + n + members.join("," + n) + n + "};"
3146 : callee + "({" + n + members.join("," + n) + n + "});");
3147 if (options.namespaceToStringTag) {
3148 output += n + "if" + _ + "(typeof Symbol" + _ + "!==" + _ + "'undefined'" + _ + "&&" + _ + "Symbol.toStringTag)" + n;
3149 output += t + "Object.defineProperty(" + name + "," + _ + "Symbol.toStringTag," + _ + "{" + _ + "value:" + _ + "'Module'" + _ + "});" + n;
3150 output += "else" + (n || ' ');
3151 output += t + "Object.defineProperty(" + name + "," + _ + "'toString'," + _ + "{" + _ + "value:" + _ + "function" + _ + "()" + _ + "{" + _ + "return" + _ + "'[object Module]'" + (options.compact ? ';' : '') + _ + "}" + _ + "});" + n;
3152 output += callee + "(" + name + ");";
3153 }
3154 if (options.format === 'system' && this.exportName) {
3155 output += n + "exports('" + this.exportName + "'," + _ + name + ");";
3156 }
3157 return output;
3158 };
3159 NamespaceVariable.prototype.renderFirst = function () {
3160 return this.referencedEarly;
3161 };
3162 return NamespaceVariable;
3163}(Variable));
3164NamespaceVariable.prototype.isNamespace = true;
3165
3166var ExternalVariable = /** @class */ (function (_super) {
3167 __extends(ExternalVariable, _super);
3168 function ExternalVariable(module, name) {
3169 var _this = _super.call(this, name) || this;
3170 _this.module = module;
3171 _this.isNamespace = name === '*';
3172 _this.referenced = false;
3173 return _this;
3174 }
3175 ExternalVariable.prototype.addReference = function (identifier) {
3176 this.referenced = true;
3177 if (this.name === 'default' || this.name === '*') {
3178 this.module.suggestName(identifier.name);
3179 }
3180 };
3181 ExternalVariable.prototype.include = function () {
3182 if (!this.included) {
3183 this.included = true;
3184 this.module.used = true;
3185 }
3186 };
3187 return ExternalVariable;
3188}(Variable));
3189ExternalVariable.prototype.isExternal = true;
3190
3191var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' ');
3192var builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' ');
3193var blacklisted = Object.create(null);
3194reservedWords.concat(builtins).forEach(function (word) { return (blacklisted[word] = true); });
3195var illegalCharacters = /[^$_a-zA-Z0-9]/g;
3196var startsWithDigit = function (str) { return /\d/.test(str[0]); };
3197function isLegal(str) {
3198 if (startsWithDigit(str) || blacklisted[str]) {
3199 return false;
3200 }
3201 return !illegalCharacters.test(str);
3202}
3203function makeLegal(str) {
3204 str = str.replace(/-(\w)/g, function (_, letter) { return letter.toUpperCase(); }).replace(illegalCharacters, '_');
3205 if (startsWithDigit(str) || blacklisted[str])
3206 str = "_" + str;
3207 return str;
3208}
3209
3210var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
3211var relativePath = /^\.?\.\//;
3212function isAbsolute(path) {
3213 return absolutePath.test(path);
3214}
3215function isRelative(path) {
3216 return relativePath.test(path);
3217}
3218function normalize(path) {
3219 if (path.indexOf('\\') == -1)
3220 return path;
3221 return path.replace(/\\/g, '/');
3222}
3223
3224var ExternalModule = /** @class */ (function () {
3225 function ExternalModule(_a) {
3226 var graph = _a.graph, id = _a.id;
3227 this.exportsNames = false;
3228 this.exportsNamespace = false;
3229 this.isEntryPoint = false;
3230 this.isExternal = true;
3231 this.mostCommonSuggestion = 0;
3232 this.reexported = false;
3233 this.renderPath = undefined;
3234 this.renormalizeRenderPath = false;
3235 this.used = false;
3236 this.graph = graph;
3237 this.id = id;
3238 this.execIndex = Infinity;
3239 var parts = id.split(/[\\/]/);
3240 this.variableName = makeLegal(parts.pop());
3241 this.nameSuggestions = Object.create(null);
3242 this.declarations = Object.create(null);
3243 this.exportedVariables = new Map();
3244 }
3245 ExternalModule.prototype.getVariableForExportName = function (name, _isExportAllSearch) {
3246 if (name !== 'default' && name !== '*')
3247 this.exportsNames = true;
3248 if (name === '*')
3249 this.exportsNamespace = true;
3250 var declaration = this.declarations[name];
3251 if (declaration)
3252 return declaration;
3253 this.declarations[name] = declaration = new ExternalVariable(this, name);
3254 this.exportedVariables.set(declaration, name);
3255 return declaration;
3256 };
3257 ExternalModule.prototype.setRenderPath = function (options, inputBase) {
3258 this.renderPath = '';
3259 if (options.paths) {
3260 this.renderPath =
3261 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
3262 }
3263 if (!this.renderPath) {
3264 if (!isAbsolute(this.id)) {
3265 this.renderPath = this.id;
3266 }
3267 else {
3268 this.renderPath = normalize(relative(inputBase, this.id));
3269 this.renormalizeRenderPath = true;
3270 }
3271 }
3272 return this.renderPath;
3273 };
3274 ExternalModule.prototype.suggestName = function (name) {
3275 if (!this.nameSuggestions[name])
3276 this.nameSuggestions[name] = 0;
3277 this.nameSuggestions[name] += 1;
3278 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
3279 this.mostCommonSuggestion = this.nameSuggestions[name];
3280 this.variableName = name;
3281 }
3282 };
3283 ExternalModule.prototype.warnUnusedImports = function () {
3284 var _this = this;
3285 var unused = Object.keys(this.declarations).filter(function (name) {
3286 if (name === '*')
3287 return false;
3288 var declaration = _this.declarations[name];
3289 return !declaration.included && !_this.reexported && !declaration.referenced;
3290 });
3291 if (unused.length === 0)
3292 return;
3293 var names = unused.length === 1
3294 ? "'" + unused[0] + "' is"
3295 : unused
3296 .slice(0, -1)
3297 .map(function (name) { return "'" + name + "'"; })
3298 .join(', ') + " and '" + unused.slice(-1) + "' are";
3299 this.graph.warn({
3300 code: 'UNUSED_EXTERNAL_IMPORT',
3301 message: names + " imported from external module '" + this.id + "' but never used",
3302 names: unused,
3303 source: this.id
3304 });
3305 };
3306 return ExternalModule;
3307}());
3308
3309var esModuleExport = "Object.defineProperty(exports, '__esModule', { value: true });";
3310var compactEsModuleExport = "Object.defineProperty(exports,'__esModule',{value:true});";
3311
3312function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism) {
3313 if (mechanism === void 0) { mechanism = 'return '; }
3314 var _ = compact ? '' : ' ';
3315 var n = compact ? '' : '\n';
3316 if (!namedExportsMode) {
3317 var local_1;
3318 exports.some(function (expt) {
3319 if (expt.exported === 'default') {
3320 local_1 = expt.local;
3321 return true;
3322 }
3323 return false;
3324 });
3325 // search for reexported default otherwise
3326 if (!local_1) {
3327 dependencies.some(function (dep) {
3328 if (!dep.reexports)
3329 return false;
3330 return dep.reexports.some(function (expt) {
3331 if (expt.reexported === 'default') {
3332 local_1 = dep.namedExportsMode ? dep.name + "." + expt.imported : dep.name;
3333 return true;
3334 }
3335 return false;
3336 });
3337 });
3338 }
3339 return "" + mechanism + local_1 + ";";
3340 }
3341 var exportBlock = '';
3342 // star exports must always output first for precedence
3343 dependencies.forEach(function (_a) {
3344 var name = _a.name, reexports = _a.reexports;
3345 if (reexports && namedExportsMode) {
3346 reexports.forEach(function (specifier) {
3347 if (specifier.reexported === '*') {
3348 if (!compact && exportBlock)
3349 exportBlock += '\n';
3350 exportBlock +=
3351 "Object.keys(" + name + ").forEach(function" + _ + "(key)" + _ + "{" + n +
3352 (t + "Object.defineProperty(exports," + _ + "key," + _ + "{" + n) +
3353 ("" + t + t + "enumerable:" + _ + "true," + n) +
3354 ("" + t + t + "get:" + _ + "function" + _ + "()" + _ + "{" + n) +
3355 ("" + t + t + t + "return " + name + "[key];" + n) +
3356 ("" + t + t + "}" + n + t + "});" + n + "});");
3357 }
3358 });
3359 }
3360 });
3361 dependencies.forEach(function (_a) {
3362 var name = _a.name, imports = _a.imports, reexports = _a.reexports, isChunk = _a.isChunk, depNamedExportsMode = _a.namedExportsMode;
3363 if (reexports && namedExportsMode) {
3364 reexports.forEach(function (specifier) {
3365 if (specifier.imported === 'default' && !isChunk) {
3366 var exportsNamesOrNamespace = (imports && imports.some(function (specifier) { return specifier.imported !== 'default'; })) ||
3367 (reexports &&
3368 reexports.some(function (specifier) { return specifier.imported !== 'default' && specifier.imported !== '*'; }));
3369 var reexportsDefaultAsDefault = reexports &&
3370 reexports.some(function (specifier) { return specifier.imported === 'default' && specifier.reexported === 'default'; });
3371 if (exportBlock && !compact)
3372 exportBlock += '\n';
3373 if (exportsNamesOrNamespace || reexportsDefaultAsDefault)
3374 exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + (interop !== false ? '__default' : '.default') + ";";
3375 else
3376 exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + ";";
3377 }
3378 else if (specifier.imported !== '*') {
3379 if (exportBlock && !compact)
3380 exportBlock += '\n';
3381 var importName = specifier.imported === 'default' && !depNamedExportsMode
3382 ? name
3383 : name + "." + specifier.imported;
3384 exportBlock += specifier.needsLiveBinding
3385 ? "Object.defineProperty(exports," + _ + "'" + specifier.reexported + "'," + _ + "{" + n +
3386 (t + "enumerable:" + _ + "true," + n) +
3387 (t + "get:" + _ + "function" + _ + "()" + _ + "{" + n) +
3388 ("" + t + t + "return " + importName + ";" + n + t + "}" + n + "});")
3389 : "exports." + specifier.reexported + _ + "=" + _ + importName + ";";
3390 }
3391 else if (specifier.reexported !== '*') {
3392 if (exportBlock && !compact)
3393 exportBlock += '\n';
3394 exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + ";";
3395 }
3396 });
3397 }
3398 });
3399 exports.forEach(function (expt) {
3400 var lhs = "exports." + expt.exported;
3401 var rhs = expt.local;
3402 if (lhs === rhs) {
3403 return;
3404 }
3405 if (exportBlock && !compact)
3406 exportBlock += '\n';
3407 exportBlock += "" + lhs + _ + "=" + _ + rhs + ";";
3408 });
3409 return exportBlock;
3410}
3411
3412function getInteropBlock(dependencies, options, varOrConst) {
3413 return dependencies
3414 .map(function (_a) {
3415 var name = _a.name, exportsNames = _a.exportsNames, exportsDefault = _a.exportsDefault, namedExportsMode = _a.namedExportsMode;
3416 if (!namedExportsMode)
3417 return;
3418 if (!exportsDefault || options.interop === false)
3419 return null;
3420 if (exportsNames) {
3421 if (options.compact)
3422 return varOrConst + " " + name + "__default='default'in " + name + "?" + name + "['default']:" + name + ";";
3423 return varOrConst + " " + name + "__default = 'default' in " + name + " ? " + name + "['default'] : " + name + ";";
3424 }
3425 if (options.compact)
3426 return name + "=" + name + "&&" + name + ".hasOwnProperty('default')?" + name + "['default']:" + name + ";";
3427 return name + " = " + name + " && " + name + ".hasOwnProperty('default') ? " + name + "['default'] : " + name + ";";
3428 })
3429 .filter(Boolean)
3430 .join(options.compact ? '' : '\n');
3431}
3432
3433var builtins$1 = {
3434 assert: true,
3435 buffer: true,
3436 console: true,
3437 constants: true,
3438 domain: true,
3439 events: true,
3440 http: true,
3441 https: true,
3442 os: true,
3443 path: true,
3444 process: true,
3445 punycode: true,
3446 querystring: true,
3447 stream: true,
3448 string_decoder: true,
3449 timers: true,
3450 tty: true,
3451 url: true,
3452 util: true,
3453 vm: true,
3454 zlib: true
3455};
3456// Creating a browser chunk that depends on Node.js built-in modules ('util'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins
3457function warnOnBuiltins(warn, dependencies) {
3458 var externalBuiltins = dependencies.map(function (_a) {
3459 var id = _a.id;
3460 return id;
3461 }).filter(function (id) { return id in builtins$1; });
3462 if (!externalBuiltins.length)
3463 return;
3464 var detail = externalBuiltins.length === 1
3465 ? "module ('" + externalBuiltins[0] + "')"
3466 : "modules (" + externalBuiltins
3467 .slice(0, -1)
3468 .map(function (name) { return "'" + name + "'"; })
3469 .join(', ') + " and '" + externalBuiltins.slice(-1) + "')";
3470 warn({
3471 code: 'MISSING_NODE_BUILTINS',
3472 message: "Creating a browser bundle that depends on Node.js built-in " + detail + ". You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins",
3473 modules: externalBuiltins
3474 });
3475}
3476
3477function amd(magicString, _a, options) {
3478 var dependencies = _a.dependencies, dynamicImport = _a.dynamicImport, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, isEntryModuleFacade = _a.isEntryModuleFacade, namedExportsMode = _a.namedExportsMode, needsAmdModule = _a.needsAmdModule, outro = _a.outro, varOrConst = _a.varOrConst, warn = _a.warn;
3479 warnOnBuiltins(warn, dependencies);
3480 var deps = dependencies.map(function (m) { return "'" + m.id + "'"; });
3481 var args = dependencies.map(function (m) { return m.name; });
3482 var n = options.compact ? '' : '\n';
3483 var _ = options.compact ? '' : ' ';
3484 if (namedExportsMode && hasExports) {
3485 args.unshift("exports");
3486 deps.unshift("'exports'");
3487 }
3488 if (dynamicImport) {
3489 args.unshift('require');
3490 deps.unshift("'require'");
3491 }
3492 if (needsAmdModule) {
3493 args.unshift('module');
3494 deps.unshift("'module'");
3495 }
3496 var amdOptions = options.amd || {};
3497 var params = (amdOptions.id ? "'" + amdOptions.id + "'," + _ : "") +
3498 (deps.length ? "[" + deps.join("," + _) + "]," + _ : "");
3499 var useStrict = options.strict !== false ? _ + "'use strict';" : "";
3500 var define = amdOptions.define || 'define';
3501 var wrapperStart = define + "(" + params + "function" + _ + "(" + args.join("," + _) + ")" + _ + "{" + useStrict + n + n;
3502 // var foo__default = 'default' in foo ? foo['default'] : foo;
3503 var interopBlock = getInteropBlock(dependencies, options, varOrConst);
3504 if (interopBlock)
3505 magicString.prepend(interopBlock + n + n);
3506 if (intro)
3507 magicString.prepend(intro);
3508 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
3509 if (exportBlock)
3510 magicString.append(n + n + exportBlock);
3511 if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
3512 magicString.append("" + n + n + (options.compact ? compactEsModuleExport : esModuleExport));
3513 if (outro)
3514 magicString.append(outro);
3515 return magicString
3516 .indent(t)
3517 .append(n + n + '});')
3518 .prepend(wrapperStart);
3519}
3520
3521function cjs(magicString, _a, options) {
3522 var dependencies = _a.dependencies, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, isEntryModuleFacade = _a.isEntryModuleFacade, namedExportsMode = _a.namedExportsMode, outro = _a.outro, varOrConst = _a.varOrConst;
3523 var n = options.compact ? '' : '\n';
3524 var _ = options.compact ? '' : ' ';
3525 intro =
3526 (options.strict === false ? intro : "'use strict';" + n + n + intro) +
3527 (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
3528 ? "" + (options.compact ? compactEsModuleExport : esModuleExport) + n + n
3529 : '');
3530 var needsInterop = false;
3531 var interop = options.interop !== false;
3532 var importBlock;
3533 var definingVariable = false;
3534 importBlock = '';
3535 for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
3536 var _b = dependencies_1[_i], id = _b.id, namedExportsMode_1 = _b.namedExportsMode, isChunk = _b.isChunk, name = _b.name, reexports = _b.reexports, imports = _b.imports, exportsNames = _b.exportsNames, exportsDefault = _b.exportsDefault;
3537 if (!reexports && !imports) {
3538 if (importBlock) {
3539 importBlock += !options.compact || definingVariable ? ";" + n : ',';
3540 }
3541 definingVariable = false;
3542 importBlock += "require('" + id + "')";
3543 }
3544 else {
3545 importBlock +=
3546 options.compact && definingVariable ? ',' : "" + (importBlock ? ";" + n : '') + varOrConst + " ";
3547 definingVariable = true;
3548 if (!interop || isChunk || !exportsDefault || !namedExportsMode_1) {
3549 importBlock += "" + name + _ + "=" + _ + "require('" + id + "')";
3550 }
3551 else {
3552 needsInterop = true;
3553 if (exportsNames)
3554 importBlock += "" + name + _ + "=" + _ + "require('" + id + "')" + (options.compact ? ',' : ";\n" + varOrConst + " ") + name + "__default" + _ + "=" + _ + INTEROP_DEFAULT_VARIABLE + "(" + name + ")";
3555 else
3556 importBlock += "" + name + _ + "=" + _ + INTEROP_DEFAULT_VARIABLE + "(require('" + id + "'))";
3557 }
3558 }
3559 }
3560 if (importBlock)
3561 importBlock += ';';
3562 if (needsInterop) {
3563 var ex = options.compact ? 'e' : 'ex';
3564 intro +=
3565 "function " + INTEROP_DEFAULT_VARIABLE + _ + "(" + ex + ")" + _ + "{" + _ + "return" + _ +
3566 ("(" + ex + _ + "&&" + _ + "(typeof " + ex + _ + "===" + _ + "'object')" + _ + "&&" + _ + "'default'" + _ + "in " + ex + ")" + _) +
3567 ("?" + _ + ex + "['default']" + _ + ":" + _ + ex + (options.compact ? '' : '; ') + "}" + n + n);
3568 }
3569 if (importBlock)
3570 intro += importBlock + n + n;
3571 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, "module.exports" + _ + "=" + _);
3572 magicString.prepend(intro);
3573 if (exportBlock)
3574 magicString.append(n + n + exportBlock);
3575 if (outro)
3576 magicString.append(outro);
3577 return magicString;
3578}
3579
3580function esm(magicString, _a, options) {
3581 var intro = _a.intro, outro = _a.outro, dependencies = _a.dependencies, exports = _a.exports;
3582 var _ = options.compact ? '' : ' ';
3583 var n = options.compact ? '' : '\n';
3584 var importBlock = dependencies
3585 .map(function (_a) {
3586 var id = _a.id, reexports = _a.reexports, imports = _a.imports, name = _a.name;
3587 if (!reexports && !imports) {
3588 return "import" + _ + "'" + id + "';";
3589 }
3590 var output = '';
3591 if (imports) {
3592 var defaultImport_1 = imports.find(function (specifier) { return specifier.imported === 'default'; });
3593 var starImport_1 = imports.find(function (specifier) { return specifier.imported === '*'; });
3594 if (starImport_1) {
3595 output += "import" + _ + "*" + _ + "as " + starImport_1.local + " from" + _ + "'" + id + "';";
3596 if (imports.length > 1)
3597 output += n;
3598 }
3599 if (defaultImport_1 && imports.length === 1) {
3600 output += "import " + defaultImport_1.local + " from" + _ + "'" + id + "';";
3601 }
3602 else if (!starImport_1 || imports.length > 1) {
3603 output += "import " + (defaultImport_1 ? defaultImport_1.local + "," + _ : '') + "{" + _ + imports
3604 .filter(function (specifier) { return specifier !== defaultImport_1 && specifier !== starImport_1; })
3605 .map(function (specifier) {
3606 if (specifier.imported === specifier.local) {
3607 return specifier.imported;
3608 }
3609 else {
3610 return specifier.imported + " as " + specifier.local;
3611 }
3612 })
3613 .join("," + _) + _ + "}" + _ + "from" + _ + "'" + id + "';";
3614 }
3615 }
3616 if (reexports) {
3617 if (imports)
3618 output += n;
3619 var starExport_1 = reexports.find(function (specifier) { return specifier.reexported === '*'; });
3620 var namespaceReexport_1 = reexports.find(function (specifier) { return specifier.imported === '*' && specifier.reexported !== '*'; });
3621 if (starExport_1) {
3622 output += "export" + _ + "*" + _ + "from" + _ + "'" + id + "';";
3623 if (reexports.length === 1) {
3624 return output;
3625 }
3626 output += n;
3627 }
3628 if (namespaceReexport_1) {
3629 if (!imports ||
3630 !imports.some(function (specifier) { return specifier.imported === '*' && specifier.local === name; }))
3631 output += "import" + _ + "*" + _ + "as " + name + " from" + _ + "'" + id + "';" + n;
3632 output += "export" + _ + "{" + _ + (name === namespaceReexport_1.reexported
3633 ? name
3634 : name + " as " + namespaceReexport_1.reexported) + " };";
3635 if (reexports.length === (starExport_1 ? 2 : 1)) {
3636 return output;
3637 }
3638 output += n;
3639 }
3640 output += "export" + _ + "{" + _ + reexports
3641 .filter(function (specifier) { return specifier !== starExport_1 && specifier !== namespaceReexport_1; })
3642 .map(function (specifier) {
3643 if (specifier.imported === specifier.reexported) {
3644 return specifier.imported;
3645 }
3646 else {
3647 return specifier.imported + " as " + specifier.reexported;
3648 }
3649 })
3650 .join("," + _) + _ + "}" + _ + "from" + _ + "'" + id + "';";
3651 }
3652 return output;
3653 })
3654 .join(n);
3655 if (importBlock)
3656 intro += importBlock + n + n;
3657 if (intro)
3658 magicString.prepend(intro);
3659 var exportBlock = [];
3660 var exportDeclaration = [];
3661 exports.forEach(function (specifier) {
3662 if (specifier.exported === 'default') {
3663 exportBlock.push("export default " + specifier.local + ";");
3664 }
3665 else {
3666 exportDeclaration.push(specifier.exported === specifier.local
3667 ? specifier.local
3668 : specifier.local + " as " + specifier.exported);
3669 }
3670 });
3671 if (exportDeclaration.length) {
3672 exportBlock.push("export" + _ + "{" + _ + exportDeclaration.join("," + _) + _ + "};");
3673 }
3674 if (exportBlock.length)
3675 magicString.append(n + n + exportBlock.join(n).trim());
3676 if (outro)
3677 magicString.append(outro);
3678 return magicString.trim();
3679}
3680
3681function getLocator$1(source, options) {
3682 if (options === void 0) { options = {}; }
3683 var offsetLine = options.offsetLine || 0;
3684 var offsetColumn = options.offsetColumn || 0;
3685 var originalLines = source.split('\n');
3686 var start = 0;
3687 var lineRanges = originalLines.map(function (line, i) {
3688 var end = start + line.length + 1;
3689 var range = { start: start, end: end, line: i };
3690 start = end;
3691 return range;
3692 });
3693 var i = 0;
3694 function rangeContains(range, index) {
3695 return range.start <= index && index < range.end;
3696 }
3697 function getLocation(range, index) {
3698 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
3699 }
3700 function locate(search, startIndex) {
3701 if (typeof search === 'string') {
3702 search = source.indexOf(search, startIndex || 0);
3703 }
3704 var range = lineRanges[i];
3705 var d = search >= range.end ? 1 : -1;
3706 while (range) {
3707 if (rangeContains(range, search))
3708 return getLocation(range, search);
3709 i += d;
3710 range = lineRanges[i];
3711 }
3712 }
3713 return locate;
3714}
3715function locate(source, search, options) {
3716 if (typeof options === 'number') {
3717 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
3718 }
3719 return getLocator$1(source, options)(search, options && options.startIndex);
3720}
3721
3722function spaces(i) {
3723 var result = '';
3724 while (i--)
3725 result += ' ';
3726 return result;
3727}
3728function tabsToSpaces(str) {
3729 return str.replace(/^\t+/, function (match) { return match.split('\t').join(' '); });
3730}
3731function getCodeFrame(source, line, column) {
3732 var lines = source.split('\n');
3733 var frameStart = Math.max(0, line - 3);
3734 var frameEnd = Math.min(line + 2, lines.length);
3735 lines = lines.slice(frameStart, frameEnd);
3736 while (!/\S/.test(lines[lines.length - 1])) {
3737 lines.pop();
3738 frameEnd -= 1;
3739 }
3740 var digits = String(frameEnd).length;
3741 return lines
3742 .map(function (str, i) {
3743 var isErrorLine = frameStart + i + 1 === line;
3744 var lineNum = String(i + frameStart + 1);
3745 while (lineNum.length < digits)
3746 lineNum = " " + lineNum;
3747 if (isErrorLine) {
3748 var indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
3749 return lineNum + ": " + tabsToSpaces(str) + "\n" + indicator;
3750 }
3751 return lineNum + ": " + tabsToSpaces(str);
3752 })
3753 .join('\n');
3754}
3755
3756function error(base, props) {
3757 if (base instanceof Error === false)
3758 base = Object.assign(new Error(base.message), base);
3759 if (props)
3760 Object.assign(base, props);
3761 throw base;
3762}
3763function augmentCodeLocation(object, pos, source, id) {
3764 if (pos.line !== undefined && pos.column !== undefined) {
3765 var line = pos.line, column = pos.column;
3766 object.loc = { file: id, line: line, column: column };
3767 }
3768 else {
3769 object.pos = pos;
3770 var _a = locate(source, pos, { offsetLine: 1 }), line = _a.line, column = _a.column;
3771 object.loc = { file: id, line: line, column: column };
3772 }
3773 if (object.frame === undefined) {
3774 var _b = object.loc, line = _b.line, column = _b.column;
3775 object.frame = getCodeFrame(source, line, column);
3776 }
3777}
3778
3779// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
3780// if the property name isn't trivial
3781var shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
3782function property(prop) {
3783 return shouldUseDot.test(prop) ? "." + prop : "['" + prop + "']";
3784}
3785function keypath(keypath) {
3786 return keypath
3787 .split('.')
3788 .map(property)
3789 .join('');
3790}
3791
3792function setupNamespace(name, root, globals, compact) {
3793 var parts = name.split('.');
3794 if (globals) {
3795 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
3796 }
3797 var _ = compact ? '' : ' ';
3798 parts.pop();
3799 var acc = root;
3800 return (parts
3801 .map(function (part) { return ((acc += property(part)), "" + acc + _ + "=" + _ + acc + _ + "||" + _ + "{}" + (compact ? '' : ';')); })
3802 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
3803}
3804function assignToDeepVariable(deepName, root, globals, compact, assignment) {
3805 var _ = compact ? '' : ' ';
3806 var parts = deepName.split('.');
3807 if (globals) {
3808 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
3809 }
3810 var last = parts.pop();
3811 var acc = root;
3812 var deepAssignment = parts
3813 .map(function (part) { return ((acc += property(part)), "" + acc + _ + "=" + _ + acc + _ + "||" + _ + "{}"); })
3814 .concat("" + acc + property(last))
3815 .join("," + _)
3816 .concat(_ + "=" + _ + assignment);
3817 if (parts.length > 0) {
3818 deepAssignment = "(" + deepAssignment + ")";
3819 }
3820 return deepAssignment;
3821}
3822
3823function trimEmptyImports(dependencies) {
3824 var i = dependencies.length;
3825 while (i--) {
3826 var dependency = dependencies[i];
3827 if (dependency.exportsDefault || dependency.exportsNames) {
3828 return dependencies.slice(0, i + 1);
3829 }
3830 }
3831 return [];
3832}
3833
3834var thisProp = function (name) { return "this" + keypath(name); };
3835function iife(magicString, _a, options) {
3836 var dependencies = _a.dependencies, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, namedExportsMode = _a.namedExportsMode, outro = _a.outro, varOrConst = _a.varOrConst, warn = _a.warn;
3837 var _ = options.compact ? '' : ' ';
3838 var n = options.compact ? '' : '\n';
3839 var extend = options.extend, name = options.name;
3840 var isNamespaced = name && name.indexOf('.') !== -1;
3841 var useVariableAssignment = !extend && !isNamespaced;
3842 if (name && useVariableAssignment && !isLegal(name)) {
3843 error({
3844 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
3845 message: "Given name (" + name + ") is not legal JS identifier. If you need this you can try --extend option"
3846 });
3847 }
3848 warnOnBuiltins(warn, dependencies);
3849 var external = trimEmptyImports(dependencies);
3850 var deps = external.map(function (dep) { return dep.globalName || 'null'; });
3851 var args = external.map(function (m) { return m.name; });
3852 if (hasExports && !name) {
3853 error({
3854 code: 'INVALID_OPTION',
3855 message: "You must supply \"output.name\" for IIFE bundles."
3856 });
3857 }
3858 if (namedExportsMode && hasExports) {
3859 if (extend) {
3860 deps.unshift("" + thisProp(name) + _ + "=" + _ + thisProp(name) + _ + "||" + _ + "{}");
3861 args.unshift('exports');
3862 }
3863 else {
3864 deps.unshift('{}');
3865 args.unshift('exports');
3866 }
3867 }
3868 var useStrict = options.strict !== false ? t + "'use strict';" + n + n : "";
3869 var wrapperIntro = "(function" + _ + "(" + args.join("," + _) + ")" + _ + "{" + n + useStrict;
3870 if (hasExports && (!extend || !namedExportsMode)) {
3871 wrapperIntro =
3872 (useVariableAssignment ? varOrConst + " " + name : thisProp(name)) +
3873 (_ + "=" + _ + wrapperIntro);
3874 }
3875 if (isNamespaced && hasExports) {
3876 wrapperIntro = setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
3877 }
3878 var wrapperOutro = "" + n + n + "}(" + deps.join("," + _) + "));";
3879 if (!extend && namedExportsMode && hasExports) {
3880 wrapperOutro = "" + n + n + t + "return exports;" + wrapperOutro;
3881 }
3882 // var foo__default = 'default' in foo ? foo['default'] : foo;
3883 var interopBlock = getInteropBlock(dependencies, options, varOrConst);
3884 if (interopBlock)
3885 magicString.prepend(interopBlock + n + n);
3886 if (intro)
3887 magicString.prepend(intro);
3888 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
3889 if (exportBlock)
3890 magicString.append(n + n + exportBlock);
3891 if (outro)
3892 magicString.append(outro);
3893 return magicString
3894 .indent(t)
3895 .prepend(wrapperIntro)
3896 .append(wrapperOutro);
3897}
3898
3899function getStarExcludes(_a) {
3900 var dependencies = _a.dependencies, exports = _a.exports;
3901 var starExcludes = new Set(exports.map(function (expt) { return expt.exported; }));
3902 if (!starExcludes.has('default'))
3903 starExcludes.add('default');
3904 // also include reexport names
3905 dependencies.forEach(function (_a) {
3906 var reexports = _a.reexports;
3907 if (reexports)
3908 reexports.forEach(function (reexport) {
3909 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
3910 starExcludes.add(reexport.reexported);
3911 });
3912 });
3913 return starExcludes;
3914}
3915var getStarExcludesBlock = function (starExcludes, varOrConst, _, t, n) {
3916 return starExcludes
3917 ? "" + n + t + varOrConst + " _starExcludes" + _ + "=" + _ + "{" + _ + Array.from(starExcludes).join(":" + _ + "1," + _) + (starExcludes.size ? ":" + _ + "1" : '') + _ + "};"
3918 : '';
3919};
3920var getImportBindingsBlock = function (importBindings, _, t, n) { return (importBindings.length ? "" + n + t + "var " + importBindings.join("," + _) + ";" : ''); };
3921function getExportsBlock(exports, _, t, n) {
3922 if (exports.length === 0) {
3923 return '';
3924 }
3925 if (exports.length === 1) {
3926 return "" + t + t + t + "exports('" + exports[0].name + "'," + _ + exports[0].value + ");" + n + n;
3927 }
3928 return ("" + t + t + t + "exports({" + n +
3929 exports.map(function (_a) {
3930 var name = _a.name, value = _a.value;
3931 return "" + t + t + t + t + name + ":" + _ + value;
3932 }).join("," + n) +
3933 ("" + n + t + t + t + "});" + n + n));
3934}
3935var getHoistedExportsBlock = function (exports, _, t, n) {
3936 return getExportsBlock(exports
3937 .filter(function (expt) { return expt.hoisted || expt.uninitialized; })
3938 .map(function (expt) { return ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local }); }), _, t, n);
3939};
3940var getMissingExportsBlock = function (exports, _, t, n) {
3941 return getExportsBlock(exports
3942 .filter(function (expt) { return expt.local === MISSING_EXPORT_SHIM_VARIABLE; })
3943 .map(function (expt) { return ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE }); }), _, t, n);
3944};
3945function system(magicString, _a, options) {
3946 var dependencies = _a.dependencies, exports = _a.exports, t = _a.indentString, intro = _a.intro, outro = _a.outro, usesTopLevelAwait = _a.usesTopLevelAwait, varOrConst = _a.varOrConst;
3947 var n = options.compact ? '' : '\n';
3948 var _ = options.compact ? '' : ' ';
3949 var dependencyIds = dependencies.map(function (m) { return "'" + m.id + "'"; });
3950 var importBindings = [];
3951 var starExcludes;
3952 var setters = [];
3953 dependencies.forEach(function (_a) {
3954 var imports = _a.imports, reexports = _a.reexports;
3955 var setter = [];
3956 if (imports) {
3957 imports.forEach(function (specifier) {
3958 importBindings.push(specifier.local);
3959 if (specifier.imported === '*') {
3960 setter.push("" + specifier.local + _ + "=" + _ + "module;");
3961 }
3962 else {
3963 setter.push("" + specifier.local + _ + "=" + _ + "module." + specifier.imported + ";");
3964 }
3965 });
3966 }
3967 if (reexports) {
3968 var createdSetter_1 = false;
3969 // bulk-reexport form
3970 if (reexports.length > 1 ||
3971 (reexports.length === 1 &&
3972 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
3973 // star reexports
3974 reexports.forEach(function (specifier) {
3975 if (specifier.reexported !== '*')
3976 return;
3977 // need own exports list for deduping in star export case
3978 if (!starExcludes) {
3979 starExcludes = getStarExcludes({ dependencies: dependencies, exports: exports });
3980 }
3981 if (!createdSetter_1) {
3982 setter.push(varOrConst + " _setter" + _ + "=" + _ + "{};");
3983 createdSetter_1 = true;
3984 }
3985 setter.push("for" + _ + "(var _$p" + _ + "in" + _ + "module)" + _ + "{");
3986 setter.push(t + "if" + _ + "(!_starExcludes[_$p])" + _ + "_setter[_$p]" + _ + "=" + _ + "module[_$p];");
3987 setter.push('}');
3988 });
3989 // star import reexport
3990 reexports.forEach(function (specifier) {
3991 if (specifier.imported !== '*' || specifier.reexported === '*')
3992 return;
3993 setter.push("exports('" + specifier.reexported + "'," + _ + "module);");
3994 });
3995 // reexports
3996 reexports.forEach(function (specifier) {
3997 if (specifier.reexported === '*' || specifier.imported === '*')
3998 return;
3999 if (!createdSetter_1) {
4000 setter.push(varOrConst + " _setter" + _ + "=" + _ + "{};");
4001 createdSetter_1 = true;
4002 }
4003 setter.push("_setter." + specifier.reexported + _ + "=" + _ + "module." + specifier.imported + ";");
4004 });
4005 if (createdSetter_1) {
4006 setter.push('exports(_setter);');
4007 }
4008 }
4009 else {
4010 // single reexport
4011 reexports.forEach(function (specifier) {
4012 setter.push("exports('" + specifier.reexported + "'," + _ + "module." + specifier.imported + ");");
4013 });
4014 }
4015 }
4016 setters.push(setter.join("" + n + t + t + t));
4017 });
4018 var registeredName = options.name ? "'" + options.name + "'," + _ : '';
4019 var wrapperStart = "System.register(" + registeredName + "[" +
4020 dependencyIds.join("," + _) +
4021 ("]," + _ + "function" + _ + "(exports," + _ + "module)" + _ + "{" + n + t + "'use strict';") +
4022 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
4023 getImportBindingsBlock(importBindings, _, t, n) +
4024 ("" + n + t + "return" + _ + "{" + (setters.length
4025 ? "" + n + t + t + "setters:" + _ + "[" + setters
4026 .map(function (s) {
4027 return s
4028 ? "function" + _ + "(module)" + _ + "{" + n + t + t + t + s + n + t + t + "}"
4029 : "function" + _ + "()" + _ + "{}";
4030 })
4031 .join("," + _) + "],"
4032 : '') + n);
4033 wrapperStart +=
4034 "" + t + t + "execute:" + _ + (usesTopLevelAwait ? "async" + _ : '') + "function" + _ + "()" + _ + "{" + n + n +
4035 getHoistedExportsBlock(exports, _, t, n);
4036 var wrapperEnd = "" + n + n +
4037 getMissingExportsBlock(exports, _, t, n) +
4038 ("" + t + t + "}" + n + t + "}" + (options.compact ? '' : ';') + n + "});");
4039 if (intro)
4040 magicString.prepend(intro);
4041 if (outro)
4042 magicString.append(outro);
4043 return magicString
4044 .indent("" + t + t + t)
4045 .append(wrapperEnd)
4046 .prepend(wrapperStart);
4047}
4048
4049function globalProp(name, globalVar) {
4050 if (!name)
4051 return 'null';
4052 return "" + globalVar + keypath(name);
4053}
4054function safeAccess(name, globalVar, _) {
4055 var parts = name.split('.');
4056 var acc = globalVar;
4057 return parts.map(function (part) { return ((acc += property(part)), acc); }).join(_ + "&&" + _);
4058}
4059function umd(magicString, _a, options) {
4060 var dependencies = _a.dependencies, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, namedExportsMode = _a.namedExportsMode, outro = _a.outro, varOrConst = _a.varOrConst, warn = _a.warn;
4061 var _ = options.compact ? '' : ' ';
4062 var n = options.compact ? '' : '\n';
4063 var factoryVar = options.compact ? 'f' : 'factory';
4064 var globalVar = options.compact ? 'g' : 'global';
4065 if (hasExports && !options.name) {
4066 error({
4067 code: 'INVALID_OPTION',
4068 message: 'You must supply "output.name" for UMD bundles.'
4069 });
4070 }
4071 warnOnBuiltins(warn, dependencies);
4072 var amdDeps = dependencies.map(function (m) { return "'" + m.id + "'"; });
4073 var cjsDeps = dependencies.map(function (m) { return "require('" + m.id + "')"; });
4074 var trimmedImports = trimEmptyImports(dependencies);
4075 var globalDeps = trimmedImports.map(function (module) { return globalProp(module.globalName, globalVar); });
4076 var factoryArgs = trimmedImports.map(function (m) { return m.name; });
4077 if (namedExportsMode && (hasExports || options.noConflict === true)) {
4078 amdDeps.unshift("'exports'");
4079 cjsDeps.unshift("exports");
4080 globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, (options.extend ? "" + globalProp(options.name, globalVar) + _ + "||" + _ : '') + "{}"));
4081 factoryArgs.unshift('exports');
4082 }
4083 var amdOptions = options.amd || {};
4084 var amdParams = (amdOptions.id ? "'" + amdOptions.id + "'," + _ : "") +
4085 (amdDeps.length ? "[" + amdDeps.join("," + _) + "]," + _ : "");
4086 var define = amdOptions.define || 'define';
4087 var cjsExport = !namedExportsMode && hasExports ? "module.exports" + _ + "=" + _ : "";
4088 var useStrict = options.strict !== false ? _ + "'use strict';" + n : "";
4089 var iifeExport;
4090 if (options.noConflict === true) {
4091 var noConflictExportsVar = options.compact ? 'e' : 'exports';
4092 var factory = void 0;
4093 if (!namedExportsMode && hasExports) {
4094 factory = "var " + noConflictExportsVar + _ + "=" + _ + assignToDeepVariable(options.name, globalVar, options.globals, options.compact, factoryVar + "(" + globalDeps.join("," + _) + ")") + ";";
4095 }
4096 else if (namedExportsMode) {
4097 var module = globalDeps.shift();
4098 factory =
4099 "var " + noConflictExportsVar + _ + "=" + _ + module + ";" + n +
4100 ("" + t + t + factoryVar + "(" + [noConflictExportsVar].concat(globalDeps).join("," + _) + ");");
4101 }
4102 iifeExport =
4103 "(function" + _ + "()" + _ + "{" + n +
4104 ("" + t + t + "var current" + _ + "=" + _ + safeAccess(options.name, globalVar, _) + ";" + n) +
4105 ("" + t + t + factory + n) +
4106 ("" + t + t + noConflictExportsVar + ".noConflict" + _ + "=" + _ + "function" + _ + "()" + _ + "{" + _) +
4107 ("" + globalProp(options.name, globalVar) + _ + "=" + _ + "current;" + _ + "return " + noConflictExportsVar + (options.compact ? '' : '; ') + "};" + n) +
4108 (t + "}())");
4109 }
4110 else {
4111 iifeExport = factoryVar + "(" + globalDeps.join("," + _) + ")";
4112 if (!namedExportsMode && hasExports) {
4113 iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
4114 }
4115 }
4116 var iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
4117 var globalParam = iifeNeedsGlobal ? globalVar + "," + _ : '';
4118 var globalArg = iifeNeedsGlobal ? "this," + _ : '';
4119 var iifeStart = iifeNeedsGlobal ? "(" + globalVar + _ + "=" + _ + globalVar + _ + "||" + _ + "self," + _ : '';
4120 var iifeEnd = iifeNeedsGlobal ? ')' : '';
4121 var cjsIntro = iifeNeedsGlobal
4122 ? t + "typeof exports" + _ + "===" + _ + "'object'" + _ + "&&" + _ + "typeof module" + _ + "!==" + _ + "'undefined'" + _ + "?" +
4123 ("" + _ + cjsExport + factoryVar + "(" + cjsDeps.join("," + _) + ")" + _ + ":" + n)
4124 : '';
4125 var wrapperIntro = "(function" + _ + "(" + globalParam + factoryVar + ")" + _ + "{" + n +
4126 cjsIntro +
4127 (t + "typeof " + define + _ + "===" + _ + "'function'" + _ + "&&" + _ + define + ".amd" + _ + "?" + _ + define + "(" + amdParams + factoryVar + ")" + _ + ":" + n) +
4128 ("" + t + iifeStart + iifeExport + iifeEnd + ";" + n) +
4129 ("}(" + globalArg + "function" + _ + "(" + factoryArgs.join(', ') + ")" + _ + "{" + useStrict + n);
4130 var wrapperOutro = n + n + '}));';
4131 // var foo__default = 'default' in foo ? foo['default'] : foo;
4132 var interopBlock = getInteropBlock(dependencies, options, varOrConst);
4133 if (interopBlock)
4134 magicString.prepend(interopBlock + n + n);
4135 if (intro)
4136 magicString.prepend(intro);
4137 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
4138 if (exportBlock)
4139 magicString.append(n + n + exportBlock);
4140 if (namedExportsMode && hasExports && options.esModule)
4141 magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
4142 if (outro)
4143 magicString.append(outro);
4144 return magicString
4145 .trim()
4146 .indent(t)
4147 .append(wrapperOutro)
4148 .prepend(wrapperIntro);
4149}
4150
4151var finalisers = { system: system, amd: amd, cjs: cjs, es: esm, iife: iife, umd: umd };
4152
4153var extractors = {
4154 ArrayPattern: function (names, param) {
4155 for (var _i = 0, _a = param.elements; _i < _a.length; _i++) {
4156 var element = _a[_i];
4157 if (element)
4158 extractors[element.type](names, element);
4159 }
4160 },
4161 AssignmentPattern: function (names, param) {
4162 extractors[param.left.type](names, param.left);
4163 },
4164 Identifier: function (names, param) {
4165 names.push(param.name);
4166 },
4167 MemberExpression: function () { },
4168 ObjectPattern: function (names, param) {
4169 for (var _i = 0, _a = param.properties; _i < _a.length; _i++) {
4170 var prop = _a[_i];
4171 if (prop.type === 'RestElement') {
4172 extractors.RestElement(names, prop);
4173 }
4174 else {
4175 extractors[prop.value.type](names, prop.value);
4176 }
4177 }
4178 },
4179 RestElement: function (names, param) {
4180 extractors[param.argument.type](names, param.argument);
4181 }
4182};
4183var extractAssignedNames = function extractAssignedNames(param) {
4184 var names = [];
4185 extractors[param.type](names, param);
4186 return names;
4187};
4188
4189var BLANK = Object.create(null);
4190
4191function treeshakeNode(node, code, start, end) {
4192 code.remove(start, end);
4193 if (node.annotations) {
4194 for (var _i = 0, _a = node.annotations; _i < _a.length; _i++) {
4195 var annotation = _a[_i];
4196 if (annotation.start < start) {
4197 code.remove(annotation.start, annotation.end);
4198 }
4199 else {
4200 return;
4201 }
4202 }
4203 }
4204}
4205function removeAnnotations(node, code) {
4206 if (!node.annotations && node.parent.type === ExpressionStatement) {
4207 node = node.parent;
4208 }
4209 if (node.annotations) {
4210 for (var _i = 0, _a = node.annotations; _i < _a.length; _i++) {
4211 var annotation = _a[_i];
4212 code.remove(annotation.start, annotation.end);
4213 }
4214 }
4215}
4216
4217var NO_SEMICOLON = { isNoStatement: true };
4218function findFirstOccurrenceOutsideComment(code, searchString, start) {
4219 if (start === void 0) { start = 0; }
4220 var searchPos, charCodeAfterSlash;
4221 searchPos = code.indexOf(searchString, start);
4222 while (true) {
4223 start = code.indexOf('/', start);
4224 if (start === -1 || start > searchPos)
4225 return searchPos;
4226 charCodeAfterSlash = code.charCodeAt(++start);
4227 ++start;
4228 if (charCodeAfterSlash === 47 /*"/"*/) {
4229 start = code.indexOf('\n', start) + 1;
4230 if (start === 0)
4231 return -1;
4232 if (start > searchPos) {
4233 searchPos = code.indexOf(searchString, start);
4234 }
4235 }
4236 else if (charCodeAfterSlash === 42 /*"*"*/) {
4237 start = code.indexOf('*/', start) + 2;
4238 if (start > searchPos) {
4239 searchPos = code.indexOf(searchString, start);
4240 }
4241 }
4242 }
4243}
4244function findFirstLineBreakOutsideComment(code, start) {
4245 if (start === void 0) { start = 0; }
4246 var lineBreakPos, charCodeAfterSlash;
4247 lineBreakPos = code.indexOf('\n', start);
4248 while (true) {
4249 start = code.indexOf('/', start);
4250 if (start === -1 || start > lineBreakPos)
4251 return lineBreakPos;
4252 charCodeAfterSlash = code.charCodeAt(++start);
4253 if (charCodeAfterSlash === 47 /*"/"*/)
4254 return lineBreakPos;
4255 ++start;
4256 if (charCodeAfterSlash === 42 /*"*"*/) {
4257 start = code.indexOf('*/', start) + 2;
4258 if (start > lineBreakPos) {
4259 lineBreakPos = code.indexOf('\n', start);
4260 }
4261 }
4262 }
4263}
4264function renderStatementList(statements, code, start, end, options) {
4265 if (statements.length === 0)
4266 return;
4267 var currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
4268 var nextNode = statements[0];
4269 var nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
4270 if (nextNodeNeedsBoundaries) {
4271 nextNodeStart =
4272 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
4273 }
4274 for (var nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
4275 currentNode = nextNode;
4276 currentNodeStart = nextNodeStart;
4277 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
4278 nextNode = statements[nextIndex];
4279 nextNodeNeedsBoundaries =
4280 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
4281 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
4282 nextNodeStart =
4283 currentNode.end +
4284 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
4285 1;
4286 if (currentNode.included) {
4287 currentNodeNeedsBoundaries
4288 ? currentNode.render(code, options, {
4289 end: nextNodeStart,
4290 start: currentNodeStart
4291 })
4292 : currentNode.render(code, options);
4293 }
4294 else {
4295 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
4296 }
4297 }
4298 else {
4299 currentNode.render(code, options);
4300 }
4301 }
4302}
4303// This assumes that the first character is not part of the first node
4304function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
4305 var splitUpNodes = [];
4306 var node, nextNode, nextNodeStart, contentEnd, char;
4307 var separator = start - 1;
4308 for (var nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
4309 nextNode = nodes[nextIndex];
4310 if (node !== undefined) {
4311 separator =
4312 node.end +
4313 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
4314 }
4315 nextNodeStart = contentEnd =
4316 separator +
4317 2 +
4318 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
4319 while (((char = code.original.charCodeAt(nextNodeStart)),
4320 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
4321 nextNodeStart++;
4322 if (node !== undefined) {
4323 splitUpNodes.push({
4324 contentEnd: contentEnd,
4325 end: nextNodeStart,
4326 node: node,
4327 separator: separator,
4328 start: start
4329 });
4330 }
4331 node = nextNode;
4332 start = nextNodeStart;
4333 }
4334 splitUpNodes.push({
4335 contentEnd: end,
4336 end: end,
4337 node: node,
4338 separator: null,
4339 start: start
4340 });
4341 return splitUpNodes;
4342}
4343
4344var chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
4345var base = 64;
4346function toBase64(num) {
4347 var outStr = '';
4348 do {
4349 var curDigit = num % base;
4350 num = Math.floor(num / base);
4351 outStr = chars$1[curDigit] + outStr;
4352 } while (num !== 0);
4353 return outStr;
4354}
4355
4356function getSafeName(baseName, usedNames) {
4357 var safeName = baseName;
4358 var count = 1;
4359 while (usedNames[safeName]) {
4360 safeName = baseName + "$" + toBase64(count++);
4361 }
4362 usedNames[safeName] = true;
4363 return safeName;
4364}
4365
4366var Scope = /** @class */ (function () {
4367 function Scope() {
4368 this.children = [];
4369 this.variables = Object.create(null);
4370 }
4371 Scope.prototype.addDeclaration = function (identifier, context, init, _isHoisted) {
4372 if (init === void 0) { init = null; }
4373 var name = identifier.name;
4374 if (this.variables[name]) {
4375 this.variables[name].addDeclaration(identifier, init);
4376 }
4377 else {
4378 this.variables[name] = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
4379 }
4380 return this.variables[name];
4381 };
4382 Scope.prototype.contains = function (name) {
4383 return name in this.variables;
4384 };
4385 Scope.prototype.findVariable = function (_name) {
4386 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
4387 };
4388 return Scope;
4389}());
4390
4391var ChildScope = /** @class */ (function (_super) {
4392 __extends(ChildScope, _super);
4393 function ChildScope(parent) {
4394 var _this = _super.call(this) || this;
4395 _this.accessedOutsideVariables = Object.create(null);
4396 _this.parent = parent;
4397 parent.children.push(_this);
4398 return _this;
4399 }
4400 ChildScope.prototype.addNamespaceMemberAccess = function (name, variable) {
4401 this.accessedOutsideVariables[name] = variable;
4402 if (this.parent instanceof ChildScope) {
4403 this.parent.addNamespaceMemberAccess(name, variable);
4404 }
4405 };
4406 ChildScope.prototype.addReturnExpression = function (expression) {
4407 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
4408 };
4409 ChildScope.prototype.contains = function (name) {
4410 return name in this.variables || this.parent.contains(name);
4411 };
4412 ChildScope.prototype.deconflict = function (forbiddenNames) {
4413 var usedNames = Object.assign(Object.create(null), forbiddenNames);
4414 for (var _i = 0, _a = Object.keys(this.accessedOutsideVariables); _i < _a.length; _i++) {
4415 var name = _a[_i];
4416 var variable = this.accessedOutsideVariables[name];
4417 if (variable.included) {
4418 usedNames[variable.getBaseVariableName()] = true;
4419 }
4420 }
4421 for (var _b = 0, _c = Object.keys(this.variables); _b < _c.length; _b++) {
4422 var name = _c[_b];
4423 var variable = this.variables[name];
4424 if (variable.included) {
4425 variable.setSafeName(getSafeName(name, usedNames));
4426 }
4427 }
4428 for (var _d = 0, _e = this.children; _d < _e.length; _d++) {
4429 var scope = _e[_d];
4430 scope.deconflict(forbiddenNames);
4431 }
4432 };
4433 ChildScope.prototype.findLexicalBoundary = function () {
4434 return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this;
4435 };
4436 ChildScope.prototype.findVariable = function (name) {
4437 var knownVariable = this.variables[name] || this.accessedOutsideVariables[name];
4438 if (knownVariable) {
4439 return knownVariable;
4440 }
4441 return (this.accessedOutsideVariables[name] = this.parent.findVariable(name));
4442 };
4443 return ChildScope;
4444}(Scope));
4445
4446/**
4447 * Copyright (c) 2014-present, Facebook, Inc.
4448 *
4449 * This source code is licensed under the MIT license found in the
4450 * LICENSE file in the root directory of this source tree.
4451 */
4452
4453// Used for setting prototype methods that IE8 chokes on.
4454var DELETE = 'delete';
4455
4456// Constants describing the size of trie nodes.
4457var SHIFT = 5; // Resulted in best performance after ______?
4458var SIZE = 1 << SHIFT;
4459var MASK = SIZE - 1;
4460
4461// A consistent shared value representing "not set" which equals nothing other
4462// than itself, and nothing that could be provided externally.
4463var NOT_SET = {};
4464
4465// Boolean references, Rough equivalent of `bool &`.
4466function MakeRef() {
4467 return { value: false };
4468}
4469
4470function SetRef(ref) {
4471 if (ref) {
4472 ref.value = true;
4473 }
4474}
4475
4476// A function which returns a value representing an "owner" for transient writes
4477// to tries. The return value will only ever equal itself, and will not equal
4478// the return of any subsequent call of this function.
4479function OwnerID() {}
4480
4481function ensureSize(iter) {
4482 if (iter.size === undefined) {
4483 iter.size = iter.__iterate(returnTrue);
4484 }
4485 return iter.size;
4486}
4487
4488function wrapIndex(iter, index) {
4489 // This implements "is array index" which the ECMAString spec defines as:
4490 //
4491 // A String property name P is an array index if and only if
4492 // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
4493 // to 2^32−1.
4494 //
4495 // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
4496 if (typeof index !== 'number') {
4497 var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
4498 if ('' + uint32Index !== index || uint32Index === 4294967295) {
4499 return NaN;
4500 }
4501 index = uint32Index;
4502 }
4503 return index < 0 ? ensureSize(iter) + index : index;
4504}
4505
4506function returnTrue() {
4507 return true;
4508}
4509
4510function wholeSlice(begin, end, size) {
4511 return (
4512 ((begin === 0 && !isNeg(begin)) ||
4513 (size !== undefined && begin <= -size)) &&
4514 (end === undefined || (size !== undefined && end >= size))
4515 );
4516}
4517
4518function resolveBegin(begin, size) {
4519 return resolveIndex(begin, size, 0);
4520}
4521
4522function resolveEnd(end, size) {
4523 return resolveIndex(end, size, size);
4524}
4525
4526function resolveIndex(index, size, defaultIndex) {
4527 // Sanitize indices using this shorthand for ToInt32(argument)
4528 // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
4529 return index === undefined
4530 ? defaultIndex
4531 : isNeg(index)
4532 ? size === Infinity
4533 ? size
4534 : Math.max(0, size + index) | 0
4535 : size === undefined || size === index
4536 ? index
4537 : Math.min(size, index) | 0;
4538}
4539
4540function isNeg(value) {
4541 // Account for -0 which is negative, but not less than 0.
4542 return value < 0 || (value === 0 && 1 / value === -Infinity);
4543}
4544
4545// Note: value is unchanged to not break immutable-devtools.
4546var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@';
4547
4548function isCollection(maybeCollection) {
4549 return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]);
4550}
4551
4552var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@';
4553
4554function isKeyed(maybeKeyed) {
4555 return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]);
4556}
4557
4558var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@';
4559
4560function isIndexed(maybeIndexed) {
4561 return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]);
4562}
4563
4564function isAssociative(maybeAssociative) {
4565 return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
4566}
4567
4568var Collection = function Collection(value) {
4569 return isCollection(value) ? value : Seq(value);
4570};
4571
4572var KeyedCollection = /*@__PURE__*/(function (Collection) {
4573 function KeyedCollection(value) {
4574 return isKeyed(value) ? value : KeyedSeq(value);
4575 }
4576
4577 if ( Collection ) KeyedCollection.__proto__ = Collection;
4578 KeyedCollection.prototype = Object.create( Collection && Collection.prototype );
4579 KeyedCollection.prototype.constructor = KeyedCollection;
4580
4581 return KeyedCollection;
4582}(Collection));
4583
4584var IndexedCollection = /*@__PURE__*/(function (Collection) {
4585 function IndexedCollection(value) {
4586 return isIndexed(value) ? value : IndexedSeq(value);
4587 }
4588
4589 if ( Collection ) IndexedCollection.__proto__ = Collection;
4590 IndexedCollection.prototype = Object.create( Collection && Collection.prototype );
4591 IndexedCollection.prototype.constructor = IndexedCollection;
4592
4593 return IndexedCollection;
4594}(Collection));
4595
4596var SetCollection = /*@__PURE__*/(function (Collection) {
4597 function SetCollection(value) {
4598 return isCollection(value) && !isAssociative(value) ? value : SetSeq(value);
4599 }
4600
4601 if ( Collection ) SetCollection.__proto__ = Collection;
4602 SetCollection.prototype = Object.create( Collection && Collection.prototype );
4603 SetCollection.prototype.constructor = SetCollection;
4604
4605 return SetCollection;
4606}(Collection));
4607
4608Collection.Keyed = KeyedCollection;
4609Collection.Indexed = IndexedCollection;
4610Collection.Set = SetCollection;
4611
4612var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@';
4613
4614function isSeq(maybeSeq) {
4615 return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]);
4616}
4617
4618var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@';
4619
4620function isRecord(maybeRecord) {
4621 return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]);
4622}
4623
4624function isImmutable(maybeImmutable) {
4625 return isCollection(maybeImmutable) || isRecord(maybeImmutable);
4626}
4627
4628var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@';
4629
4630function isOrdered(maybeOrdered) {
4631 return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]);
4632}
4633
4634var ITERATE_KEYS = 0;
4635var ITERATE_VALUES = 1;
4636var ITERATE_ENTRIES = 2;
4637
4638var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
4639var FAUX_ITERATOR_SYMBOL = '@@iterator';
4640
4641var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
4642
4643var Iterator = function Iterator(next) {
4644 this.next = next;
4645};
4646
4647Iterator.prototype.toString = function toString () {
4648 return '[Iterator]';
4649};
4650
4651Iterator.KEYS = ITERATE_KEYS;
4652Iterator.VALUES = ITERATE_VALUES;
4653Iterator.ENTRIES = ITERATE_ENTRIES;
4654
4655Iterator.prototype.inspect = Iterator.prototype.toSource = function() {
4656 return this.toString();
4657};
4658Iterator.prototype[ITERATOR_SYMBOL] = function() {
4659 return this;
4660};
4661
4662function iteratorValue(type, k, v, iteratorResult) {
4663 var value = type === 0 ? k : type === 1 ? v : [k, v];
4664 iteratorResult
4665 ? (iteratorResult.value = value)
4666 : (iteratorResult = {
4667 value: value,
4668 done: false,
4669 });
4670 return iteratorResult;
4671}
4672
4673function iteratorDone() {
4674 return { value: undefined, done: true };
4675}
4676
4677function hasIterator(maybeIterable) {
4678 return !!getIteratorFn(maybeIterable);
4679}
4680
4681function isIterator(maybeIterator) {
4682 return maybeIterator && typeof maybeIterator.next === 'function';
4683}
4684
4685function getIterator(iterable) {
4686 var iteratorFn = getIteratorFn(iterable);
4687 return iteratorFn && iteratorFn.call(iterable);
4688}
4689
4690function getIteratorFn(iterable) {
4691 var iteratorFn =
4692 iterable &&
4693 ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
4694 iterable[FAUX_ITERATOR_SYMBOL]);
4695 if (typeof iteratorFn === 'function') {
4696 return iteratorFn;
4697 }
4698}
4699
4700var hasOwnProperty = Object.prototype.hasOwnProperty;
4701
4702function isArrayLike(value) {
4703 if (Array.isArray(value) || typeof value === 'string') {
4704 return true;
4705 }
4706
4707 return (
4708 value &&
4709 typeof value === 'object' &&
4710 Number.isInteger(value.length) &&
4711 value.length >= 0 &&
4712 (value.length === 0
4713 ? // Only {length: 0} is considered Array-like.
4714 Object.keys(value).length === 1
4715 : // An object is only Array-like if it has a property where the last value
4716 // in the array-like may be found (which could be undefined).
4717 value.hasOwnProperty(value.length - 1))
4718 );
4719}
4720
4721var Seq = /*@__PURE__*/(function (Collection$$1) {
4722 function Seq(value) {
4723 return value === null || value === undefined
4724 ? emptySequence()
4725 : isImmutable(value)
4726 ? value.toSeq()
4727 : seqFromValue(value);
4728 }
4729
4730 if ( Collection$$1 ) Seq.__proto__ = Collection$$1;
4731 Seq.prototype = Object.create( Collection$$1 && Collection$$1.prototype );
4732 Seq.prototype.constructor = Seq;
4733
4734 Seq.prototype.toSeq = function toSeq () {
4735 return this;
4736 };
4737
4738 Seq.prototype.toString = function toString () {
4739 return this.__toString('Seq {', '}');
4740 };
4741
4742 Seq.prototype.cacheResult = function cacheResult () {
4743 if (!this._cache && this.__iterateUncached) {
4744 this._cache = this.entrySeq().toArray();
4745 this.size = this._cache.length;
4746 }
4747 return this;
4748 };
4749
4750 // abstract __iterateUncached(fn, reverse)
4751
4752 Seq.prototype.__iterate = function __iterate (fn, reverse) {
4753 var cache = this._cache;
4754 if (cache) {
4755 var size = cache.length;
4756 var i = 0;
4757 while (i !== size) {
4758 var entry = cache[reverse ? size - ++i : i++];
4759 if (fn(entry[1], entry[0], this) === false) {
4760 break;
4761 }
4762 }
4763 return i;
4764 }
4765 return this.__iterateUncached(fn, reverse);
4766 };
4767
4768 // abstract __iteratorUncached(type, reverse)
4769
4770 Seq.prototype.__iterator = function __iterator (type, reverse) {
4771 var cache = this._cache;
4772 if (cache) {
4773 var size = cache.length;
4774 var i = 0;
4775 return new Iterator(function () {
4776 if (i === size) {
4777 return iteratorDone();
4778 }
4779 var entry = cache[reverse ? size - ++i : i++];
4780 return iteratorValue(type, entry[0], entry[1]);
4781 });
4782 }
4783 return this.__iteratorUncached(type, reverse);
4784 };
4785
4786 return Seq;
4787}(Collection));
4788
4789var KeyedSeq = /*@__PURE__*/(function (Seq) {
4790 function KeyedSeq(value) {
4791 return value === null || value === undefined
4792 ? emptySequence().toKeyedSeq()
4793 : isCollection(value)
4794 ? isKeyed(value)
4795 ? value.toSeq()
4796 : value.fromEntrySeq()
4797 : isRecord(value)
4798 ? value.toSeq()
4799 : keyedSeqFromValue(value);
4800 }
4801
4802 if ( Seq ) KeyedSeq.__proto__ = Seq;
4803 KeyedSeq.prototype = Object.create( Seq && Seq.prototype );
4804 KeyedSeq.prototype.constructor = KeyedSeq;
4805
4806 KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () {
4807 return this;
4808 };
4809
4810 return KeyedSeq;
4811}(Seq));
4812
4813var IndexedSeq = /*@__PURE__*/(function (Seq) {
4814 function IndexedSeq(value) {
4815 return value === null || value === undefined
4816 ? emptySequence()
4817 : isCollection(value)
4818 ? isKeyed(value)
4819 ? value.entrySeq()
4820 : value.toIndexedSeq()
4821 : isRecord(value)
4822 ? value.toSeq().entrySeq()
4823 : indexedSeqFromValue(value);
4824 }
4825
4826 if ( Seq ) IndexedSeq.__proto__ = Seq;
4827 IndexedSeq.prototype = Object.create( Seq && Seq.prototype );
4828 IndexedSeq.prototype.constructor = IndexedSeq;
4829
4830 IndexedSeq.of = function of (/*...values*/) {
4831 return IndexedSeq(arguments);
4832 };
4833
4834 IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () {
4835 return this;
4836 };
4837
4838 IndexedSeq.prototype.toString = function toString () {
4839 return this.__toString('Seq [', ']');
4840 };
4841
4842 return IndexedSeq;
4843}(Seq));
4844
4845var SetSeq = /*@__PURE__*/(function (Seq) {
4846 function SetSeq(value) {
4847 return (isCollection(value) && !isAssociative(value)
4848 ? value
4849 : IndexedSeq(value)
4850 ).toSetSeq();
4851 }
4852
4853 if ( Seq ) SetSeq.__proto__ = Seq;
4854 SetSeq.prototype = Object.create( Seq && Seq.prototype );
4855 SetSeq.prototype.constructor = SetSeq;
4856
4857 SetSeq.of = function of (/*...values*/) {
4858 return SetSeq(arguments);
4859 };
4860
4861 SetSeq.prototype.toSetSeq = function toSetSeq () {
4862 return this;
4863 };
4864
4865 return SetSeq;
4866}(Seq));
4867
4868Seq.isSeq = isSeq;
4869Seq.Keyed = KeyedSeq;
4870Seq.Set = SetSeq;
4871Seq.Indexed = IndexedSeq;
4872
4873Seq.prototype[IS_SEQ_SYMBOL] = true;
4874
4875// #pragma Root Sequences
4876
4877var ArraySeq = /*@__PURE__*/(function (IndexedSeq) {
4878 function ArraySeq(array) {
4879 this._array = array;
4880 this.size = array.length;
4881 }
4882
4883 if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq;
4884 ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
4885 ArraySeq.prototype.constructor = ArraySeq;
4886
4887 ArraySeq.prototype.get = function get (index, notSetValue) {
4888 return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
4889 };
4890
4891 ArraySeq.prototype.__iterate = function __iterate (fn, reverse) {
4892 var array = this._array;
4893 var size = array.length;
4894 var i = 0;
4895 while (i !== size) {
4896 var ii = reverse ? size - ++i : i++;
4897 if (fn(array[ii], ii, this) === false) {
4898 break;
4899 }
4900 }
4901 return i;
4902 };
4903
4904 ArraySeq.prototype.__iterator = function __iterator (type, reverse) {
4905 var array = this._array;
4906 var size = array.length;
4907 var i = 0;
4908 return new Iterator(function () {
4909 if (i === size) {
4910 return iteratorDone();
4911 }
4912 var ii = reverse ? size - ++i : i++;
4913 return iteratorValue(type, ii, array[ii]);
4914 });
4915 };
4916
4917 return ArraySeq;
4918}(IndexedSeq));
4919
4920var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) {
4921 function ObjectSeq(object) {
4922 var keys = Object.keys(object);
4923 this._object = object;
4924 this._keys = keys;
4925 this.size = keys.length;
4926 }
4927
4928 if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq;
4929 ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
4930 ObjectSeq.prototype.constructor = ObjectSeq;
4931
4932 ObjectSeq.prototype.get = function get (key, notSetValue) {
4933 if (notSetValue !== undefined && !this.has(key)) {
4934 return notSetValue;
4935 }
4936 return this._object[key];
4937 };
4938
4939 ObjectSeq.prototype.has = function has (key) {
4940 return hasOwnProperty.call(this._object, key);
4941 };
4942
4943 ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) {
4944 var object = this._object;
4945 var keys = this._keys;
4946 var size = keys.length;
4947 var i = 0;
4948 while (i !== size) {
4949 var key = keys[reverse ? size - ++i : i++];
4950 if (fn(object[key], key, this) === false) {
4951 break;
4952 }
4953 }
4954 return i;
4955 };
4956
4957 ObjectSeq.prototype.__iterator = function __iterator (type, reverse) {
4958 var object = this._object;
4959 var keys = this._keys;
4960 var size = keys.length;
4961 var i = 0;
4962 return new Iterator(function () {
4963 if (i === size) {
4964 return iteratorDone();
4965 }
4966 var key = keys[reverse ? size - ++i : i++];
4967 return iteratorValue(type, key, object[key]);
4968 });
4969 };
4970
4971 return ObjectSeq;
4972}(KeyedSeq));
4973ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true;
4974
4975var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) {
4976 function CollectionSeq(collection) {
4977 this._collection = collection;
4978 this.size = collection.length || collection.size;
4979 }
4980
4981 if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq;
4982 CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
4983 CollectionSeq.prototype.constructor = CollectionSeq;
4984
4985 CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) {
4986 if (reverse) {
4987 return this.cacheResult().__iterate(fn, reverse);
4988 }
4989 var collection = this._collection;
4990 var iterator = getIterator(collection);
4991 var iterations = 0;
4992 if (isIterator(iterator)) {
4993 var step;
4994 while (!(step = iterator.next()).done) {
4995 if (fn(step.value, iterations++, this) === false) {
4996 break;
4997 }
4998 }
4999 }
5000 return iterations;
5001 };
5002
5003 CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) {
5004 if (reverse) {
5005 return this.cacheResult().__iterator(type, reverse);
5006 }
5007 var collection = this._collection;
5008 var iterator = getIterator(collection);
5009 if (!isIterator(iterator)) {
5010 return new Iterator(iteratorDone);
5011 }
5012 var iterations = 0;
5013 return new Iterator(function () {
5014 var step = iterator.next();
5015 return step.done ? step : iteratorValue(type, iterations++, step.value);
5016 });
5017 };
5018
5019 return CollectionSeq;
5020}(IndexedSeq));
5021
5022// # pragma Helper functions
5023
5024var EMPTY_SEQ;
5025
5026function emptySequence() {
5027 return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
5028}
5029
5030function keyedSeqFromValue(value) {
5031 var seq = Array.isArray(value)
5032 ? new ArraySeq(value)
5033 : hasIterator(value)
5034 ? new CollectionSeq(value)
5035 : undefined;
5036 if (seq) {
5037 return seq.fromEntrySeq();
5038 }
5039 if (typeof value === 'object') {
5040 return new ObjectSeq(value);
5041 }
5042 throw new TypeError(
5043 'Expected Array or collection object of [k, v] entries, or keyed object: ' +
5044 value
5045 );
5046}
5047
5048function indexedSeqFromValue(value) {
5049 var seq = maybeIndexedSeqFromValue(value);
5050 if (seq) {
5051 return seq;
5052 }
5053 throw new TypeError(
5054 'Expected Array or collection object of values: ' + value
5055 );
5056}
5057
5058function seqFromValue(value) {
5059 var seq = maybeIndexedSeqFromValue(value);
5060 if (seq) {
5061 return seq;
5062 }
5063 if (typeof value === 'object') {
5064 return new ObjectSeq(value);
5065 }
5066 throw new TypeError(
5067 'Expected Array or collection object of values, or keyed object: ' + value
5068 );
5069}
5070
5071function maybeIndexedSeqFromValue(value) {
5072 return isArrayLike(value)
5073 ? new ArraySeq(value)
5074 : hasIterator(value)
5075 ? new CollectionSeq(value)
5076 : undefined;
5077}
5078
5079var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@';
5080
5081function isMap(maybeMap) {
5082 return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]);
5083}
5084
5085function isOrderedMap(maybeOrderedMap) {
5086 return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
5087}
5088
5089function isValueObject(maybeValue) {
5090 return Boolean(
5091 maybeValue &&
5092 typeof maybeValue.equals === 'function' &&
5093 typeof maybeValue.hashCode === 'function'
5094 );
5095}
5096
5097/**
5098 * An extension of the "same-value" algorithm as [described for use by ES6 Map
5099 * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
5100 *
5101 * NaN is considered the same as NaN, however -0 and 0 are considered the same
5102 * value, which is different from the algorithm described by
5103 * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
5104 *
5105 * This is extended further to allow Objects to describe the values they
5106 * represent, by way of `valueOf` or `equals` (and `hashCode`).
5107 *
5108 * Note: because of this extension, the key equality of Immutable.Map and the
5109 * value equality of Immutable.Set will differ from ES6 Map and Set.
5110 *
5111 * ### Defining custom values
5112 *
5113 * The easiest way to describe the value an object represents is by implementing
5114 * `valueOf`. For example, `Date` represents a value by returning a unix
5115 * timestamp for `valueOf`:
5116 *
5117 * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
5118 * var date2 = new Date(1234567890000);
5119 * date1.valueOf(); // 1234567890000
5120 * assert( date1 !== date2 );
5121 * assert( Immutable.is( date1, date2 ) );
5122 *
5123 * Note: overriding `valueOf` may have other implications if you use this object
5124 * where JavaScript expects a primitive, such as implicit string coercion.
5125 *
5126 * For more complex types, especially collections, implementing `valueOf` may
5127 * not be performant. An alternative is to implement `equals` and `hashCode`.
5128 *
5129 * `equals` takes another object, presumably of similar type, and returns true
5130 * if it is equal. Equality is symmetrical, so the same result should be
5131 * returned if this and the argument are flipped.
5132 *
5133 * assert( a.equals(b) === b.equals(a) );
5134 *
5135 * `hashCode` returns a 32bit integer number representing the object which will
5136 * be used to determine how to store the value object in a Map or Set. You must
5137 * provide both or neither methods, one must not exist without the other.
5138 *
5139 * Also, an important relationship between these methods must be upheld: if two
5140 * values are equal, they *must* return the same hashCode. If the values are not
5141 * equal, they might have the same hashCode; this is called a hash collision,
5142 * and while undesirable for performance reasons, it is acceptable.
5143 *
5144 * if (a.equals(b)) {
5145 * assert( a.hashCode() === b.hashCode() );
5146 * }
5147 *
5148 * All Immutable collections are Value Objects: they implement `equals()`
5149 * and `hashCode()`.
5150 */
5151function is(valueA, valueB) {
5152 if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
5153 return true;
5154 }
5155 if (!valueA || !valueB) {
5156 return false;
5157 }
5158 if (
5159 typeof valueA.valueOf === 'function' &&
5160 typeof valueB.valueOf === 'function'
5161 ) {
5162 valueA = valueA.valueOf();
5163 valueB = valueB.valueOf();
5164 if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
5165 return true;
5166 }
5167 if (!valueA || !valueB) {
5168 return false;
5169 }
5170 }
5171 return !!(
5172 isValueObject(valueA) &&
5173 isValueObject(valueB) &&
5174 valueA.equals(valueB)
5175 );
5176}
5177
5178var imul =
5179 typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2
5180 ? Math.imul
5181 : function imul(a, b) {
5182 a |= 0; // int
5183 b |= 0; // int
5184 var c = a & 0xffff;
5185 var d = b & 0xffff;
5186 // Shift by 0 fixes the sign on the high part.
5187 return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int
5188 };
5189
5190// v8 has an optimization for storing 31-bit signed numbers.
5191// Values which have either 00 or 11 as the high order bits qualify.
5192// This function drops the highest order bit in a signed number, maintaining
5193// the sign bit.
5194function smi(i32) {
5195 return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
5196}
5197
5198var defaultValueOf = Object.prototype.valueOf;
5199
5200function hash(o) {
5201 switch (typeof o) {
5202 case 'boolean':
5203 // The hash values for built-in constants are a 1 value for each 5-byte
5204 // shift region expect for the first, which encodes the value. This
5205 // reduces the odds of a hash collision for these common values.
5206 return o ? 0x42108421 : 0x42108420;
5207 case 'number':
5208 return hashNumber(o);
5209 case 'string':
5210 return o.length > STRING_HASH_CACHE_MIN_STRLEN
5211 ? cachedHashString(o)
5212 : hashString(o);
5213 case 'object':
5214 case 'function':
5215 if (o === null) {
5216 return 0x42108422;
5217 }
5218 if (typeof o.hashCode === 'function') {
5219 // Drop any high bits from accidentally long hash codes.
5220 return smi(o.hashCode(o));
5221 }
5222 if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
5223 o = o.valueOf(o);
5224 }
5225 return hashJSObj(o);
5226 case 'undefined':
5227 return 0x42108423;
5228 default:
5229 if (typeof o.toString === 'function') {
5230 return hashString(o.toString());
5231 }
5232 throw new Error('Value type ' + typeof o + ' cannot be hashed.');
5233 }
5234}
5235
5236// Compress arbitrarily large numbers into smi hashes.
5237function hashNumber(n) {
5238 if (n !== n || n === Infinity) {
5239 return 0;
5240 }
5241 var hash = n | 0;
5242 if (hash !== n) {
5243 hash ^= n * 0xffffffff;
5244 }
5245 while (n > 0xffffffff) {
5246 n /= 0xffffffff;
5247 hash ^= n;
5248 }
5249 return smi(hash);
5250}
5251
5252function cachedHashString(string) {
5253 var hashed = stringHashCache[string];
5254 if (hashed === undefined) {
5255 hashed = hashString(string);
5256 if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
5257 STRING_HASH_CACHE_SIZE = 0;
5258 stringHashCache = {};
5259 }
5260 STRING_HASH_CACHE_SIZE++;
5261 stringHashCache[string] = hashed;
5262 }
5263 return hashed;
5264}
5265
5266// http://jsperf.com/hashing-strings
5267function hashString(string) {
5268 // This is the hash from JVM
5269 // The hash code for a string is computed as
5270 // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
5271 // where s[i] is the ith character of the string and n is the length of
5272 // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
5273 // (exclusive) by dropping high bits.
5274 var hashed = 0;
5275 for (var ii = 0; ii < string.length; ii++) {
5276 hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
5277 }
5278 return smi(hashed);
5279}
5280
5281function hashJSObj(obj) {
5282 var hashed;
5283 if (usingWeakMap) {
5284 hashed = weakMap.get(obj);
5285 if (hashed !== undefined) {
5286 return hashed;
5287 }
5288 }
5289
5290 hashed = obj[UID_HASH_KEY];
5291 if (hashed !== undefined) {
5292 return hashed;
5293 }
5294
5295 if (!canDefineProperty) {
5296 hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
5297 if (hashed !== undefined) {
5298 return hashed;
5299 }
5300
5301 hashed = getIENodeHash(obj);
5302 if (hashed !== undefined) {
5303 return hashed;
5304 }
5305 }
5306
5307 hashed = ++objHashUID;
5308 if (objHashUID & 0x40000000) {
5309 objHashUID = 0;
5310 }
5311
5312 if (usingWeakMap) {
5313 weakMap.set(obj, hashed);
5314 } else if (isExtensible !== undefined && isExtensible(obj) === false) {
5315 throw new Error('Non-extensible objects are not allowed as keys.');
5316 } else if (canDefineProperty) {
5317 Object.defineProperty(obj, UID_HASH_KEY, {
5318 enumerable: false,
5319 configurable: false,
5320 writable: false,
5321 value: hashed,
5322 });
5323 } else if (
5324 obj.propertyIsEnumerable !== undefined &&
5325 obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable
5326 ) {
5327 // Since we can't define a non-enumerable property on the object
5328 // we'll hijack one of the less-used non-enumerable properties to
5329 // save our hash on it. Since this is a function it will not show up in
5330 // `JSON.stringify` which is what we want.
5331 obj.propertyIsEnumerable = function() {
5332 return this.constructor.prototype.propertyIsEnumerable.apply(
5333 this,
5334 arguments
5335 );
5336 };
5337 obj.propertyIsEnumerable[UID_HASH_KEY] = hashed;
5338 } else if (obj.nodeType !== undefined) {
5339 // At this point we couldn't get the IE `uniqueID` to use as a hash
5340 // and we couldn't use a non-enumerable property to exploit the
5341 // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
5342 // itself.
5343 obj[UID_HASH_KEY] = hashed;
5344 } else {
5345 throw new Error('Unable to set a non-enumerable property on object.');
5346 }
5347
5348 return hashed;
5349}
5350
5351// Get references to ES5 object methods.
5352var isExtensible = Object.isExtensible;
5353
5354// True if Object.defineProperty works as expected. IE8 fails this test.
5355var canDefineProperty = (function() {
5356 try {
5357 Object.defineProperty({}, '@', {});
5358 return true;
5359 } catch (e) {
5360 return false;
5361 }
5362})();
5363
5364// IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
5365// and avoid memory leaks from the IE cloneNode bug.
5366function getIENodeHash(node) {
5367 if (node && node.nodeType > 0) {
5368 switch (node.nodeType) {
5369 case 1: // Element
5370 return node.uniqueID;
5371 case 9: // Document
5372 return node.documentElement && node.documentElement.uniqueID;
5373 }
5374 }
5375}
5376
5377// If possible, use a WeakMap.
5378var usingWeakMap = typeof WeakMap === 'function';
5379var weakMap;
5380if (usingWeakMap) {
5381 weakMap = new WeakMap();
5382}
5383
5384var objHashUID = 0;
5385
5386var UID_HASH_KEY = '__immutablehash__';
5387if (typeof Symbol === 'function') {
5388 UID_HASH_KEY = Symbol(UID_HASH_KEY);
5389}
5390
5391var STRING_HASH_CACHE_MIN_STRLEN = 16;
5392var STRING_HASH_CACHE_MAX_SIZE = 255;
5393var STRING_HASH_CACHE_SIZE = 0;
5394var stringHashCache = {};
5395
5396var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq$$1) {
5397 function ToKeyedSequence(indexed, useKeys) {
5398 this._iter = indexed;
5399 this._useKeys = useKeys;
5400 this.size = indexed.size;
5401 }
5402
5403 if ( KeyedSeq$$1 ) ToKeyedSequence.__proto__ = KeyedSeq$$1;
5404 ToKeyedSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
5405 ToKeyedSequence.prototype.constructor = ToKeyedSequence;
5406
5407 ToKeyedSequence.prototype.get = function get (key, notSetValue) {
5408 return this._iter.get(key, notSetValue);
5409 };
5410
5411 ToKeyedSequence.prototype.has = function has (key) {
5412 return this._iter.has(key);
5413 };
5414
5415 ToKeyedSequence.prototype.valueSeq = function valueSeq () {
5416 return this._iter.valueSeq();
5417 };
5418
5419 ToKeyedSequence.prototype.reverse = function reverse () {
5420 var this$1 = this;
5421
5422 var reversedSequence = reverseFactory(this, true);
5423 if (!this._useKeys) {
5424 reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); };
5425 }
5426 return reversedSequence;
5427 };
5428
5429 ToKeyedSequence.prototype.map = function map (mapper, context) {
5430 var this$1 = this;
5431
5432 var mappedSequence = mapFactory(this, mapper, context);
5433 if (!this._useKeys) {
5434 mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); };
5435 }
5436 return mappedSequence;
5437 };
5438
5439 ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) {
5440 var this$1 = this;
5441
5442 return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse);
5443 };
5444
5445 ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) {
5446 return this._iter.__iterator(type, reverse);
5447 };
5448
5449 return ToKeyedSequence;
5450}(KeyedSeq));
5451ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true;
5452
5453var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq$$1) {
5454 function ToIndexedSequence(iter) {
5455 this._iter = iter;
5456 this.size = iter.size;
5457 }
5458
5459 if ( IndexedSeq$$1 ) ToIndexedSequence.__proto__ = IndexedSeq$$1;
5460 ToIndexedSequence.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
5461 ToIndexedSequence.prototype.constructor = ToIndexedSequence;
5462
5463 ToIndexedSequence.prototype.includes = function includes (value) {
5464 return this._iter.includes(value);
5465 };
5466
5467 ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) {
5468 var this$1 = this;
5469
5470 var i = 0;
5471 reverse && ensureSize(this);
5472 return this._iter.__iterate(
5473 function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); },
5474 reverse
5475 );
5476 };
5477
5478 ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) {
5479 var this$1 = this;
5480
5481 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
5482 var i = 0;
5483 reverse && ensureSize(this);
5484 return new Iterator(function () {
5485 var step = iterator.next();
5486 return step.done
5487 ? step
5488 : iteratorValue(
5489 type,
5490 reverse ? this$1.size - ++i : i++,
5491 step.value,
5492 step
5493 );
5494 });
5495 };
5496
5497 return ToIndexedSequence;
5498}(IndexedSeq));
5499
5500var ToSetSequence = /*@__PURE__*/(function (SetSeq$$1) {
5501 function ToSetSequence(iter) {
5502 this._iter = iter;
5503 this.size = iter.size;
5504 }
5505
5506 if ( SetSeq$$1 ) ToSetSequence.__proto__ = SetSeq$$1;
5507 ToSetSequence.prototype = Object.create( SetSeq$$1 && SetSeq$$1.prototype );
5508 ToSetSequence.prototype.constructor = ToSetSequence;
5509
5510 ToSetSequence.prototype.has = function has (key) {
5511 return this._iter.includes(key);
5512 };
5513
5514 ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) {
5515 var this$1 = this;
5516
5517 return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse);
5518 };
5519
5520 ToSetSequence.prototype.__iterator = function __iterator (type, reverse) {
5521 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
5522 return new Iterator(function () {
5523 var step = iterator.next();
5524 return step.done
5525 ? step
5526 : iteratorValue(type, step.value, step.value, step);
5527 });
5528 };
5529
5530 return ToSetSequence;
5531}(SetSeq));
5532
5533var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq$$1) {
5534 function FromEntriesSequence(entries) {
5535 this._iter = entries;
5536 this.size = entries.size;
5537 }
5538
5539 if ( KeyedSeq$$1 ) FromEntriesSequence.__proto__ = KeyedSeq$$1;
5540 FromEntriesSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
5541 FromEntriesSequence.prototype.constructor = FromEntriesSequence;
5542
5543 FromEntriesSequence.prototype.entrySeq = function entrySeq () {
5544 return this._iter.toSeq();
5545 };
5546
5547 FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) {
5548 var this$1 = this;
5549
5550 return this._iter.__iterate(function (entry) {
5551 // Check if entry exists first so array access doesn't throw for holes
5552 // in the parent iteration.
5553 if (entry) {
5554 validateEntry(entry);
5555 var indexedCollection = isCollection(entry);
5556 return fn(
5557 indexedCollection ? entry.get(1) : entry[1],
5558 indexedCollection ? entry.get(0) : entry[0],
5559 this$1
5560 );
5561 }
5562 }, reverse);
5563 };
5564
5565 FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) {
5566 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
5567 return new Iterator(function () {
5568 while (true) {
5569 var step = iterator.next();
5570 if (step.done) {
5571 return step;
5572 }
5573 var entry = step.value;
5574 // Check if entry exists first so array access doesn't throw for holes
5575 // in the parent iteration.
5576 if (entry) {
5577 validateEntry(entry);
5578 var indexedCollection = isCollection(entry);
5579 return iteratorValue(
5580 type,
5581 indexedCollection ? entry.get(0) : entry[0],
5582 indexedCollection ? entry.get(1) : entry[1],
5583 step
5584 );
5585 }
5586 }
5587 });
5588 };
5589
5590 return FromEntriesSequence;
5591}(KeyedSeq));
5592
5593ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough;
5594
5595function flipFactory(collection) {
5596 var flipSequence = makeSequence(collection);
5597 flipSequence._iter = collection;
5598 flipSequence.size = collection.size;
5599 flipSequence.flip = function () { return collection; };
5600 flipSequence.reverse = function() {
5601 var reversedSequence = collection.reverse.apply(this); // super.reverse()
5602 reversedSequence.flip = function () { return collection.reverse(); };
5603 return reversedSequence;
5604 };
5605 flipSequence.has = function (key) { return collection.includes(key); };
5606 flipSequence.includes = function (key) { return collection.has(key); };
5607 flipSequence.cacheResult = cacheResultThrough;
5608 flipSequence.__iterateUncached = function(fn, reverse) {
5609 var this$1 = this;
5610
5611 return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse);
5612 };
5613 flipSequence.__iteratorUncached = function(type, reverse) {
5614 if (type === ITERATE_ENTRIES) {
5615 var iterator = collection.__iterator(type, reverse);
5616 return new Iterator(function () {
5617 var step = iterator.next();
5618 if (!step.done) {
5619 var k = step.value[0];
5620 step.value[0] = step.value[1];
5621 step.value[1] = k;
5622 }
5623 return step;
5624 });
5625 }
5626 return collection.__iterator(
5627 type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
5628 reverse
5629 );
5630 };
5631 return flipSequence;
5632}
5633
5634function mapFactory(collection, mapper, context) {
5635 var mappedSequence = makeSequence(collection);
5636 mappedSequence.size = collection.size;
5637 mappedSequence.has = function (key) { return collection.has(key); };
5638 mappedSequence.get = function (key, notSetValue) {
5639 var v = collection.get(key, NOT_SET);
5640 return v === NOT_SET
5641 ? notSetValue
5642 : mapper.call(context, v, key, collection);
5643 };
5644 mappedSequence.__iterateUncached = function(fn, reverse) {
5645 var this$1 = this;
5646
5647 return collection.__iterate(
5648 function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; },
5649 reverse
5650 );
5651 };
5652 mappedSequence.__iteratorUncached = function(type, reverse) {
5653 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
5654 return new Iterator(function () {
5655 var step = iterator.next();
5656 if (step.done) {
5657 return step;
5658 }
5659 var entry = step.value;
5660 var key = entry[0];
5661 return iteratorValue(
5662 type,
5663 key,
5664 mapper.call(context, entry[1], key, collection),
5665 step
5666 );
5667 });
5668 };
5669 return mappedSequence;
5670}
5671
5672function reverseFactory(collection, useKeys) {
5673 var this$1 = this;
5674
5675 var reversedSequence = makeSequence(collection);
5676 reversedSequence._iter = collection;
5677 reversedSequence.size = collection.size;
5678 reversedSequence.reverse = function () { return collection; };
5679 if (collection.flip) {
5680 reversedSequence.flip = function() {
5681 var flipSequence = flipFactory(collection);
5682 flipSequence.reverse = function () { return collection.flip(); };
5683 return flipSequence;
5684 };
5685 }
5686 reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); };
5687 reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); };
5688 reversedSequence.includes = function (value) { return collection.includes(value); };
5689 reversedSequence.cacheResult = cacheResultThrough;
5690 reversedSequence.__iterate = function(fn, reverse) {
5691 var this$1 = this;
5692
5693 var i = 0;
5694 reverse && ensureSize(collection);
5695 return collection.__iterate(
5696 function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); },
5697 !reverse
5698 );
5699 };
5700 reversedSequence.__iterator = function (type, reverse) {
5701 var i = 0;
5702 reverse && ensureSize(collection);
5703 var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse);
5704 return new Iterator(function () {
5705 var step = iterator.next();
5706 if (step.done) {
5707 return step;
5708 }
5709 var entry = step.value;
5710 return iteratorValue(
5711 type,
5712 useKeys ? entry[0] : reverse ? this$1.size - ++i : i++,
5713 entry[1],
5714 step
5715 );
5716 });
5717 };
5718 return reversedSequence;
5719}
5720
5721function filterFactory(collection, predicate, context, useKeys) {
5722 var filterSequence = makeSequence(collection);
5723 if (useKeys) {
5724 filterSequence.has = function (key) {
5725 var v = collection.get(key, NOT_SET);
5726 return v !== NOT_SET && !!predicate.call(context, v, key, collection);
5727 };
5728 filterSequence.get = function (key, notSetValue) {
5729 var v = collection.get(key, NOT_SET);
5730 return v !== NOT_SET && predicate.call(context, v, key, collection)
5731 ? v
5732 : notSetValue;
5733 };
5734 }
5735 filterSequence.__iterateUncached = function(fn, reverse) {
5736 var this$1 = this;
5737
5738 var iterations = 0;
5739 collection.__iterate(function (v, k, c) {
5740 if (predicate.call(context, v, k, c)) {
5741 iterations++;
5742 return fn(v, useKeys ? k : iterations - 1, this$1);
5743 }
5744 }, reverse);
5745 return iterations;
5746 };
5747 filterSequence.__iteratorUncached = function(type, reverse) {
5748 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
5749 var iterations = 0;
5750 return new Iterator(function () {
5751 while (true) {
5752 var step = iterator.next();
5753 if (step.done) {
5754 return step;
5755 }
5756 var entry = step.value;
5757 var key = entry[0];
5758 var value = entry[1];
5759 if (predicate.call(context, value, key, collection)) {
5760 return iteratorValue(type, useKeys ? key : iterations++, value, step);
5761 }
5762 }
5763 });
5764 };
5765 return filterSequence;
5766}
5767
5768function countByFactory(collection, grouper, context) {
5769 var groups = Map$1().asMutable();
5770 collection.__iterate(function (v, k) {
5771 groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; });
5772 });
5773 return groups.asImmutable();
5774}
5775
5776function groupByFactory(collection, grouper, context) {
5777 var isKeyedIter = isKeyed(collection);
5778 var groups = (isOrdered(collection) ? OrderedMap() : Map$1()).asMutable();
5779 collection.__iterate(function (v, k) {
5780 groups.update(
5781 grouper.call(context, v, k, collection),
5782 function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); }
5783 );
5784 });
5785 var coerce = collectionClass(collection);
5786 return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable();
5787}
5788
5789function sliceFactory(collection, begin, end, useKeys) {
5790 var originalSize = collection.size;
5791
5792 if (wholeSlice(begin, end, originalSize)) {
5793 return collection;
5794 }
5795
5796 var resolvedBegin = resolveBegin(begin, originalSize);
5797 var resolvedEnd = resolveEnd(end, originalSize);
5798
5799 // begin or end will be NaN if they were provided as negative numbers and
5800 // this collection's size is unknown. In that case, cache first so there is
5801 // a known size and these do not resolve to NaN.
5802 if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
5803 return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
5804 }
5805
5806 // Note: resolvedEnd is undefined when the original sequence's length is
5807 // unknown and this slice did not supply an end and should contain all
5808 // elements after resolvedBegin.
5809 // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
5810 var resolvedSize = resolvedEnd - resolvedBegin;
5811 var sliceSize;
5812 if (resolvedSize === resolvedSize) {
5813 sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
5814 }
5815
5816 var sliceSeq = makeSequence(collection);
5817
5818 // If collection.size is undefined, the size of the realized sliceSeq is
5819 // unknown at this point unless the number of items to slice is 0
5820 sliceSeq.size =
5821 sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
5822
5823 if (!useKeys && isSeq(collection) && sliceSize >= 0) {
5824 sliceSeq.get = function(index, notSetValue) {
5825 index = wrapIndex(this, index);
5826 return index >= 0 && index < sliceSize
5827 ? collection.get(index + resolvedBegin, notSetValue)
5828 : notSetValue;
5829 };
5830 }
5831
5832 sliceSeq.__iterateUncached = function(fn, reverse) {
5833 var this$1 = this;
5834
5835 if (sliceSize === 0) {
5836 return 0;
5837 }
5838 if (reverse) {
5839 return this.cacheResult().__iterate(fn, reverse);
5840 }
5841 var skipped = 0;
5842 var isSkipping = true;
5843 var iterations = 0;
5844 collection.__iterate(function (v, k) {
5845 if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
5846 iterations++;
5847 return (
5848 fn(v, useKeys ? k : iterations - 1, this$1) !== false &&
5849 iterations !== sliceSize
5850 );
5851 }
5852 });
5853 return iterations;
5854 };
5855
5856 sliceSeq.__iteratorUncached = function(type, reverse) {
5857 if (sliceSize !== 0 && reverse) {
5858 return this.cacheResult().__iterator(type, reverse);
5859 }
5860 // Don't bother instantiating parent iterator if taking 0.
5861 if (sliceSize === 0) {
5862 return new Iterator(iteratorDone);
5863 }
5864 var iterator = collection.__iterator(type, reverse);
5865 var skipped = 0;
5866 var iterations = 0;
5867 return new Iterator(function () {
5868 while (skipped++ < resolvedBegin) {
5869 iterator.next();
5870 }
5871 if (++iterations > sliceSize) {
5872 return iteratorDone();
5873 }
5874 var step = iterator.next();
5875 if (useKeys || type === ITERATE_VALUES || step.done) {
5876 return step;
5877 }
5878 if (type === ITERATE_KEYS) {
5879 return iteratorValue(type, iterations - 1, undefined, step);
5880 }
5881 return iteratorValue(type, iterations - 1, step.value[1], step);
5882 });
5883 };
5884
5885 return sliceSeq;
5886}
5887
5888function takeWhileFactory(collection, predicate, context) {
5889 var takeSequence = makeSequence(collection);
5890 takeSequence.__iterateUncached = function(fn, reverse) {
5891 var this$1 = this;
5892
5893 if (reverse) {
5894 return this.cacheResult().__iterate(fn, reverse);
5895 }
5896 var iterations = 0;
5897 collection.__iterate(
5898 function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); }
5899 );
5900 return iterations;
5901 };
5902 takeSequence.__iteratorUncached = function(type, reverse) {
5903 var this$1 = this;
5904
5905 if (reverse) {
5906 return this.cacheResult().__iterator(type, reverse);
5907 }
5908 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
5909 var iterating = true;
5910 return new Iterator(function () {
5911 if (!iterating) {
5912 return iteratorDone();
5913 }
5914 var step = iterator.next();
5915 if (step.done) {
5916 return step;
5917 }
5918 var entry = step.value;
5919 var k = entry[0];
5920 var v = entry[1];
5921 if (!predicate.call(context, v, k, this$1)) {
5922 iterating = false;
5923 return iteratorDone();
5924 }
5925 return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
5926 });
5927 };
5928 return takeSequence;
5929}
5930
5931function skipWhileFactory(collection, predicate, context, useKeys) {
5932 var skipSequence = makeSequence(collection);
5933 skipSequence.__iterateUncached = function(fn, reverse) {
5934 var this$1 = this;
5935
5936 if (reverse) {
5937 return this.cacheResult().__iterate(fn, reverse);
5938 }
5939 var isSkipping = true;
5940 var iterations = 0;
5941 collection.__iterate(function (v, k, c) {
5942 if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
5943 iterations++;
5944 return fn(v, useKeys ? k : iterations - 1, this$1);
5945 }
5946 });
5947 return iterations;
5948 };
5949 skipSequence.__iteratorUncached = function(type, reverse) {
5950 var this$1 = this;
5951
5952 if (reverse) {
5953 return this.cacheResult().__iterator(type, reverse);
5954 }
5955 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
5956 var skipping = true;
5957 var iterations = 0;
5958 return new Iterator(function () {
5959 var step;
5960 var k;
5961 var v;
5962 do {
5963 step = iterator.next();
5964 if (step.done) {
5965 if (useKeys || type === ITERATE_VALUES) {
5966 return step;
5967 }
5968 if (type === ITERATE_KEYS) {
5969 return iteratorValue(type, iterations++, undefined, step);
5970 }
5971 return iteratorValue(type, iterations++, step.value[1], step);
5972 }
5973 var entry = step.value;
5974 k = entry[0];
5975 v = entry[1];
5976 skipping && (skipping = predicate.call(context, v, k, this$1));
5977 } while (skipping);
5978 return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
5979 });
5980 };
5981 return skipSequence;
5982}
5983
5984function concatFactory(collection, values) {
5985 var isKeyedCollection = isKeyed(collection);
5986 var iters = [collection]
5987 .concat(values)
5988 .map(function (v) {
5989 if (!isCollection(v)) {
5990 v = isKeyedCollection
5991 ? keyedSeqFromValue(v)
5992 : indexedSeqFromValue(Array.isArray(v) ? v : [v]);
5993 } else if (isKeyedCollection) {
5994 v = KeyedCollection(v);
5995 }
5996 return v;
5997 })
5998 .filter(function (v) { return v.size !== 0; });
5999
6000 if (iters.length === 0) {
6001 return collection;
6002 }
6003
6004 if (iters.length === 1) {
6005 var singleton = iters[0];
6006 if (
6007 singleton === collection ||
6008 (isKeyedCollection && isKeyed(singleton)) ||
6009 (isIndexed(collection) && isIndexed(singleton))
6010 ) {
6011 return singleton;
6012 }
6013 }
6014
6015 var concatSeq = new ArraySeq(iters);
6016 if (isKeyedCollection) {
6017 concatSeq = concatSeq.toKeyedSeq();
6018 } else if (!isIndexed(collection)) {
6019 concatSeq = concatSeq.toSetSeq();
6020 }
6021 concatSeq = concatSeq.flatten(true);
6022 concatSeq.size = iters.reduce(function (sum, seq) {
6023 if (sum !== undefined) {
6024 var size = seq.size;
6025 if (size !== undefined) {
6026 return sum + size;
6027 }
6028 }
6029 }, 0);
6030 return concatSeq;
6031}
6032
6033function flattenFactory(collection, depth, useKeys) {
6034 var flatSequence = makeSequence(collection);
6035 flatSequence.__iterateUncached = function(fn, reverse) {
6036 if (reverse) {
6037 return this.cacheResult().__iterate(fn, reverse);
6038 }
6039 var iterations = 0;
6040 var stopped = false;
6041 function flatDeep(iter, currentDepth) {
6042 iter.__iterate(function (v, k) {
6043 if ((!depth || currentDepth < depth) && isCollection(v)) {
6044 flatDeep(v, currentDepth + 1);
6045 } else {
6046 iterations++;
6047 if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) {
6048 stopped = true;
6049 }
6050 }
6051 return !stopped;
6052 }, reverse);
6053 }
6054 flatDeep(collection, 0);
6055 return iterations;
6056 };
6057 flatSequence.__iteratorUncached = function(type, reverse) {
6058 if (reverse) {
6059 return this.cacheResult().__iterator(type, reverse);
6060 }
6061 var iterator = collection.__iterator(type, reverse);
6062 var stack = [];
6063 var iterations = 0;
6064 return new Iterator(function () {
6065 while (iterator) {
6066 var step = iterator.next();
6067 if (step.done !== false) {
6068 iterator = stack.pop();
6069 continue;
6070 }
6071 var v = step.value;
6072 if (type === ITERATE_ENTRIES) {
6073 v = v[1];
6074 }
6075 if ((!depth || stack.length < depth) && isCollection(v)) {
6076 stack.push(iterator);
6077 iterator = v.__iterator(type, reverse);
6078 } else {
6079 return useKeys ? step : iteratorValue(type, iterations++, v, step);
6080 }
6081 }
6082 return iteratorDone();
6083 });
6084 };
6085 return flatSequence;
6086}
6087
6088function flatMapFactory(collection, mapper, context) {
6089 var coerce = collectionClass(collection);
6090 return collection
6091 .toSeq()
6092 .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); })
6093 .flatten(true);
6094}
6095
6096function interposeFactory(collection, separator) {
6097 var interposedSequence = makeSequence(collection);
6098 interposedSequence.size = collection.size && collection.size * 2 - 1;
6099 interposedSequence.__iterateUncached = function(fn, reverse) {
6100 var this$1 = this;
6101
6102 var iterations = 0;
6103 collection.__iterate(
6104 function (v) { return (!iterations || fn(separator, iterations++, this$1) !== false) &&
6105 fn(v, iterations++, this$1) !== false; },
6106 reverse
6107 );
6108 return iterations;
6109 };
6110 interposedSequence.__iteratorUncached = function(type, reverse) {
6111 var iterator = collection.__iterator(ITERATE_VALUES, reverse);
6112 var iterations = 0;
6113 var step;
6114 return new Iterator(function () {
6115 if (!step || iterations % 2) {
6116 step = iterator.next();
6117 if (step.done) {
6118 return step;
6119 }
6120 }
6121 return iterations % 2
6122 ? iteratorValue(type, iterations++, separator)
6123 : iteratorValue(type, iterations++, step.value, step);
6124 });
6125 };
6126 return interposedSequence;
6127}
6128
6129function sortFactory(collection, comparator, mapper) {
6130 if (!comparator) {
6131 comparator = defaultComparator;
6132 }
6133 var isKeyedCollection = isKeyed(collection);
6134 var index = 0;
6135 var entries = collection
6136 .toSeq()
6137 .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; })
6138 .valueSeq()
6139 .toArray();
6140 entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach(
6141 isKeyedCollection
6142 ? function (v, i) {
6143 entries[i].length = 2;
6144 }
6145 : function (v, i) {
6146 entries[i] = v[1];
6147 }
6148 );
6149 return isKeyedCollection
6150 ? KeyedSeq(entries)
6151 : isIndexed(collection)
6152 ? IndexedSeq(entries)
6153 : SetSeq(entries);
6154}
6155
6156function maxFactory(collection, comparator, mapper) {
6157 if (!comparator) {
6158 comparator = defaultComparator;
6159 }
6160 if (mapper) {
6161 var entry = collection
6162 .toSeq()
6163 .map(function (v, k) { return [v, mapper(v, k, collection)]; })
6164 .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); });
6165 return entry && entry[0];
6166 }
6167 return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); });
6168}
6169
6170function maxCompare(comparator, a, b) {
6171 var comp = comparator(b, a);
6172 // b is considered the new max if the comparator declares them equal, but
6173 // they are not equal and b is in fact a nullish value.
6174 return (
6175 (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) ||
6176 comp > 0
6177 );
6178}
6179
6180function zipWithFactory(keyIter, zipper, iters, zipAll) {
6181 var zipSequence = makeSequence(keyIter);
6182 var sizes = new ArraySeq(iters).map(function (i) { return i.size; });
6183 zipSequence.size = zipAll ? sizes.max() : sizes.min();
6184 // Note: this a generic base implementation of __iterate in terms of
6185 // __iterator which may be more generically useful in the future.
6186 zipSequence.__iterate = function(fn, reverse) {
6187 /* generic:
6188 var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
6189 var step;
6190 var iterations = 0;
6191 while (!(step = iterator.next()).done) {
6192 iterations++;
6193 if (fn(step.value[1], step.value[0], this) === false) {
6194 break;
6195 }
6196 }
6197 return iterations;
6198 */
6199 // indexed:
6200 var iterator = this.__iterator(ITERATE_VALUES, reverse);
6201 var step;
6202 var iterations = 0;
6203 while (!(step = iterator.next()).done) {
6204 if (fn(step.value, iterations++, this) === false) {
6205 break;
6206 }
6207 }
6208 return iterations;
6209 };
6210 zipSequence.__iteratorUncached = function(type, reverse) {
6211 var iterators = iters.map(
6212 function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); }
6213 );
6214 var iterations = 0;
6215 var isDone = false;
6216 return new Iterator(function () {
6217 var steps;
6218 if (!isDone) {
6219 steps = iterators.map(function (i) { return i.next(); });
6220 isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; });
6221 }
6222 if (isDone) {
6223 return iteratorDone();
6224 }
6225 return iteratorValue(
6226 type,
6227 iterations++,
6228 zipper.apply(null, steps.map(function (s) { return s.value; }))
6229 );
6230 });
6231 };
6232 return zipSequence;
6233}
6234
6235// #pragma Helper Functions
6236
6237function reify(iter, seq) {
6238 return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
6239}
6240
6241function validateEntry(entry) {
6242 if (entry !== Object(entry)) {
6243 throw new TypeError('Expected [K, V] tuple: ' + entry);
6244 }
6245}
6246
6247function collectionClass(collection) {
6248 return isKeyed(collection)
6249 ? KeyedCollection
6250 : isIndexed(collection)
6251 ? IndexedCollection
6252 : SetCollection;
6253}
6254
6255function makeSequence(collection) {
6256 return Object.create(
6257 (isKeyed(collection)
6258 ? KeyedSeq
6259 : isIndexed(collection)
6260 ? IndexedSeq
6261 : SetSeq
6262 ).prototype
6263 );
6264}
6265
6266function cacheResultThrough() {
6267 if (this._iter.cacheResult) {
6268 this._iter.cacheResult();
6269 this.size = this._iter.size;
6270 return this;
6271 }
6272 return Seq.prototype.cacheResult.call(this);
6273}
6274
6275function defaultComparator(a, b) {
6276 if (a === undefined && b === undefined) {
6277 return 0;
6278 }
6279
6280 if (a === undefined) {
6281 return 1;
6282 }
6283
6284 if (b === undefined) {
6285 return -1;
6286 }
6287
6288 return a > b ? 1 : a < b ? -1 : 0;
6289}
6290
6291// http://jsperf.com/copy-array-inline
6292function arrCopy(arr, offset) {
6293 offset = offset || 0;
6294 var len = Math.max(0, arr.length - offset);
6295 var newArr = new Array(len);
6296 for (var ii = 0; ii < len; ii++) {
6297 newArr[ii] = arr[ii + offset];
6298 }
6299 return newArr;
6300}
6301
6302function invariant(condition, error) {
6303 if (!condition) { throw new Error(error); }
6304}
6305
6306function assertNotInfinite(size) {
6307 invariant(
6308 size !== Infinity,
6309 'Cannot perform this action with an infinite size.'
6310 );
6311}
6312
6313function coerceKeyPath(keyPath) {
6314 if (isArrayLike(keyPath) && typeof keyPath !== 'string') {
6315 return keyPath;
6316 }
6317 if (isOrdered(keyPath)) {
6318 return keyPath.toArray();
6319 }
6320 throw new TypeError(
6321 'Invalid keyPath: expected Ordered Collection or Array: ' + keyPath
6322 );
6323}
6324
6325function isPlainObj(value) {
6326 return (
6327 value &&
6328 (typeof value.constructor !== 'function' ||
6329 value.constructor.name === 'Object')
6330 );
6331}
6332
6333/**
6334 * Returns true if the value is a potentially-persistent data structure, either
6335 * provided by Immutable.js or a plain Array or Object.
6336 */
6337function isDataStructure(value) {
6338 return (
6339 typeof value === 'object' &&
6340 (isImmutable(value) || Array.isArray(value) || isPlainObj(value))
6341 );
6342}
6343
6344/**
6345 * Converts a value to a string, adding quotes if a string was provided.
6346 */
6347function quoteString(value) {
6348 try {
6349 return typeof value === 'string' ? JSON.stringify(value) : String(value);
6350 } catch (_ignoreError) {
6351 return JSON.stringify(value);
6352 }
6353}
6354
6355function has(collection, key) {
6356 return isImmutable(collection)
6357 ? collection.has(key)
6358 : isDataStructure(collection) && hasOwnProperty.call(collection, key);
6359}
6360
6361function get(collection, key, notSetValue) {
6362 return isImmutable(collection)
6363 ? collection.get(key, notSetValue)
6364 : !has(collection, key)
6365 ? notSetValue
6366 : typeof collection.get === 'function'
6367 ? collection.get(key)
6368 : collection[key];
6369}
6370
6371function shallowCopy(from) {
6372 if (Array.isArray(from)) {
6373 return arrCopy(from);
6374 }
6375 var to = {};
6376 for (var key in from) {
6377 if (hasOwnProperty.call(from, key)) {
6378 to[key] = from[key];
6379 }
6380 }
6381 return to;
6382}
6383
6384function remove(collection, key) {
6385 if (!isDataStructure(collection)) {
6386 throw new TypeError(
6387 'Cannot update non-data-structure value: ' + collection
6388 );
6389 }
6390 if (isImmutable(collection)) {
6391 if (!collection.remove) {
6392 throw new TypeError(
6393 'Cannot update immutable value without .remove() method: ' + collection
6394 );
6395 }
6396 return collection.remove(key);
6397 }
6398 if (!hasOwnProperty.call(collection, key)) {
6399 return collection;
6400 }
6401 var collectionCopy = shallowCopy(collection);
6402 if (Array.isArray(collectionCopy)) {
6403 collectionCopy.splice(key, 1);
6404 } else {
6405 delete collectionCopy[key];
6406 }
6407 return collectionCopy;
6408}
6409
6410function set(collection, key, value) {
6411 if (!isDataStructure(collection)) {
6412 throw new TypeError(
6413 'Cannot update non-data-structure value: ' + collection
6414 );
6415 }
6416 if (isImmutable(collection)) {
6417 if (!collection.set) {
6418 throw new TypeError(
6419 'Cannot update immutable value without .set() method: ' + collection
6420 );
6421 }
6422 return collection.set(key, value);
6423 }
6424 if (hasOwnProperty.call(collection, key) && value === collection[key]) {
6425 return collection;
6426 }
6427 var collectionCopy = shallowCopy(collection);
6428 collectionCopy[key] = value;
6429 return collectionCopy;
6430}
6431
6432function updateIn(collection, keyPath, notSetValue, updater) {
6433 if (!updater) {
6434 updater = notSetValue;
6435 notSetValue = undefined;
6436 }
6437 var updatedValue = updateInDeeply(
6438 isImmutable(collection),
6439 collection,
6440 coerceKeyPath(keyPath),
6441 0,
6442 notSetValue,
6443 updater
6444 );
6445 return updatedValue === NOT_SET ? notSetValue : updatedValue;
6446}
6447
6448function updateInDeeply(
6449 inImmutable,
6450 existing,
6451 keyPath,
6452 i,
6453 notSetValue,
6454 updater
6455) {
6456 var wasNotSet = existing === NOT_SET;
6457 if (i === keyPath.length) {
6458 var existingValue = wasNotSet ? notSetValue : existing;
6459 var newValue = updater(existingValue);
6460 return newValue === existingValue ? existing : newValue;
6461 }
6462 if (!wasNotSet && !isDataStructure(existing)) {
6463 throw new TypeError(
6464 'Cannot update within non-data-structure value in path [' +
6465 keyPath.slice(0, i).map(quoteString) +
6466 ']: ' +
6467 existing
6468 );
6469 }
6470 var key = keyPath[i];
6471 var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET);
6472 var nextUpdated = updateInDeeply(
6473 nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting),
6474 nextExisting,
6475 keyPath,
6476 i + 1,
6477 notSetValue,
6478 updater
6479 );
6480 return nextUpdated === nextExisting
6481 ? existing
6482 : nextUpdated === NOT_SET
6483 ? remove(existing, key)
6484 : set(
6485 wasNotSet ? (inImmutable ? emptyMap() : {}) : existing,
6486 key,
6487 nextUpdated
6488 );
6489}
6490
6491function setIn(collection, keyPath, value) {
6492 return updateIn(collection, keyPath, NOT_SET, function () { return value; });
6493}
6494
6495function setIn$1(keyPath, v) {
6496 return setIn(this, keyPath, v);
6497}
6498
6499function removeIn(collection, keyPath) {
6500 return updateIn(collection, keyPath, function () { return NOT_SET; });
6501}
6502
6503function deleteIn(keyPath) {
6504 return removeIn(this, keyPath);
6505}
6506
6507function update(collection, key, notSetValue, updater) {
6508 return updateIn(collection, [key], notSetValue, updater);
6509}
6510
6511function update$1(key, notSetValue, updater) {
6512 return arguments.length === 1
6513 ? key(this)
6514 : update(this, key, notSetValue, updater);
6515}
6516
6517function updateIn$1(keyPath, notSetValue, updater) {
6518 return updateIn(this, keyPath, notSetValue, updater);
6519}
6520
6521function merge() {
6522 var iters = [], len = arguments.length;
6523 while ( len-- ) iters[ len ] = arguments[ len ];
6524
6525 return mergeIntoKeyedWith(this, iters);
6526}
6527
6528function mergeWith(merger) {
6529 var iters = [], len = arguments.length - 1;
6530 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6531
6532 if (typeof merger !== 'function') {
6533 throw new TypeError('Invalid merger function: ' + merger);
6534 }
6535 return mergeIntoKeyedWith(this, iters, merger);
6536}
6537
6538function mergeIntoKeyedWith(collection, collections, merger) {
6539 var iters = [];
6540 for (var ii = 0; ii < collections.length; ii++) {
6541 var collection$1 = KeyedCollection(collections[ii]);
6542 if (collection$1.size !== 0) {
6543 iters.push(collection$1);
6544 }
6545 }
6546 if (iters.length === 0) {
6547 return collection;
6548 }
6549 if (
6550 collection.toSeq().size === 0 &&
6551 !collection.__ownerID &&
6552 iters.length === 1
6553 ) {
6554 return collection.constructor(iters[0]);
6555 }
6556 return collection.withMutations(function (collection) {
6557 var mergeIntoCollection = merger
6558 ? function (value, key) {
6559 update(
6560 collection,
6561 key,
6562 NOT_SET,
6563 function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); }
6564 );
6565 }
6566 : function (value, key) {
6567 collection.set(key, value);
6568 };
6569 for (var ii = 0; ii < iters.length; ii++) {
6570 iters[ii].forEach(mergeIntoCollection);
6571 }
6572 });
6573}
6574
6575function merge$1(collection) {
6576 var sources = [], len = arguments.length - 1;
6577 while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
6578
6579 return mergeWithSources(collection, sources);
6580}
6581
6582function mergeWith$1(merger, collection) {
6583 var sources = [], len = arguments.length - 2;
6584 while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
6585
6586 return mergeWithSources(collection, sources, merger);
6587}
6588
6589function mergeDeep(collection) {
6590 var sources = [], len = arguments.length - 1;
6591 while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
6592
6593 return mergeDeepWithSources(collection, sources);
6594}
6595
6596function mergeDeepWith(merger, collection) {
6597 var sources = [], len = arguments.length - 2;
6598 while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
6599
6600 return mergeDeepWithSources(collection, sources, merger);
6601}
6602
6603function mergeDeepWithSources(collection, sources, merger) {
6604 return mergeWithSources(collection, sources, deepMergerWith(merger));
6605}
6606
6607function mergeWithSources(collection, sources, merger) {
6608 if (!isDataStructure(collection)) {
6609 throw new TypeError(
6610 'Cannot merge into non-data-structure value: ' + collection
6611 );
6612 }
6613 if (isImmutable(collection)) {
6614 return typeof merger === 'function' && collection.mergeWith
6615 ? collection.mergeWith.apply(collection, [ merger ].concat( sources ))
6616 : collection.merge
6617 ? collection.merge.apply(collection, sources)
6618 : collection.concat.apply(collection, sources);
6619 }
6620 var isArray = Array.isArray(collection);
6621 var merged = collection;
6622 var Collection$$1 = isArray ? IndexedCollection : KeyedCollection;
6623 var mergeItem = isArray
6624 ? function (value) {
6625 // Copy on write
6626 if (merged === collection) {
6627 merged = shallowCopy(merged);
6628 }
6629 merged.push(value);
6630 }
6631 : function (value, key) {
6632 var hasVal = hasOwnProperty.call(merged, key);
6633 var nextVal =
6634 hasVal && merger ? merger(merged[key], value, key) : value;
6635 if (!hasVal || nextVal !== merged[key]) {
6636 // Copy on write
6637 if (merged === collection) {
6638 merged = shallowCopy(merged);
6639 }
6640 merged[key] = nextVal;
6641 }
6642 };
6643 for (var i = 0; i < sources.length; i++) {
6644 Collection$$1(sources[i]).forEach(mergeItem);
6645 }
6646 return merged;
6647}
6648
6649function deepMergerWith(merger) {
6650 function deepMerger(oldValue, newValue, key) {
6651 return isDataStructure(oldValue) && isDataStructure(newValue)
6652 ? mergeWithSources(oldValue, [newValue], deepMerger)
6653 : merger
6654 ? merger(oldValue, newValue, key)
6655 : newValue;
6656 }
6657 return deepMerger;
6658}
6659
6660function mergeDeep$1() {
6661 var iters = [], len = arguments.length;
6662 while ( len-- ) iters[ len ] = arguments[ len ];
6663
6664 return mergeDeepWithSources(this, iters);
6665}
6666
6667function mergeDeepWith$1(merger) {
6668 var iters = [], len = arguments.length - 1;
6669 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6670
6671 return mergeDeepWithSources(this, iters, merger);
6672}
6673
6674function mergeIn(keyPath) {
6675 var iters = [], len = arguments.length - 1;
6676 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6677
6678 return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); });
6679}
6680
6681function mergeDeepIn(keyPath) {
6682 var iters = [], len = arguments.length - 1;
6683 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6684
6685 return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); }
6686 );
6687}
6688
6689function withMutations(fn) {
6690 var mutable = this.asMutable();
6691 fn(mutable);
6692 return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
6693}
6694
6695function asMutable() {
6696 return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
6697}
6698
6699function asImmutable() {
6700 return this.__ensureOwner();
6701}
6702
6703function wasAltered() {
6704 return this.__altered;
6705}
6706
6707var Map$1 = /*@__PURE__*/(function (KeyedCollection$$1) {
6708 function Map(value) {
6709 return value === null || value === undefined
6710 ? emptyMap()
6711 : isMap(value) && !isOrdered(value)
6712 ? value
6713 : emptyMap().withMutations(function (map) {
6714 var iter = KeyedCollection$$1(value);
6715 assertNotInfinite(iter.size);
6716 iter.forEach(function (v, k) { return map.set(k, v); });
6717 });
6718 }
6719
6720 if ( KeyedCollection$$1 ) Map.__proto__ = KeyedCollection$$1;
6721 Map.prototype = Object.create( KeyedCollection$$1 && KeyedCollection$$1.prototype );
6722 Map.prototype.constructor = Map;
6723
6724 Map.of = function of () {
6725 var keyValues = [], len = arguments.length;
6726 while ( len-- ) keyValues[ len ] = arguments[ len ];
6727
6728 return emptyMap().withMutations(function (map) {
6729 for (var i = 0; i < keyValues.length; i += 2) {
6730 if (i + 1 >= keyValues.length) {
6731 throw new Error('Missing value for key: ' + keyValues[i]);
6732 }
6733 map.set(keyValues[i], keyValues[i + 1]);
6734 }
6735 });
6736 };
6737
6738 Map.prototype.toString = function toString () {
6739 return this.__toString('Map {', '}');
6740 };
6741
6742 // @pragma Access
6743
6744 Map.prototype.get = function get (k, notSetValue) {
6745 return this._root
6746 ? this._root.get(0, undefined, k, notSetValue)
6747 : notSetValue;
6748 };
6749
6750 // @pragma Modification
6751
6752 Map.prototype.set = function set (k, v) {
6753 return updateMap(this, k, v);
6754 };
6755
6756 Map.prototype.remove = function remove (k) {
6757 return updateMap(this, k, NOT_SET);
6758 };
6759
6760 Map.prototype.deleteAll = function deleteAll (keys) {
6761 var collection = Collection(keys);
6762
6763 if (collection.size === 0) {
6764 return this;
6765 }
6766
6767 return this.withMutations(function (map) {
6768 collection.forEach(function (key) { return map.remove(key); });
6769 });
6770 };
6771
6772 Map.prototype.clear = function clear () {
6773 if (this.size === 0) {
6774 return this;
6775 }
6776 if (this.__ownerID) {
6777 this.size = 0;
6778 this._root = null;
6779 this.__hash = undefined;
6780 this.__altered = true;
6781 return this;
6782 }
6783 return emptyMap();
6784 };
6785
6786 // @pragma Composition
6787
6788 Map.prototype.sort = function sort (comparator) {
6789 // Late binding
6790 return OrderedMap(sortFactory(this, comparator));
6791 };
6792
6793 Map.prototype.sortBy = function sortBy (mapper, comparator) {
6794 // Late binding
6795 return OrderedMap(sortFactory(this, comparator, mapper));
6796 };
6797
6798 Map.prototype.map = function map (mapper, context) {
6799 return this.withMutations(function (map) {
6800 map.forEach(function (value, key) {
6801 map.set(key, mapper.call(context, value, key, map));
6802 });
6803 });
6804 };
6805
6806 // @pragma Mutability
6807
6808 Map.prototype.__iterator = function __iterator (type, reverse) {
6809 return new MapIterator(this, type, reverse);
6810 };
6811
6812 Map.prototype.__iterate = function __iterate (fn, reverse) {
6813 var this$1 = this;
6814
6815 var iterations = 0;
6816 this._root &&
6817 this._root.iterate(function (entry) {
6818 iterations++;
6819 return fn(entry[1], entry[0], this$1);
6820 }, reverse);
6821 return iterations;
6822 };
6823
6824 Map.prototype.__ensureOwner = function __ensureOwner (ownerID) {
6825 if (ownerID === this.__ownerID) {
6826 return this;
6827 }
6828 if (!ownerID) {
6829 if (this.size === 0) {
6830 return emptyMap();
6831 }
6832 this.__ownerID = ownerID;
6833 this.__altered = false;
6834 return this;
6835 }
6836 return makeMap(this.size, this._root, ownerID, this.__hash);
6837 };
6838
6839 return Map;
6840}(KeyedCollection));
6841
6842Map$1.isMap = isMap;
6843
6844var MapPrototype = Map$1.prototype;
6845MapPrototype[IS_MAP_SYMBOL] = true;
6846MapPrototype[DELETE] = MapPrototype.remove;
6847MapPrototype.removeAll = MapPrototype.deleteAll;
6848MapPrototype.setIn = setIn$1;
6849MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn;
6850MapPrototype.update = update$1;
6851MapPrototype.updateIn = updateIn$1;
6852MapPrototype.merge = MapPrototype.concat = merge;
6853MapPrototype.mergeWith = mergeWith;
6854MapPrototype.mergeDeep = mergeDeep$1;
6855MapPrototype.mergeDeepWith = mergeDeepWith$1;
6856MapPrototype.mergeIn = mergeIn;
6857MapPrototype.mergeDeepIn = mergeDeepIn;
6858MapPrototype.withMutations = withMutations;
6859MapPrototype.wasAltered = wasAltered;
6860MapPrototype.asImmutable = asImmutable;
6861MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable;
6862MapPrototype['@@transducer/step'] = function(result, arr) {
6863 return result.set(arr[0], arr[1]);
6864};
6865MapPrototype['@@transducer/result'] = function(obj) {
6866 return obj.asImmutable();
6867};
6868
6869// #pragma Trie Nodes
6870
6871var ArrayMapNode = function ArrayMapNode(ownerID, entries) {
6872 this.ownerID = ownerID;
6873 this.entries = entries;
6874};
6875
6876ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
6877 var entries = this.entries;
6878 for (var ii = 0, len = entries.length; ii < len; ii++) {
6879 if (is(key, entries[ii][0])) {
6880 return entries[ii][1];
6881 }
6882 }
6883 return notSetValue;
6884};
6885
6886ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
6887 var removed = value === NOT_SET;
6888
6889 var entries = this.entries;
6890 var idx = 0;
6891 var len = entries.length;
6892 for (; idx < len; idx++) {
6893 if (is(key, entries[idx][0])) {
6894 break;
6895 }
6896 }
6897 var exists = idx < len;
6898
6899 if (exists ? entries[idx][1] === value : removed) {
6900 return this;
6901 }
6902
6903 SetRef(didAlter);
6904 (removed || !exists) && SetRef(didChangeSize);
6905
6906 if (removed && entries.length === 1) {
6907 return; // undefined
6908 }
6909
6910 if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
6911 return createNodes(ownerID, entries, key, value);
6912 }
6913
6914 var isEditable = ownerID && ownerID === this.ownerID;
6915 var newEntries = isEditable ? entries : arrCopy(entries);
6916
6917 if (exists) {
6918 if (removed) {
6919 idx === len - 1
6920 ? newEntries.pop()
6921 : (newEntries[idx] = newEntries.pop());
6922 } else {
6923 newEntries[idx] = [key, value];
6924 }
6925 } else {
6926 newEntries.push([key, value]);
6927 }
6928
6929 if (isEditable) {
6930 this.entries = newEntries;
6931 return this;
6932 }
6933
6934 return new ArrayMapNode(ownerID, newEntries);
6935};
6936
6937var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) {
6938 this.ownerID = ownerID;
6939 this.bitmap = bitmap;
6940 this.nodes = nodes;
6941};
6942
6943BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
6944 if (keyHash === undefined) {
6945 keyHash = hash(key);
6946 }
6947 var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK);
6948 var bitmap = this.bitmap;
6949 return (bitmap & bit) === 0
6950 ? notSetValue
6951 : this.nodes[popCount(bitmap & (bit - 1))].get(
6952 shift + SHIFT,
6953 keyHash,
6954 key,
6955 notSetValue
6956 );
6957};
6958
6959BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
6960 if (keyHash === undefined) {
6961 keyHash = hash(key);
6962 }
6963 var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
6964 var bit = 1 << keyHashFrag;
6965 var bitmap = this.bitmap;
6966 var exists = (bitmap & bit) !== 0;
6967
6968 if (!exists && value === NOT_SET) {
6969 return this;
6970 }
6971
6972 var idx = popCount(bitmap & (bit - 1));
6973 var nodes = this.nodes;
6974 var node = exists ? nodes[idx] : undefined;
6975 var newNode = updateNode(
6976 node,
6977 ownerID,
6978 shift + SHIFT,
6979 keyHash,
6980 key,
6981 value,
6982 didChangeSize,
6983 didAlter
6984 );
6985
6986 if (newNode === node) {
6987 return this;
6988 }
6989
6990 if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
6991 return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
6992 }
6993
6994 if (
6995 exists &&
6996 !newNode &&
6997 nodes.length === 2 &&
6998 isLeafNode(nodes[idx ^ 1])
6999 ) {
7000 return nodes[idx ^ 1];
7001 }
7002
7003 if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
7004 return newNode;
7005 }
7006
7007 var isEditable = ownerID && ownerID === this.ownerID;
7008 var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit;
7009 var newNodes = exists
7010 ? newNode
7011 ? setAt(nodes, idx, newNode, isEditable)
7012 : spliceOut(nodes, idx, isEditable)
7013 : spliceIn(nodes, idx, newNode, isEditable);
7014
7015 if (isEditable) {
7016 this.bitmap = newBitmap;
7017 this.nodes = newNodes;
7018 return this;
7019 }
7020
7021 return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
7022};
7023
7024var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) {
7025 this.ownerID = ownerID;
7026 this.count = count;
7027 this.nodes = nodes;
7028};
7029
7030HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7031 if (keyHash === undefined) {
7032 keyHash = hash(key);
7033 }
7034 var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7035 var node = this.nodes[idx];
7036 return node
7037 ? node.get(shift + SHIFT, keyHash, key, notSetValue)
7038 : notSetValue;
7039};
7040
7041HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7042 if (keyHash === undefined) {
7043 keyHash = hash(key);
7044 }
7045 var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7046 var removed = value === NOT_SET;
7047 var nodes = this.nodes;
7048 var node = nodes[idx];
7049
7050 if (removed && !node) {
7051 return this;
7052 }
7053
7054 var newNode = updateNode(
7055 node,
7056 ownerID,
7057 shift + SHIFT,
7058 keyHash,
7059 key,
7060 value,
7061 didChangeSize,
7062 didAlter
7063 );
7064 if (newNode === node) {
7065 return this;
7066 }
7067
7068 var newCount = this.count;
7069 if (!node) {
7070 newCount++;
7071 } else if (!newNode) {
7072 newCount--;
7073 if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
7074 return packNodes(ownerID, nodes, newCount, idx);
7075 }
7076 }
7077
7078 var isEditable = ownerID && ownerID === this.ownerID;
7079 var newNodes = setAt(nodes, idx, newNode, isEditable);
7080
7081 if (isEditable) {
7082 this.count = newCount;
7083 this.nodes = newNodes;
7084 return this;
7085 }
7086
7087 return new HashArrayMapNode(ownerID, newCount, newNodes);
7088};
7089
7090var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) {
7091 this.ownerID = ownerID;
7092 this.keyHash = keyHash;
7093 this.entries = entries;
7094};
7095
7096HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7097 var entries = this.entries;
7098 for (var ii = 0, len = entries.length; ii < len; ii++) {
7099 if (is(key, entries[ii][0])) {
7100 return entries[ii][1];
7101 }
7102 }
7103 return notSetValue;
7104};
7105
7106HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7107 if (keyHash === undefined) {
7108 keyHash = hash(key);
7109 }
7110
7111 var removed = value === NOT_SET;
7112
7113 if (keyHash !== this.keyHash) {
7114 if (removed) {
7115 return this;
7116 }
7117 SetRef(didAlter);
7118 SetRef(didChangeSize);
7119 return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
7120 }
7121
7122 var entries = this.entries;
7123 var idx = 0;
7124 var len = entries.length;
7125 for (; idx < len; idx++) {
7126 if (is(key, entries[idx][0])) {
7127 break;
7128 }
7129 }
7130 var exists = idx < len;
7131
7132 if (exists ? entries[idx][1] === value : removed) {
7133 return this;
7134 }
7135
7136 SetRef(didAlter);
7137 (removed || !exists) && SetRef(didChangeSize);
7138
7139 if (removed && len === 2) {
7140 return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
7141 }
7142
7143 var isEditable = ownerID && ownerID === this.ownerID;
7144 var newEntries = isEditable ? entries : arrCopy(entries);
7145
7146 if (exists) {
7147 if (removed) {
7148 idx === len - 1
7149 ? newEntries.pop()
7150 : (newEntries[idx] = newEntries.pop());
7151 } else {
7152 newEntries[idx] = [key, value];
7153 }
7154 } else {
7155 newEntries.push([key, value]);
7156 }
7157
7158 if (isEditable) {
7159 this.entries = newEntries;
7160 return this;
7161 }
7162
7163 return new HashCollisionNode(ownerID, this.keyHash, newEntries);
7164};
7165
7166var ValueNode = function ValueNode(ownerID, keyHash, entry) {
7167 this.ownerID = ownerID;
7168 this.keyHash = keyHash;
7169 this.entry = entry;
7170};
7171
7172ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7173 return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
7174};
7175
7176ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7177 var removed = value === NOT_SET;
7178 var keyMatch = is(key, this.entry[0]);
7179 if (keyMatch ? value === this.entry[1] : removed) {
7180 return this;
7181 }
7182
7183 SetRef(didAlter);
7184
7185 if (removed) {
7186 SetRef(didChangeSize);
7187 return; // undefined
7188 }
7189
7190 if (keyMatch) {
7191 if (ownerID && ownerID === this.ownerID) {
7192 this.entry[1] = value;
7193 return this;
7194 }
7195 return new ValueNode(ownerID, this.keyHash, [key, value]);
7196 }
7197
7198 SetRef(didChangeSize);
7199 return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
7200};
7201
7202// #pragma Iterators
7203
7204ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function(
7205 fn,
7206 reverse
7207) {
7208 var entries = this.entries;
7209 for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
7210 if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
7211 return false;
7212 }
7213 }
7214};
7215
7216BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function(
7217 fn,
7218 reverse
7219) {
7220 var nodes = this.nodes;
7221 for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
7222 var node = nodes[reverse ? maxIndex - ii : ii];
7223 if (node && node.iterate(fn, reverse) === false) {
7224 return false;
7225 }
7226 }
7227};
7228
7229// eslint-disable-next-line no-unused-vars
7230ValueNode.prototype.iterate = function(fn, reverse) {
7231 return fn(this.entry);
7232};
7233
7234var MapIterator = /*@__PURE__*/(function (Iterator$$1) {
7235 function MapIterator(map, type, reverse) {
7236 this._type = type;
7237 this._reverse = reverse;
7238 this._stack = map._root && mapIteratorFrame(map._root);
7239 }
7240
7241 if ( Iterator$$1 ) MapIterator.__proto__ = Iterator$$1;
7242 MapIterator.prototype = Object.create( Iterator$$1 && Iterator$$1.prototype );
7243 MapIterator.prototype.constructor = MapIterator;
7244
7245 MapIterator.prototype.next = function next () {
7246 var type = this._type;
7247 var stack = this._stack;
7248 while (stack) {
7249 var node = stack.node;
7250 var index = stack.index++;
7251 var maxIndex = (void 0);
7252 if (node.entry) {
7253 if (index === 0) {
7254 return mapIteratorValue(type, node.entry);
7255 }
7256 } else if (node.entries) {
7257 maxIndex = node.entries.length - 1;
7258 if (index <= maxIndex) {
7259 return mapIteratorValue(
7260 type,
7261 node.entries[this._reverse ? maxIndex - index : index]
7262 );
7263 }
7264 } else {
7265 maxIndex = node.nodes.length - 1;
7266 if (index <= maxIndex) {
7267 var subNode = node.nodes[this._reverse ? maxIndex - index : index];
7268 if (subNode) {
7269 if (subNode.entry) {
7270 return mapIteratorValue(type, subNode.entry);
7271 }
7272 stack = this._stack = mapIteratorFrame(subNode, stack);
7273 }
7274 continue;
7275 }
7276 }
7277 stack = this._stack = this._stack.__prev;
7278 }
7279 return iteratorDone();
7280 };
7281
7282 return MapIterator;
7283}(Iterator));
7284
7285function mapIteratorValue(type, entry) {
7286 return iteratorValue(type, entry[0], entry[1]);
7287}
7288
7289function mapIteratorFrame(node, prev) {
7290 return {
7291 node: node,
7292 index: 0,
7293 __prev: prev,
7294 };
7295}
7296
7297function makeMap(size, root, ownerID, hash$$1) {
7298 var map = Object.create(MapPrototype);
7299 map.size = size;
7300 map._root = root;
7301 map.__ownerID = ownerID;
7302 map.__hash = hash$$1;
7303 map.__altered = false;
7304 return map;
7305}
7306
7307var EMPTY_MAP;
7308function emptyMap() {
7309 return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
7310}
7311
7312function updateMap(map, k, v) {
7313 var newRoot;
7314 var newSize;
7315 if (!map._root) {
7316 if (v === NOT_SET) {
7317 return map;
7318 }
7319 newSize = 1;
7320 newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
7321 } else {
7322 var didChangeSize = MakeRef();
7323 var didAlter = MakeRef();
7324 newRoot = updateNode(
7325 map._root,
7326 map.__ownerID,
7327 0,
7328 undefined,
7329 k,
7330 v,
7331 didChangeSize,
7332 didAlter
7333 );
7334 if (!didAlter.value) {
7335 return map;
7336 }
7337 newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0);
7338 }
7339 if (map.__ownerID) {
7340 map.size = newSize;
7341 map._root = newRoot;
7342 map.__hash = undefined;
7343 map.__altered = true;
7344 return map;
7345 }
7346 return newRoot ? makeMap(newSize, newRoot) : emptyMap();
7347}
7348
7349function updateNode(
7350 node,
7351 ownerID,
7352 shift,
7353 keyHash,
7354 key,
7355 value,
7356 didChangeSize,
7357 didAlter
7358) {
7359 if (!node) {
7360 if (value === NOT_SET) {
7361 return node;
7362 }
7363 SetRef(didAlter);
7364 SetRef(didChangeSize);
7365 return new ValueNode(ownerID, keyHash, [key, value]);
7366 }
7367 return node.update(
7368 ownerID,
7369 shift,
7370 keyHash,
7371 key,
7372 value,
7373 didChangeSize,
7374 didAlter
7375 );
7376}
7377
7378function isLeafNode(node) {
7379 return (
7380 node.constructor === ValueNode || node.constructor === HashCollisionNode
7381 );
7382}
7383
7384function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
7385 if (node.keyHash === keyHash) {
7386 return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
7387 }
7388
7389 var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
7390 var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7391
7392 var newNode;
7393 var nodes =
7394 idx1 === idx2
7395 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]
7396 : ((newNode = new ValueNode(ownerID, keyHash, entry)),
7397 idx1 < idx2 ? [node, newNode] : [newNode, node]);
7398
7399 return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
7400}
7401
7402function createNodes(ownerID, entries, key, value) {
7403 if (!ownerID) {
7404 ownerID = new OwnerID();
7405 }
7406 var node = new ValueNode(ownerID, hash(key), [key, value]);
7407 for (var ii = 0; ii < entries.length; ii++) {
7408 var entry = entries[ii];
7409 node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
7410 }
7411 return node;
7412}
7413
7414function packNodes(ownerID, nodes, count, excluding) {
7415 var bitmap = 0;
7416 var packedII = 0;
7417 var packedNodes = new Array(count);
7418 for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
7419 var node = nodes[ii];
7420 if (node !== undefined && ii !== excluding) {
7421 bitmap |= bit;
7422 packedNodes[packedII++] = node;
7423 }
7424 }
7425 return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
7426}
7427
7428function expandNodes(ownerID, nodes, bitmap, including, node) {
7429 var count = 0;
7430 var expandedNodes = new Array(SIZE);
7431 for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
7432 expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
7433 }
7434 expandedNodes[including] = node;
7435 return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
7436}
7437
7438function popCount(x) {
7439 x -= (x >> 1) & 0x55555555;
7440 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
7441 x = (x + (x >> 4)) & 0x0f0f0f0f;
7442 x += x >> 8;
7443 x += x >> 16;
7444 return x & 0x7f;
7445}
7446
7447function setAt(array, idx, val, canEdit) {
7448 var newArray = canEdit ? array : arrCopy(array);
7449 newArray[idx] = val;
7450 return newArray;
7451}
7452
7453function spliceIn(array, idx, val, canEdit) {
7454 var newLen = array.length + 1;
7455 if (canEdit && idx + 1 === newLen) {
7456 array[idx] = val;
7457 return array;
7458 }
7459 var newArray = new Array(newLen);
7460 var after = 0;
7461 for (var ii = 0; ii < newLen; ii++) {
7462 if (ii === idx) {
7463 newArray[ii] = val;
7464 after = -1;
7465 } else {
7466 newArray[ii] = array[ii + after];
7467 }
7468 }
7469 return newArray;
7470}
7471
7472function spliceOut(array, idx, canEdit) {
7473 var newLen = array.length - 1;
7474 if (canEdit && idx === newLen) {
7475 array.pop();
7476 return array;
7477 }
7478 var newArray = new Array(newLen);
7479 var after = 0;
7480 for (var ii = 0; ii < newLen; ii++) {
7481 if (ii === idx) {
7482 after = 1;
7483 }
7484 newArray[ii] = array[ii + after];
7485 }
7486 return newArray;
7487}
7488
7489var MAX_ARRAY_MAP_SIZE = SIZE / 4;
7490var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
7491var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
7492
7493var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@';
7494
7495function isList(maybeList) {
7496 return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]);
7497}
7498
7499var List = /*@__PURE__*/(function (IndexedCollection$$1) {
7500 function List(value) {
7501 var empty = emptyList();
7502 if (value === null || value === undefined) {
7503 return empty;
7504 }
7505 if (isList(value)) {
7506 return value;
7507 }
7508 var iter = IndexedCollection$$1(value);
7509 var size = iter.size;
7510 if (size === 0) {
7511 return empty;
7512 }
7513 assertNotInfinite(size);
7514 if (size > 0 && size < SIZE) {
7515 return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
7516 }
7517 return empty.withMutations(function (list) {
7518 list.setSize(size);
7519 iter.forEach(function (v, i) { return list.set(i, v); });
7520 });
7521 }
7522
7523 if ( IndexedCollection$$1 ) List.__proto__ = IndexedCollection$$1;
7524 List.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
7525 List.prototype.constructor = List;
7526
7527 List.of = function of (/*...values*/) {
7528 return this(arguments);
7529 };
7530
7531 List.prototype.toString = function toString () {
7532 return this.__toString('List [', ']');
7533 };
7534
7535 // @pragma Access
7536
7537 List.prototype.get = function get (index, notSetValue) {
7538 index = wrapIndex(this, index);
7539 if (index >= 0 && index < this.size) {
7540 index += this._origin;
7541 var node = listNodeFor(this, index);
7542 return node && node.array[index & MASK];
7543 }
7544 return notSetValue;
7545 };
7546
7547 // @pragma Modification
7548
7549 List.prototype.set = function set (index, value) {
7550 return updateList(this, index, value);
7551 };
7552
7553 List.prototype.remove = function remove (index) {
7554 return !this.has(index)
7555 ? this
7556 : index === 0
7557 ? this.shift()
7558 : index === this.size - 1
7559 ? this.pop()
7560 : this.splice(index, 1);
7561 };
7562
7563 List.prototype.insert = function insert (index, value) {
7564 return this.splice(index, 0, value);
7565 };
7566
7567 List.prototype.clear = function clear () {
7568 if (this.size === 0) {
7569 return this;
7570 }
7571 if (this.__ownerID) {
7572 this.size = this._origin = this._capacity = 0;
7573 this._level = SHIFT;
7574 this._root = this._tail = null;
7575 this.__hash = undefined;
7576 this.__altered = true;
7577 return this;
7578 }
7579 return emptyList();
7580 };
7581
7582 List.prototype.push = function push (/*...values*/) {
7583 var values = arguments;
7584 var oldSize = this.size;
7585 return this.withMutations(function (list) {
7586 setListBounds(list, 0, oldSize + values.length);
7587 for (var ii = 0; ii < values.length; ii++) {
7588 list.set(oldSize + ii, values[ii]);
7589 }
7590 });
7591 };
7592
7593 List.prototype.pop = function pop () {
7594 return setListBounds(this, 0, -1);
7595 };
7596
7597 List.prototype.unshift = function unshift (/*...values*/) {
7598 var values = arguments;
7599 return this.withMutations(function (list) {
7600 setListBounds(list, -values.length);
7601 for (var ii = 0; ii < values.length; ii++) {
7602 list.set(ii, values[ii]);
7603 }
7604 });
7605 };
7606
7607 List.prototype.shift = function shift () {
7608 return setListBounds(this, 1);
7609 };
7610
7611 // @pragma Composition
7612
7613 List.prototype.concat = function concat (/*...collections*/) {
7614 var arguments$1 = arguments;
7615
7616 var seqs = [];
7617 for (var i = 0; i < arguments.length; i++) {
7618 var argument = arguments$1[i];
7619 var seq = IndexedCollection$$1(
7620 typeof argument !== 'string' && hasIterator(argument)
7621 ? argument
7622 : [argument]
7623 );
7624 if (seq.size !== 0) {
7625 seqs.push(seq);
7626 }
7627 }
7628 if (seqs.length === 0) {
7629 return this;
7630 }
7631 if (this.size === 0 && !this.__ownerID && seqs.length === 1) {
7632 return this.constructor(seqs[0]);
7633 }
7634 return this.withMutations(function (list) {
7635 seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); });
7636 });
7637 };
7638
7639 List.prototype.setSize = function setSize (size) {
7640 return setListBounds(this, 0, size);
7641 };
7642
7643 List.prototype.map = function map (mapper, context) {
7644 var this$1 = this;
7645
7646 return this.withMutations(function (list) {
7647 for (var i = 0; i < this$1.size; i++) {
7648 list.set(i, mapper.call(context, list.get(i), i, list));
7649 }
7650 });
7651 };
7652
7653 // @pragma Iteration
7654
7655 List.prototype.slice = function slice (begin, end) {
7656 var size = this.size;
7657 if (wholeSlice(begin, end, size)) {
7658 return this;
7659 }
7660 return setListBounds(
7661 this,
7662 resolveBegin(begin, size),
7663 resolveEnd(end, size)
7664 );
7665 };
7666
7667 List.prototype.__iterator = function __iterator (type, reverse) {
7668 var index = reverse ? this.size : 0;
7669 var values = iterateList(this, reverse);
7670 return new Iterator(function () {
7671 var value = values();
7672 return value === DONE
7673 ? iteratorDone()
7674 : iteratorValue(type, reverse ? --index : index++, value);
7675 });
7676 };
7677
7678 List.prototype.__iterate = function __iterate (fn, reverse) {
7679 var index = reverse ? this.size : 0;
7680 var values = iterateList(this, reverse);
7681 var value;
7682 while ((value = values()) !== DONE) {
7683 if (fn(value, reverse ? --index : index++, this) === false) {
7684 break;
7685 }
7686 }
7687 return index;
7688 };
7689
7690 List.prototype.__ensureOwner = function __ensureOwner (ownerID) {
7691 if (ownerID === this.__ownerID) {
7692 return this;
7693 }
7694 if (!ownerID) {
7695 if (this.size === 0) {
7696 return emptyList();
7697 }
7698 this.__ownerID = ownerID;
7699 this.__altered = false;
7700 return this;
7701 }
7702 return makeList(
7703 this._origin,
7704 this._capacity,
7705 this._level,
7706 this._root,
7707 this._tail,
7708 ownerID,
7709 this.__hash
7710 );
7711 };
7712
7713 return List;
7714}(IndexedCollection));
7715
7716List.isList = isList;
7717
7718var ListPrototype = List.prototype;
7719ListPrototype[IS_LIST_SYMBOL] = true;
7720ListPrototype[DELETE] = ListPrototype.remove;
7721ListPrototype.merge = ListPrototype.concat;
7722ListPrototype.setIn = setIn$1;
7723ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn;
7724ListPrototype.update = update$1;
7725ListPrototype.updateIn = updateIn$1;
7726ListPrototype.mergeIn = mergeIn;
7727ListPrototype.mergeDeepIn = mergeDeepIn;
7728ListPrototype.withMutations = withMutations;
7729ListPrototype.wasAltered = wasAltered;
7730ListPrototype.asImmutable = asImmutable;
7731ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable;
7732ListPrototype['@@transducer/step'] = function(result, arr) {
7733 return result.push(arr);
7734};
7735ListPrototype['@@transducer/result'] = function(obj) {
7736 return obj.asImmutable();
7737};
7738
7739var VNode = function VNode(array, ownerID) {
7740 this.array = array;
7741 this.ownerID = ownerID;
7742};
7743
7744// TODO: seems like these methods are very similar
7745
7746VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) {
7747 if (index === level ? 1 << level : this.array.length === 0) {
7748 return this;
7749 }
7750 var originIndex = (index >>> level) & MASK;
7751 if (originIndex >= this.array.length) {
7752 return new VNode([], ownerID);
7753 }
7754 var removingFirst = originIndex === 0;
7755 var newChild;
7756 if (level > 0) {
7757 var oldChild = this.array[originIndex];
7758 newChild =
7759 oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
7760 if (newChild === oldChild && removingFirst) {
7761 return this;
7762 }
7763 }
7764 if (removingFirst && !newChild) {
7765 return this;
7766 }
7767 var editable = editableVNode(this, ownerID);
7768 if (!removingFirst) {
7769 for (var ii = 0; ii < originIndex; ii++) {
7770 editable.array[ii] = undefined;
7771 }
7772 }
7773 if (newChild) {
7774 editable.array[originIndex] = newChild;
7775 }
7776 return editable;
7777};
7778
7779VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) {
7780 if (index === (level ? 1 << level : 0) || this.array.length === 0) {
7781 return this;
7782 }
7783 var sizeIndex = ((index - 1) >>> level) & MASK;
7784 if (sizeIndex >= this.array.length) {
7785 return this;
7786 }
7787
7788 var newChild;
7789 if (level > 0) {
7790 var oldChild = this.array[sizeIndex];
7791 newChild =
7792 oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
7793 if (newChild === oldChild && sizeIndex === this.array.length - 1) {
7794 return this;
7795 }
7796 }
7797
7798 var editable = editableVNode(this, ownerID);
7799 editable.array.splice(sizeIndex + 1);
7800 if (newChild) {
7801 editable.array[sizeIndex] = newChild;
7802 }
7803 return editable;
7804};
7805
7806var DONE = {};
7807
7808function iterateList(list, reverse) {
7809 var left = list._origin;
7810 var right = list._capacity;
7811 var tailPos = getTailOffset(right);
7812 var tail = list._tail;
7813
7814 return iterateNodeOrLeaf(list._root, list._level, 0);
7815
7816 function iterateNodeOrLeaf(node, level, offset) {
7817 return level === 0
7818 ? iterateLeaf(node, offset)
7819 : iterateNode(node, level, offset);
7820 }
7821
7822 function iterateLeaf(node, offset) {
7823 var array = offset === tailPos ? tail && tail.array : node && node.array;
7824 var from = offset > left ? 0 : left - offset;
7825 var to = right - offset;
7826 if (to > SIZE) {
7827 to = SIZE;
7828 }
7829 return function () {
7830 if (from === to) {
7831 return DONE;
7832 }
7833 var idx = reverse ? --to : from++;
7834 return array && array[idx];
7835 };
7836 }
7837
7838 function iterateNode(node, level, offset) {
7839 var values;
7840 var array = node && node.array;
7841 var from = offset > left ? 0 : (left - offset) >> level;
7842 var to = ((right - offset) >> level) + 1;
7843 if (to > SIZE) {
7844 to = SIZE;
7845 }
7846 return function () {
7847 while (true) {
7848 if (values) {
7849 var value = values();
7850 if (value !== DONE) {
7851 return value;
7852 }
7853 values = null;
7854 }
7855 if (from === to) {
7856 return DONE;
7857 }
7858 var idx = reverse ? --to : from++;
7859 values = iterateNodeOrLeaf(
7860 array && array[idx],
7861 level - SHIFT,
7862 offset + (idx << level)
7863 );
7864 }
7865 };
7866 }
7867}
7868
7869function makeList(origin, capacity, level, root, tail, ownerID, hash) {
7870 var list = Object.create(ListPrototype);
7871 list.size = capacity - origin;
7872 list._origin = origin;
7873 list._capacity = capacity;
7874 list._level = level;
7875 list._root = root;
7876 list._tail = tail;
7877 list.__ownerID = ownerID;
7878 list.__hash = hash;
7879 list.__altered = false;
7880 return list;
7881}
7882
7883var EMPTY_LIST;
7884function emptyList() {
7885 return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
7886}
7887
7888function updateList(list, index, value) {
7889 index = wrapIndex(list, index);
7890
7891 if (index !== index) {
7892 return list;
7893 }
7894
7895 if (index >= list.size || index < 0) {
7896 return list.withMutations(function (list) {
7897 index < 0
7898 ? setListBounds(list, index).set(0, value)
7899 : setListBounds(list, 0, index + 1).set(index, value);
7900 });
7901 }
7902
7903 index += list._origin;
7904
7905 var newTail = list._tail;
7906 var newRoot = list._root;
7907 var didAlter = MakeRef();
7908 if (index >= getTailOffset(list._capacity)) {
7909 newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
7910 } else {
7911 newRoot = updateVNode(
7912 newRoot,
7913 list.__ownerID,
7914 list._level,
7915 index,
7916 value,
7917 didAlter
7918 );
7919 }
7920
7921 if (!didAlter.value) {
7922 return list;
7923 }
7924
7925 if (list.__ownerID) {
7926 list._root = newRoot;
7927 list._tail = newTail;
7928 list.__hash = undefined;
7929 list.__altered = true;
7930 return list;
7931 }
7932 return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
7933}
7934
7935function updateVNode(node, ownerID, level, index, value, didAlter) {
7936 var idx = (index >>> level) & MASK;
7937 var nodeHas = node && idx < node.array.length;
7938 if (!nodeHas && value === undefined) {
7939 return node;
7940 }
7941
7942 var newNode;
7943
7944 if (level > 0) {
7945 var lowerNode = node && node.array[idx];
7946 var newLowerNode = updateVNode(
7947 lowerNode,
7948 ownerID,
7949 level - SHIFT,
7950 index,
7951 value,
7952 didAlter
7953 );
7954 if (newLowerNode === lowerNode) {
7955 return node;
7956 }
7957 newNode = editableVNode(node, ownerID);
7958 newNode.array[idx] = newLowerNode;
7959 return newNode;
7960 }
7961
7962 if (nodeHas && node.array[idx] === value) {
7963 return node;
7964 }
7965
7966 if (didAlter) {
7967 SetRef(didAlter);
7968 }
7969
7970 newNode = editableVNode(node, ownerID);
7971 if (value === undefined && idx === newNode.array.length - 1) {
7972 newNode.array.pop();
7973 } else {
7974 newNode.array[idx] = value;
7975 }
7976 return newNode;
7977}
7978
7979function editableVNode(node, ownerID) {
7980 if (ownerID && node && ownerID === node.ownerID) {
7981 return node;
7982 }
7983 return new VNode(node ? node.array.slice() : [], ownerID);
7984}
7985
7986function listNodeFor(list, rawIndex) {
7987 if (rawIndex >= getTailOffset(list._capacity)) {
7988 return list._tail;
7989 }
7990 if (rawIndex < 1 << (list._level + SHIFT)) {
7991 var node = list._root;
7992 var level = list._level;
7993 while (node && level > 0) {
7994 node = node.array[(rawIndex >>> level) & MASK];
7995 level -= SHIFT;
7996 }
7997 return node;
7998 }
7999}
8000
8001function setListBounds(list, begin, end) {
8002 // Sanitize begin & end using this shorthand for ToInt32(argument)
8003 // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
8004 if (begin !== undefined) {
8005 begin |= 0;
8006 }
8007 if (end !== undefined) {
8008 end |= 0;
8009 }
8010 var owner = list.__ownerID || new OwnerID();
8011 var oldOrigin = list._origin;
8012 var oldCapacity = list._capacity;
8013 var newOrigin = oldOrigin + begin;
8014 var newCapacity =
8015 end === undefined
8016 ? oldCapacity
8017 : end < 0
8018 ? oldCapacity + end
8019 : oldOrigin + end;
8020 if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
8021 return list;
8022 }
8023
8024 // If it's going to end after it starts, it's empty.
8025 if (newOrigin >= newCapacity) {
8026 return list.clear();
8027 }
8028
8029 var newLevel = list._level;
8030 var newRoot = list._root;
8031
8032 // New origin might need creating a higher root.
8033 var offsetShift = 0;
8034 while (newOrigin + offsetShift < 0) {
8035 newRoot = new VNode(
8036 newRoot && newRoot.array.length ? [undefined, newRoot] : [],
8037 owner
8038 );
8039 newLevel += SHIFT;
8040 offsetShift += 1 << newLevel;
8041 }
8042 if (offsetShift) {
8043 newOrigin += offsetShift;
8044 oldOrigin += offsetShift;
8045 newCapacity += offsetShift;
8046 oldCapacity += offsetShift;
8047 }
8048
8049 var oldTailOffset = getTailOffset(oldCapacity);
8050 var newTailOffset = getTailOffset(newCapacity);
8051
8052 // New size might need creating a higher root.
8053 while (newTailOffset >= 1 << (newLevel + SHIFT)) {
8054 newRoot = new VNode(
8055 newRoot && newRoot.array.length ? [newRoot] : [],
8056 owner
8057 );
8058 newLevel += SHIFT;
8059 }
8060
8061 // Locate or create the new tail.
8062 var oldTail = list._tail;
8063 var newTail =
8064 newTailOffset < oldTailOffset
8065 ? listNodeFor(list, newCapacity - 1)
8066 : newTailOffset > oldTailOffset
8067 ? new VNode([], owner)
8068 : oldTail;
8069
8070 // Merge Tail into tree.
8071 if (
8072 oldTail &&
8073 newTailOffset > oldTailOffset &&
8074 newOrigin < oldCapacity &&
8075 oldTail.array.length
8076 ) {
8077 newRoot = editableVNode(newRoot, owner);
8078 var node = newRoot;
8079 for (var level = newLevel; level > SHIFT; level -= SHIFT) {
8080 var idx = (oldTailOffset >>> level) & MASK;
8081 node = node.array[idx] = editableVNode(node.array[idx], owner);
8082 }
8083 node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
8084 }
8085
8086 // If the size has been reduced, there's a chance the tail needs to be trimmed.
8087 if (newCapacity < oldCapacity) {
8088 newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
8089 }
8090
8091 // If the new origin is within the tail, then we do not need a root.
8092 if (newOrigin >= newTailOffset) {
8093 newOrigin -= newTailOffset;
8094 newCapacity -= newTailOffset;
8095 newLevel = SHIFT;
8096 newRoot = null;
8097 newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
8098
8099 // Otherwise, if the root has been trimmed, garbage collect.
8100 } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
8101 offsetShift = 0;
8102
8103 // Identify the new top root node of the subtree of the old root.
8104 while (newRoot) {
8105 var beginIndex = (newOrigin >>> newLevel) & MASK;
8106 if ((beginIndex !== newTailOffset >>> newLevel) & MASK) {
8107 break;
8108 }
8109 if (beginIndex) {
8110 offsetShift += (1 << newLevel) * beginIndex;
8111 }
8112 newLevel -= SHIFT;
8113 newRoot = newRoot.array[beginIndex];
8114 }
8115
8116 // Trim the new sides of the new root.
8117 if (newRoot && newOrigin > oldOrigin) {
8118 newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
8119 }
8120 if (newRoot && newTailOffset < oldTailOffset) {
8121 newRoot = newRoot.removeAfter(
8122 owner,
8123 newLevel,
8124 newTailOffset - offsetShift
8125 );
8126 }
8127 if (offsetShift) {
8128 newOrigin -= offsetShift;
8129 newCapacity -= offsetShift;
8130 }
8131 }
8132
8133 if (list.__ownerID) {
8134 list.size = newCapacity - newOrigin;
8135 list._origin = newOrigin;
8136 list._capacity = newCapacity;
8137 list._level = newLevel;
8138 list._root = newRoot;
8139 list._tail = newTail;
8140 list.__hash = undefined;
8141 list.__altered = true;
8142 return list;
8143 }
8144 return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
8145}
8146
8147function getTailOffset(size) {
8148 return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT;
8149}
8150
8151var OrderedMap = /*@__PURE__*/(function (Map$$1) {
8152 function OrderedMap(value) {
8153 return value === null || value === undefined
8154 ? emptyOrderedMap()
8155 : isOrderedMap(value)
8156 ? value
8157 : emptyOrderedMap().withMutations(function (map) {
8158 var iter = KeyedCollection(value);
8159 assertNotInfinite(iter.size);
8160 iter.forEach(function (v, k) { return map.set(k, v); });
8161 });
8162 }
8163
8164 if ( Map$$1 ) OrderedMap.__proto__ = Map$$1;
8165 OrderedMap.prototype = Object.create( Map$$1 && Map$$1.prototype );
8166 OrderedMap.prototype.constructor = OrderedMap;
8167
8168 OrderedMap.of = function of (/*...values*/) {
8169 return this(arguments);
8170 };
8171
8172 OrderedMap.prototype.toString = function toString () {
8173 return this.__toString('OrderedMap {', '}');
8174 };
8175
8176 // @pragma Access
8177
8178 OrderedMap.prototype.get = function get (k, notSetValue) {
8179 var index = this._map.get(k);
8180 return index !== undefined ? this._list.get(index)[1] : notSetValue;
8181 };
8182
8183 // @pragma Modification
8184
8185 OrderedMap.prototype.clear = function clear () {
8186 if (this.size === 0) {
8187 return this;
8188 }
8189 if (this.__ownerID) {
8190 this.size = 0;
8191 this._map.clear();
8192 this._list.clear();
8193 return this;
8194 }
8195 return emptyOrderedMap();
8196 };
8197
8198 OrderedMap.prototype.set = function set (k, v) {
8199 return updateOrderedMap(this, k, v);
8200 };
8201
8202 OrderedMap.prototype.remove = function remove (k) {
8203 return updateOrderedMap(this, k, NOT_SET);
8204 };
8205
8206 OrderedMap.prototype.wasAltered = function wasAltered () {
8207 return this._map.wasAltered() || this._list.wasAltered();
8208 };
8209
8210 OrderedMap.prototype.__iterate = function __iterate (fn, reverse) {
8211 var this$1 = this;
8212
8213 return this._list.__iterate(
8214 function (entry) { return entry && fn(entry[1], entry[0], this$1); },
8215 reverse
8216 );
8217 };
8218
8219 OrderedMap.prototype.__iterator = function __iterator (type, reverse) {
8220 return this._list.fromEntrySeq().__iterator(type, reverse);
8221 };
8222
8223 OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) {
8224 if (ownerID === this.__ownerID) {
8225 return this;
8226 }
8227 var newMap = this._map.__ensureOwner(ownerID);
8228 var newList = this._list.__ensureOwner(ownerID);
8229 if (!ownerID) {
8230 if (this.size === 0) {
8231 return emptyOrderedMap();
8232 }
8233 this.__ownerID = ownerID;
8234 this._map = newMap;
8235 this._list = newList;
8236 return this;
8237 }
8238 return makeOrderedMap(newMap, newList, ownerID, this.__hash);
8239 };
8240
8241 return OrderedMap;
8242}(Map$1));
8243
8244OrderedMap.isOrderedMap = isOrderedMap;
8245
8246OrderedMap.prototype[IS_ORDERED_SYMBOL] = true;
8247OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
8248
8249function makeOrderedMap(map, list, ownerID, hash) {
8250 var omap = Object.create(OrderedMap.prototype);
8251 omap.size = map ? map.size : 0;
8252 omap._map = map;
8253 omap._list = list;
8254 omap.__ownerID = ownerID;
8255 omap.__hash = hash;
8256 return omap;
8257}
8258
8259var EMPTY_ORDERED_MAP;
8260function emptyOrderedMap() {
8261 return (
8262 EMPTY_ORDERED_MAP ||
8263 (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()))
8264 );
8265}
8266
8267function updateOrderedMap(omap, k, v) {
8268 var map = omap._map;
8269 var list = omap._list;
8270 var i = map.get(k);
8271 var has = i !== undefined;
8272 var newMap;
8273 var newList;
8274 if (v === NOT_SET) {
8275 // removed
8276 if (!has) {
8277 return omap;
8278 }
8279 if (list.size >= SIZE && list.size >= map.size * 2) {
8280 newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; });
8281 newMap = newList
8282 .toKeyedSeq()
8283 .map(function (entry) { return entry[0]; })
8284 .flip()
8285 .toMap();
8286 if (omap.__ownerID) {
8287 newMap.__ownerID = newList.__ownerID = omap.__ownerID;
8288 }
8289 } else {
8290 newMap = map.remove(k);
8291 newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
8292 }
8293 } else if (has) {
8294 if (v === list.get(i)[1]) {
8295 return omap;
8296 }
8297 newMap = map;
8298 newList = list.set(i, [k, v]);
8299 } else {
8300 newMap = map.set(k, list.size);
8301 newList = list.set(list.size, [k, v]);
8302 }
8303 if (omap.__ownerID) {
8304 omap.size = newMap.size;
8305 omap._map = newMap;
8306 omap._list = newList;
8307 omap.__hash = undefined;
8308 return omap;
8309 }
8310 return makeOrderedMap(newMap, newList);
8311}
8312
8313var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@';
8314
8315function isStack(maybeStack) {
8316 return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]);
8317}
8318
8319var Stack = /*@__PURE__*/(function (IndexedCollection$$1) {
8320 function Stack(value) {
8321 return value === null || value === undefined
8322 ? emptyStack()
8323 : isStack(value)
8324 ? value
8325 : emptyStack().pushAll(value);
8326 }
8327
8328 if ( IndexedCollection$$1 ) Stack.__proto__ = IndexedCollection$$1;
8329 Stack.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
8330 Stack.prototype.constructor = Stack;
8331
8332 Stack.of = function of (/*...values*/) {
8333 return this(arguments);
8334 };
8335
8336 Stack.prototype.toString = function toString () {
8337 return this.__toString('Stack [', ']');
8338 };
8339
8340 // @pragma Access
8341
8342 Stack.prototype.get = function get (index, notSetValue) {
8343 var head = this._head;
8344 index = wrapIndex(this, index);
8345 while (head && index--) {
8346 head = head.next;
8347 }
8348 return head ? head.value : notSetValue;
8349 };
8350
8351 Stack.prototype.peek = function peek () {
8352 return this._head && this._head.value;
8353 };
8354
8355 // @pragma Modification
8356
8357 Stack.prototype.push = function push (/*...values*/) {
8358 var arguments$1 = arguments;
8359
8360 if (arguments.length === 0) {
8361 return this;
8362 }
8363 var newSize = this.size + arguments.length;
8364 var head = this._head;
8365 for (var ii = arguments.length - 1; ii >= 0; ii--) {
8366 head = {
8367 value: arguments$1[ii],
8368 next: head,
8369 };
8370 }
8371 if (this.__ownerID) {
8372 this.size = newSize;
8373 this._head = head;
8374 this.__hash = undefined;
8375 this.__altered = true;
8376 return this;
8377 }
8378 return makeStack(newSize, head);
8379 };
8380
8381 Stack.prototype.pushAll = function pushAll (iter) {
8382 iter = IndexedCollection$$1(iter);
8383 if (iter.size === 0) {
8384 return this;
8385 }
8386 if (this.size === 0 && isStack(iter)) {
8387 return iter;
8388 }
8389 assertNotInfinite(iter.size);
8390 var newSize = this.size;
8391 var head = this._head;
8392 iter.__iterate(function (value) {
8393 newSize++;
8394 head = {
8395 value: value,
8396 next: head,
8397 };
8398 }, /* reverse */ true);
8399 if (this.__ownerID) {
8400 this.size = newSize;
8401 this._head = head;
8402 this.__hash = undefined;
8403 this.__altered = true;
8404 return this;
8405 }
8406 return makeStack(newSize, head);
8407 };
8408
8409 Stack.prototype.pop = function pop () {
8410 return this.slice(1);
8411 };
8412
8413 Stack.prototype.clear = function clear () {
8414 if (this.size === 0) {
8415 return this;
8416 }
8417 if (this.__ownerID) {
8418 this.size = 0;
8419 this._head = undefined;
8420 this.__hash = undefined;
8421 this.__altered = true;
8422 return this;
8423 }
8424 return emptyStack();
8425 };
8426
8427 Stack.prototype.slice = function slice (begin, end) {
8428 if (wholeSlice(begin, end, this.size)) {
8429 return this;
8430 }
8431 var resolvedBegin = resolveBegin(begin, this.size);
8432 var resolvedEnd = resolveEnd(end, this.size);
8433 if (resolvedEnd !== this.size) {
8434 // super.slice(begin, end);
8435 return IndexedCollection$$1.prototype.slice.call(this, begin, end);
8436 }
8437 var newSize = this.size - resolvedBegin;
8438 var head = this._head;
8439 while (resolvedBegin--) {
8440 head = head.next;
8441 }
8442 if (this.__ownerID) {
8443 this.size = newSize;
8444 this._head = head;
8445 this.__hash = undefined;
8446 this.__altered = true;
8447 return this;
8448 }
8449 return makeStack(newSize, head);
8450 };
8451
8452 // @pragma Mutability
8453
8454 Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) {
8455 if (ownerID === this.__ownerID) {
8456 return this;
8457 }
8458 if (!ownerID) {
8459 if (this.size === 0) {
8460 return emptyStack();
8461 }
8462 this.__ownerID = ownerID;
8463 this.__altered = false;
8464 return this;
8465 }
8466 return makeStack(this.size, this._head, ownerID, this.__hash);
8467 };
8468
8469 // @pragma Iteration
8470
8471 Stack.prototype.__iterate = function __iterate (fn, reverse) {
8472 var this$1 = this;
8473
8474 if (reverse) {
8475 return new ArraySeq(this.toArray()).__iterate(
8476 function (v, k) { return fn(v, k, this$1); },
8477 reverse
8478 );
8479 }
8480 var iterations = 0;
8481 var node = this._head;
8482 while (node) {
8483 if (fn(node.value, iterations++, this) === false) {
8484 break;
8485 }
8486 node = node.next;
8487 }
8488 return iterations;
8489 };
8490
8491 Stack.prototype.__iterator = function __iterator (type, reverse) {
8492 if (reverse) {
8493 return new ArraySeq(this.toArray()).__iterator(type, reverse);
8494 }
8495 var iterations = 0;
8496 var node = this._head;
8497 return new Iterator(function () {
8498 if (node) {
8499 var value = node.value;
8500 node = node.next;
8501 return iteratorValue(type, iterations++, value);
8502 }
8503 return iteratorDone();
8504 });
8505 };
8506
8507 return Stack;
8508}(IndexedCollection));
8509
8510Stack.isStack = isStack;
8511
8512var StackPrototype = Stack.prototype;
8513StackPrototype[IS_STACK_SYMBOL] = true;
8514StackPrototype.shift = StackPrototype.pop;
8515StackPrototype.unshift = StackPrototype.push;
8516StackPrototype.unshiftAll = StackPrototype.pushAll;
8517StackPrototype.withMutations = withMutations;
8518StackPrototype.wasAltered = wasAltered;
8519StackPrototype.asImmutable = asImmutable;
8520StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable;
8521StackPrototype['@@transducer/step'] = function(result, arr) {
8522 return result.unshift(arr);
8523};
8524StackPrototype['@@transducer/result'] = function(obj) {
8525 return obj.asImmutable();
8526};
8527
8528function makeStack(size, head, ownerID, hash) {
8529 var map = Object.create(StackPrototype);
8530 map.size = size;
8531 map._head = head;
8532 map.__ownerID = ownerID;
8533 map.__hash = hash;
8534 map.__altered = false;
8535 return map;
8536}
8537
8538var EMPTY_STACK;
8539function emptyStack() {
8540 return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
8541}
8542
8543var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@';
8544
8545function isSet(maybeSet) {
8546 return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]);
8547}
8548
8549function isOrderedSet(maybeOrderedSet) {
8550 return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
8551}
8552
8553function deepEqual(a, b) {
8554 if (a === b) {
8555 return true;
8556 }
8557
8558 if (
8559 !isCollection(b) ||
8560 (a.size !== undefined && b.size !== undefined && a.size !== b.size) ||
8561 (a.__hash !== undefined &&
8562 b.__hash !== undefined &&
8563 a.__hash !== b.__hash) ||
8564 isKeyed(a) !== isKeyed(b) ||
8565 isIndexed(a) !== isIndexed(b) ||
8566 isOrdered(a) !== isOrdered(b)
8567 ) {
8568 return false;
8569 }
8570
8571 if (a.size === 0 && b.size === 0) {
8572 return true;
8573 }
8574
8575 var notAssociative = !isAssociative(a);
8576
8577 if (isOrdered(a)) {
8578 var entries = a.entries();
8579 return (
8580 b.every(function (v, k) {
8581 var entry = entries.next().value;
8582 return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
8583 }) && entries.next().done
8584 );
8585 }
8586
8587 var flipped = false;
8588
8589 if (a.size === undefined) {
8590 if (b.size === undefined) {
8591 if (typeof a.cacheResult === 'function') {
8592 a.cacheResult();
8593 }
8594 } else {
8595 flipped = true;
8596 var _ = a;
8597 a = b;
8598 b = _;
8599 }
8600 }
8601
8602 var allEqual = true;
8603 var bSize = b.__iterate(function (v, k) {
8604 if (
8605 notAssociative
8606 ? !a.has(v)
8607 : flipped
8608 ? !is(v, a.get(k, NOT_SET))
8609 : !is(a.get(k, NOT_SET), v)
8610 ) {
8611 allEqual = false;
8612 return false;
8613 }
8614 });
8615
8616 return allEqual && a.size === bSize;
8617}
8618
8619/**
8620 * Contributes additional methods to a constructor
8621 */
8622function mixin(ctor, methods) {
8623 var keyCopier = function (key) {
8624 ctor.prototype[key] = methods[key];
8625 };
8626 Object.keys(methods).forEach(keyCopier);
8627 Object.getOwnPropertySymbols &&
8628 Object.getOwnPropertySymbols(methods).forEach(keyCopier);
8629 return ctor;
8630}
8631
8632function toJS(value) {
8633 if (!value || typeof value !== 'object') {
8634 return value;
8635 }
8636 if (!isCollection(value)) {
8637 if (!isDataStructure(value)) {
8638 return value;
8639 }
8640 value = Seq(value);
8641 }
8642 if (isKeyed(value)) {
8643 var result$1 = {};
8644 value.__iterate(function (v, k) {
8645 result$1[k] = toJS(v);
8646 });
8647 return result$1;
8648 }
8649 var result = [];
8650 value.__iterate(function (v) {
8651 result.push(toJS(v));
8652 });
8653 return result;
8654}
8655
8656var Set$1 = /*@__PURE__*/(function (SetCollection$$1) {
8657 function Set(value) {
8658 return value === null || value === undefined
8659 ? emptySet()
8660 : isSet(value) && !isOrdered(value)
8661 ? value
8662 : emptySet().withMutations(function (set) {
8663 var iter = SetCollection$$1(value);
8664 assertNotInfinite(iter.size);
8665 iter.forEach(function (v) { return set.add(v); });
8666 });
8667 }
8668
8669 if ( SetCollection$$1 ) Set.__proto__ = SetCollection$$1;
8670 Set.prototype = Object.create( SetCollection$$1 && SetCollection$$1.prototype );
8671 Set.prototype.constructor = Set;
8672
8673 Set.of = function of (/*...values*/) {
8674 return this(arguments);
8675 };
8676
8677 Set.fromKeys = function fromKeys (value) {
8678 return this(KeyedCollection(value).keySeq());
8679 };
8680
8681 Set.intersect = function intersect (sets) {
8682 sets = Collection(sets).toArray();
8683 return sets.length
8684 ? SetPrototype.intersect.apply(Set(sets.pop()), sets)
8685 : emptySet();
8686 };
8687
8688 Set.union = function union (sets) {
8689 sets = Collection(sets).toArray();
8690 return sets.length
8691 ? SetPrototype.union.apply(Set(sets.pop()), sets)
8692 : emptySet();
8693 };
8694
8695 Set.prototype.toString = function toString () {
8696 return this.__toString('Set {', '}');
8697 };
8698
8699 // @pragma Access
8700
8701 Set.prototype.has = function has (value) {
8702 return this._map.has(value);
8703 };
8704
8705 // @pragma Modification
8706
8707 Set.prototype.add = function add (value) {
8708 return updateSet(this, this._map.set(value, value));
8709 };
8710
8711 Set.prototype.remove = function remove (value) {
8712 return updateSet(this, this._map.remove(value));
8713 };
8714
8715 Set.prototype.clear = function clear () {
8716 return updateSet(this, this._map.clear());
8717 };
8718
8719 // @pragma Composition
8720
8721 Set.prototype.map = function map (mapper, context) {
8722 var this$1 = this;
8723
8724 var removes = [];
8725 var adds = [];
8726 this.forEach(function (value) {
8727 var mapped = mapper.call(context, value, value, this$1);
8728 if (mapped !== value) {
8729 removes.push(value);
8730 adds.push(mapped);
8731 }
8732 });
8733 return this.withMutations(function (set) {
8734 removes.forEach(function (value) { return set.remove(value); });
8735 adds.forEach(function (value) { return set.add(value); });
8736 });
8737 };
8738
8739 Set.prototype.union = function union () {
8740 var iters = [], len = arguments.length;
8741 while ( len-- ) iters[ len ] = arguments[ len ];
8742
8743 iters = iters.filter(function (x) { return x.size !== 0; });
8744 if (iters.length === 0) {
8745 return this;
8746 }
8747 if (this.size === 0 && !this.__ownerID && iters.length === 1) {
8748 return this.constructor(iters[0]);
8749 }
8750 return this.withMutations(function (set) {
8751 for (var ii = 0; ii < iters.length; ii++) {
8752 SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); });
8753 }
8754 });
8755 };
8756
8757 Set.prototype.intersect = function intersect () {
8758 var iters = [], len = arguments.length;
8759 while ( len-- ) iters[ len ] = arguments[ len ];
8760
8761 if (iters.length === 0) {
8762 return this;
8763 }
8764 iters = iters.map(function (iter) { return SetCollection$$1(iter); });
8765 var toRemove = [];
8766 this.forEach(function (value) {
8767 if (!iters.every(function (iter) { return iter.includes(value); })) {
8768 toRemove.push(value);
8769 }
8770 });
8771 return this.withMutations(function (set) {
8772 toRemove.forEach(function (value) {
8773 set.remove(value);
8774 });
8775 });
8776 };
8777
8778 Set.prototype.subtract = function subtract () {
8779 var iters = [], len = arguments.length;
8780 while ( len-- ) iters[ len ] = arguments[ len ];
8781
8782 if (iters.length === 0) {
8783 return this;
8784 }
8785 iters = iters.map(function (iter) { return SetCollection$$1(iter); });
8786 var toRemove = [];
8787 this.forEach(function (value) {
8788 if (iters.some(function (iter) { return iter.includes(value); })) {
8789 toRemove.push(value);
8790 }
8791 });
8792 return this.withMutations(function (set) {
8793 toRemove.forEach(function (value) {
8794 set.remove(value);
8795 });
8796 });
8797 };
8798
8799 Set.prototype.sort = function sort (comparator) {
8800 // Late binding
8801 return OrderedSet(sortFactory(this, comparator));
8802 };
8803
8804 Set.prototype.sortBy = function sortBy (mapper, comparator) {
8805 // Late binding
8806 return OrderedSet(sortFactory(this, comparator, mapper));
8807 };
8808
8809 Set.prototype.wasAltered = function wasAltered () {
8810 return this._map.wasAltered();
8811 };
8812
8813 Set.prototype.__iterate = function __iterate (fn, reverse) {
8814 var this$1 = this;
8815
8816 return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse);
8817 };
8818
8819 Set.prototype.__iterator = function __iterator (type, reverse) {
8820 return this._map.__iterator(type, reverse);
8821 };
8822
8823 Set.prototype.__ensureOwner = function __ensureOwner (ownerID) {
8824 if (ownerID === this.__ownerID) {
8825 return this;
8826 }
8827 var newMap = this._map.__ensureOwner(ownerID);
8828 if (!ownerID) {
8829 if (this.size === 0) {
8830 return this.__empty();
8831 }
8832 this.__ownerID = ownerID;
8833 this._map = newMap;
8834 return this;
8835 }
8836 return this.__make(newMap, ownerID);
8837 };
8838
8839 return Set;
8840}(SetCollection));
8841
8842Set$1.isSet = isSet;
8843
8844var SetPrototype = Set$1.prototype;
8845SetPrototype[IS_SET_SYMBOL] = true;
8846SetPrototype[DELETE] = SetPrototype.remove;
8847SetPrototype.merge = SetPrototype.concat = SetPrototype.union;
8848SetPrototype.withMutations = withMutations;
8849SetPrototype.asImmutable = asImmutable;
8850SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable;
8851SetPrototype['@@transducer/step'] = function(result, arr) {
8852 return result.add(arr);
8853};
8854SetPrototype['@@transducer/result'] = function(obj) {
8855 return obj.asImmutable();
8856};
8857
8858SetPrototype.__empty = emptySet;
8859SetPrototype.__make = makeSet;
8860
8861function updateSet(set, newMap) {
8862 if (set.__ownerID) {
8863 set.size = newMap.size;
8864 set._map = newMap;
8865 return set;
8866 }
8867 return newMap === set._map
8868 ? set
8869 : newMap.size === 0
8870 ? set.__empty()
8871 : set.__make(newMap);
8872}
8873
8874function makeSet(map, ownerID) {
8875 var set = Object.create(SetPrototype);
8876 set.size = map ? map.size : 0;
8877 set._map = map;
8878 set.__ownerID = ownerID;
8879 return set;
8880}
8881
8882var EMPTY_SET;
8883function emptySet() {
8884 return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
8885}
8886
8887/**
8888 * Returns a lazy seq of nums from start (inclusive) to end
8889 * (exclusive), by step, where start defaults to 0, step to 1, and end to
8890 * infinity. When start is equal to end, returns empty list.
8891 */
8892var Range = /*@__PURE__*/(function (IndexedSeq$$1) {
8893 function Range(start, end, step) {
8894 if (!(this instanceof Range)) {
8895 return new Range(start, end, step);
8896 }
8897 invariant(step !== 0, 'Cannot step a Range by 0');
8898 start = start || 0;
8899 if (end === undefined) {
8900 end = Infinity;
8901 }
8902 step = step === undefined ? 1 : Math.abs(step);
8903 if (end < start) {
8904 step = -step;
8905 }
8906 this._start = start;
8907 this._end = end;
8908 this._step = step;
8909 this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
8910 if (this.size === 0) {
8911 if (EMPTY_RANGE) {
8912 return EMPTY_RANGE;
8913 }
8914 EMPTY_RANGE = this;
8915 }
8916 }
8917
8918 if ( IndexedSeq$$1 ) Range.__proto__ = IndexedSeq$$1;
8919 Range.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
8920 Range.prototype.constructor = Range;
8921
8922 Range.prototype.toString = function toString () {
8923 if (this.size === 0) {
8924 return 'Range []';
8925 }
8926 return (
8927 'Range [ ' +
8928 this._start +
8929 '...' +
8930 this._end +
8931 (this._step !== 1 ? ' by ' + this._step : '') +
8932 ' ]'
8933 );
8934 };
8935
8936 Range.prototype.get = function get (index, notSetValue) {
8937 return this.has(index)
8938 ? this._start + wrapIndex(this, index) * this._step
8939 : notSetValue;
8940 };
8941
8942 Range.prototype.includes = function includes (searchValue) {
8943 var possibleIndex = (searchValue - this._start) / this._step;
8944 return (
8945 possibleIndex >= 0 &&
8946 possibleIndex < this.size &&
8947 possibleIndex === Math.floor(possibleIndex)
8948 );
8949 };
8950
8951 Range.prototype.slice = function slice (begin, end) {
8952 if (wholeSlice(begin, end, this.size)) {
8953 return this;
8954 }
8955 begin = resolveBegin(begin, this.size);
8956 end = resolveEnd(end, this.size);
8957 if (end <= begin) {
8958 return new Range(0, 0);
8959 }
8960 return new Range(
8961 this.get(begin, this._end),
8962 this.get(end, this._end),
8963 this._step
8964 );
8965 };
8966
8967 Range.prototype.indexOf = function indexOf (searchValue) {
8968 var offsetValue = searchValue - this._start;
8969 if (offsetValue % this._step === 0) {
8970 var index = offsetValue / this._step;
8971 if (index >= 0 && index < this.size) {
8972 return index;
8973 }
8974 }
8975 return -1;
8976 };
8977
8978 Range.prototype.lastIndexOf = function lastIndexOf (searchValue) {
8979 return this.indexOf(searchValue);
8980 };
8981
8982 Range.prototype.__iterate = function __iterate (fn, reverse) {
8983 var size = this.size;
8984 var step = this._step;
8985 var value = reverse ? this._start + (size - 1) * step : this._start;
8986 var i = 0;
8987 while (i !== size) {
8988 if (fn(value, reverse ? size - ++i : i++, this) === false) {
8989 break;
8990 }
8991 value += reverse ? -step : step;
8992 }
8993 return i;
8994 };
8995
8996 Range.prototype.__iterator = function __iterator (type, reverse) {
8997 var size = this.size;
8998 var step = this._step;
8999 var value = reverse ? this._start + (size - 1) * step : this._start;
9000 var i = 0;
9001 return new Iterator(function () {
9002 if (i === size) {
9003 return iteratorDone();
9004 }
9005 var v = value;
9006 value += reverse ? -step : step;
9007 return iteratorValue(type, reverse ? size - ++i : i++, v);
9008 });
9009 };
9010
9011 Range.prototype.equals = function equals (other) {
9012 return other instanceof Range
9013 ? this._start === other._start &&
9014 this._end === other._end &&
9015 this._step === other._step
9016 : deepEqual(this, other);
9017 };
9018
9019 return Range;
9020}(IndexedSeq));
9021
9022var EMPTY_RANGE;
9023
9024function getIn(collection, searchKeyPath, notSetValue) {
9025 var keyPath = coerceKeyPath(searchKeyPath);
9026 var i = 0;
9027 while (i !== keyPath.length) {
9028 collection = get(collection, keyPath[i++], NOT_SET);
9029 if (collection === NOT_SET) {
9030 return notSetValue;
9031 }
9032 }
9033 return collection;
9034}
9035
9036function getIn$1(searchKeyPath, notSetValue) {
9037 return getIn(this, searchKeyPath, notSetValue);
9038}
9039
9040function hasIn(collection, keyPath) {
9041 return getIn(collection, keyPath, NOT_SET) !== NOT_SET;
9042}
9043
9044function hasIn$1(searchKeyPath) {
9045 return hasIn(this, searchKeyPath);
9046}
9047
9048function toObject() {
9049 assertNotInfinite(this.size);
9050 var object = {};
9051 this.__iterate(function (v, k) {
9052 object[k] = v;
9053 });
9054 return object;
9055}
9056
9057// Note: all of these methods are deprecated.
9058Collection.isIterable = isCollection;
9059Collection.isKeyed = isKeyed;
9060Collection.isIndexed = isIndexed;
9061Collection.isAssociative = isAssociative;
9062Collection.isOrdered = isOrdered;
9063
9064Collection.Iterator = Iterator;
9065
9066mixin(Collection, {
9067 // ### Conversion to other types
9068
9069 toArray: function toArray() {
9070 assertNotInfinite(this.size);
9071 var array = new Array(this.size || 0);
9072 var useTuples = isKeyed(this);
9073 var i = 0;
9074 this.__iterate(function (v, k) {
9075 // Keyed collections produce an array of tuples.
9076 array[i++] = useTuples ? [k, v] : v;
9077 });
9078 return array;
9079 },
9080
9081 toIndexedSeq: function toIndexedSeq() {
9082 return new ToIndexedSequence(this);
9083 },
9084
9085 toJS: function toJS$1() {
9086 return toJS(this);
9087 },
9088
9089 toKeyedSeq: function toKeyedSeq() {
9090 return new ToKeyedSequence(this, true);
9091 },
9092
9093 toMap: function toMap() {
9094 // Use Late Binding here to solve the circular dependency.
9095 return Map$1(this.toKeyedSeq());
9096 },
9097
9098 toObject: toObject,
9099
9100 toOrderedMap: function toOrderedMap() {
9101 // Use Late Binding here to solve the circular dependency.
9102 return OrderedMap(this.toKeyedSeq());
9103 },
9104
9105 toOrderedSet: function toOrderedSet() {
9106 // Use Late Binding here to solve the circular dependency.
9107 return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
9108 },
9109
9110 toSet: function toSet() {
9111 // Use Late Binding here to solve the circular dependency.
9112 return Set$1(isKeyed(this) ? this.valueSeq() : this);
9113 },
9114
9115 toSetSeq: function toSetSeq() {
9116 return new ToSetSequence(this);
9117 },
9118
9119 toSeq: function toSeq() {
9120 return isIndexed(this)
9121 ? this.toIndexedSeq()
9122 : isKeyed(this)
9123 ? this.toKeyedSeq()
9124 : this.toSetSeq();
9125 },
9126
9127 toStack: function toStack() {
9128 // Use Late Binding here to solve the circular dependency.
9129 return Stack(isKeyed(this) ? this.valueSeq() : this);
9130 },
9131
9132 toList: function toList() {
9133 // Use Late Binding here to solve the circular dependency.
9134 return List(isKeyed(this) ? this.valueSeq() : this);
9135 },
9136
9137 // ### Common JavaScript methods and properties
9138
9139 toString: function toString() {
9140 return '[Collection]';
9141 },
9142
9143 __toString: function __toString(head, tail) {
9144 if (this.size === 0) {
9145 return head + tail;
9146 }
9147 return (
9148 head +
9149 ' ' +
9150 this.toSeq()
9151 .map(this.__toStringMapper)
9152 .join(', ') +
9153 ' ' +
9154 tail
9155 );
9156 },
9157
9158 // ### ES6 Collection methods (ES6 Array and Map)
9159
9160 concat: function concat() {
9161 var values = [], len = arguments.length;
9162 while ( len-- ) values[ len ] = arguments[ len ];
9163
9164 return reify(this, concatFactory(this, values));
9165 },
9166
9167 includes: function includes(searchValue) {
9168 return this.some(function (value) { return is(value, searchValue); });
9169 },
9170
9171 entries: function entries() {
9172 return this.__iterator(ITERATE_ENTRIES);
9173 },
9174
9175 every: function every(predicate, context) {
9176 assertNotInfinite(this.size);
9177 var returnValue = true;
9178 this.__iterate(function (v, k, c) {
9179 if (!predicate.call(context, v, k, c)) {
9180 returnValue = false;
9181 return false;
9182 }
9183 });
9184 return returnValue;
9185 },
9186
9187 filter: function filter(predicate, context) {
9188 return reify(this, filterFactory(this, predicate, context, true));
9189 },
9190
9191 find: function find(predicate, context, notSetValue) {
9192 var entry = this.findEntry(predicate, context);
9193 return entry ? entry[1] : notSetValue;
9194 },
9195
9196 forEach: function forEach(sideEffect, context) {
9197 assertNotInfinite(this.size);
9198 return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
9199 },
9200
9201 join: function join(separator) {
9202 assertNotInfinite(this.size);
9203 separator = separator !== undefined ? '' + separator : ',';
9204 var joined = '';
9205 var isFirst = true;
9206 this.__iterate(function (v) {
9207 isFirst ? (isFirst = false) : (joined += separator);
9208 joined += v !== null && v !== undefined ? v.toString() : '';
9209 });
9210 return joined;
9211 },
9212
9213 keys: function keys() {
9214 return this.__iterator(ITERATE_KEYS);
9215 },
9216
9217 map: function map(mapper, context) {
9218 return reify(this, mapFactory(this, mapper, context));
9219 },
9220
9221 reduce: function reduce$1(reducer, initialReduction, context) {
9222 return reduce(
9223 this,
9224 reducer,
9225 initialReduction,
9226 context,
9227 arguments.length < 2,
9228 false
9229 );
9230 },
9231
9232 reduceRight: function reduceRight(reducer, initialReduction, context) {
9233 return reduce(
9234 this,
9235 reducer,
9236 initialReduction,
9237 context,
9238 arguments.length < 2,
9239 true
9240 );
9241 },
9242
9243 reverse: function reverse() {
9244 return reify(this, reverseFactory(this, true));
9245 },
9246
9247 slice: function slice(begin, end) {
9248 return reify(this, sliceFactory(this, begin, end, true));
9249 },
9250
9251 some: function some(predicate, context) {
9252 return !this.every(not(predicate), context);
9253 },
9254
9255 sort: function sort(comparator) {
9256 return reify(this, sortFactory(this, comparator));
9257 },
9258
9259 values: function values() {
9260 return this.__iterator(ITERATE_VALUES);
9261 },
9262
9263 // ### More sequential methods
9264
9265 butLast: function butLast() {
9266 return this.slice(0, -1);
9267 },
9268
9269 isEmpty: function isEmpty() {
9270 return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; });
9271 },
9272
9273 count: function count(predicate, context) {
9274 return ensureSize(
9275 predicate ? this.toSeq().filter(predicate, context) : this
9276 );
9277 },
9278
9279 countBy: function countBy(grouper, context) {
9280 return countByFactory(this, grouper, context);
9281 },
9282
9283 equals: function equals(other) {
9284 return deepEqual(this, other);
9285 },
9286
9287 entrySeq: function entrySeq() {
9288 var collection = this;
9289 if (collection._cache) {
9290 // We cache as an entries array, so we can just return the cache!
9291 return new ArraySeq(collection._cache);
9292 }
9293 var entriesSequence = collection
9294 .toSeq()
9295 .map(entryMapper)
9296 .toIndexedSeq();
9297 entriesSequence.fromEntrySeq = function () { return collection.toSeq(); };
9298 return entriesSequence;
9299 },
9300
9301 filterNot: function filterNot(predicate, context) {
9302 return this.filter(not(predicate), context);
9303 },
9304
9305 findEntry: function findEntry(predicate, context, notSetValue) {
9306 var found = notSetValue;
9307 this.__iterate(function (v, k, c) {
9308 if (predicate.call(context, v, k, c)) {
9309 found = [k, v];
9310 return false;
9311 }
9312 });
9313 return found;
9314 },
9315
9316 findKey: function findKey(predicate, context) {
9317 var entry = this.findEntry(predicate, context);
9318 return entry && entry[0];
9319 },
9320
9321 findLast: function findLast(predicate, context, notSetValue) {
9322 return this.toKeyedSeq()
9323 .reverse()
9324 .find(predicate, context, notSetValue);
9325 },
9326
9327 findLastEntry: function findLastEntry(predicate, context, notSetValue) {
9328 return this.toKeyedSeq()
9329 .reverse()
9330 .findEntry(predicate, context, notSetValue);
9331 },
9332
9333 findLastKey: function findLastKey(predicate, context) {
9334 return this.toKeyedSeq()
9335 .reverse()
9336 .findKey(predicate, context);
9337 },
9338
9339 first: function first(notSetValue) {
9340 return this.find(returnTrue, null, notSetValue);
9341 },
9342
9343 flatMap: function flatMap(mapper, context) {
9344 return reify(this, flatMapFactory(this, mapper, context));
9345 },
9346
9347 flatten: function flatten(depth) {
9348 return reify(this, flattenFactory(this, depth, true));
9349 },
9350
9351 fromEntrySeq: function fromEntrySeq() {
9352 return new FromEntriesSequence(this);
9353 },
9354
9355 get: function get(searchKey, notSetValue) {
9356 return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue);
9357 },
9358
9359 getIn: getIn$1,
9360
9361 groupBy: function groupBy(grouper, context) {
9362 return groupByFactory(this, grouper, context);
9363 },
9364
9365 has: function has(searchKey) {
9366 return this.get(searchKey, NOT_SET) !== NOT_SET;
9367 },
9368
9369 hasIn: hasIn$1,
9370
9371 isSubset: function isSubset(iter) {
9372 iter = typeof iter.includes === 'function' ? iter : Collection(iter);
9373 return this.every(function (value) { return iter.includes(value); });
9374 },
9375
9376 isSuperset: function isSuperset(iter) {
9377 iter = typeof iter.isSubset === 'function' ? iter : Collection(iter);
9378 return iter.isSubset(this);
9379 },
9380
9381 keyOf: function keyOf(searchValue) {
9382 return this.findKey(function (value) { return is(value, searchValue); });
9383 },
9384
9385 keySeq: function keySeq() {
9386 return this.toSeq()
9387 .map(keyMapper)
9388 .toIndexedSeq();
9389 },
9390
9391 last: function last(notSetValue) {
9392 return this.toSeq()
9393 .reverse()
9394 .first(notSetValue);
9395 },
9396
9397 lastKeyOf: function lastKeyOf(searchValue) {
9398 return this.toKeyedSeq()
9399 .reverse()
9400 .keyOf(searchValue);
9401 },
9402
9403 max: function max(comparator) {
9404 return maxFactory(this, comparator);
9405 },
9406
9407 maxBy: function maxBy(mapper, comparator) {
9408 return maxFactory(this, comparator, mapper);
9409 },
9410
9411 min: function min(comparator) {
9412 return maxFactory(
9413 this,
9414 comparator ? neg(comparator) : defaultNegComparator
9415 );
9416 },
9417
9418 minBy: function minBy(mapper, comparator) {
9419 return maxFactory(
9420 this,
9421 comparator ? neg(comparator) : defaultNegComparator,
9422 mapper
9423 );
9424 },
9425
9426 rest: function rest() {
9427 return this.slice(1);
9428 },
9429
9430 skip: function skip(amount) {
9431 return amount === 0 ? this : this.slice(Math.max(0, amount));
9432 },
9433
9434 skipLast: function skipLast(amount) {
9435 return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
9436 },
9437
9438 skipWhile: function skipWhile(predicate, context) {
9439 return reify(this, skipWhileFactory(this, predicate, context, true));
9440 },
9441
9442 skipUntil: function skipUntil(predicate, context) {
9443 return this.skipWhile(not(predicate), context);
9444 },
9445
9446 sortBy: function sortBy(mapper, comparator) {
9447 return reify(this, sortFactory(this, comparator, mapper));
9448 },
9449
9450 take: function take(amount) {
9451 return this.slice(0, Math.max(0, amount));
9452 },
9453
9454 takeLast: function takeLast(amount) {
9455 return this.slice(-Math.max(0, amount));
9456 },
9457
9458 takeWhile: function takeWhile(predicate, context) {
9459 return reify(this, takeWhileFactory(this, predicate, context));
9460 },
9461
9462 takeUntil: function takeUntil(predicate, context) {
9463 return this.takeWhile(not(predicate), context);
9464 },
9465
9466 update: function update(fn) {
9467 return fn(this);
9468 },
9469
9470 valueSeq: function valueSeq() {
9471 return this.toIndexedSeq();
9472 },
9473
9474 // ### Hashable Object
9475
9476 hashCode: function hashCode() {
9477 return this.__hash || (this.__hash = hashCollection(this));
9478 },
9479
9480 // ### Internal
9481
9482 // abstract __iterate(fn, reverse)
9483
9484 // abstract __iterator(type, reverse)
9485});
9486
9487var CollectionPrototype = Collection.prototype;
9488CollectionPrototype[IS_COLLECTION_SYMBOL] = true;
9489CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values;
9490CollectionPrototype.toJSON = CollectionPrototype.toArray;
9491CollectionPrototype.__toStringMapper = quoteString;
9492CollectionPrototype.inspect = CollectionPrototype.toSource = function() {
9493 return this.toString();
9494};
9495CollectionPrototype.chain = CollectionPrototype.flatMap;
9496CollectionPrototype.contains = CollectionPrototype.includes;
9497
9498mixin(KeyedCollection, {
9499 // ### More sequential methods
9500
9501 flip: function flip() {
9502 return reify(this, flipFactory(this));
9503 },
9504
9505 mapEntries: function mapEntries(mapper, context) {
9506 var this$1 = this;
9507
9508 var iterations = 0;
9509 return reify(
9510 this,
9511 this.toSeq()
9512 .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); })
9513 .fromEntrySeq()
9514 );
9515 },
9516
9517 mapKeys: function mapKeys(mapper, context) {
9518 var this$1 = this;
9519
9520 return reify(
9521 this,
9522 this.toSeq()
9523 .flip()
9524 .map(function (k, v) { return mapper.call(context, k, v, this$1); })
9525 .flip()
9526 );
9527 },
9528});
9529
9530var KeyedCollectionPrototype = KeyedCollection.prototype;
9531KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true;
9532KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries;
9533KeyedCollectionPrototype.toJSON = toObject;
9534KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); };
9535
9536mixin(IndexedCollection, {
9537 // ### Conversion to other types
9538
9539 toKeyedSeq: function toKeyedSeq() {
9540 return new ToKeyedSequence(this, false);
9541 },
9542
9543 // ### ES6 Collection methods (ES6 Array and Map)
9544
9545 filter: function filter(predicate, context) {
9546 return reify(this, filterFactory(this, predicate, context, false));
9547 },
9548
9549 findIndex: function findIndex(predicate, context) {
9550 var entry = this.findEntry(predicate, context);
9551 return entry ? entry[0] : -1;
9552 },
9553
9554 indexOf: function indexOf(searchValue) {
9555 var key = this.keyOf(searchValue);
9556 return key === undefined ? -1 : key;
9557 },
9558
9559 lastIndexOf: function lastIndexOf(searchValue) {
9560 var key = this.lastKeyOf(searchValue);
9561 return key === undefined ? -1 : key;
9562 },
9563
9564 reverse: function reverse() {
9565 return reify(this, reverseFactory(this, false));
9566 },
9567
9568 slice: function slice(begin, end) {
9569 return reify(this, sliceFactory(this, begin, end, false));
9570 },
9571
9572 splice: function splice(index, removeNum /*, ...values*/) {
9573 var numArgs = arguments.length;
9574 removeNum = Math.max(removeNum || 0, 0);
9575 if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
9576 return this;
9577 }
9578 // If index is negative, it should resolve relative to the size of the
9579 // collection. However size may be expensive to compute if not cached, so
9580 // only call count() if the number is in fact negative.
9581 index = resolveBegin(index, index < 0 ? this.count() : this.size);
9582 var spliced = this.slice(0, index);
9583 return reify(
9584 this,
9585 numArgs === 1
9586 ? spliced
9587 : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
9588 );
9589 },
9590
9591 // ### More collection methods
9592
9593 findLastIndex: function findLastIndex(predicate, context) {
9594 var entry = this.findLastEntry(predicate, context);
9595 return entry ? entry[0] : -1;
9596 },
9597
9598 first: function first(notSetValue) {
9599 return this.get(0, notSetValue);
9600 },
9601
9602 flatten: function flatten(depth) {
9603 return reify(this, flattenFactory(this, depth, false));
9604 },
9605
9606 get: function get(index, notSetValue) {
9607 index = wrapIndex(this, index);
9608 return index < 0 ||
9609 (this.size === Infinity || (this.size !== undefined && index > this.size))
9610 ? notSetValue
9611 : this.find(function (_, key) { return key === index; }, undefined, notSetValue);
9612 },
9613
9614 has: function has(index) {
9615 index = wrapIndex(this, index);
9616 return (
9617 index >= 0 &&
9618 (this.size !== undefined
9619 ? this.size === Infinity || index < this.size
9620 : this.indexOf(index) !== -1)
9621 );
9622 },
9623
9624 interpose: function interpose(separator) {
9625 return reify(this, interposeFactory(this, separator));
9626 },
9627
9628 interleave: function interleave(/*...collections*/) {
9629 var collections = [this].concat(arrCopy(arguments));
9630 var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections);
9631 var interleaved = zipped.flatten(true);
9632 if (zipped.size) {
9633 interleaved.size = zipped.size * collections.length;
9634 }
9635 return reify(this, interleaved);
9636 },
9637
9638 keySeq: function keySeq() {
9639 return Range(0, this.size);
9640 },
9641
9642 last: function last(notSetValue) {
9643 return this.get(-1, notSetValue);
9644 },
9645
9646 skipWhile: function skipWhile(predicate, context) {
9647 return reify(this, skipWhileFactory(this, predicate, context, false));
9648 },
9649
9650 zip: function zip(/*, ...collections */) {
9651 var collections = [this].concat(arrCopy(arguments));
9652 return reify(this, zipWithFactory(this, defaultZipper, collections));
9653 },
9654
9655 zipAll: function zipAll(/*, ...collections */) {
9656 var collections = [this].concat(arrCopy(arguments));
9657 return reify(this, zipWithFactory(this, defaultZipper, collections, true));
9658 },
9659
9660 zipWith: function zipWith(zipper /*, ...collections */) {
9661 var collections = arrCopy(arguments);
9662 collections[0] = this;
9663 return reify(this, zipWithFactory(this, zipper, collections));
9664 },
9665});
9666
9667var IndexedCollectionPrototype = IndexedCollection.prototype;
9668IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true;
9669IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true;
9670
9671mixin(SetCollection, {
9672 // ### ES6 Collection methods (ES6 Array and Map)
9673
9674 get: function get(value, notSetValue) {
9675 return this.has(value) ? value : notSetValue;
9676 },
9677
9678 includes: function includes(value) {
9679 return this.has(value);
9680 },
9681
9682 // ### More sequential methods
9683
9684 keySeq: function keySeq() {
9685 return this.valueSeq();
9686 },
9687});
9688
9689SetCollection.prototype.has = CollectionPrototype.includes;
9690SetCollection.prototype.contains = SetCollection.prototype.includes;
9691
9692// Mixin subclasses
9693
9694mixin(KeyedSeq, KeyedCollection.prototype);
9695mixin(IndexedSeq, IndexedCollection.prototype);
9696mixin(SetSeq, SetCollection.prototype);
9697
9698// #pragma Helper functions
9699
9700function reduce(collection, reducer, reduction, context, useFirst, reverse) {
9701 assertNotInfinite(collection.size);
9702 collection.__iterate(function (v, k, c) {
9703 if (useFirst) {
9704 useFirst = false;
9705 reduction = v;
9706 } else {
9707 reduction = reducer.call(context, reduction, v, k, c);
9708 }
9709 }, reverse);
9710 return reduction;
9711}
9712
9713function keyMapper(v, k) {
9714 return k;
9715}
9716
9717function entryMapper(v, k) {
9718 return [k, v];
9719}
9720
9721function not(predicate) {
9722 return function() {
9723 return !predicate.apply(this, arguments);
9724 };
9725}
9726
9727function neg(predicate) {
9728 return function() {
9729 return -predicate.apply(this, arguments);
9730 };
9731}
9732
9733function defaultZipper() {
9734 return arrCopy(arguments);
9735}
9736
9737function defaultNegComparator(a, b) {
9738 return a < b ? 1 : a > b ? -1 : 0;
9739}
9740
9741function hashCollection(collection) {
9742 if (collection.size === Infinity) {
9743 return 0;
9744 }
9745 var ordered = isOrdered(collection);
9746 var keyed = isKeyed(collection);
9747 var h = ordered ? 1 : 0;
9748 var size = collection.__iterate(
9749 keyed
9750 ? ordered
9751 ? function (v, k) {
9752 h = (31 * h + hashMerge(hash(v), hash(k))) | 0;
9753 }
9754 : function (v, k) {
9755 h = (h + hashMerge(hash(v), hash(k))) | 0;
9756 }
9757 : ordered
9758 ? function (v) {
9759 h = (31 * h + hash(v)) | 0;
9760 }
9761 : function (v) {
9762 h = (h + hash(v)) | 0;
9763 }
9764 );
9765 return murmurHashOfSize(size, h);
9766}
9767
9768function murmurHashOfSize(size, h) {
9769 h = imul(h, 0xcc9e2d51);
9770 h = imul((h << 15) | (h >>> -15), 0x1b873593);
9771 h = imul((h << 13) | (h >>> -13), 5);
9772 h = ((h + 0xe6546b64) | 0) ^ size;
9773 h = imul(h ^ (h >>> 16), 0x85ebca6b);
9774 h = imul(h ^ (h >>> 13), 0xc2b2ae35);
9775 h = smi(h ^ (h >>> 16));
9776 return h;
9777}
9778
9779function hashMerge(a, b) {
9780 return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int
9781}
9782
9783var OrderedSet = /*@__PURE__*/(function (Set$$1) {
9784 function OrderedSet(value) {
9785 return value === null || value === undefined
9786 ? emptyOrderedSet()
9787 : isOrderedSet(value)
9788 ? value
9789 : emptyOrderedSet().withMutations(function (set) {
9790 var iter = SetCollection(value);
9791 assertNotInfinite(iter.size);
9792 iter.forEach(function (v) { return set.add(v); });
9793 });
9794 }
9795
9796 if ( Set$$1 ) OrderedSet.__proto__ = Set$$1;
9797 OrderedSet.prototype = Object.create( Set$$1 && Set$$1.prototype );
9798 OrderedSet.prototype.constructor = OrderedSet;
9799
9800 OrderedSet.of = function of (/*...values*/) {
9801 return this(arguments);
9802 };
9803
9804 OrderedSet.fromKeys = function fromKeys (value) {
9805 return this(KeyedCollection(value).keySeq());
9806 };
9807
9808 OrderedSet.prototype.toString = function toString () {
9809 return this.__toString('OrderedSet {', '}');
9810 };
9811
9812 return OrderedSet;
9813}(Set$1));
9814
9815OrderedSet.isOrderedSet = isOrderedSet;
9816
9817var OrderedSetPrototype = OrderedSet.prototype;
9818OrderedSetPrototype[IS_ORDERED_SYMBOL] = true;
9819OrderedSetPrototype.zip = IndexedCollectionPrototype.zip;
9820OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith;
9821
9822OrderedSetPrototype.__empty = emptyOrderedSet;
9823OrderedSetPrototype.__make = makeOrderedSet;
9824
9825function makeOrderedSet(map, ownerID) {
9826 var set = Object.create(OrderedSetPrototype);
9827 set.size = map ? map.size : 0;
9828 set._map = map;
9829 set.__ownerID = ownerID;
9830 return set;
9831}
9832
9833var EMPTY_ORDERED_SET;
9834function emptyOrderedSet() {
9835 return (
9836 EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()))
9837 );
9838}
9839
9840var Record = function Record(defaultValues, name) {
9841 var hasInitialized;
9842
9843 var RecordType = function Record(values) {
9844 var this$1 = this;
9845
9846 if (values instanceof RecordType) {
9847 return values;
9848 }
9849 if (!(this instanceof RecordType)) {
9850 return new RecordType(values);
9851 }
9852 if (!hasInitialized) {
9853 hasInitialized = true;
9854 var keys = Object.keys(defaultValues);
9855 var indices = (RecordTypePrototype._indices = {});
9856 // Deprecated: left to attempt not to break any external code which
9857 // relies on a ._name property existing on record instances.
9858 // Use Record.getDescriptiveName() instead
9859 RecordTypePrototype._name = name;
9860 RecordTypePrototype._keys = keys;
9861 RecordTypePrototype._defaultValues = defaultValues;
9862 for (var i = 0; i < keys.length; i++) {
9863 var propName = keys[i];
9864 indices[propName] = i;
9865 if (RecordTypePrototype[propName]) {
9866 /* eslint-disable no-console */
9867 typeof console === 'object' &&
9868 console.warn &&
9869 console.warn(
9870 'Cannot define ' +
9871 recordName(this) +
9872 ' with property "' +
9873 propName +
9874 '" since that property name is part of the Record API.'
9875 );
9876 /* eslint-enable no-console */
9877 } else {
9878 setProp(RecordTypePrototype, propName);
9879 }
9880 }
9881 }
9882 this.__ownerID = undefined;
9883 this._values = List().withMutations(function (l) {
9884 l.setSize(this$1._keys.length);
9885 KeyedCollection(values).forEach(function (v, k) {
9886 l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v);
9887 });
9888 });
9889 };
9890
9891 var RecordTypePrototype = (RecordType.prototype = Object.create(
9892 RecordPrototype
9893 ));
9894 RecordTypePrototype.constructor = RecordType;
9895
9896 if (name) {
9897 RecordType.displayName = name;
9898 }
9899
9900 return RecordType;
9901};
9902
9903Record.prototype.toString = function toString () {
9904 var str = recordName(this) + ' { ';
9905 var keys = this._keys;
9906 var k;
9907 for (var i = 0, l = keys.length; i !== l; i++) {
9908 k = keys[i];
9909 str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k));
9910 }
9911 return str + ' }';
9912};
9913
9914Record.prototype.equals = function equals (other) {
9915 return (
9916 this === other ||
9917 (other &&
9918 this._keys === other._keys &&
9919 recordSeq(this).equals(recordSeq(other)))
9920 );
9921};
9922
9923Record.prototype.hashCode = function hashCode () {
9924 return recordSeq(this).hashCode();
9925};
9926
9927// @pragma Access
9928
9929Record.prototype.has = function has (k) {
9930 return this._indices.hasOwnProperty(k);
9931};
9932
9933Record.prototype.get = function get (k, notSetValue) {
9934 if (!this.has(k)) {
9935 return notSetValue;
9936 }
9937 var index = this._indices[k];
9938 var value = this._values.get(index);
9939 return value === undefined ? this._defaultValues[k] : value;
9940};
9941
9942// @pragma Modification
9943
9944Record.prototype.set = function set (k, v) {
9945 if (this.has(k)) {
9946 var newValues = this._values.set(
9947 this._indices[k],
9948 v === this._defaultValues[k] ? undefined : v
9949 );
9950 if (newValues !== this._values && !this.__ownerID) {
9951 return makeRecord(this, newValues);
9952 }
9953 }
9954 return this;
9955};
9956
9957Record.prototype.remove = function remove (k) {
9958 return this.set(k);
9959};
9960
9961Record.prototype.clear = function clear () {
9962 var newValues = this._values.clear().setSize(this._keys.length);
9963 return this.__ownerID ? this : makeRecord(this, newValues);
9964};
9965
9966Record.prototype.wasAltered = function wasAltered () {
9967 return this._values.wasAltered();
9968};
9969
9970Record.prototype.toSeq = function toSeq () {
9971 return recordSeq(this);
9972};
9973
9974Record.prototype.toJS = function toJS$1 () {
9975 return toJS(this);
9976};
9977
9978Record.prototype.entries = function entries () {
9979 return this.__iterator(ITERATE_ENTRIES);
9980};
9981
9982Record.prototype.__iterator = function __iterator (type, reverse) {
9983 return recordSeq(this).__iterator(type, reverse);
9984};
9985
9986Record.prototype.__iterate = function __iterate (fn, reverse) {
9987 return recordSeq(this).__iterate(fn, reverse);
9988};
9989
9990Record.prototype.__ensureOwner = function __ensureOwner (ownerID) {
9991 if (ownerID === this.__ownerID) {
9992 return this;
9993 }
9994 var newValues = this._values.__ensureOwner(ownerID);
9995 if (!ownerID) {
9996 this.__ownerID = ownerID;
9997 this._values = newValues;
9998 return this;
9999 }
10000 return makeRecord(this, newValues, ownerID);
10001};
10002
10003Record.isRecord = isRecord;
10004Record.getDescriptiveName = recordName;
10005var RecordPrototype = Record.prototype;
10006RecordPrototype[IS_RECORD_SYMBOL] = true;
10007RecordPrototype[DELETE] = RecordPrototype.remove;
10008RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn;
10009RecordPrototype.getIn = getIn$1;
10010RecordPrototype.hasIn = CollectionPrototype.hasIn;
10011RecordPrototype.merge = merge;
10012RecordPrototype.mergeWith = mergeWith;
10013RecordPrototype.mergeIn = mergeIn;
10014RecordPrototype.mergeDeep = mergeDeep$1;
10015RecordPrototype.mergeDeepWith = mergeDeepWith$1;
10016RecordPrototype.mergeDeepIn = mergeDeepIn;
10017RecordPrototype.setIn = setIn$1;
10018RecordPrototype.update = update$1;
10019RecordPrototype.updateIn = updateIn$1;
10020RecordPrototype.withMutations = withMutations;
10021RecordPrototype.asMutable = asMutable;
10022RecordPrototype.asImmutable = asImmutable;
10023RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries;
10024RecordPrototype.toJSON = RecordPrototype.toObject =
10025 CollectionPrototype.toObject;
10026RecordPrototype.inspect = RecordPrototype.toSource = function() {
10027 return this.toString();
10028};
10029
10030function makeRecord(likeRecord, values, ownerID) {
10031 var record = Object.create(Object.getPrototypeOf(likeRecord));
10032 record._values = values;
10033 record.__ownerID = ownerID;
10034 return record;
10035}
10036
10037function recordName(record) {
10038 return record.constructor.displayName || record.constructor.name || 'Record';
10039}
10040
10041function recordSeq(record) {
10042 return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; }));
10043}
10044
10045function setProp(prototype, name) {
10046 try {
10047 Object.defineProperty(prototype, name, {
10048 get: function() {
10049 return this.get(name);
10050 },
10051 set: function(value) {
10052 invariant(this.__ownerID, 'Cannot set on an immutable record.');
10053 this.set(name, value);
10054 },
10055 });
10056 } catch (error) {
10057 // Object.defineProperty failed. Probably IE8.
10058 }
10059}
10060
10061/**
10062 * Returns a lazy Seq of `value` repeated `times` times. When `times` is
10063 * undefined, returns an infinite sequence of `value`.
10064 */
10065var Repeat = /*@__PURE__*/(function (IndexedSeq$$1) {
10066 function Repeat(value, times) {
10067 if (!(this instanceof Repeat)) {
10068 return new Repeat(value, times);
10069 }
10070 this._value = value;
10071 this.size = times === undefined ? Infinity : Math.max(0, times);
10072 if (this.size === 0) {
10073 if (EMPTY_REPEAT) {
10074 return EMPTY_REPEAT;
10075 }
10076 EMPTY_REPEAT = this;
10077 }
10078 }
10079
10080 if ( IndexedSeq$$1 ) Repeat.__proto__ = IndexedSeq$$1;
10081 Repeat.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
10082 Repeat.prototype.constructor = Repeat;
10083
10084 Repeat.prototype.toString = function toString () {
10085 if (this.size === 0) {
10086 return 'Repeat []';
10087 }
10088 return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
10089 };
10090
10091 Repeat.prototype.get = function get (index, notSetValue) {
10092 return this.has(index) ? this._value : notSetValue;
10093 };
10094
10095 Repeat.prototype.includes = function includes (searchValue) {
10096 return is(this._value, searchValue);
10097 };
10098
10099 Repeat.prototype.slice = function slice (begin, end) {
10100 var size = this.size;
10101 return wholeSlice(begin, end, size)
10102 ? this
10103 : new Repeat(
10104 this._value,
10105 resolveEnd(end, size) - resolveBegin(begin, size)
10106 );
10107 };
10108
10109 Repeat.prototype.reverse = function reverse () {
10110 return this;
10111 };
10112
10113 Repeat.prototype.indexOf = function indexOf (searchValue) {
10114 if (is(this._value, searchValue)) {
10115 return 0;
10116 }
10117 return -1;
10118 };
10119
10120 Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) {
10121 if (is(this._value, searchValue)) {
10122 return this.size;
10123 }
10124 return -1;
10125 };
10126
10127 Repeat.prototype.__iterate = function __iterate (fn, reverse) {
10128 var size = this.size;
10129 var i = 0;
10130 while (i !== size) {
10131 if (fn(this._value, reverse ? size - ++i : i++, this) === false) {
10132 break;
10133 }
10134 }
10135 return i;
10136 };
10137
10138 Repeat.prototype.__iterator = function __iterator (type, reverse) {
10139 var this$1 = this;
10140
10141 var size = this.size;
10142 var i = 0;
10143 return new Iterator(
10144 function () { return i === size
10145 ? iteratorDone()
10146 : iteratorValue(type, reverse ? size - ++i : i++, this$1._value); }
10147 );
10148 };
10149
10150 Repeat.prototype.equals = function equals (other) {
10151 return other instanceof Repeat
10152 ? is(this._value, other._value)
10153 : deepEqual(other);
10154 };
10155
10156 return Repeat;
10157}(IndexedSeq));
10158
10159var EMPTY_REPEAT;
10160
10161function fromJS(value, converter) {
10162 return fromJSWith(
10163 [],
10164 converter || defaultConverter,
10165 value,
10166 '',
10167 converter && converter.length > 2 ? [] : undefined,
10168 { '': value }
10169 );
10170}
10171
10172function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
10173 var toSeq = Array.isArray(value)
10174 ? IndexedSeq
10175 : isPlainObj(value)
10176 ? KeyedSeq
10177 : null;
10178 if (toSeq) {
10179 if (~stack.indexOf(value)) {
10180 throw new TypeError('Cannot convert circular structure to Immutable');
10181 }
10182 stack.push(value);
10183 keyPath && key !== '' && keyPath.push(key);
10184 var converted = converter.call(
10185 parentValue,
10186 key,
10187 toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }
10188 ),
10189 keyPath && keyPath.slice()
10190 );
10191 stack.pop();
10192 keyPath && keyPath.pop();
10193 return converted;
10194 }
10195 return value;
10196}
10197
10198function defaultConverter(k, v) {
10199 return isKeyed(v) ? v.toMap() : v.toList();
10200}
10201
10202var version$1 = "4.0.0-rc.11";
10203
10204var Immutable = {
10205 version: version$1,
10206
10207 Collection: Collection,
10208 // Note: Iterable is deprecated
10209 Iterable: Collection,
10210
10211 Seq: Seq,
10212 Map: Map$1,
10213 OrderedMap: OrderedMap,
10214 List: List,
10215 Stack: Stack,
10216 Set: Set$1,
10217 OrderedSet: OrderedSet,
10218
10219 Record: Record,
10220 Range: Range,
10221 Repeat: Repeat,
10222
10223 is: is,
10224 fromJS: fromJS,
10225 hash: hash,
10226
10227 isImmutable: isImmutable,
10228 isCollection: isCollection,
10229 isKeyed: isKeyed,
10230 isIndexed: isIndexed,
10231 isAssociative: isAssociative,
10232 isOrdered: isOrdered,
10233 isValueObject: isValueObject,
10234 isSeq: isSeq,
10235 isList: isList,
10236 isMap: isMap,
10237 isOrderedMap: isOrderedMap,
10238 isStack: isStack,
10239 isSet: isSet,
10240 isOrderedSet: isOrderedSet,
10241 isRecord: isRecord,
10242
10243 get: get,
10244 getIn: getIn,
10245 has: has,
10246 hasIn: hasIn,
10247 merge: merge$1,
10248 mergeDeep: mergeDeep,
10249 mergeWith: mergeWith$1,
10250 mergeDeepWith: mergeDeepWith,
10251 remove: remove,
10252 removeIn: removeIn,
10253 set: set,
10254 setIn: setIn,
10255 update: update,
10256 updateIn: updateIn,
10257};
10258
10259var OptionTypes;
10260(function (OptionTypes) {
10261 OptionTypes[OptionTypes["IGNORED_LABELS"] = 0] = "IGNORED_LABELS";
10262 OptionTypes[OptionTypes["ACCESSED_NODES"] = 1] = "ACCESSED_NODES";
10263 OptionTypes[OptionTypes["ARGUMENTS_VARIABLES"] = 2] = "ARGUMENTS_VARIABLES";
10264 OptionTypes[OptionTypes["ASSIGNED_NODES"] = 3] = "ASSIGNED_NODES";
10265 OptionTypes[OptionTypes["IGNORE_BREAK_STATEMENTS"] = 4] = "IGNORE_BREAK_STATEMENTS";
10266 OptionTypes[OptionTypes["IGNORE_RETURN_AWAIT_YIELD"] = 5] = "IGNORE_RETURN_AWAIT_YIELD";
10267 OptionTypes[OptionTypes["NODES_CALLED_AT_PATH_WITH_OPTIONS"] = 6] = "NODES_CALLED_AT_PATH_WITH_OPTIONS";
10268 OptionTypes[OptionTypes["REPLACED_VARIABLE_INITS"] = 7] = "REPLACED_VARIABLE_INITS";
10269 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ACCESSED_AT_PATH"] = 8] = "RETURN_EXPRESSIONS_ACCESSED_AT_PATH";
10270 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ASSIGNED_AT_PATH"] = 9] = "RETURN_EXPRESSIONS_ASSIGNED_AT_PATH";
10271 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_CALLED_AT_PATH"] = 10] = "RETURN_EXPRESSIONS_CALLED_AT_PATH";
10272})(OptionTypes || (OptionTypes = {}));
10273var RESULT_KEY = {};
10274var ExecutionPathOptions = /** @class */ (function () {
10275 function ExecutionPathOptions(optionValues) {
10276 this.optionValues = optionValues;
10277 }
10278 ExecutionPathOptions.create = function () {
10279 return new this(Immutable.Map());
10280 };
10281 ExecutionPathOptions.prototype.addAccessedNodeAtPath = function (path, node) {
10282 return this.setIn([OptionTypes.ACCESSED_NODES, node].concat(path, [RESULT_KEY]), true);
10283 };
10284 ExecutionPathOptions.prototype.addAccessedReturnExpressionAtPath = function (path, callExpression) {
10285 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
10286 };
10287 ExecutionPathOptions.prototype.addAssignedNodeAtPath = function (path, node) {
10288 return this.setIn([OptionTypes.ASSIGNED_NODES, node].concat(path, [RESULT_KEY]), true);
10289 };
10290 ExecutionPathOptions.prototype.addAssignedReturnExpressionAtPath = function (path, callExpression) {
10291 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
10292 };
10293 ExecutionPathOptions.prototype.addCalledNodeAtPathWithOptions = function (path, node, callOptions) {
10294 return this.setIn([OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS, node].concat(path, [RESULT_KEY, callOptions]), true);
10295 };
10296 ExecutionPathOptions.prototype.addCalledReturnExpressionAtPath = function (path, callExpression) {
10297 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
10298 };
10299 ExecutionPathOptions.prototype.getArgumentsVariables = function () {
10300 return (this.get(OptionTypes.ARGUMENTS_VARIABLES) || []);
10301 };
10302 ExecutionPathOptions.prototype.getHasEffectsWhenCalledOptions = function () {
10303 return this.setIgnoreReturnAwaitYield()
10304 .setIgnoreBreakStatements(false)
10305 .setIgnoreNoLabels();
10306 };
10307 ExecutionPathOptions.prototype.getReplacedVariableInit = function (variable) {
10308 return this.optionValues.getIn([OptionTypes.REPLACED_VARIABLE_INITS, variable]);
10309 };
10310 ExecutionPathOptions.prototype.hasNodeBeenAccessedAtPath = function (path, node) {
10311 return this.optionValues.getIn([OptionTypes.ACCESSED_NODES, node].concat(path, [RESULT_KEY]));
10312 };
10313 ExecutionPathOptions.prototype.hasNodeBeenAssignedAtPath = function (path, node) {
10314 return this.optionValues.getIn([OptionTypes.ASSIGNED_NODES, node].concat(path, [RESULT_KEY]));
10315 };
10316 ExecutionPathOptions.prototype.hasNodeBeenCalledAtPathWithOptions = function (path, node, callOptions) {
10317 var previousCallOptions = this.optionValues.getIn([
10318 OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS,
10319 node
10320 ].concat(path, [
10321 RESULT_KEY
10322 ]));
10323 return (previousCallOptions &&
10324 previousCallOptions.find(function (_, otherCallOptions) {
10325 return otherCallOptions.equals(callOptions);
10326 }));
10327 };
10328 ExecutionPathOptions.prototype.hasReturnExpressionBeenAccessedAtPath = function (path, callExpression) {
10329 return this.optionValues.getIn([
10330 OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH,
10331 callExpression
10332 ].concat(path, [
10333 RESULT_KEY
10334 ]));
10335 };
10336 ExecutionPathOptions.prototype.hasReturnExpressionBeenAssignedAtPath = function (path, callExpression) {
10337 return this.optionValues.getIn([
10338 OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH,
10339 callExpression
10340 ].concat(path, [
10341 RESULT_KEY
10342 ]));
10343 };
10344 ExecutionPathOptions.prototype.hasReturnExpressionBeenCalledAtPath = function (path, callExpression) {
10345 return this.optionValues.getIn([
10346 OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH,
10347 callExpression
10348 ].concat(path, [
10349 RESULT_KEY
10350 ]));
10351 };
10352 ExecutionPathOptions.prototype.ignoreBreakStatements = function () {
10353 return this.get(OptionTypes.IGNORE_BREAK_STATEMENTS);
10354 };
10355 ExecutionPathOptions.prototype.ignoreLabel = function (labelName) {
10356 return this.optionValues.getIn([OptionTypes.IGNORED_LABELS, labelName]);
10357 };
10358 ExecutionPathOptions.prototype.ignoreReturnAwaitYield = function () {
10359 return this.get(OptionTypes.IGNORE_RETURN_AWAIT_YIELD);
10360 };
10361 ExecutionPathOptions.prototype.replaceVariableInit = function (variable, init) {
10362 return this.setIn([OptionTypes.REPLACED_VARIABLE_INITS, variable], init);
10363 };
10364 ExecutionPathOptions.prototype.setArgumentsVariables = function (variables) {
10365 return this.set(OptionTypes.ARGUMENTS_VARIABLES, variables);
10366 };
10367 ExecutionPathOptions.prototype.setIgnoreBreakStatements = function (value) {
10368 if (value === void 0) { value = true; }
10369 return this.set(OptionTypes.IGNORE_BREAK_STATEMENTS, value);
10370 };
10371 ExecutionPathOptions.prototype.setIgnoreLabel = function (labelName) {
10372 return this.setIn([OptionTypes.IGNORED_LABELS, labelName], true);
10373 };
10374 ExecutionPathOptions.prototype.setIgnoreNoLabels = function () {
10375 return this.remove(OptionTypes.IGNORED_LABELS);
10376 };
10377 ExecutionPathOptions.prototype.setIgnoreReturnAwaitYield = function (value) {
10378 if (value === void 0) { value = true; }
10379 return this.set(OptionTypes.IGNORE_RETURN_AWAIT_YIELD, value);
10380 };
10381 ExecutionPathOptions.prototype.get = function (option) {
10382 return this.optionValues.get(option);
10383 };
10384 ExecutionPathOptions.prototype.remove = function (option) {
10385 return new ExecutionPathOptions(this.optionValues.remove(option));
10386 };
10387 ExecutionPathOptions.prototype.set = function (option, value) {
10388 return new ExecutionPathOptions(this.optionValues.set(option, value));
10389 };
10390 ExecutionPathOptions.prototype.setIn = function (optionPath, value) {
10391 return new ExecutionPathOptions(this.optionValues.setIn(optionPath, value));
10392 };
10393 return ExecutionPathOptions;
10394}());
10395
10396var keys = {
10397 Literal: [],
10398 Program: ['body']
10399};
10400function getAndCreateKeys(esTreeNode) {
10401 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(function (key) { return typeof esTreeNode[key] === 'object'; });
10402 return keys[esTreeNode.type];
10403}
10404
10405var NEW_EXECUTION_PATH = ExecutionPathOptions.create();
10406var NodeBase = /** @class */ (function () {
10407 function NodeBase(esTreeNode, parent, parentScope) {
10408 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
10409 this.parent = parent;
10410 this.context = parent.context;
10411 this.createScope(parentScope);
10412 this.parseNode(esTreeNode);
10413 this.initialise();
10414 this.context.magicString.addSourcemapLocation(this.start);
10415 this.context.magicString.addSourcemapLocation(this.end);
10416 }
10417 /**
10418 * Override this to bind assignments to variables and do any initialisations that
10419 * require the scopes to be populated with variables.
10420 */
10421 NodeBase.prototype.bind = function () {
10422 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10423 var key = _a[_i];
10424 var value = this[key];
10425 if (value === null || key === 'annotations')
10426 continue;
10427 if (Array.isArray(value)) {
10428 for (var _b = 0, value_1 = value; _b < value_1.length; _b++) {
10429 var child = value_1[_b];
10430 if (child !== null)
10431 child.bind();
10432 }
10433 }
10434 else {
10435 value.bind();
10436 }
10437 }
10438 };
10439 /**
10440 * Override if this node should receive a different scope than the parent scope.
10441 */
10442 NodeBase.prototype.createScope = function (parentScope) {
10443 this.scope = parentScope;
10444 };
10445 NodeBase.prototype.declare = function (_kind, _init) { };
10446 NodeBase.prototype.deoptimizePath = function (_path) { };
10447 NodeBase.prototype.getLiteralValueAtPath = function (_path, _recursionTracker, _origin) {
10448 return UNKNOWN_VALUE;
10449 };
10450 NodeBase.prototype.getReturnExpressionWhenCalledAtPath = function (_path, _recursionTracker, _origin) {
10451 return UNKNOWN_EXPRESSION;
10452 };
10453 NodeBase.prototype.hasEffects = function (options) {
10454 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10455 var key = _a[_i];
10456 var value = this[key];
10457 if (value === null || key === 'annotations')
10458 continue;
10459 if (Array.isArray(value)) {
10460 for (var _b = 0, value_2 = value; _b < value_2.length; _b++) {
10461 var child = value_2[_b];
10462 if (child !== null && child.hasEffects(options))
10463 return true;
10464 }
10465 }
10466 else if (value.hasEffects(options))
10467 return true;
10468 }
10469 return false;
10470 };
10471 NodeBase.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
10472 return path.length > 0;
10473 };
10474 NodeBase.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
10475 return true;
10476 };
10477 NodeBase.prototype.hasEffectsWhenCalledAtPath = function (_path, _callOptions, _options) {
10478 return true;
10479 };
10480 NodeBase.prototype.include = function (includeAllChildrenRecursively) {
10481 this.included = true;
10482 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10483 var key = _a[_i];
10484 var value = this[key];
10485 if (value === null || key === 'annotations')
10486 continue;
10487 if (Array.isArray(value)) {
10488 for (var _b = 0, value_3 = value; _b < value_3.length; _b++) {
10489 var child = value_3[_b];
10490 if (child !== null)
10491 child.include(includeAllChildrenRecursively);
10492 }
10493 }
10494 else {
10495 value.include(includeAllChildrenRecursively);
10496 }
10497 }
10498 };
10499 NodeBase.prototype.includeWithAllDeclaredVariables = function (includeAllChildrenRecursively) {
10500 this.include(includeAllChildrenRecursively);
10501 };
10502 /**
10503 * Override to perform special initialisation steps after the scope is initialised
10504 */
10505 NodeBase.prototype.initialise = function () {
10506 this.included = false;
10507 };
10508 NodeBase.prototype.insertSemicolon = function (code) {
10509 if (code.original[this.end - 1] !== ';') {
10510 code.appendLeft(this.end, ';');
10511 }
10512 };
10513 NodeBase.prototype.locate = function () {
10514 // useful for debugging
10515 var location = locate(this.context.code, this.start, { offsetLine: 1 });
10516 location.file = this.context.fileName;
10517 location.toString = function () { return JSON.stringify(location); };
10518 return location;
10519 };
10520 NodeBase.prototype.parseNode = function (esTreeNode) {
10521 for (var _i = 0, _a = Object.keys(esTreeNode); _i < _a.length; _i++) {
10522 var key = _a[_i];
10523 // That way, we can override this function to add custom initialisation and then call super.parseNode
10524 if (this.hasOwnProperty(key))
10525 continue;
10526 var value = esTreeNode[key];
10527 if (typeof value !== 'object' || value === null || key === 'annotations') {
10528 this[key] = value;
10529 }
10530 else if (Array.isArray(value)) {
10531 this[key] = [];
10532 for (var _b = 0, value_4 = value; _b < value_4.length; _b++) {
10533 var child = value_4[_b];
10534 this[key].push(child === null
10535 ? null
10536 : new (this.context.nodeConstructors[child.type] ||
10537 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
10538 }
10539 }
10540 else {
10541 this[key] = new (this.context.nodeConstructors[value.type] ||
10542 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
10543 }
10544 }
10545 };
10546 NodeBase.prototype.render = function (code, options) {
10547 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10548 var key = _a[_i];
10549 var value = this[key];
10550 if (value === null || key === 'annotations')
10551 continue;
10552 if (Array.isArray(value)) {
10553 for (var _b = 0, value_5 = value; _b < value_5.length; _b++) {
10554 var child = value_5[_b];
10555 if (child !== null)
10556 child.render(code, options);
10557 }
10558 }
10559 else {
10560 value.render(code, options);
10561 }
10562 }
10563 };
10564 NodeBase.prototype.shouldBeIncluded = function () {
10565 return this.included || this.hasEffects(NEW_EXECUTION_PATH);
10566 };
10567 NodeBase.prototype.toString = function () {
10568 return this.context.code.slice(this.start, this.end);
10569 };
10570 return NodeBase;
10571}());
10572
10573var ClassNode = /** @class */ (function (_super) {
10574 __extends(ClassNode, _super);
10575 function ClassNode() {
10576 return _super !== null && _super.apply(this, arguments) || this;
10577 }
10578 ClassNode.prototype.createScope = function (parentScope) {
10579 this.scope = new ChildScope(parentScope);
10580 };
10581 ClassNode.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
10582 return path.length > 1;
10583 };
10584 ClassNode.prototype.hasEffectsWhenAssignedAtPath = function (path, _options) {
10585 return path.length > 1;
10586 };
10587 ClassNode.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10588 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
10589 (this.superClass && this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)));
10590 };
10591 ClassNode.prototype.initialise = function () {
10592 this.included = false;
10593 if (this.id !== null) {
10594 this.id.declare('class', this);
10595 }
10596 };
10597 return ClassNode;
10598}(NodeBase));
10599
10600function isClassDeclaration(node) {
10601 return node.type === ClassDeclaration;
10602}
10603var ClassDeclaration$1 = /** @class */ (function (_super) {
10604 __extends(ClassDeclaration, _super);
10605 function ClassDeclaration() {
10606 return _super !== null && _super.apply(this, arguments) || this;
10607 }
10608 ClassDeclaration.prototype.initialise = function () {
10609 _super.prototype.initialise.call(this);
10610 if (this.id !== null) {
10611 this.id.variable.isId = true;
10612 }
10613 };
10614 ClassDeclaration.prototype.parseNode = function (esTreeNode) {
10615 if (esTreeNode.id !== null) {
10616 this.id = (new this.context.nodeConstructors.Identifier(esTreeNode.id, this, (this.scope.parent)));
10617 }
10618 _super.prototype.parseNode.call(this, esTreeNode);
10619 };
10620 ClassDeclaration.prototype.render = function (code, options) {
10621 if (options.format === 'system' && this.id && this.id.variable.exportName) {
10622 code.appendLeft(this.end, " exports('" + this.id.variable.exportName + "', " + this.id.variable.getName() + ");");
10623 }
10624 _super.prototype.render.call(this, code, options);
10625 };
10626 return ClassDeclaration;
10627}(ClassNode));
10628
10629var getParameterVariable = function (path, options) {
10630 var firstArgNum = parseInt(path[0], 10);
10631 return ((firstArgNum < options.getArgumentsVariables().length &&
10632 options.getArgumentsVariables()[firstArgNum]) ||
10633 UNKNOWN_EXPRESSION);
10634};
10635var ArgumentsVariable = /** @class */ (function (_super) {
10636 __extends(ArgumentsVariable, _super);
10637 function ArgumentsVariable(parameters, context) {
10638 var _this = _super.call(this, 'arguments', null, UNKNOWN_EXPRESSION, context) || this;
10639 _this.parameters = parameters;
10640 return _this;
10641 }
10642 ArgumentsVariable.prototype.deoptimizePath = function (path) {
10643 var firstArgNum = parseInt(path[0], 10);
10644 if (path.length > 0) {
10645 if (firstArgNum >= 0 && this.parameters[firstArgNum]) {
10646 this.parameters[firstArgNum].deoptimizePath(path.slice(1));
10647 }
10648 }
10649 };
10650 ArgumentsVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
10651 return (path.length > 1 &&
10652 getParameterVariable(path, options).hasEffectsWhenAccessedAtPath(path.slice(1), options));
10653 };
10654 ArgumentsVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
10655 return (path.length === 0 ||
10656 this.included ||
10657 getParameterVariable(path, options).hasEffectsWhenAssignedAtPath(path.slice(1), options));
10658 };
10659 ArgumentsVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10660 if (path.length === 0) {
10661 return true;
10662 }
10663 return getParameterVariable(path, options).hasEffectsWhenCalledAtPath(path.slice(1), callOptions, options);
10664 };
10665 return ArgumentsVariable;
10666}(LocalVariable));
10667
10668var ThisVariable = /** @class */ (function (_super) {
10669 __extends(ThisVariable, _super);
10670 function ThisVariable(context) {
10671 return _super.call(this, 'this', null, null, context) || this;
10672 }
10673 ThisVariable.prototype._getInit = function (options) {
10674 return options.getReplacedVariableInit(this) || UNKNOWN_EXPRESSION;
10675 };
10676 ThisVariable.prototype.getLiteralValueAtPath = function () {
10677 return UNKNOWN_VALUE;
10678 };
10679 ThisVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
10680 return (this._getInit(options).hasEffectsWhenAccessedAtPath(path, options) ||
10681 _super.prototype.hasEffectsWhenAccessedAtPath.call(this, path, options));
10682 };
10683 ThisVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
10684 return (this._getInit(options).hasEffectsWhenAssignedAtPath(path, options) ||
10685 _super.prototype.hasEffectsWhenAssignedAtPath.call(this, path, options));
10686 };
10687 ThisVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10688 return (this._getInit(options).hasEffectsWhenCalledAtPath(path, callOptions, options) ||
10689 _super.prototype.hasEffectsWhenCalledAtPath.call(this, path, callOptions, options));
10690 };
10691 return ThisVariable;
10692}(LocalVariable));
10693
10694var ParameterScope = /** @class */ (function (_super) {
10695 __extends(ParameterScope, _super);
10696 function ParameterScope(parent, context) {
10697 var _this = _super.call(this, parent) || this;
10698 _this.parameters = [];
10699 _this.context = context;
10700 _this.hoistedBodyVarScope = new ChildScope(_this);
10701 return _this;
10702 }
10703 /**
10704 * Adds a parameter to this scope. Parameters must be added in the correct
10705 * order, e.g. from left to right.
10706 */
10707 ParameterScope.prototype.addParameterDeclaration = function (identifier) {
10708 var name = identifier.name;
10709 var variable;
10710 if (name in this.hoistedBodyVarScope.variables) {
10711 variable = this.hoistedBodyVarScope.variables[name];
10712 variable.addDeclaration(identifier, null);
10713 }
10714 else {
10715 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
10716 }
10717 this.variables[name] = variable;
10718 this.parameters.push(variable);
10719 return variable;
10720 };
10721 ParameterScope.prototype.getParameterVariables = function () {
10722 return this.parameters;
10723 };
10724 return ParameterScope;
10725}(ChildScope));
10726
10727var ReturnValueScope = /** @class */ (function (_super) {
10728 __extends(ReturnValueScope, _super);
10729 function ReturnValueScope() {
10730 var _this = _super !== null && _super.apply(this, arguments) || this;
10731 _this.returnExpression = null;
10732 _this.returnExpressions = [];
10733 return _this;
10734 }
10735 ReturnValueScope.prototype.addReturnExpression = function (expression) {
10736 this.returnExpressions.push(expression);
10737 };
10738 ReturnValueScope.prototype.getReturnExpression = function () {
10739 if (this.returnExpression === null)
10740 this.updateReturnExpression();
10741 return this.returnExpression;
10742 };
10743 ReturnValueScope.prototype.updateReturnExpression = function () {
10744 if (this.returnExpressions.length === 1) {
10745 this.returnExpression = this.returnExpressions[0];
10746 }
10747 else {
10748 this.returnExpression = UNKNOWN_EXPRESSION;
10749 for (var _i = 0, _a = this.returnExpressions; _i < _a.length; _i++) {
10750 var expression = _a[_i];
10751 expression.deoptimizePath(UNKNOWN_PATH);
10752 }
10753 }
10754 };
10755 return ReturnValueScope;
10756}(ParameterScope));
10757
10758var FunctionScope = /** @class */ (function (_super) {
10759 __extends(FunctionScope, _super);
10760 function FunctionScope(parent, context) {
10761 var _this = _super.call(this, parent, context) || this;
10762 _this.variables.arguments = new ArgumentsVariable(_super.prototype.getParameterVariables.call(_this), context);
10763 _this.variables.this = new ThisVariable(context);
10764 return _this;
10765 }
10766 FunctionScope.prototype.findLexicalBoundary = function () {
10767 return this;
10768 };
10769 FunctionScope.prototype.getOptionsWhenCalledWith = function (_a, options) {
10770 var _this = this;
10771 var args = _a.args, withNew = _a.withNew;
10772 return options
10773 .replaceVariableInit(this.variables.this, withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION)
10774 .setArgumentsVariables(args.map(function (parameter, index) { return _super.prototype.getParameterVariables.call(_this)[index] || parameter; }));
10775 };
10776 return FunctionScope;
10777}(ReturnValueScope));
10778
10779var FunctionNode = /** @class */ (function (_super) {
10780 __extends(FunctionNode, _super);
10781 function FunctionNode() {
10782 return _super !== null && _super.apply(this, arguments) || this;
10783 }
10784 FunctionNode.prototype.createScope = function (parentScope) {
10785 this.scope = new FunctionScope(parentScope, this.context);
10786 };
10787 FunctionNode.prototype.deoptimizePath = function (path) {
10788 if (path.length === 1) {
10789 if (path[0] === 'prototype') {
10790 this.isPrototypeDeoptimized = true;
10791 }
10792 else if (path[0] === UNKNOWN_KEY) {
10793 this.isPrototypeDeoptimized = true;
10794 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
10795 // which means the return expression needs to be reassigned as well
10796 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
10797 }
10798 }
10799 };
10800 FunctionNode.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
10801 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
10802 };
10803 FunctionNode.prototype.hasEffects = function (options) {
10804 return this.id && this.id.hasEffects(options);
10805 };
10806 FunctionNode.prototype.hasEffectsWhenAccessedAtPath = function (path) {
10807 if (path.length <= 1) {
10808 return false;
10809 }
10810 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
10811 };
10812 FunctionNode.prototype.hasEffectsWhenAssignedAtPath = function (path) {
10813 if (path.length <= 1) {
10814 return false;
10815 }
10816 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
10817 };
10818 FunctionNode.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10819 if (path.length > 0) {
10820 return true;
10821 }
10822 var innerOptions = this.scope.getOptionsWhenCalledWith(callOptions, options);
10823 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
10824 var param = _a[_i];
10825 if (param.hasEffects(innerOptions))
10826 return true;
10827 }
10828 return this.body.hasEffects(innerOptions);
10829 };
10830 FunctionNode.prototype.include = function (includeAllChildrenRecursively) {
10831 this.scope.variables.arguments.include();
10832 _super.prototype.include.call(this, includeAllChildrenRecursively);
10833 };
10834 FunctionNode.prototype.initialise = function () {
10835 this.included = false;
10836 this.isPrototypeDeoptimized = false;
10837 if (this.id !== null) {
10838 this.id.declare('function', this);
10839 }
10840 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
10841 var param = _a[_i];
10842 param.declare('parameter', UNKNOWN_EXPRESSION);
10843 }
10844 this.body.addImplicitReturnExpressionToScope();
10845 };
10846 FunctionNode.prototype.parseNode = function (esTreeNode) {
10847 this.body = (new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope));
10848 _super.prototype.parseNode.call(this, esTreeNode);
10849 };
10850 return FunctionNode;
10851}(NodeBase));
10852FunctionNode.prototype.preventChildBlockScope = true;
10853
10854function isFunctionDeclaration(node) {
10855 return node.type === FunctionDeclaration;
10856}
10857var FunctionDeclaration$1 = /** @class */ (function (_super) {
10858 __extends(FunctionDeclaration, _super);
10859 function FunctionDeclaration() {
10860 return _super !== null && _super.apply(this, arguments) || this;
10861 }
10862 FunctionDeclaration.prototype.initialise = function () {
10863 _super.prototype.initialise.call(this);
10864 if (this.id !== null) {
10865 this.id.variable.isId = true;
10866 }
10867 };
10868 FunctionDeclaration.prototype.parseNode = function (esTreeNode) {
10869 if (esTreeNode.id !== null) {
10870 this.id = (new this.context.nodeConstructors.Identifier(esTreeNode.id, this, (this.scope.parent)));
10871 }
10872 _super.prototype.parseNode.call(this, esTreeNode);
10873 };
10874 return FunctionDeclaration;
10875}(FunctionNode));
10876
10877var WHITESPACE = /\s/;
10878// The header ends at the first non-white-space after "default"
10879function getDeclarationStart(code, start) {
10880 if (start === void 0) { start = 0; }
10881 start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
10882 while (WHITESPACE.test(code[start]))
10883 start++;
10884 return start;
10885}
10886function getIdInsertPosition(code, declarationKeyword, start) {
10887 if (start === void 0) { start = 0; }
10888 var declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
10889 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
10890 var generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
10891 if (generatorStarPos === -1) {
10892 return declarationEnd;
10893 }
10894 return declarationEnd + generatorStarPos + 1;
10895}
10896function isExportDefaultDeclaration(node) {
10897 return node.type === ExportDefaultDeclaration;
10898}
10899var ExportDefaultDeclaration$1 = /** @class */ (function (_super) {
10900 __extends(ExportDefaultDeclaration, _super);
10901 function ExportDefaultDeclaration() {
10902 return _super !== null && _super.apply(this, arguments) || this;
10903 }
10904 ExportDefaultDeclaration.prototype.include = function (includeAllChildrenRecursively) {
10905 _super.prototype.include.call(this, includeAllChildrenRecursively);
10906 if (includeAllChildrenRecursively) {
10907 this.context.includeVariable(this.variable);
10908 }
10909 };
10910 ExportDefaultDeclaration.prototype.initialise = function () {
10911 this.included = false;
10912 this.declarationName =
10913 (this.declaration.id &&
10914 this.declaration.id.name) ||
10915 this.declaration.name;
10916 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
10917 this.context.addExport(this);
10918 };
10919 ExportDefaultDeclaration.prototype.render = function (code, options, _a) {
10920 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
10921 var declarationStart = getDeclarationStart(code.original, this.start);
10922 if (isFunctionDeclaration(this.declaration)) {
10923 this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
10924 }
10925 else if (isClassDeclaration(this.declaration)) {
10926 this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
10927 }
10928 else if (this.variable.referencesOriginal()) {
10929 // Remove altogether to prevent re-declaring the same variable
10930 if (options.format === 'system' && this.variable.exportName) {
10931 code.overwrite(start, end, "exports('" + this.variable.exportName + "', " + this.variable.getName() + ");");
10932 }
10933 else {
10934 treeshakeNode(this, code, start, end);
10935 }
10936 return;
10937 }
10938 else if (this.variable.included) {
10939 this.renderVariableDeclaration(code, declarationStart, options);
10940 }
10941 else {
10942 code.remove(this.start, declarationStart);
10943 this.declaration.render(code, options, {
10944 isCalleeOfRenderedParent: false,
10945 renderedParentType: ExpressionStatement
10946 });
10947 if (code.original[this.end - 1] !== ';') {
10948 code.appendLeft(this.end, ';');
10949 }
10950 return;
10951 }
10952 this.declaration.render(code, options);
10953 };
10954 ExportDefaultDeclaration.prototype.renderNamedDeclaration = function (code, declarationStart, declarationKeyword, needsId, options) {
10955 var name = this.variable.getName();
10956 // Remove `export default`
10957 code.remove(this.start, declarationStart);
10958 if (needsId) {
10959 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), " " + name);
10960 }
10961 if (options.format === 'system' &&
10962 isClassDeclaration(this.declaration) &&
10963 this.variable.exportName) {
10964 code.appendLeft(this.end, " exports('" + this.variable.exportName + "', " + name + ");");
10965 }
10966 };
10967 ExportDefaultDeclaration.prototype.renderVariableDeclaration = function (code, declarationStart, options) {
10968 var systemBinding = options.format === 'system' && this.variable.exportName
10969 ? "exports('" + this.variable.exportName + "', "
10970 : '';
10971 code.overwrite(this.start, declarationStart, options.varOrConst + " " + this.variable.getName() + " = " + systemBinding);
10972 var hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
10973 if (systemBinding) {
10974 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
10975 }
10976 else if (!hasTrailingSemicolon) {
10977 code.appendLeft(this.end, ';');
10978 }
10979 };
10980 return ExportDefaultDeclaration;
10981}(NodeBase));
10982ExportDefaultDeclaration$1.prototype.needsBoundaries = true;
10983
10984var ArrayExpression = /** @class */ (function (_super) {
10985 __extends(ArrayExpression, _super);
10986 function ArrayExpression() {
10987 return _super !== null && _super.apply(this, arguments) || this;
10988 }
10989 ArrayExpression.prototype.bind = function () {
10990 _super.prototype.bind.call(this);
10991 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
10992 var element = _a[_i];
10993 if (element !== null)
10994 element.deoptimizePath(UNKNOWN_PATH);
10995 }
10996 };
10997 ArrayExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
10998 if (path.length !== 1)
10999 return UNKNOWN_EXPRESSION;
11000 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
11001 };
11002 ArrayExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
11003 return path.length > 1;
11004 };
11005 ArrayExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11006 if (path.length === 1) {
11007 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
11008 }
11009 return true;
11010 };
11011 return ArrayExpression;
11012}(NodeBase));
11013
11014var ArrayPattern = /** @class */ (function (_super) {
11015 __extends(ArrayPattern, _super);
11016 function ArrayPattern() {
11017 return _super !== null && _super.apply(this, arguments) || this;
11018 }
11019 ArrayPattern.prototype.addExportedVariables = function (variables) {
11020 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11021 var element = _a[_i];
11022 if (element !== null) {
11023 element.addExportedVariables(variables);
11024 }
11025 }
11026 };
11027 ArrayPattern.prototype.declare = function (kind, _init) {
11028 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11029 var element = _a[_i];
11030 if (element !== null) {
11031 element.declare(kind, UNKNOWN_EXPRESSION);
11032 }
11033 }
11034 };
11035 ArrayPattern.prototype.deoptimizePath = function (path) {
11036 if (path.length === 0) {
11037 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11038 var element = _a[_i];
11039 if (element !== null) {
11040 element.deoptimizePath(path);
11041 }
11042 }
11043 }
11044 };
11045 ArrayPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11046 if (path.length > 0)
11047 return true;
11048 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11049 var element = _a[_i];
11050 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
11051 return true;
11052 }
11053 return false;
11054 };
11055 return ArrayPattern;
11056}(NodeBase));
11057
11058var BlockScope = /** @class */ (function (_super) {
11059 __extends(BlockScope, _super);
11060 function BlockScope() {
11061 return _super !== null && _super.apply(this, arguments) || this;
11062 }
11063 BlockScope.prototype.addDeclaration = function (identifier, context, init, isHoisted) {
11064 if (init === void 0) { init = null; }
11065 if (isHoisted === void 0) { isHoisted = false; }
11066 if (isHoisted) {
11067 return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, true);
11068 }
11069 else {
11070 return _super.prototype.addDeclaration.call(this, identifier, context, init, false);
11071 }
11072 };
11073 return BlockScope;
11074}(ChildScope));
11075
11076var BlockStatement$1 = /** @class */ (function (_super) {
11077 __extends(BlockStatement, _super);
11078 function BlockStatement() {
11079 return _super !== null && _super.apply(this, arguments) || this;
11080 }
11081 BlockStatement.prototype.addImplicitReturnExpressionToScope = function () {
11082 var lastStatement = this.body[this.body.length - 1];
11083 if (!lastStatement || lastStatement.type !== ReturnStatement) {
11084 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
11085 }
11086 };
11087 BlockStatement.prototype.createScope = function (parentScope) {
11088 this.scope = this.parent.preventChildBlockScope
11089 ? parentScope
11090 : new BlockScope(parentScope);
11091 };
11092 BlockStatement.prototype.hasEffects = function (options) {
11093 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
11094 var node = _a[_i];
11095 if (node.hasEffects(options))
11096 return true;
11097 }
11098 };
11099 BlockStatement.prototype.include = function (includeAllChildrenRecursively) {
11100 this.included = true;
11101 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
11102 var node = _a[_i];
11103 if (includeAllChildrenRecursively || node.shouldBeIncluded())
11104 node.include(includeAllChildrenRecursively);
11105 }
11106 };
11107 BlockStatement.prototype.render = function (code, options) {
11108 if (this.body.length) {
11109 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
11110 }
11111 else {
11112 _super.prototype.render.call(this, code, options);
11113 }
11114 };
11115 return BlockStatement;
11116}(NodeBase));
11117
11118var ArrowFunctionExpression = /** @class */ (function (_super) {
11119 __extends(ArrowFunctionExpression, _super);
11120 function ArrowFunctionExpression() {
11121 return _super !== null && _super.apply(this, arguments) || this;
11122 }
11123 ArrowFunctionExpression.prototype.createScope = function (parentScope) {
11124 this.scope = new ReturnValueScope(parentScope, this.context);
11125 };
11126 ArrowFunctionExpression.prototype.deoptimizePath = function (path) {
11127 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
11128 // which means the return expression needs to be reassigned
11129 if (path.length === 1 && path[0] === UNKNOWN_KEY) {
11130 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
11131 }
11132 };
11133 ArrowFunctionExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
11134 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
11135 };
11136 ArrowFunctionExpression.prototype.hasEffects = function (_options) {
11137 return false;
11138 };
11139 ArrowFunctionExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
11140 return path.length > 1;
11141 };
11142 ArrowFunctionExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, _options) {
11143 return path.length > 1;
11144 };
11145 ArrowFunctionExpression.prototype.hasEffectsWhenCalledAtPath = function (path, _callOptions, options) {
11146 if (path.length > 0) {
11147 return true;
11148 }
11149 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
11150 var param = _a[_i];
11151 if (param.hasEffects(options))
11152 return true;
11153 }
11154 return this.body.hasEffects(options);
11155 };
11156 ArrowFunctionExpression.prototype.initialise = function () {
11157 this.included = false;
11158 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
11159 var param = _a[_i];
11160 param.declare('parameter', UNKNOWN_EXPRESSION);
11161 }
11162 if (this.body instanceof BlockStatement$1) {
11163 this.body.addImplicitReturnExpressionToScope();
11164 }
11165 else {
11166 this.scope.addReturnExpression(this.body);
11167 }
11168 };
11169 ArrowFunctionExpression.prototype.parseNode = function (esTreeNode) {
11170 if (esTreeNode.body.type === BlockStatement) {
11171 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
11172 }
11173 _super.prototype.parseNode.call(this, esTreeNode);
11174 };
11175 return ArrowFunctionExpression;
11176}(NodeBase));
11177ArrowFunctionExpression.prototype.preventChildBlockScope = true;
11178
11179function getSystemExportStatement(exportedVariables) {
11180 if (exportedVariables.length === 1) {
11181 return "exports('" + (exportedVariables[0].safeExportName ||
11182 exportedVariables[0].exportName) + "', " + exportedVariables[0].getName() + ");";
11183 }
11184 else {
11185 return "exports({" + exportedVariables
11186 .map(function (variable) { return (variable.safeExportName || variable.exportName) + ": " + variable.getName(); })
11187 .join(', ') + "});";
11188 }
11189}
11190
11191var AssignmentExpression = /** @class */ (function (_super) {
11192 __extends(AssignmentExpression, _super);
11193 function AssignmentExpression() {
11194 return _super !== null && _super.apply(this, arguments) || this;
11195 }
11196 AssignmentExpression.prototype.bind = function () {
11197 _super.prototype.bind.call(this);
11198 this.left.deoptimizePath(EMPTY_PATH);
11199 // We cannot propagate mutations of the new binding to the old binding with certainty
11200 this.right.deoptimizePath(UNKNOWN_PATH);
11201 };
11202 AssignmentExpression.prototype.hasEffects = function (options) {
11203 return (this.right.hasEffects(options) ||
11204 this.left.hasEffects(options) ||
11205 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
11206 };
11207 AssignmentExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11208 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, options);
11209 };
11210 AssignmentExpression.prototype.render = function (code, options) {
11211 this.left.render(code, options);
11212 this.right.render(code, options);
11213 if (options.format === 'system') {
11214 if (this.left.variable && this.left.variable.exportName) {
11215 code.prependLeft(code.original.indexOf('=', this.left.end) + 1, " exports('" + this.left.variable.exportName + "',");
11216 code.appendLeft(this.right.end, ")");
11217 }
11218 else if ('addExportedVariables' in this.left) {
11219 var systemPatternExports = [];
11220 this.left.addExportedVariables(systemPatternExports);
11221 if (systemPatternExports.length > 0) {
11222 code.prependRight(this.start, "function (v) {" + getSystemExportStatement(systemPatternExports) + " return v;} (");
11223 code.appendLeft(this.end, ')');
11224 }
11225 }
11226 }
11227 };
11228 return AssignmentExpression;
11229}(NodeBase));
11230
11231var AssignmentPattern = /** @class */ (function (_super) {
11232 __extends(AssignmentPattern, _super);
11233 function AssignmentPattern() {
11234 return _super !== null && _super.apply(this, arguments) || this;
11235 }
11236 AssignmentPattern.prototype.addExportedVariables = function (variables) {
11237 this.left.addExportedVariables(variables);
11238 };
11239 AssignmentPattern.prototype.bind = function () {
11240 _super.prototype.bind.call(this);
11241 this.left.deoptimizePath(EMPTY_PATH);
11242 this.right.deoptimizePath(UNKNOWN_PATH);
11243 };
11244 AssignmentPattern.prototype.declare = function (kind, init) {
11245 this.left.declare(kind, init);
11246 };
11247 AssignmentPattern.prototype.deoptimizePath = function (path) {
11248 path.length === 0 && this.left.deoptimizePath(path);
11249 };
11250 AssignmentPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11251 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
11252 };
11253 AssignmentPattern.prototype.render = function (code, options, _a) {
11254 var isShorthandProperty = (_a === void 0 ? BLANK : _a).isShorthandProperty;
11255 this.left.render(code, options, { isShorthandProperty: isShorthandProperty });
11256 this.right.render(code, options);
11257 };
11258 return AssignmentPattern;
11259}(NodeBase));
11260
11261var AwaitExpression = /** @class */ (function (_super) {
11262 __extends(AwaitExpression, _super);
11263 function AwaitExpression() {
11264 return _super !== null && _super.apply(this, arguments) || this;
11265 }
11266 AwaitExpression.prototype.hasEffects = function (options) {
11267 return _super.prototype.hasEffects.call(this, options) || !options.ignoreReturnAwaitYield();
11268 };
11269 AwaitExpression.prototype.include = function (includeAllChildrenRecursively) {
11270 _super.prototype.include.call(this, includeAllChildrenRecursively);
11271 if (!this.context.usesTopLevelAwait) {
11272 var parent = this.parent;
11273 do {
11274 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
11275 return;
11276 } while ((parent = parent.parent));
11277 this.context.usesTopLevelAwait = true;
11278 }
11279 };
11280 AwaitExpression.prototype.render = function (code, options) {
11281 _super.prototype.render.call(this, code, options);
11282 };
11283 return AwaitExpression;
11284}(NodeBase));
11285
11286var binaryOperators = {
11287 '!=': function (left, right) { return left != right; },
11288 '!==': function (left, right) { return left !== right; },
11289 '%': function (left, right) { return left % right; },
11290 '&': function (left, right) { return left & right; },
11291 '*': function (left, right) { return left * right; },
11292 // At the moment, "**" will be transpiled to Math.pow
11293 '**': function (left, right) { return Math.pow(left, right); },
11294 '+': function (left, right) { return left + right; },
11295 '-': function (left, right) { return left - right; },
11296 '/': function (left, right) { return left / right; },
11297 '<': function (left, right) { return left < right; },
11298 '<<': function (left, right) { return left << right; },
11299 '<=': function (left, right) { return left <= right; },
11300 '==': function (left, right) { return left == right; },
11301 '===': function (left, right) { return left === right; },
11302 '>': function (left, right) { return left > right; },
11303 '>=': function (left, right) { return left >= right; },
11304 '>>': function (left, right) { return left >> right; },
11305 '>>>': function (left, right) { return left >>> right; },
11306 '^': function (left, right) { return left ^ right; },
11307 in: function () { return UNKNOWN_VALUE; },
11308 instanceof: function () { return UNKNOWN_VALUE; },
11309 '|': function (left, right) { return left | right; }
11310};
11311var BinaryExpression = /** @class */ (function (_super) {
11312 __extends(BinaryExpression, _super);
11313 function BinaryExpression() {
11314 return _super !== null && _super.apply(this, arguments) || this;
11315 }
11316 BinaryExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11317 if (path.length > 0)
11318 return UNKNOWN_VALUE;
11319 var leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11320 if (leftValue === UNKNOWN_VALUE)
11321 return UNKNOWN_VALUE;
11322 var rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11323 if (rightValue === UNKNOWN_VALUE)
11324 return UNKNOWN_VALUE;
11325 var operatorFn = binaryOperators[this.operator];
11326 if (!operatorFn)
11327 return UNKNOWN_VALUE;
11328 return operatorFn(leftValue, rightValue);
11329 };
11330 BinaryExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
11331 return path.length > 1;
11332 };
11333 return BinaryExpression;
11334}(NodeBase));
11335
11336var BreakStatement = /** @class */ (function (_super) {
11337 __extends(BreakStatement, _super);
11338 function BreakStatement() {
11339 return _super !== null && _super.apply(this, arguments) || this;
11340 }
11341 BreakStatement.prototype.hasEffects = function (options) {
11342 return (_super.prototype.hasEffects.call(this, options) ||
11343 !options.ignoreBreakStatements() ||
11344 (this.label && !options.ignoreLabel(this.label.name)));
11345 };
11346 return BreakStatement;
11347}(NodeBase));
11348
11349var RESULT_KEY$1 = {};
11350var ImmutableEntityPathTracker = /** @class */ (function () {
11351 function ImmutableEntityPathTracker(existingEntityPaths) {
11352 if (existingEntityPaths === void 0) { existingEntityPaths = Immutable.Map(); }
11353 this.entityPaths = existingEntityPaths;
11354 }
11355 ImmutableEntityPathTracker.prototype.isTracked = function (entity, path) {
11356 return this.entityPaths.getIn([entity].concat(path, [RESULT_KEY$1]));
11357 };
11358 ImmutableEntityPathTracker.prototype.track = function (entity, path) {
11359 return new ImmutableEntityPathTracker(this.entityPaths.setIn([entity].concat(path, [RESULT_KEY$1]), true));
11360 };
11361 return ImmutableEntityPathTracker;
11362}());
11363var EMPTY_IMMUTABLE_TRACKER = new ImmutableEntityPathTracker();
11364
11365function isReference(node, parent) {
11366 if (node.type === 'MemberExpression') {
11367 return !node.computed && isReference(node.object, node);
11368 }
11369 if (node.type === 'Identifier') {
11370 switch (parent.type) {
11371 // disregard `bar` in `foo.bar`
11372 case 'MemberExpression': return parent.computed || node === parent.object;
11373 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
11374 case 'MethodDefinition': return parent.computed;
11375 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
11376 case 'Property': return parent.computed || node === parent.value;
11377 // disregard the `bar` in `export { foo as bar }`
11378 case 'ExportSpecifier': return node === parent.local;
11379 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
11380 case 'LabeledStatement':
11381 case 'BreakStatement':
11382 case 'ContinueStatement': return false;
11383 default: return true;
11384 }
11385 }
11386 return false;
11387}
11388
11389function isIdentifier(node) {
11390 return node.type === Identifier;
11391}
11392var Identifier$1 = /** @class */ (function (_super) {
11393 __extends(Identifier, _super);
11394 function Identifier() {
11395 return _super !== null && _super.apply(this, arguments) || this;
11396 }
11397 Identifier.prototype.addExportedVariables = function (variables) {
11398 if (this.variable.exportName) {
11399 variables.push(this.variable);
11400 }
11401 };
11402 Identifier.prototype.bind = function () {
11403 if (this.bound)
11404 return;
11405 this.bound = true;
11406 if (this.variable === null && isReference(this, this.parent)) {
11407 this.variable = this.scope.findVariable(this.name);
11408 this.variable.addReference(this);
11409 }
11410 if (this.variable !== null &&
11411 this.variable.isLocal &&
11412 this.variable.additionalInitializers !== null) {
11413 this.variable.consolidateInitializers();
11414 }
11415 };
11416 Identifier.prototype.declare = function (kind, init) {
11417 switch (kind) {
11418 case 'var':
11419 case 'function':
11420 this.variable = this.scope.addDeclaration(this, this.context, init, true);
11421 break;
11422 case 'let':
11423 case 'const':
11424 case 'class':
11425 this.variable = this.scope.addDeclaration(this, this.context, init, false);
11426 break;
11427 case 'parameter':
11428 this.variable = this.scope.addParameterDeclaration(this);
11429 break;
11430 default:
11431 throw new Error("Unexpected identifier kind " + kind + ".");
11432 }
11433 };
11434 Identifier.prototype.deoptimizePath = function (path) {
11435 if (!this.bound)
11436 this.bind();
11437 if (this.variable !== null) {
11438 if (path.length === 0 &&
11439 this.name in this.context.importDescriptions &&
11440 !this.scope.contains(this.name)) {
11441 this.disallowImportReassignment();
11442 }
11443 this.variable.deoptimizePath(path);
11444 }
11445 };
11446 Identifier.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11447 if (!this.bound)
11448 this.bind();
11449 if (this.variable !== null) {
11450 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
11451 }
11452 return UNKNOWN_VALUE;
11453 };
11454 Identifier.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11455 if (!this.bound)
11456 this.bind();
11457 if (this.variable !== null) {
11458 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11459 }
11460 return UNKNOWN_EXPRESSION;
11461 };
11462 Identifier.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11463 return this.variable && this.variable.hasEffectsWhenAccessedAtPath(path, options);
11464 };
11465 Identifier.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11466 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, options);
11467 };
11468 Identifier.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11469 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
11470 };
11471 Identifier.prototype.include = function (_includeAllChildrenRecursively) {
11472 if (!this.included) {
11473 this.included = true;
11474 if (this.variable !== null) {
11475 this.context.includeVariable(this.variable);
11476 }
11477 }
11478 };
11479 Identifier.prototype.initialise = function () {
11480 this.included = false;
11481 this.bound = false;
11482 // To avoid later shape mutations
11483 if (!this.variable) {
11484 this.variable = null;
11485 }
11486 };
11487 Identifier.prototype.render = function (code, _options, _a) {
11488 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent, isShorthandProperty = _b.isShorthandProperty;
11489 if (this.variable) {
11490 var name = this.variable.getName();
11491 if (name !== this.name) {
11492 code.overwrite(this.start, this.end, name, {
11493 contentOnly: true,
11494 storeName: true
11495 });
11496 if (isShorthandProperty) {
11497 code.prependRight(this.start, this.name + ": ");
11498 }
11499 }
11500 // In strict mode, any variable named "eval" must be the actual "eval" function
11501 if (name === 'eval' &&
11502 renderedParentType === CallExpression &&
11503 isCalleeOfRenderedParent) {
11504 code.appendRight(this.start, '0, ');
11505 }
11506 }
11507 };
11508 Identifier.prototype.disallowImportReassignment = function () {
11509 this.context.error({
11510 code: 'ILLEGAL_REASSIGNMENT',
11511 message: "Illegal reassignment to import '" + this.name + "'"
11512 }, this.start);
11513 };
11514 return Identifier;
11515}(NodeBase));
11516
11517var CallExpression$1 = /** @class */ (function (_super) {
11518 __extends(CallExpression, _super);
11519 function CallExpression() {
11520 return _super !== null && _super.apply(this, arguments) || this;
11521 }
11522 CallExpression.prototype.bind = function () {
11523 _super.prototype.bind.call(this);
11524 if (this.callee instanceof Identifier$1) {
11525 var variable = this.scope.findVariable(this.callee.name);
11526 if (variable.isNamespace) {
11527 this.context.error({
11528 code: 'CANNOT_CALL_NAMESPACE',
11529 message: "Cannot call a namespace ('" + this.callee.name + "')"
11530 }, this.start);
11531 }
11532 if (this.callee.name === 'eval') {
11533 this.context.warn({
11534 code: 'EVAL',
11535 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
11536 url: 'https://rollupjs.org/guide/en#avoiding-eval'
11537 }, this.start);
11538 }
11539 }
11540 if (this.returnExpression === null) {
11541 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11542 }
11543 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
11544 var argument = _a[_i];
11545 // This will make sure all properties of parameters behave as "unknown"
11546 argument.deoptimizePath(UNKNOWN_PATH);
11547 }
11548 };
11549 CallExpression.prototype.deoptimizeCache = function () {
11550 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
11551 this.returnExpression = UNKNOWN_EXPRESSION;
11552 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
11553 var expression = _a[_i];
11554 expression.deoptimizeCache();
11555 }
11556 }
11557 };
11558 CallExpression.prototype.deoptimizePath = function (path) {
11559 if (path.length > 0 && !this.context.deoptimizationTracker.track(this, path)) {
11560 if (this.returnExpression === null) {
11561 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11562 }
11563 this.returnExpression.deoptimizePath(path);
11564 }
11565 };
11566 CallExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11567 if (this.returnExpression === null) {
11568 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
11569 }
11570 if (this.returnExpression === UNKNOWN_EXPRESSION ||
11571 recursionTracker.isTracked(this.returnExpression, path)) {
11572 return UNKNOWN_VALUE;
11573 }
11574 this.expressionsToBeDeoptimized.push(origin);
11575 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
11576 };
11577 CallExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11578 if (this.returnExpression === null) {
11579 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
11580 }
11581 if (this.returnExpression === UNKNOWN_EXPRESSION ||
11582 recursionTracker.isTracked(this.returnExpression, path)) {
11583 return UNKNOWN_EXPRESSION;
11584 }
11585 this.expressionsToBeDeoptimized.push(origin);
11586 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
11587 };
11588 CallExpression.prototype.hasEffects = function (options) {
11589 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
11590 var argument = _a[_i];
11591 if (argument.hasEffects(options))
11592 return true;
11593 }
11594 if (this.context.annotations && this.annotatedPure)
11595 return false;
11596 return (this.callee.hasEffects(options) ||
11597 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
11598 };
11599 CallExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11600 return (path.length > 0 &&
11601 !options.hasReturnExpressionBeenAccessedAtPath(path, this) &&
11602 this.returnExpression.hasEffectsWhenAccessedAtPath(path, options.addAccessedReturnExpressionAtPath(path, this)));
11603 };
11604 CallExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11605 return (path.length === 0 ||
11606 (!options.hasReturnExpressionBeenAssignedAtPath(path, this) &&
11607 this.returnExpression.hasEffectsWhenAssignedAtPath(path, options.addAssignedReturnExpressionAtPath(path, this))));
11608 };
11609 CallExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11610 if (options.hasReturnExpressionBeenCalledAtPath(path, this))
11611 return false;
11612 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledReturnExpressionAtPath(path, this));
11613 };
11614 CallExpression.prototype.include = function (includeAllChildrenRecursively) {
11615 _super.prototype.include.call(this, includeAllChildrenRecursively);
11616 if (!this.returnExpression.included) {
11617 this.returnExpression.include(false);
11618 }
11619 };
11620 CallExpression.prototype.initialise = function () {
11621 this.included = false;
11622 this.returnExpression = null;
11623 this.callOptions = CallOptions.create({
11624 args: this.arguments,
11625 callIdentifier: this,
11626 withNew: false
11627 });
11628 this.expressionsToBeDeoptimized = [];
11629 };
11630 CallExpression.prototype.render = function (code, options, _a) {
11631 var renderedParentType = (_a === void 0 ? BLANK : _a).renderedParentType;
11632 _super.prototype.render.call(this, code, options);
11633 if (renderedParentType === ExpressionStatement &&
11634 this.callee.type === FunctionExpression) {
11635 code.appendRight(this.start, '(');
11636 code.prependLeft(this.end, ')');
11637 }
11638 };
11639 return CallExpression;
11640}(NodeBase));
11641
11642var CatchScope = /** @class */ (function (_super) {
11643 __extends(CatchScope, _super);
11644 function CatchScope() {
11645 return _super !== null && _super.apply(this, arguments) || this;
11646 }
11647 CatchScope.prototype.addDeclaration = function (identifier, context, init, isHoisted) {
11648 if (init === void 0) { init = null; }
11649 if (isHoisted === void 0) { isHoisted = false; }
11650 if (isHoisted) {
11651 return this.parent.addDeclaration(identifier, context, init, true);
11652 }
11653 else {
11654 return _super.prototype.addDeclaration.call(this, identifier, context, init, false);
11655 }
11656 };
11657 return CatchScope;
11658}(ParameterScope));
11659
11660var CatchClause = /** @class */ (function (_super) {
11661 __extends(CatchClause, _super);
11662 function CatchClause() {
11663 return _super !== null && _super.apply(this, arguments) || this;
11664 }
11665 CatchClause.prototype.createScope = function (parentScope) {
11666 this.scope = new CatchScope(parentScope, this.context);
11667 };
11668 CatchClause.prototype.initialise = function () {
11669 this.included = false;
11670 if (this.param) {
11671 this.param.declare('parameter', UNKNOWN_EXPRESSION);
11672 }
11673 };
11674 CatchClause.prototype.parseNode = function (esTreeNode) {
11675 this.body = (new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope));
11676 _super.prototype.parseNode.call(this, esTreeNode);
11677 };
11678 return CatchClause;
11679}(NodeBase));
11680CatchClause.prototype.preventChildBlockScope = true;
11681
11682var ClassBody = /** @class */ (function (_super) {
11683 __extends(ClassBody, _super);
11684 function ClassBody() {
11685 return _super !== null && _super.apply(this, arguments) || this;
11686 }
11687 ClassBody.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11688 if (path.length > 0) {
11689 return true;
11690 }
11691 return (this.classConstructor !== null &&
11692 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
11693 };
11694 ClassBody.prototype.initialise = function () {
11695 this.included = false;
11696 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
11697 var method = _a[_i];
11698 if (method.kind === 'constructor') {
11699 this.classConstructor = method;
11700 return;
11701 }
11702 }
11703 this.classConstructor = null;
11704 };
11705 return ClassBody;
11706}(NodeBase));
11707
11708var ClassExpression = /** @class */ (function (_super) {
11709 __extends(ClassExpression, _super);
11710 function ClassExpression() {
11711 return _super !== null && _super.apply(this, arguments) || this;
11712 }
11713 return ClassExpression;
11714}(ClassNode));
11715
11716var MultiExpression = /** @class */ (function () {
11717 function MultiExpression(expressions) {
11718 this.expressions = expressions;
11719 }
11720 MultiExpression.prototype.deoptimizePath = function (path) {
11721 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11722 var expression = _a[_i];
11723 expression.deoptimizePath(path);
11724 }
11725 };
11726 MultiExpression.prototype.getLiteralValueAtPath = function () {
11727 return UNKNOWN_VALUE;
11728 };
11729 MultiExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11730 return new MultiExpression(this.expressions.map(function (expression) {
11731 return expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11732 }));
11733 };
11734 MultiExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11735 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11736 var expression = _a[_i];
11737 if (expression.hasEffectsWhenAccessedAtPath(path, options))
11738 return true;
11739 }
11740 return false;
11741 };
11742 MultiExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11743 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11744 var expression = _a[_i];
11745 if (expression.hasEffectsWhenAssignedAtPath(path, options))
11746 return true;
11747 }
11748 return false;
11749 };
11750 MultiExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11751 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11752 var expression = _a[_i];
11753 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, options))
11754 return true;
11755 }
11756 return false;
11757 };
11758 MultiExpression.prototype.include = function () { };
11759 return MultiExpression;
11760}());
11761
11762var ConditionalExpression = /** @class */ (function (_super) {
11763 __extends(ConditionalExpression, _super);
11764 function ConditionalExpression() {
11765 return _super !== null && _super.apply(this, arguments) || this;
11766 }
11767 ConditionalExpression.prototype.bind = function () {
11768 _super.prototype.bind.call(this);
11769 if (!this.isBranchResolutionAnalysed)
11770 this.analyseBranchResolution();
11771 };
11772 ConditionalExpression.prototype.deoptimizeCache = function () {
11773 if (this.usedBranch !== null) {
11774 // We did not track if there were reassignments to the previous branch.
11775 // Also, the return value might need to be reassigned.
11776 this.usedBranch = null;
11777 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
11778 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
11779 var expression = _a[_i];
11780 expression.deoptimizeCache();
11781 }
11782 }
11783 };
11784 ConditionalExpression.prototype.deoptimizePath = function (path) {
11785 if (path.length > 0) {
11786 if (!this.isBranchResolutionAnalysed)
11787 this.analyseBranchResolution();
11788 if (this.usedBranch === null) {
11789 this.consequent.deoptimizePath(path);
11790 this.alternate.deoptimizePath(path);
11791 }
11792 else {
11793 this.usedBranch.deoptimizePath(path);
11794 }
11795 }
11796 };
11797 ConditionalExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11798 if (!this.isBranchResolutionAnalysed)
11799 this.analyseBranchResolution();
11800 if (this.usedBranch === null)
11801 return UNKNOWN_VALUE;
11802 this.expressionsToBeDeoptimized.push(origin);
11803 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
11804 };
11805 ConditionalExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11806 if (!this.isBranchResolutionAnalysed)
11807 this.analyseBranchResolution();
11808 if (this.usedBranch === null)
11809 return new MultiExpression([
11810 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
11811 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
11812 ]);
11813 this.expressionsToBeDeoptimized.push(origin);
11814 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11815 };
11816 ConditionalExpression.prototype.hasEffects = function (options) {
11817 if (this.test.hasEffects(options))
11818 return true;
11819 if (this.usedBranch === null) {
11820 return this.consequent.hasEffects(options) || this.alternate.hasEffects(options);
11821 }
11822 return this.usedBranch.hasEffects(options);
11823 };
11824 ConditionalExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11825 if (path.length === 0)
11826 return false;
11827 if (this.usedBranch === null) {
11828 return (this.consequent.hasEffectsWhenAccessedAtPath(path, options) ||
11829 this.alternate.hasEffectsWhenAccessedAtPath(path, options));
11830 }
11831 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
11832 };
11833 ConditionalExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11834 if (path.length === 0)
11835 return true;
11836 if (this.usedBranch === null) {
11837 return (this.consequent.hasEffectsWhenAssignedAtPath(path, options) ||
11838 this.alternate.hasEffectsWhenAssignedAtPath(path, options));
11839 }
11840 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
11841 };
11842 ConditionalExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11843 if (this.usedBranch === null) {
11844 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
11845 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, options));
11846 }
11847 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
11848 };
11849 ConditionalExpression.prototype.include = function (includeAllChildrenRecursively) {
11850 this.included = true;
11851 if (includeAllChildrenRecursively || this.usedBranch === null || this.test.shouldBeIncluded()) {
11852 this.test.include(includeAllChildrenRecursively);
11853 this.consequent.include(includeAllChildrenRecursively);
11854 this.alternate.include(includeAllChildrenRecursively);
11855 }
11856 else {
11857 this.usedBranch.include(includeAllChildrenRecursively);
11858 }
11859 };
11860 ConditionalExpression.prototype.initialise = function () {
11861 this.included = false;
11862 this.isBranchResolutionAnalysed = false;
11863 this.usedBranch = null;
11864 this.unusedBranch = null;
11865 this.expressionsToBeDeoptimized = [];
11866 };
11867 ConditionalExpression.prototype.render = function (code, options, _a) {
11868 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
11869 if (!this.test.included) {
11870 code.remove(this.start, this.usedBranch.start);
11871 code.remove(this.usedBranch.end, this.end);
11872 removeAnnotations(this, code);
11873 this.usedBranch.render(code, options, {
11874 isCalleeOfRenderedParent: renderedParentType
11875 ? isCalleeOfRenderedParent
11876 : this.parent.callee === this,
11877 renderedParentType: renderedParentType || this.parent.type
11878 });
11879 }
11880 else {
11881 _super.prototype.render.call(this, code, options);
11882 }
11883 };
11884 ConditionalExpression.prototype.analyseBranchResolution = function () {
11885 this.isBranchResolutionAnalysed = true;
11886 var testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11887 if (testValue !== UNKNOWN_VALUE) {
11888 if (testValue) {
11889 this.usedBranch = this.consequent;
11890 this.unusedBranch = this.alternate;
11891 }
11892 else {
11893 this.usedBranch = this.alternate;
11894 this.unusedBranch = this.consequent;
11895 }
11896 }
11897 };
11898 return ConditionalExpression;
11899}(NodeBase));
11900
11901var DoWhileStatement = /** @class */ (function (_super) {
11902 __extends(DoWhileStatement, _super);
11903 function DoWhileStatement() {
11904 return _super !== null && _super.apply(this, arguments) || this;
11905 }
11906 DoWhileStatement.prototype.hasEffects = function (options) {
11907 return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
11908 };
11909 return DoWhileStatement;
11910}(NodeBase));
11911
11912var EmptyStatement = /** @class */ (function (_super) {
11913 __extends(EmptyStatement, _super);
11914 function EmptyStatement() {
11915 return _super !== null && _super.apply(this, arguments) || this;
11916 }
11917 EmptyStatement.prototype.hasEffects = function () {
11918 return false;
11919 };
11920 return EmptyStatement;
11921}(NodeBase));
11922
11923var ExportAllDeclaration$1 = /** @class */ (function (_super) {
11924 __extends(ExportAllDeclaration, _super);
11925 function ExportAllDeclaration() {
11926 return _super !== null && _super.apply(this, arguments) || this;
11927 }
11928 ExportAllDeclaration.prototype.hasEffects = function () {
11929 return false;
11930 };
11931 ExportAllDeclaration.prototype.initialise = function () {
11932 this.included = false;
11933 this.context.addExport(this);
11934 };
11935 ExportAllDeclaration.prototype.render = function (code, _options, _a) {
11936 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
11937 code.remove(start, end);
11938 };
11939 return ExportAllDeclaration;
11940}(NodeBase));
11941ExportAllDeclaration$1.prototype.needsBoundaries = true;
11942
11943var ExportNamedDeclaration = /** @class */ (function (_super) {
11944 __extends(ExportNamedDeclaration, _super);
11945 function ExportNamedDeclaration() {
11946 return _super !== null && _super.apply(this, arguments) || this;
11947 }
11948 ExportNamedDeclaration.prototype.bind = function () {
11949 // Do not bind specifiers
11950 if (this.declaration !== null)
11951 this.declaration.bind();
11952 };
11953 ExportNamedDeclaration.prototype.hasEffects = function (options) {
11954 return this.declaration && this.declaration.hasEffects(options);
11955 };
11956 ExportNamedDeclaration.prototype.initialise = function () {
11957 this.included = false;
11958 this.context.addExport(this);
11959 };
11960 ExportNamedDeclaration.prototype.render = function (code, options, _a) {
11961 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
11962 if (this.declaration === null) {
11963 code.remove(start, end);
11964 }
11965 else {
11966 code.remove(this.start, this.declaration.start);
11967 this.declaration.render(code, options, { start: start, end: end });
11968 }
11969 };
11970 return ExportNamedDeclaration;
11971}(NodeBase));
11972ExportNamedDeclaration.prototype.needsBoundaries = true;
11973
11974var ExpressionStatement$1 = /** @class */ (function (_super) {
11975 __extends(ExpressionStatement, _super);
11976 function ExpressionStatement() {
11977 return _super !== null && _super.apply(this, arguments) || this;
11978 }
11979 ExpressionStatement.prototype.initialise = function () {
11980 this.included = false;
11981 if (this.directive &&
11982 this.directive !== 'use strict' &&
11983 this.parent.type === Program) {
11984 this.context.warn(
11985 // This is necessary, because either way (deleting or not) can lead to errors.
11986 {
11987 code: 'MODULE_LEVEL_DIRECTIVE',
11988 message: "Module level directives cause errors when bundled, '" + this.directive + "' was ignored."
11989 }, this.start);
11990 }
11991 };
11992 ExpressionStatement.prototype.render = function (code, options) {
11993 _super.prototype.render.call(this, code, options);
11994 if (this.included)
11995 this.insertSemicolon(code);
11996 };
11997 ExpressionStatement.prototype.shouldBeIncluded = function () {
11998 if (this.directive && this.directive !== 'use strict')
11999 return this.parent.type !== Program;
12000 return _super.prototype.shouldBeIncluded.call(this);
12001 };
12002 return ExpressionStatement;
12003}(NodeBase));
12004
12005var ForInStatement = /** @class */ (function (_super) {
12006 __extends(ForInStatement, _super);
12007 function ForInStatement() {
12008 return _super !== null && _super.apply(this, arguments) || this;
12009 }
12010 ForInStatement.prototype.bind = function () {
12011 this.left.bind();
12012 this.left.deoptimizePath(EMPTY_PATH);
12013 this.right.bind();
12014 this.body.bind();
12015 };
12016 ForInStatement.prototype.createScope = function (parentScope) {
12017 this.scope = new BlockScope(parentScope);
12018 };
12019 ForInStatement.prototype.hasEffects = function (options) {
12020 return ((this.left &&
12021 (this.left.hasEffects(options) ||
12022 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
12023 (this.right && this.right.hasEffects(options)) ||
12024 this.body.hasEffects(options.setIgnoreBreakStatements()));
12025 };
12026 ForInStatement.prototype.include = function (includeAllChildrenRecursively) {
12027 this.included = true;
12028 this.left.includeWithAllDeclaredVariables(includeAllChildrenRecursively);
12029 this.left.deoptimizePath(EMPTY_PATH);
12030 this.right.include(includeAllChildrenRecursively);
12031 this.body.include(includeAllChildrenRecursively);
12032 };
12033 ForInStatement.prototype.render = function (code, options) {
12034 this.left.render(code, options, NO_SEMICOLON);
12035 this.right.render(code, options, NO_SEMICOLON);
12036 this.body.render(code, options);
12037 };
12038 return ForInStatement;
12039}(NodeBase));
12040
12041var ForOfStatement = /** @class */ (function (_super) {
12042 __extends(ForOfStatement, _super);
12043 function ForOfStatement() {
12044 return _super !== null && _super.apply(this, arguments) || this;
12045 }
12046 ForOfStatement.prototype.bind = function () {
12047 this.left.bind();
12048 this.left.deoptimizePath(EMPTY_PATH);
12049 this.right.bind();
12050 this.body.bind();
12051 };
12052 ForOfStatement.prototype.createScope = function (parentScope) {
12053 this.scope = new BlockScope(parentScope);
12054 };
12055 ForOfStatement.prototype.hasEffects = function (options) {
12056 return ((this.left &&
12057 (this.left.hasEffects(options) ||
12058 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
12059 (this.right && this.right.hasEffects(options)) ||
12060 this.body.hasEffects(options.setIgnoreBreakStatements()));
12061 };
12062 ForOfStatement.prototype.include = function (includeAllChildrenRecursively) {
12063 this.included = true;
12064 this.left.includeWithAllDeclaredVariables(includeAllChildrenRecursively);
12065 this.left.deoptimizePath(EMPTY_PATH);
12066 this.right.include(includeAllChildrenRecursively);
12067 this.body.include(includeAllChildrenRecursively);
12068 };
12069 ForOfStatement.prototype.render = function (code, options) {
12070 this.left.render(code, options, NO_SEMICOLON);
12071 this.right.render(code, options, NO_SEMICOLON);
12072 this.body.render(code, options);
12073 };
12074 return ForOfStatement;
12075}(NodeBase));
12076
12077var ForStatement = /** @class */ (function (_super) {
12078 __extends(ForStatement, _super);
12079 function ForStatement() {
12080 return _super !== null && _super.apply(this, arguments) || this;
12081 }
12082 ForStatement.prototype.createScope = function (parentScope) {
12083 this.scope = new BlockScope(parentScope);
12084 };
12085 ForStatement.prototype.hasEffects = function (options) {
12086 return ((this.init && this.init.hasEffects(options)) ||
12087 (this.test && this.test.hasEffects(options)) ||
12088 (this.update && this.update.hasEffects(options)) ||
12089 this.body.hasEffects(options.setIgnoreBreakStatements()));
12090 };
12091 ForStatement.prototype.render = function (code, options) {
12092 if (this.init)
12093 this.init.render(code, options, NO_SEMICOLON);
12094 if (this.test)
12095 this.test.render(code, options, NO_SEMICOLON);
12096 if (this.update)
12097 this.update.render(code, options, NO_SEMICOLON);
12098 this.body.render(code, options);
12099 };
12100 return ForStatement;
12101}(NodeBase));
12102
12103var FunctionExpression$1 = /** @class */ (function (_super) {
12104 __extends(FunctionExpression, _super);
12105 function FunctionExpression() {
12106 return _super !== null && _super.apply(this, arguments) || this;
12107 }
12108 return FunctionExpression;
12109}(FunctionNode));
12110
12111var IfStatement = /** @class */ (function (_super) {
12112 __extends(IfStatement, _super);
12113 function IfStatement() {
12114 return _super !== null && _super.apply(this, arguments) || this;
12115 }
12116 IfStatement.prototype.bind = function () {
12117 _super.prototype.bind.call(this);
12118 if (!this.isTestValueAnalysed) {
12119 this.testValue = UNKNOWN_VALUE;
12120 this.isTestValueAnalysed = true;
12121 this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12122 }
12123 };
12124 IfStatement.prototype.deoptimizeCache = function () {
12125 this.testValue = UNKNOWN_VALUE;
12126 };
12127 IfStatement.prototype.hasEffects = function (options) {
12128 if (this.test.hasEffects(options))
12129 return true;
12130 if (this.testValue === UNKNOWN_VALUE) {
12131 return (this.consequent.hasEffects(options) ||
12132 (this.alternate !== null && this.alternate.hasEffects(options)));
12133 }
12134 return this.testValue
12135 ? this.consequent.hasEffects(options)
12136 : this.alternate !== null && this.alternate.hasEffects(options);
12137 };
12138 IfStatement.prototype.include = function (includeAllChildrenRecursively) {
12139 this.included = true;
12140 if (includeAllChildrenRecursively) {
12141 this.test.include(true);
12142 this.consequent.include(true);
12143 if (this.alternate !== null) {
12144 this.alternate.include(true);
12145 }
12146 return;
12147 }
12148 var hasUnknownTest = this.testValue === UNKNOWN_VALUE;
12149 if (hasUnknownTest || this.test.shouldBeIncluded()) {
12150 this.test.include(false);
12151 }
12152 if ((hasUnknownTest || this.testValue) && this.consequent.shouldBeIncluded()) {
12153 this.consequent.include(false);
12154 }
12155 if (this.alternate !== null &&
12156 ((hasUnknownTest || !this.testValue) && this.alternate.shouldBeIncluded())) {
12157 this.alternate.include(false);
12158 }
12159 };
12160 IfStatement.prototype.initialise = function () {
12161 this.included = false;
12162 this.isTestValueAnalysed = false;
12163 };
12164 IfStatement.prototype.render = function (code, options) {
12165 // Note that unknown test values are always included
12166 if (!this.test.included &&
12167 (this.testValue
12168 ? this.alternate === null || !this.alternate.included
12169 : !this.consequent.included)) {
12170 var singleRetainedBranch = this.testValue ? this.consequent : this.alternate;
12171 code.remove(this.start, singleRetainedBranch.start);
12172 code.remove(singleRetainedBranch.end, this.end);
12173 removeAnnotations(this, code);
12174 singleRetainedBranch.render(code, options);
12175 }
12176 else {
12177 if (this.test.included) {
12178 this.test.render(code, options);
12179 }
12180 else {
12181 code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false');
12182 }
12183 if (this.consequent.included) {
12184 this.consequent.render(code, options);
12185 }
12186 else {
12187 code.overwrite(this.consequent.start, this.consequent.end, ';');
12188 }
12189 if (this.alternate !== null) {
12190 if (this.alternate.included) {
12191 this.alternate.render(code, options);
12192 }
12193 else {
12194 code.remove(this.consequent.end, this.alternate.end);
12195 }
12196 }
12197 }
12198 };
12199 return IfStatement;
12200}(NodeBase));
12201
12202var getDynamicImportMechanism = function (options) {
12203 switch (options.format) {
12204 case 'cjs': {
12205 var _ = options.compact ? '' : ' ';
12206 return {
12207 interopLeft: "Promise.resolve({" + _ + "default:" + _ + "require(",
12208 interopRight: ")" + _ + "})",
12209 left: 'Promise.resolve(require(',
12210 right: '))'
12211 };
12212 }
12213 case 'amd': {
12214 var _ = options.compact ? '' : ' ';
12215 var resolve = options.compact ? 'c' : 'resolve';
12216 var reject = options.compact ? 'e' : 'reject';
12217 return {
12218 interopLeft: "new Promise(function" + _ + "(" + resolve + "," + _ + reject + ")" + _ + "{" + _ + "require([",
12219 interopRight: "]," + _ + "function" + _ + "(m)" + _ + "{" + _ + resolve + "({" + _ + "default:" + _ + "m" + _ + "})" + _ + "}," + _ + reject + ")" + _ + "})",
12220 left: "new Promise(function" + _ + "(" + resolve + "," + _ + reject + ")" + _ + "{" + _ + "require([",
12221 right: "]," + _ + resolve + "," + _ + reject + ")" + _ + "})"
12222 };
12223 }
12224 case 'system':
12225 return {
12226 left: 'module.import(',
12227 right: ')'
12228 };
12229 case 'es':
12230 return {
12231 left: (options.dynamicImportFunction || 'import') + "(",
12232 right: ')'
12233 };
12234 }
12235};
12236var Import = /** @class */ (function (_super) {
12237 __extends(Import, _super);
12238 function Import() {
12239 return _super !== null && _super.apply(this, arguments) || this;
12240 }
12241 Import.prototype.include = function () {
12242 this.included = true;
12243 this.context.includeDynamicImport(this);
12244 };
12245 Import.prototype.initialise = function () {
12246 this.included = false;
12247 this.resolutionNamespace = undefined;
12248 this.resolutionInterop = false;
12249 this.context.addDynamicImport(this);
12250 };
12251 Import.prototype.render = function (code, options) {
12252 if (this.resolutionNamespace) {
12253 var _ = options.compact ? '' : ' ';
12254 var s = options.compact ? '' : ';';
12255 code.overwrite(this.parent.start, this.parent.end, "Promise.resolve().then(function" + _ + "()" + _ + "{" + _ + "return " + this.resolutionNamespace + s + _ + "})");
12256 return;
12257 }
12258 var importMechanism = getDynamicImportMechanism(options);
12259 if (importMechanism) {
12260 var leftMechanism = (this.resolutionInterop && importMechanism.interopLeft) || importMechanism.left;
12261 var leftMechanismEnd = findFirstOccurrenceOutsideComment(code.original, '(', this.parent.callee.end) + 1;
12262 code.overwrite(this.parent.start, leftMechanismEnd, leftMechanism);
12263 var rightMechanism = (this.resolutionInterop && importMechanism.interopRight) || importMechanism.right;
12264 code.overwrite(this.parent.end - 1, this.parent.end, rightMechanism);
12265 }
12266 };
12267 Import.prototype.renderFinalResolution = function (code, resolution) {
12268 if (this.included) {
12269 code.overwrite(this.parent.arguments[0].start, this.parent.arguments[0].end, resolution);
12270 }
12271 };
12272 Import.prototype.setResolution = function (interop, namespace) {
12273 if (namespace === void 0) { namespace = undefined; }
12274 this.resolutionInterop = interop;
12275 this.resolutionNamespace = namespace;
12276 };
12277 return Import;
12278}(NodeBase));
12279
12280var ImportDeclaration = /** @class */ (function (_super) {
12281 __extends(ImportDeclaration, _super);
12282 function ImportDeclaration() {
12283 return _super !== null && _super.apply(this, arguments) || this;
12284 }
12285 ImportDeclaration.prototype.bind = function () { };
12286 ImportDeclaration.prototype.hasEffects = function () {
12287 return false;
12288 };
12289 ImportDeclaration.prototype.initialise = function () {
12290 this.included = false;
12291 this.context.addImport(this);
12292 };
12293 ImportDeclaration.prototype.render = function (code, _options, _a) {
12294 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
12295 code.remove(start, end);
12296 };
12297 return ImportDeclaration;
12298}(NodeBase));
12299ImportDeclaration.prototype.needsBoundaries = true;
12300
12301var LabeledStatement = /** @class */ (function (_super) {
12302 __extends(LabeledStatement, _super);
12303 function LabeledStatement() {
12304 return _super !== null && _super.apply(this, arguments) || this;
12305 }
12306 LabeledStatement.prototype.hasEffects = function (options) {
12307 return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements());
12308 };
12309 return LabeledStatement;
12310}(NodeBase));
12311
12312function isLiteral(node) {
12313 return node.type === Literal;
12314}
12315var Literal$1 = /** @class */ (function (_super) {
12316 __extends(Literal, _super);
12317 function Literal() {
12318 return _super !== null && _super.apply(this, arguments) || this;
12319 }
12320 Literal.prototype.getLiteralValueAtPath = function (path) {
12321 if (path.length > 0 ||
12322 // unknown literals such as bigints can also be null but do not start with an "n"
12323 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
12324 typeof this.value === 'bigint') {
12325 return UNKNOWN_VALUE;
12326 }
12327 return this.value;
12328 };
12329 Literal.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
12330 if (path.length !== 1)
12331 return UNKNOWN_EXPRESSION;
12332 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
12333 };
12334 Literal.prototype.hasEffectsWhenAccessedAtPath = function (path) {
12335 if (this.value === null) {
12336 return path.length > 0;
12337 }
12338 return path.length > 1;
12339 };
12340 Literal.prototype.hasEffectsWhenAssignedAtPath = function (path) {
12341 return path.length > 0;
12342 };
12343 Literal.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12344 if (path.length === 1) {
12345 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, options);
12346 }
12347 return true;
12348 };
12349 Literal.prototype.initialise = function () {
12350 this.included = false;
12351 this.members = getLiteralMembersForValue(this.value);
12352 };
12353 Literal.prototype.render = function (code, _options) {
12354 if (typeof this.value === 'string') {
12355 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
12356 }
12357 };
12358 return Literal;
12359}(NodeBase));
12360
12361var LogicalExpression = /** @class */ (function (_super) {
12362 __extends(LogicalExpression, _super);
12363 function LogicalExpression() {
12364 return _super !== null && _super.apply(this, arguments) || this;
12365 }
12366 LogicalExpression.prototype.bind = function () {
12367 _super.prototype.bind.call(this);
12368 if (!this.isBranchResolutionAnalysed)
12369 this.analyseBranchResolution();
12370 };
12371 LogicalExpression.prototype.deoptimizeCache = function () {
12372 if (this.usedBranch !== null) {
12373 // We did not track if there were reassignments to any of the branches.
12374 // Also, the return values might need reassignment.
12375 this.usedBranch = null;
12376 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
12377 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
12378 var expression = _a[_i];
12379 expression.deoptimizeCache();
12380 }
12381 }
12382 };
12383 LogicalExpression.prototype.deoptimizePath = function (path) {
12384 if (path.length > 0) {
12385 if (!this.isBranchResolutionAnalysed)
12386 this.analyseBranchResolution();
12387 if (this.usedBranch === null) {
12388 this.left.deoptimizePath(path);
12389 this.right.deoptimizePath(path);
12390 }
12391 else {
12392 this.usedBranch.deoptimizePath(path);
12393 }
12394 }
12395 };
12396 LogicalExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
12397 if (!this.isBranchResolutionAnalysed)
12398 this.analyseBranchResolution();
12399 if (this.usedBranch === null)
12400 return UNKNOWN_VALUE;
12401 this.expressionsToBeDeoptimized.push(origin);
12402 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
12403 };
12404 LogicalExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
12405 if (!this.isBranchResolutionAnalysed)
12406 this.analyseBranchResolution();
12407 if (this.usedBranch === null)
12408 return new MultiExpression([
12409 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
12410 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
12411 ]);
12412 this.expressionsToBeDeoptimized.push(origin);
12413 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
12414 };
12415 LogicalExpression.prototype.hasEffects = function (options) {
12416 if (this.usedBranch === null) {
12417 return this.left.hasEffects(options) || this.right.hasEffects(options);
12418 }
12419 return this.usedBranch.hasEffects(options);
12420 };
12421 LogicalExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
12422 if (path.length === 0)
12423 return false;
12424 if (this.usedBranch === null) {
12425 return (this.left.hasEffectsWhenAccessedAtPath(path, options) ||
12426 this.right.hasEffectsWhenAccessedAtPath(path, options));
12427 }
12428 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
12429 };
12430 LogicalExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
12431 if (path.length === 0)
12432 return true;
12433 if (this.usedBranch === null) {
12434 return (this.left.hasEffectsWhenAssignedAtPath(path, options) ||
12435 this.right.hasEffectsWhenAssignedAtPath(path, options));
12436 }
12437 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
12438 };
12439 LogicalExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12440 if (this.usedBranch === null) {
12441 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
12442 this.right.hasEffectsWhenCalledAtPath(path, callOptions, options));
12443 }
12444 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
12445 };
12446 LogicalExpression.prototype.include = function (includeAllChildrenRecursively) {
12447 this.included = true;
12448 if (includeAllChildrenRecursively ||
12449 this.usedBranch === null ||
12450 this.unusedBranch.shouldBeIncluded()) {
12451 this.left.include(includeAllChildrenRecursively);
12452 this.right.include(includeAllChildrenRecursively);
12453 }
12454 else {
12455 this.usedBranch.include(includeAllChildrenRecursively);
12456 }
12457 };
12458 LogicalExpression.prototype.initialise = function () {
12459 this.included = false;
12460 this.isBranchResolutionAnalysed = false;
12461 this.usedBranch = null;
12462 this.unusedBranch = null;
12463 this.expressionsToBeDeoptimized = [];
12464 };
12465 LogicalExpression.prototype.render = function (code, options, _a) {
12466 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
12467 if (!this.left.included || !this.right.included) {
12468 code.remove(this.start, this.usedBranch.start);
12469 code.remove(this.usedBranch.end, this.end);
12470 removeAnnotations(this, code);
12471 this.usedBranch.render(code, options, {
12472 isCalleeOfRenderedParent: renderedParentType
12473 ? isCalleeOfRenderedParent
12474 : this.parent.callee === this,
12475 renderedParentType: renderedParentType || this.parent.type
12476 });
12477 }
12478 else {
12479 _super.prototype.render.call(this, code, options);
12480 }
12481 };
12482 LogicalExpression.prototype.analyseBranchResolution = function () {
12483 this.isBranchResolutionAnalysed = true;
12484 var leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12485 if (leftValue !== UNKNOWN_VALUE) {
12486 if (this.operator === '||' ? leftValue : !leftValue) {
12487 this.usedBranch = this.left;
12488 this.unusedBranch = this.right;
12489 }
12490 else {
12491 this.usedBranch = this.right;
12492 this.unusedBranch = this.left;
12493 }
12494 }
12495 };
12496 return LogicalExpression;
12497}(NodeBase));
12498
12499function getAliasName(resolved, unresolved) {
12500 var alias = basename(unresolved || resolved);
12501 var ext = extname(resolved);
12502 if (alias.endsWith(ext))
12503 alias = alias.substr(0, alias.length - ext.length);
12504 return alias;
12505}
12506function relativeId(id) {
12507 if (typeof process === 'undefined' || !isAbsolute(id))
12508 return id;
12509 return relative(process.cwd(), id);
12510}
12511function isPlainName(name) {
12512 // not starting with "./", "/". "../"
12513 if (name[0] === '/' ||
12514 (name[1] === '.' && (name[2] === '/' || (name[2] === '.' && name[3] === '/'))))
12515 return false;
12516 return true;
12517}
12518
12519function getResolvablePropertyKey(memberExpression) {
12520 return memberExpression.computed
12521 ? getResolvableComputedPropertyKey(memberExpression.property)
12522 : memberExpression.property.name;
12523}
12524function getResolvableComputedPropertyKey(propertyKey) {
12525 if (propertyKey instanceof Literal$1) {
12526 return String(propertyKey.value);
12527 }
12528 return null;
12529}
12530function getPathIfNotComputed(memberExpression) {
12531 var nextPathKey = memberExpression.propertyKey;
12532 var object = memberExpression.object;
12533 if (typeof nextPathKey === 'string') {
12534 if (object instanceof Identifier$1) {
12535 return [
12536 { key: object.name, pos: object.start },
12537 { key: nextPathKey, pos: memberExpression.property.start }
12538 ];
12539 }
12540 if (isMemberExpression(object)) {
12541 var parentPath = getPathIfNotComputed(object);
12542 return (parentPath && parentPath.concat([{ key: nextPathKey, pos: memberExpression.property.start }]));
12543 }
12544 }
12545 return null;
12546}
12547function getStringFromPath(path) {
12548 var pathString = path[0].key;
12549 for (var index = 1; index < path.length; index++) {
12550 pathString += '.' + path[index].key;
12551 }
12552 return pathString;
12553}
12554function isMemberExpression(node) {
12555 return node.type === MemberExpression;
12556}
12557var MemberExpression$1 = /** @class */ (function (_super) {
12558 __extends(MemberExpression, _super);
12559 function MemberExpression() {
12560 var _this = _super !== null && _super.apply(this, arguments) || this;
12561 _this.variable = null;
12562 return _this;
12563 }
12564 MemberExpression.prototype.addExportedVariables = function () { };
12565 MemberExpression.prototype.bind = function () {
12566 if (this.bound)
12567 return;
12568 this.bound = true;
12569 var path = getPathIfNotComputed(this);
12570 var baseVariable = path && this.scope.findVariable(path[0].key);
12571 if (baseVariable && baseVariable.isNamespace) {
12572 var resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
12573 if (!resolvedVariable) {
12574 _super.prototype.bind.call(this);
12575 }
12576 else if (typeof resolvedVariable === 'string') {
12577 this.replacement = resolvedVariable;
12578 }
12579 else {
12580 if (resolvedVariable.isExternal && resolvedVariable.module) {
12581 resolvedVariable.module.suggestName(path[0].key);
12582 }
12583 this.variable = resolvedVariable;
12584 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
12585 }
12586 }
12587 else {
12588 _super.prototype.bind.call(this);
12589 if (this.propertyKey === null)
12590 this.analysePropertyKey();
12591 }
12592 };
12593 MemberExpression.prototype.deoptimizeCache = function () {
12594 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
12595 var expression = _a[_i];
12596 expression.deoptimizeCache();
12597 }
12598 };
12599 MemberExpression.prototype.deoptimizePath = function (path) {
12600 if (!this.bound)
12601 this.bind();
12602 if (path.length === 0)
12603 this.disallowNamespaceReassignment();
12604 if (this.variable) {
12605 this.variable.deoptimizePath(path);
12606 }
12607 else {
12608 if (this.propertyKey === null)
12609 this.analysePropertyKey();
12610 this.object.deoptimizePath([this.propertyKey].concat(path));
12611 }
12612 };
12613 MemberExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
12614 if (this.variable !== null) {
12615 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
12616 }
12617 if (this.propertyKey === null)
12618 this.analysePropertyKey();
12619 this.expressionsToBeDeoptimized.push(origin);
12620 return this.object.getLiteralValueAtPath([this.propertyKey].concat(path), recursionTracker, origin);
12621 };
12622 MemberExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
12623 if (this.variable !== null) {
12624 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
12625 }
12626 if (this.propertyKey === null)
12627 this.analysePropertyKey();
12628 this.expressionsToBeDeoptimized.push(origin);
12629 return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey].concat(path), recursionTracker, origin);
12630 };
12631 MemberExpression.prototype.hasEffects = function (options) {
12632 return (this.property.hasEffects(options) ||
12633 this.object.hasEffects(options) ||
12634 (this.context.propertyReadSideEffects &&
12635 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], options)));
12636 };
12637 MemberExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
12638 if (path.length === 0) {
12639 return false;
12640 }
12641 if (this.variable !== null) {
12642 return this.variable.hasEffectsWhenAccessedAtPath(path, options);
12643 }
12644 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey].concat(path), options);
12645 };
12646 MemberExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
12647 if (this.variable !== null) {
12648 return this.variable.hasEffectsWhenAssignedAtPath(path, options);
12649 }
12650 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey].concat(path), options);
12651 };
12652 MemberExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12653 if (this.variable !== null) {
12654 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
12655 }
12656 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey].concat(path), callOptions, options);
12657 };
12658 MemberExpression.prototype.include = function (includeAllChildrenRecursively) {
12659 if (!this.included) {
12660 this.included = true;
12661 if (this.variable !== null) {
12662 this.context.includeVariable(this.variable);
12663 }
12664 }
12665 this.object.include(includeAllChildrenRecursively);
12666 this.property.include(includeAllChildrenRecursively);
12667 };
12668 MemberExpression.prototype.initialise = function () {
12669 this.included = false;
12670 this.propertyKey = getResolvablePropertyKey(this);
12671 this.variable = null;
12672 this.bound = false;
12673 this.replacement = null;
12674 this.expressionsToBeDeoptimized = [];
12675 };
12676 MemberExpression.prototype.render = function (code, options, _a) {
12677 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
12678 var isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
12679 if (this.variable || this.replacement) {
12680 var replacement = this.variable ? this.variable.getName() : this.replacement;
12681 if (isCalleeOfDifferentParent)
12682 replacement = '0, ' + replacement;
12683 code.overwrite(this.start, this.end, replacement, {
12684 contentOnly: true,
12685 storeName: true
12686 });
12687 }
12688 else {
12689 if (isCalleeOfDifferentParent) {
12690 code.appendRight(this.start, '0, ');
12691 }
12692 _super.prototype.render.call(this, code, options);
12693 }
12694 };
12695 MemberExpression.prototype.analysePropertyKey = function () {
12696 this.propertyKey = UNKNOWN_KEY;
12697 var value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12698 this.propertyKey = value === UNKNOWN_VALUE ? UNKNOWN_KEY : String(value);
12699 };
12700 MemberExpression.prototype.disallowNamespaceReassignment = function () {
12701 if (this.object instanceof Identifier$1 &&
12702 this.scope.findVariable(this.object.name).isNamespace) {
12703 this.context.error({
12704 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
12705 message: "Illegal reassignment to import '" + this.object.name + "'"
12706 }, this.start);
12707 }
12708 };
12709 MemberExpression.prototype.resolveNamespaceVariables = function (baseVariable, path) {
12710 if (path.length === 0)
12711 return baseVariable;
12712 if (!baseVariable.isNamespace)
12713 return null;
12714 var exportName = path[0].key;
12715 var variable = baseVariable.isExternal
12716 ? baseVariable.module.getVariableForExportName(exportName)
12717 : baseVariable.context.traceExport(exportName);
12718 if (!variable) {
12719 var fileName = baseVariable.isExternal
12720 ? baseVariable.module.id
12721 : baseVariable.context.fileName;
12722 this.context.warn({
12723 code: 'MISSING_EXPORT',
12724 exporter: relativeId(fileName),
12725 importer: relativeId(this.context.fileName),
12726 message: "'" + exportName + "' is not exported by '" + relativeId(fileName) + "'",
12727 missing: exportName,
12728 url: "https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-"
12729 }, path[0].pos);
12730 return 'undefined';
12731 }
12732 return this.resolveNamespaceVariables(variable, path.slice(1));
12733 };
12734 return MemberExpression;
12735}(NodeBase));
12736
12737var globalImportMetaUrlMechanism = "(typeof document !== 'undefined' ? document.currentScript && document.currentScript.src || document.baseURI : new (typeof URL !== 'undefined' ? URL : require('ur'+'l').URL)('file:' + __filename).href)";
12738var importMetaUrlMechanisms = {
12739 amd: "new URL((typeof process !== 'undefined' && process.versions && process.versions.node ? 'file:' : '') + module.uri).href",
12740 cjs: "new (typeof URL !== 'undefined' ? URL : require('ur'+'l').URL)((process.browser ? '' : 'file:') + __filename, process.browser && document.baseURI).href",
12741 iife: globalImportMetaUrlMechanism,
12742 umd: globalImportMetaUrlMechanism
12743};
12744var globalImportMetaUrlMechanismCompact = "(typeof document!=='undefined'?document.currentScript&&document.currentScript.src||document.baseURI:new(typeof URL!=='undefined'?URL:require('ur'+'l').URL)('file:'+__filename).href)";
12745var importMetaUrlMechanismsCompact = {
12746 amd: "new URL((typeof process!=='undefined'&&process.versions&&process.versions.node?'file:':'')+module.uri).href",
12747 cjs: "new(typeof URL!=='undefined'?URL:require('ur'+'l').URL)((process.browser?'':'file:')+__filename,process.browser&&document.baseURI).href",
12748 iife: globalImportMetaUrlMechanismCompact,
12749 umd: globalImportMetaUrlMechanismCompact
12750};
12751var globalRelUrlMechanism = function (relPath, compact) {
12752 var _ = compact ? '' : ' ';
12753 return "new" + _ + "(typeof URL" + _ + "!==" + _ + "'undefined'" + _ + "?" + _ + "URL" + _ + ":" + _ + "require('ur'+'l').URL)((typeof document" + _ + "!==" + _ + "'undefined'" + _ + "?" + _ + "document.currentScript" + _ + "&&" + _ + "document.currentScript.src" + _ + "||" + _ + "document.baseURI" + _ + ":" + _ + "'file:'" + _ + "+" + _ + "__filename)" + _ + "+" + _ + "'/../" + relPath + "').href";
12754};
12755var relUrlMechanisms = {
12756 amd: function (relPath, compact) {
12757 var _ = compact ? '' : ' ';
12758 return "new URL((typeof process" + _ + "!==" + _ + "'undefined'" + _ + "&&" + _ + "process.versions" + _ + "&&" + _ + "process.versions.node" + _ + "?" + _ + "'file:'" + _ + ":" + _ + "'')" + _ + "+" + _ + "module.uri" + _ + "+" + _ + "'/../" + relPath + "').href";
12759 },
12760 cjs: function (relPath, compact) {
12761 var _ = compact ? '' : ' ';
12762 return "new" + _ + "(typeof URL" + _ + "!==" + _ + "'undefined'" + _ + "?" + _ + "URL" + _ + ":" + _ + "require('ur'+'l').URL)((process.browser" + _ + "?" + _ + "''" + _ + ":" + _ + "'file:')" + _ + "+" + _ + "__dirname" + _ + "+" + _ + "'/" + relPath + "'," + _ + "process.browser" + _ + "&&" + _ + "document.baseURI).href";
12763 },
12764 es: function (relPath, compact) {
12765 var _ = compact ? '' : ' ';
12766 return "new URL('../" + relPath + "'," + _ + "import.meta.url).href";
12767 },
12768 iife: globalRelUrlMechanism,
12769 system: function (relPath, compact) {
12770 var _ = compact ? '' : ' ';
12771 return "new URL('../" + relPath + "'," + _ + "module.url).href";
12772 },
12773 umd: globalRelUrlMechanism
12774};
12775var MetaProperty = /** @class */ (function (_super) {
12776 __extends(MetaProperty, _super);
12777 function MetaProperty() {
12778 return _super !== null && _super.apply(this, arguments) || this;
12779 }
12780 MetaProperty.prototype.initialise = function () {
12781 if (this.meta.name === 'import') {
12782 this.rendered = false;
12783 this.context.addImportMeta(this);
12784 }
12785 this.included = false;
12786 };
12787 MetaProperty.prototype.render = function (code, options) {
12788 if (this.meta.name === 'import')
12789 this.rendered = true;
12790 _super.prototype.render.call(this, code, options);
12791 };
12792 MetaProperty.prototype.renderFinalMechanism = function (code, chunkId, format, compact) {
12793 if (!this.rendered)
12794 return false;
12795 if (this.parent instanceof MemberExpression$1 === false)
12796 return false;
12797 var parent = this.parent;
12798 var importMetaProperty;
12799 if (parent.property instanceof Identifier$1)
12800 importMetaProperty = parent.property.name;
12801 else if (parent.property instanceof Literal$1 && typeof parent.property.value === 'string')
12802 importMetaProperty = parent.property.value;
12803 else
12804 return false;
12805 // support import.meta.ROLLUP_ASSET_URL_[ID]
12806 if (importMetaProperty.startsWith('ROLLUP_ASSET_URL_')) {
12807 var assetFileName = this.context.getAssetFileName(importMetaProperty.substr(17));
12808 var relPath = normalize(relative(dirname(chunkId), assetFileName));
12809 code.overwrite(parent.start, parent.end, relUrlMechanisms[format](relPath, compact));
12810 return true;
12811 }
12812 if (format === 'system') {
12813 code.overwrite(this.meta.start, this.meta.end, 'module');
12814 }
12815 else if (importMetaProperty === 'url') {
12816 var importMetaUrlMechanism = (compact
12817 ? importMetaUrlMechanismsCompact
12818 : importMetaUrlMechanisms)[format];
12819 if (importMetaUrlMechanism)
12820 code.overwrite(parent.start, parent.end, importMetaUrlMechanism);
12821 return true;
12822 }
12823 return false;
12824 };
12825 return MetaProperty;
12826}(NodeBase));
12827
12828var MethodDefinition = /** @class */ (function (_super) {
12829 __extends(MethodDefinition, _super);
12830 function MethodDefinition() {
12831 return _super !== null && _super.apply(this, arguments) || this;
12832 }
12833 MethodDefinition.prototype.hasEffects = function (options) {
12834 return this.key.hasEffects(options);
12835 };
12836 MethodDefinition.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12837 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
12838 };
12839 return MethodDefinition;
12840}(NodeBase));
12841
12842var NewExpression = /** @class */ (function (_super) {
12843 __extends(NewExpression, _super);
12844 function NewExpression() {
12845 return _super !== null && _super.apply(this, arguments) || this;
12846 }
12847 NewExpression.prototype.bind = function () {
12848 _super.prototype.bind.call(this);
12849 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
12850 var argument = _a[_i];
12851 // This will make sure all properties of parameters behave as "unknown"
12852 argument.deoptimizePath(UNKNOWN_PATH);
12853 }
12854 };
12855 NewExpression.prototype.hasEffects = function (options) {
12856 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
12857 var argument = _a[_i];
12858 if (argument.hasEffects(options))
12859 return true;
12860 }
12861 if (this.annotatedPure)
12862 return false;
12863 return this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions());
12864 };
12865 NewExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
12866 return path.length > 1;
12867 };
12868 NewExpression.prototype.initialise = function () {
12869 this.included = false;
12870 this.callOptions = CallOptions.create({
12871 args: this.arguments,
12872 callIdentifier: this,
12873 withNew: true
12874 });
12875 };
12876 return NewExpression;
12877}(NodeBase));
12878
12879var SpreadElement = /** @class */ (function (_super) {
12880 __extends(SpreadElement, _super);
12881 function SpreadElement() {
12882 return _super !== null && _super.apply(this, arguments) || this;
12883 }
12884 SpreadElement.prototype.bind = function () {
12885 _super.prototype.bind.call(this);
12886 // Only properties of properties of the argument could become subject to reassignment
12887 // This will also reassign the return values of iterators
12888 this.argument.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
12889 };
12890 return SpreadElement;
12891}(NodeBase));
12892
12893var ObjectExpression = /** @class */ (function (_super) {
12894 __extends(ObjectExpression, _super);
12895 function ObjectExpression() {
12896 return _super !== null && _super.apply(this, arguments) || this;
12897 }
12898 ObjectExpression.prototype.bind = function () {
12899 _super.prototype.bind.call(this);
12900 if (this.propertyMap === null)
12901 this.buildPropertyMap();
12902 };
12903 // We could also track this per-property but this would quickly become much more complex
12904 ObjectExpression.prototype.deoptimizeCache = function () {
12905 if (!this.hasUnknownDeoptimizedProperty)
12906 this.deoptimizeAllProperties();
12907 };
12908 ObjectExpression.prototype.deoptimizePath = function (path) {
12909 if (this.hasUnknownDeoptimizedProperty)
12910 return;
12911 if (this.propertyMap === null)
12912 this.buildPropertyMap();
12913 if (path.length === 0) {
12914 this.deoptimizeAllProperties();
12915 return;
12916 }
12917 var key = path[0];
12918 if (path.length === 1) {
12919 if (typeof key !== 'string') {
12920 this.deoptimizeAllProperties();
12921 return;
12922 }
12923 if (!this.deoptimizedPaths[key]) {
12924 this.deoptimizedPaths[key] = true;
12925 // we only deoptimizeCache exact matches as in all other cases,
12926 // we do not return a literal value or return expression
12927 if (this.expressionsToBeDeoptimized[key]) {
12928 for (var _i = 0, _a = this.expressionsToBeDeoptimized[key]; _i < _a.length; _i++) {
12929 var expression = _a[_i];
12930 expression.deoptimizeCache();
12931 }
12932 }
12933 }
12934 }
12935 var subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
12936 for (var _b = 0, _c = typeof key === 'string'
12937 ? this.propertyMap[key]
12938 ? this.propertyMap[key].propertiesRead
12939 : []
12940 : this.properties; _b < _c.length; _b++) {
12941 var property = _c[_b];
12942 property.deoptimizePath(subPath);
12943 }
12944 };
12945 ObjectExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
12946 if (this.propertyMap === null)
12947 this.buildPropertyMap();
12948 var key = path[0];
12949 if (path.length === 0 ||
12950 this.hasUnknownDeoptimizedProperty ||
12951 typeof key !== 'string' ||
12952 this.deoptimizedPaths[key])
12953 return UNKNOWN_VALUE;
12954 if (path.length === 1 &&
12955 !this.propertyMap[key] &&
12956 !objectMembers[key] &&
12957 this.unmatchablePropertiesRead.length === 0) {
12958 if (!this.expressionsToBeDeoptimized[key]) {
12959 this.expressionsToBeDeoptimized[key] = [origin];
12960 }
12961 else {
12962 this.expressionsToBeDeoptimized[key].push(origin);
12963 }
12964 return undefined;
12965 }
12966 if (!this.propertyMap[key] ||
12967 this.propertyMap[key].exactMatchRead === null ||
12968 this.propertyMap[key].propertiesRead.length > 1)
12969 return UNKNOWN_VALUE;
12970 if (!this.expressionsToBeDeoptimized[key]) {
12971 this.expressionsToBeDeoptimized[key] = [origin];
12972 }
12973 else {
12974 this.expressionsToBeDeoptimized[key].push(origin);
12975 }
12976 return this.propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
12977 };
12978 ObjectExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
12979 if (this.propertyMap === null)
12980 this.buildPropertyMap();
12981 var key = path[0];
12982 if (path.length === 0 ||
12983 this.hasUnknownDeoptimizedProperty ||
12984 typeof key !== 'string' ||
12985 this.deoptimizedPaths[key])
12986 return UNKNOWN_EXPRESSION;
12987 if (path.length === 1 &&
12988 objectMembers[key] &&
12989 this.unmatchablePropertiesRead.length === 0 &&
12990 (!this.propertyMap[key] || this.propertyMap[key].exactMatchRead === null))
12991 return getMemberReturnExpressionWhenCalled(objectMembers, key);
12992 if (!this.propertyMap[key] ||
12993 this.propertyMap[key].exactMatchRead === null ||
12994 this.propertyMap[key].propertiesRead.length > 1)
12995 return UNKNOWN_EXPRESSION;
12996 if (!this.expressionsToBeDeoptimized[key]) {
12997 this.expressionsToBeDeoptimized[key] = [origin];
12998 }
12999 else {
13000 this.expressionsToBeDeoptimized[key].push(origin);
13001 }
13002 return this.propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
13003 };
13004 ObjectExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13005 if (path.length === 0)
13006 return false;
13007 var key = path[0];
13008 if (path.length > 1 &&
13009 (this.hasUnknownDeoptimizedProperty ||
13010 typeof key !== 'string' ||
13011 this.deoptimizedPaths[key] ||
13012 !this.propertyMap[key] ||
13013 this.propertyMap[key].exactMatchRead === null))
13014 return true;
13015 var subPath = path.slice(1);
13016 for (var _i = 0, _a = typeof key !== 'string'
13017 ? this.properties
13018 : this.propertyMap[key]
13019 ? this.propertyMap[key].propertiesRead
13020 : []; _i < _a.length; _i++) {
13021 var property = _a[_i];
13022 if (property.hasEffectsWhenAccessedAtPath(subPath, options))
13023 return true;
13024 }
13025 return false;
13026 };
13027 ObjectExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13028 if (path.length === 0)
13029 return false;
13030 var key = path[0];
13031 if (path.length > 1 &&
13032 (this.hasUnknownDeoptimizedProperty ||
13033 typeof key !== 'string' ||
13034 this.deoptimizedPaths[key] ||
13035 !this.propertyMap[key] ||
13036 this.propertyMap[key].exactMatchRead === null))
13037 return true;
13038 var subPath = path.slice(1);
13039 for (var _i = 0, _a = typeof key !== 'string'
13040 ? this.properties
13041 : path.length > 1
13042 ? this.propertyMap[key].propertiesRead
13043 : this.propertyMap[key]
13044 ? this.propertyMap[key].propertiesSet
13045 : []; _i < _a.length; _i++) {
13046 var property = _a[_i];
13047 if (property.hasEffectsWhenAssignedAtPath(subPath, options))
13048 return true;
13049 }
13050 return false;
13051 };
13052 ObjectExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
13053 var key = path[0];
13054 if (path.length === 0 ||
13055 this.hasUnknownDeoptimizedProperty ||
13056 typeof key !== 'string' ||
13057 this.deoptimizedPaths[key] ||
13058 (this.propertyMap[key]
13059 ? !this.propertyMap[key].exactMatchRead
13060 : path.length > 1 || !objectMembers[key]))
13061 return true;
13062 var subPath = path.slice(1);
13063 for (var _i = 0, _a = this.propertyMap[key] ? this.propertyMap[key].propertiesRead : []; _i < _a.length; _i++) {
13064 var property = _a[_i];
13065 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, options))
13066 return true;
13067 }
13068 if (path.length === 1 && objectMembers[key])
13069 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, options);
13070 return false;
13071 };
13072 ObjectExpression.prototype.initialise = function () {
13073 this.included = false;
13074 this.hasUnknownDeoptimizedProperty = false;
13075 this.deoptimizedPaths = Object.create(null);
13076 this.propertyMap = null;
13077 this.expressionsToBeDeoptimized = Object.create(null);
13078 };
13079 ObjectExpression.prototype.render = function (code, options, _a) {
13080 var renderedParentType = (_a === void 0 ? BLANK : _a).renderedParentType;
13081 _super.prototype.render.call(this, code, options);
13082 if (renderedParentType === ExpressionStatement) {
13083 code.appendRight(this.start, '(');
13084 code.prependLeft(this.end, ')');
13085 }
13086 };
13087 ObjectExpression.prototype.buildPropertyMap = function () {
13088 var _a, _b;
13089 this.propertyMap = Object.create(null);
13090 this.unmatchablePropertiesRead = [];
13091 this.unmatchablePropertiesWrite = [];
13092 for (var index = this.properties.length - 1; index >= 0; index--) {
13093 var property = this.properties[index];
13094 if (property instanceof SpreadElement) {
13095 this.unmatchablePropertiesRead.push(property);
13096 continue;
13097 }
13098 var isWrite = property.kind !== 'get';
13099 var isRead = property.kind !== 'set';
13100 var key = void 0;
13101 if (property.computed) {
13102 var keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
13103 if (keyValue === UNKNOWN_VALUE) {
13104 if (isRead) {
13105 this.unmatchablePropertiesRead.push(property);
13106 }
13107 else {
13108 this.unmatchablePropertiesWrite.push(property);
13109 }
13110 continue;
13111 }
13112 key = String(keyValue);
13113 }
13114 else if (property.key instanceof Identifier$1) {
13115 key = property.key.name;
13116 }
13117 else {
13118 key = String(property.key.value);
13119 }
13120 var propertyMapProperty = this.propertyMap[key];
13121 if (!propertyMapProperty) {
13122 this.propertyMap[key] = {
13123 exactMatchRead: isRead ? property : null,
13124 exactMatchWrite: isWrite ? property : null,
13125 propertiesRead: isRead ? [property].concat(this.unmatchablePropertiesRead) : [],
13126 propertiesSet: isWrite && !isRead ? [property].concat(this.unmatchablePropertiesWrite) : []
13127 };
13128 continue;
13129 }
13130 if (isRead && propertyMapProperty.exactMatchRead === null) {
13131 propertyMapProperty.exactMatchRead = property;
13132 (_a = propertyMapProperty.propertiesRead).push.apply(_a, [property].concat(this.unmatchablePropertiesRead));
13133 }
13134 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
13135 propertyMapProperty.exactMatchWrite = property;
13136 (_b = propertyMapProperty.propertiesSet).push.apply(_b, [property].concat(this.unmatchablePropertiesWrite));
13137 }
13138 }
13139 };
13140 ObjectExpression.prototype.deoptimizeAllProperties = function () {
13141 this.hasUnknownDeoptimizedProperty = true;
13142 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13143 var property = _a[_i];
13144 property.deoptimizePath(UNKNOWN_PATH);
13145 }
13146 for (var _b = 0, _c = Object.keys(this.expressionsToBeDeoptimized); _b < _c.length; _b++) {
13147 var key = _c[_b];
13148 for (var _d = 0, _e = this.expressionsToBeDeoptimized[key]; _d < _e.length; _d++) {
13149 var expression = _e[_d];
13150 expression.deoptimizeCache();
13151 }
13152 }
13153 };
13154 return ObjectExpression;
13155}(NodeBase));
13156
13157var ObjectPattern = /** @class */ (function (_super) {
13158 __extends(ObjectPattern, _super);
13159 function ObjectPattern() {
13160 return _super !== null && _super.apply(this, arguments) || this;
13161 }
13162 ObjectPattern.prototype.addExportedVariables = function (variables) {
13163 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13164 var property = _a[_i];
13165 if (property.type === Property) {
13166 property.value.addExportedVariables(variables);
13167 }
13168 else {
13169 property.argument.addExportedVariables(variables);
13170 }
13171 }
13172 };
13173 ObjectPattern.prototype.declare = function (kind, init) {
13174 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13175 var property = _a[_i];
13176 property.declare(kind, init);
13177 }
13178 };
13179 ObjectPattern.prototype.deoptimizePath = function (path) {
13180 if (path.length === 0) {
13181 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13182 var property = _a[_i];
13183 property.deoptimizePath(path);
13184 }
13185 }
13186 };
13187 ObjectPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13188 if (path.length > 0)
13189 return true;
13190 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13191 var property = _a[_i];
13192 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
13193 return true;
13194 }
13195 return false;
13196 };
13197 return ObjectPattern;
13198}(NodeBase));
13199
13200var Program$1 = /** @class */ (function (_super) {
13201 __extends(Program, _super);
13202 function Program() {
13203 return _super !== null && _super.apply(this, arguments) || this;
13204 }
13205 Program.prototype.hasEffects = function (options) {
13206 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
13207 var node = _a[_i];
13208 if (node.hasEffects(options))
13209 return true;
13210 }
13211 };
13212 Program.prototype.include = function (includeAllChildrenRecursively) {
13213 this.included = true;
13214 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
13215 var node = _a[_i];
13216 if (includeAllChildrenRecursively || node.shouldBeIncluded()) {
13217 node.include(includeAllChildrenRecursively);
13218 }
13219 }
13220 };
13221 Program.prototype.render = function (code, options) {
13222 if (this.body.length) {
13223 renderStatementList(this.body, code, this.start, this.end, options);
13224 }
13225 else {
13226 _super.prototype.render.call(this, code, options);
13227 }
13228 };
13229 return Program;
13230}(NodeBase));
13231
13232var Property$1 = /** @class */ (function (_super) {
13233 __extends(Property, _super);
13234 function Property() {
13235 var _this = _super !== null && _super.apply(this, arguments) || this;
13236 _this.declarationInit = null;
13237 return _this;
13238 }
13239 Property.prototype.bind = function () {
13240 _super.prototype.bind.call(this);
13241 if (this.kind === 'get' && this.returnExpression === null)
13242 this.updateReturnExpression();
13243 if (this.declarationInit !== null) {
13244 this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
13245 }
13246 };
13247 Property.prototype.declare = function (kind, init) {
13248 this.declarationInit = init;
13249 this.value.declare(kind, UNKNOWN_EXPRESSION);
13250 };
13251 Property.prototype.deoptimizeCache = function () {
13252 // As getter properties directly receive their values from function expressions that always
13253 // have a fixed return value, there is no known situation where a getter is deoptimized.
13254 throw new Error('Unexpected deoptimization');
13255 };
13256 Property.prototype.deoptimizePath = function (path) {
13257 if (this.kind === 'get') {
13258 if (path.length > 0) {
13259 if (this.returnExpression === null)
13260 this.updateReturnExpression();
13261 this.returnExpression.deoptimizePath(path);
13262 }
13263 }
13264 else if (this.kind !== 'set') {
13265 this.value.deoptimizePath(path);
13266 }
13267 };
13268 Property.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13269 if (this.kind === 'set') {
13270 return UNKNOWN_VALUE;
13271 }
13272 if (this.kind === 'get') {
13273 if (this.returnExpression === null)
13274 this.updateReturnExpression();
13275 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
13276 }
13277 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
13278 };
13279 Property.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
13280 if (this.kind === 'set') {
13281 return UNKNOWN_EXPRESSION;
13282 }
13283 if (this.kind === 'get') {
13284 if (this.returnExpression === null)
13285 this.updateReturnExpression();
13286 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
13287 }
13288 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
13289 };
13290 Property.prototype.hasEffects = function (options) {
13291 return this.key.hasEffects(options) || this.value.hasEffects(options);
13292 };
13293 Property.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13294 if (this.kind === 'get') {
13295 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()) ||
13296 (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, options)));
13297 }
13298 return this.value.hasEffectsWhenAccessedAtPath(path, options);
13299 };
13300 Property.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13301 if (this.kind === 'get') {
13302 return path.length === 0 || this.returnExpression.hasEffectsWhenAssignedAtPath(path, options);
13303 }
13304 if (this.kind === 'set') {
13305 return (path.length > 0 ||
13306 this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()));
13307 }
13308 return this.value.hasEffectsWhenAssignedAtPath(path, options);
13309 };
13310 Property.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
13311 if (this.kind === 'get') {
13312 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options);
13313 }
13314 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, options);
13315 };
13316 Property.prototype.initialise = function () {
13317 this.included = false;
13318 this.returnExpression = null;
13319 this.accessorCallOptions = CallOptions.create({
13320 callIdentifier: this,
13321 withNew: false
13322 });
13323 };
13324 Property.prototype.render = function (code, options) {
13325 if (!this.shorthand) {
13326 this.key.render(code, options);
13327 }
13328 this.value.render(code, options, { isShorthandProperty: this.shorthand });
13329 };
13330 Property.prototype.updateReturnExpression = function () {
13331 this.returnExpression = UNKNOWN_EXPRESSION;
13332 this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
13333 };
13334 return Property;
13335}(NodeBase));
13336
13337var RestElement = /** @class */ (function (_super) {
13338 __extends(RestElement, _super);
13339 function RestElement() {
13340 var _this = _super !== null && _super.apply(this, arguments) || this;
13341 _this.declarationInit = null;
13342 return _this;
13343 }
13344 RestElement.prototype.addExportedVariables = function (variables) {
13345 this.argument.addExportedVariables(variables);
13346 };
13347 RestElement.prototype.bind = function () {
13348 _super.prototype.bind.call(this);
13349 if (this.declarationInit !== null) {
13350 this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
13351 }
13352 };
13353 RestElement.prototype.declare = function (kind, init) {
13354 this.argument.declare(kind, UNKNOWN_EXPRESSION);
13355 this.declarationInit = init;
13356 };
13357 RestElement.prototype.deoptimizePath = function (path) {
13358 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
13359 };
13360 RestElement.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13361 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
13362 };
13363 return RestElement;
13364}(NodeBase));
13365
13366var ReturnStatement$1 = /** @class */ (function (_super) {
13367 __extends(ReturnStatement, _super);
13368 function ReturnStatement() {
13369 return _super !== null && _super.apply(this, arguments) || this;
13370 }
13371 ReturnStatement.prototype.hasEffects = function (options) {
13372 return (!options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)));
13373 };
13374 ReturnStatement.prototype.initialise = function () {
13375 this.included = false;
13376 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
13377 };
13378 ReturnStatement.prototype.render = function (code, options) {
13379 if (this.argument) {
13380 this.argument.render(code, options);
13381 if (this.argument.start === this.start + 6 /* 'return'.length */) {
13382 code.prependLeft(this.start + 6, ' ');
13383 }
13384 }
13385 };
13386 return ReturnStatement;
13387}(NodeBase));
13388
13389var SequenceExpression = /** @class */ (function (_super) {
13390 __extends(SequenceExpression, _super);
13391 function SequenceExpression() {
13392 return _super !== null && _super.apply(this, arguments) || this;
13393 }
13394 SequenceExpression.prototype.deoptimizePath = function (path) {
13395 if (path.length > 0)
13396 this.expressions[this.expressions.length - 1].deoptimizePath(path);
13397 };
13398 SequenceExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13399 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
13400 };
13401 SequenceExpression.prototype.hasEffects = function (options) {
13402 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
13403 var expression = _a[_i];
13404 if (expression.hasEffects(options))
13405 return true;
13406 }
13407 return false;
13408 };
13409 SequenceExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13410 return (path.length > 0 &&
13411 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, options));
13412 };
13413 SequenceExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13414 return (path.length === 0 ||
13415 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, options));
13416 };
13417 SequenceExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
13418 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, options);
13419 };
13420 SequenceExpression.prototype.include = function (includeAllChildrenRecursively) {
13421 this.included = true;
13422 for (var i = 0; i < this.expressions.length - 1; i++) {
13423 var node = this.expressions[i];
13424 if (includeAllChildrenRecursively || node.shouldBeIncluded())
13425 node.include(includeAllChildrenRecursively);
13426 }
13427 this.expressions[this.expressions.length - 1].include(includeAllChildrenRecursively);
13428 };
13429 SequenceExpression.prototype.render = function (code, options, _a) {
13430 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
13431 var firstStart = 0, lastEnd, includedNodes = 0;
13432 for (var _i = 0, _c = getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end); _i < _c.length; _i++) {
13433 var _d = _c[_i], node = _d.node, start = _d.start, end = _d.end;
13434 if (!node.included) {
13435 treeshakeNode(node, code, start, end);
13436 continue;
13437 }
13438 includedNodes++;
13439 if (firstStart === 0)
13440 firstStart = start;
13441 lastEnd = end;
13442 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
13443 node.render(code, options, {
13444 isCalleeOfRenderedParent: renderedParentType
13445 ? isCalleeOfRenderedParent
13446 : this.parent.callee === this,
13447 renderedParentType: renderedParentType || this.parent.type
13448 });
13449 }
13450 else {
13451 node.render(code, options);
13452 }
13453 }
13454 // Round brackets are part of the actual parent and should be re-added in case the parent changed
13455 if (includedNodes > 1 && renderedParentType) {
13456 code.prependRight(firstStart, '(');
13457 code.appendLeft(lastEnd, ')');
13458 }
13459 };
13460 return SequenceExpression;
13461}(NodeBase));
13462
13463var SwitchCase = /** @class */ (function (_super) {
13464 __extends(SwitchCase, _super);
13465 function SwitchCase() {
13466 return _super !== null && _super.apply(this, arguments) || this;
13467 }
13468 SwitchCase.prototype.include = function (includeAllChildrenRecursively) {
13469 this.included = true;
13470 if (this.test)
13471 this.test.include(includeAllChildrenRecursively);
13472 for (var _i = 0, _a = this.consequent; _i < _a.length; _i++) {
13473 var node = _a[_i];
13474 if (includeAllChildrenRecursively || node.shouldBeIncluded())
13475 node.include(includeAllChildrenRecursively);
13476 }
13477 };
13478 SwitchCase.prototype.render = function (code, options) {
13479 if (this.consequent.length) {
13480 this.test && this.test.render(code, options);
13481 var testEnd = this.test
13482 ? this.test.end
13483 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
13484 var consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
13485 renderStatementList(this.consequent, code, consequentStart, this.end, options);
13486 }
13487 else {
13488 _super.prototype.render.call(this, code, options);
13489 }
13490 };
13491 return SwitchCase;
13492}(NodeBase));
13493
13494var SwitchStatement = /** @class */ (function (_super) {
13495 __extends(SwitchStatement, _super);
13496 function SwitchStatement() {
13497 return _super !== null && _super.apply(this, arguments) || this;
13498 }
13499 SwitchStatement.prototype.createScope = function (parentScope) {
13500 this.scope = new BlockScope(parentScope);
13501 };
13502 SwitchStatement.prototype.hasEffects = function (options) {
13503 return _super.prototype.hasEffects.call(this, options.setIgnoreBreakStatements());
13504 };
13505 return SwitchStatement;
13506}(NodeBase));
13507
13508var TaggedTemplateExpression = /** @class */ (function (_super) {
13509 __extends(TaggedTemplateExpression, _super);
13510 function TaggedTemplateExpression() {
13511 return _super !== null && _super.apply(this, arguments) || this;
13512 }
13513 TaggedTemplateExpression.prototype.bind = function () {
13514 _super.prototype.bind.call(this);
13515 if (this.tag.type === Identifier) {
13516 var variable = this.scope.findVariable(this.tag.name);
13517 if (variable.isNamespace) {
13518 this.context.error({
13519 code: 'CANNOT_CALL_NAMESPACE',
13520 message: "Cannot call a namespace ('" + this.tag.name + "')"
13521 }, this.start);
13522 }
13523 if (this.tag.name === 'eval') {
13524 this.context.warn({
13525 code: 'EVAL',
13526 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
13527 url: 'https://rollupjs.org/guide/en#avoiding-eval'
13528 }, this.start);
13529 }
13530 }
13531 };
13532 TaggedTemplateExpression.prototype.hasEffects = function (options) {
13533 return (_super.prototype.hasEffects.call(this, options) ||
13534 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
13535 };
13536 TaggedTemplateExpression.prototype.initialise = function () {
13537 this.included = false;
13538 this.callOptions = CallOptions.create({
13539 callIdentifier: this,
13540 withNew: false
13541 });
13542 };
13543 return TaggedTemplateExpression;
13544}(NodeBase));
13545
13546var TemplateElement = /** @class */ (function (_super) {
13547 __extends(TemplateElement, _super);
13548 function TemplateElement() {
13549 return _super !== null && _super.apply(this, arguments) || this;
13550 }
13551 TemplateElement.prototype.hasEffects = function (_options) {
13552 return false;
13553 };
13554 return TemplateElement;
13555}(NodeBase));
13556
13557function isTemplateLiteral(node) {
13558 return node.type === TemplateLiteral;
13559}
13560var TemplateLiteral$1 = /** @class */ (function (_super) {
13561 __extends(TemplateLiteral, _super);
13562 function TemplateLiteral() {
13563 return _super !== null && _super.apply(this, arguments) || this;
13564 }
13565 TemplateLiteral.prototype.getLiteralValueAtPath = function (path) {
13566 if (path.length > 0 || this.quasis.length !== 1) {
13567 return UNKNOWN_VALUE;
13568 }
13569 return this.quasis[0].value.cooked;
13570 };
13571 TemplateLiteral.prototype.render = function (code, options) {
13572 code.indentExclusionRanges.push([this.start, this.end]);
13573 _super.prototype.render.call(this, code, options);
13574 };
13575 return TemplateLiteral;
13576}(NodeBase));
13577
13578var ModuleScope = /** @class */ (function (_super) {
13579 __extends(ModuleScope, _super);
13580 function ModuleScope(parent, context) {
13581 var _this = _super.call(this, parent) || this;
13582 _this.context = context;
13583 _this.variables.this = new LocalVariable('this', null, UNDEFINED_EXPRESSION, context);
13584 return _this;
13585 }
13586 ModuleScope.prototype.addExportDefaultDeclaration = function (name, exportDefaultDeclaration, context) {
13587 return (this.variables.default = new ExportDefaultVariable(name, exportDefaultDeclaration, context));
13588 };
13589 ModuleScope.prototype.addNamespaceMemberAccess = function (_name, variable) {
13590 if (variable instanceof GlobalVariable) {
13591 this.accessedOutsideVariables[variable.name] = variable;
13592 }
13593 };
13594 ModuleScope.prototype.deconflict = function (forbiddenNames) {
13595 // all module level variables are already deconflicted when deconflicting the chunk
13596 for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
13597 var scope = _a[_i];
13598 scope.deconflict(forbiddenNames);
13599 }
13600 };
13601 ModuleScope.prototype.findLexicalBoundary = function () {
13602 return this;
13603 };
13604 ModuleScope.prototype.findVariable = function (name) {
13605 var knownVariable = this.variables[name] || this.accessedOutsideVariables[name];
13606 if (knownVariable) {
13607 return knownVariable;
13608 }
13609 var variable = this.context.traceVariable(name) || this.parent.findVariable(name);
13610 if (variable instanceof GlobalVariable) {
13611 this.accessedOutsideVariables[name] = variable;
13612 }
13613 return variable;
13614 };
13615 return ModuleScope;
13616}(ChildScope));
13617
13618var ThisExpression = /** @class */ (function (_super) {
13619 __extends(ThisExpression, _super);
13620 function ThisExpression() {
13621 return _super !== null && _super.apply(this, arguments) || this;
13622 }
13623 ThisExpression.prototype.bind = function () {
13624 _super.prototype.bind.call(this);
13625 this.variable = this.scope.findVariable('this');
13626 };
13627 ThisExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13628 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, options);
13629 };
13630 ThisExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13631 return this.variable.hasEffectsWhenAssignedAtPath(path, options);
13632 };
13633 ThisExpression.prototype.initialise = function () {
13634 this.included = false;
13635 this.variable = null;
13636 this.alias =
13637 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
13638 if (this.alias === 'undefined') {
13639 this.context.warn({
13640 code: 'THIS_IS_UNDEFINED',
13641 message: "The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten",
13642 url: "https://rollupjs.org/guide/en#error-this-is-undefined"
13643 }, this.start);
13644 }
13645 };
13646 ThisExpression.prototype.render = function (code, _options) {
13647 if (this.alias !== null) {
13648 code.overwrite(this.start, this.end, this.alias, {
13649 contentOnly: false,
13650 storeName: true
13651 });
13652 }
13653 };
13654 return ThisExpression;
13655}(NodeBase));
13656
13657var ThrowStatement = /** @class */ (function (_super) {
13658 __extends(ThrowStatement, _super);
13659 function ThrowStatement() {
13660 return _super !== null && _super.apply(this, arguments) || this;
13661 }
13662 ThrowStatement.prototype.hasEffects = function (_options) {
13663 return true;
13664 };
13665 return ThrowStatement;
13666}(NodeBase));
13667
13668var unaryOperators = {
13669 '!': function (value) { return !value; },
13670 '+': function (value) { return +value; },
13671 '-': function (value) { return -value; },
13672 delete: function () { return UNKNOWN_VALUE; },
13673 typeof: function (value) { return typeof value; },
13674 void: function () { return undefined; },
13675 '~': function (value) { return ~value; }
13676};
13677var UnaryExpression = /** @class */ (function (_super) {
13678 __extends(UnaryExpression, _super);
13679 function UnaryExpression() {
13680 return _super !== null && _super.apply(this, arguments) || this;
13681 }
13682 UnaryExpression.prototype.bind = function () {
13683 _super.prototype.bind.call(this);
13684 if (this.operator === 'delete') {
13685 this.argument.deoptimizePath(EMPTY_PATH);
13686 }
13687 };
13688 UnaryExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13689 if (path.length > 0)
13690 return UNKNOWN_VALUE;
13691 var argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
13692 if (argumentValue === UNKNOWN_VALUE)
13693 return UNKNOWN_VALUE;
13694 return unaryOperators[this.operator](argumentValue);
13695 };
13696 UnaryExpression.prototype.hasEffects = function (options) {
13697 return (this.argument.hasEffects(options) ||
13698 (this.operator === 'delete' &&
13699 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)));
13700 };
13701 UnaryExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
13702 if (this.operator === 'void') {
13703 return path.length > 0;
13704 }
13705 return path.length > 1;
13706 };
13707 return UnaryExpression;
13708}(NodeBase));
13709
13710var UnknownNode = /** @class */ (function (_super) {
13711 __extends(UnknownNode, _super);
13712 function UnknownNode() {
13713 return _super !== null && _super.apply(this, arguments) || this;
13714 }
13715 UnknownNode.prototype.hasEffects = function (_options) {
13716 return true;
13717 };
13718 UnknownNode.prototype.include = function () {
13719 _super.prototype.include.call(this, true);
13720 };
13721 return UnknownNode;
13722}(NodeBase));
13723
13724var UpdateExpression = /** @class */ (function (_super) {
13725 __extends(UpdateExpression, _super);
13726 function UpdateExpression() {
13727 return _super !== null && _super.apply(this, arguments) || this;
13728 }
13729 UpdateExpression.prototype.bind = function () {
13730 _super.prototype.bind.call(this);
13731 this.argument.deoptimizePath(EMPTY_PATH);
13732 if (isIdentifier(this.argument)) {
13733 var variable = this.scope.findVariable(this.argument.name);
13734 variable.isReassigned = true;
13735 }
13736 };
13737 UpdateExpression.prototype.hasEffects = function (options) {
13738 return (this.argument.hasEffects(options) ||
13739 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
13740 };
13741 UpdateExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
13742 return path.length > 1;
13743 };
13744 UpdateExpression.prototype.render = function (code, options) {
13745 this.argument.render(code, options);
13746 var variable = this.argument.variable;
13747 if (options.format === 'system' && variable && variable.exportName) {
13748 var name = variable.getName();
13749 if (this.prefix) {
13750 code.overwrite(this.start, this.end, "exports('" + variable.exportName + "', " + this.operator + name + ")");
13751 }
13752 else {
13753 var op = void 0;
13754 switch (this.operator) {
13755 case '++':
13756 op = name + " + 1";
13757 break;
13758 case '--':
13759 op = name + " - 1";
13760 break;
13761 }
13762 code.overwrite(this.start, this.end, "(exports('" + variable.exportName + "', " + op + "), " + name + this.operator + ")");
13763 }
13764 }
13765 };
13766 return UpdateExpression;
13767}(NodeBase));
13768
13769function isReassignedExportsMember(variable) {
13770 return variable.renderBaseName && variable.exportName && variable.isReassigned;
13771}
13772function areAllDeclarationsIncludedAndNotExported(declarations) {
13773 for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
13774 var declarator = declarations_1[_i];
13775 if (!declarator.included) {
13776 return false;
13777 }
13778 if (declarator.id.type === Identifier) {
13779 if (declarator.id.variable.exportName)
13780 return false;
13781 }
13782 else {
13783 var exportedVariables = [];
13784 declarator.id.addExportedVariables(exportedVariables);
13785 if (exportedVariables.length > 0)
13786 return false;
13787 }
13788 }
13789 return true;
13790}
13791var VariableDeclaration$1 = /** @class */ (function (_super) {
13792 __extends(VariableDeclaration, _super);
13793 function VariableDeclaration() {
13794 return _super !== null && _super.apply(this, arguments) || this;
13795 }
13796 VariableDeclaration.prototype.deoptimizePath = function (_path) {
13797 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13798 var declarator = _a[_i];
13799 declarator.deoptimizePath(EMPTY_PATH);
13800 }
13801 };
13802 VariableDeclaration.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
13803 return false;
13804 };
13805 VariableDeclaration.prototype.include = function (includeAllChildrenRecursively) {
13806 this.included = true;
13807 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13808 var declarator = _a[_i];
13809 if (includeAllChildrenRecursively || declarator.shouldBeIncluded())
13810 declarator.include(includeAllChildrenRecursively);
13811 }
13812 };
13813 VariableDeclaration.prototype.includeWithAllDeclaredVariables = function (includeAllChildrenRecursively) {
13814 this.included = true;
13815 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13816 var declarator = _a[_i];
13817 declarator.include(includeAllChildrenRecursively);
13818 }
13819 };
13820 VariableDeclaration.prototype.initialise = function () {
13821 this.included = false;
13822 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13823 var declarator = _a[_i];
13824 declarator.declareDeclarator(this.kind);
13825 }
13826 };
13827 VariableDeclaration.prototype.render = function (code, options, nodeRenderOptions) {
13828 if (nodeRenderOptions === void 0) { nodeRenderOptions = BLANK; }
13829 if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
13830 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13831 var declarator = _a[_i];
13832 declarator.render(code, options);
13833 }
13834 if (!nodeRenderOptions.isNoStatement &&
13835 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
13836 code.appendLeft(this.end, ';');
13837 }
13838 }
13839 else {
13840 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
13841 }
13842 };
13843 VariableDeclaration.prototype.renderDeclarationEnd = function (code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
13844 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
13845 code.remove(this.end - 1, this.end);
13846 }
13847 if (addSemicolon) {
13848 separatorString += ';';
13849 }
13850 if (lastSeparatorPos !== null) {
13851 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
13852 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
13853 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
13854 actualContentEnd--;
13855 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
13856 actualContentEnd--;
13857 }
13858 }
13859 if (actualContentEnd === lastSeparatorPos + 1) {
13860 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
13861 }
13862 else {
13863 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
13864 code.remove(actualContentEnd, renderedContentEnd);
13865 }
13866 }
13867 else {
13868 code.appendLeft(renderedContentEnd, separatorString);
13869 }
13870 if (systemPatternExports.length > 0) {
13871 code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
13872 }
13873 };
13874 VariableDeclaration.prototype.renderReplacedDeclarations = function (code, options, _a) {
13875 var _b = _a.start, start = _b === void 0 ? this.start : _b, _c = _a.end, end = _c === void 0 ? this.end : _c, isNoStatement = _a.isNoStatement;
13876 var separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
13877 var actualContentEnd, renderedContentEnd;
13878 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
13879 renderedContentEnd = this.start + this.kind.length;
13880 }
13881 else {
13882 renderedContentEnd = separatedNodes[0].start;
13883 }
13884 var lastSeparatorPos = renderedContentEnd - 1;
13885 code.remove(this.start, lastSeparatorPos);
13886 var isInDeclaration = false;
13887 var hasRenderedContent = false;
13888 var separatorString = '', leadingString, nextSeparatorString;
13889 var systemPatternExports = [];
13890 for (var _i = 0, separatedNodes_1 = separatedNodes; _i < separatedNodes_1.length; _i++) {
13891 var _d = separatedNodes_1[_i], node = _d.node, start_1 = _d.start, separator = _d.separator, contentEnd = _d.contentEnd, end_1 = _d.end;
13892 if (!node.included ||
13893 (isIdentifier(node.id) && isReassignedExportsMember(node.id.variable) && node.init === null)) {
13894 code.remove(start_1, end_1);
13895 continue;
13896 }
13897 leadingString = '';
13898 nextSeparatorString = '';
13899 if (isIdentifier(node.id) && isReassignedExportsMember(node.id.variable)) {
13900 if (hasRenderedContent) {
13901 separatorString += ';';
13902 }
13903 isInDeclaration = false;
13904 }
13905 else {
13906 if (options.format === 'system' && node.init !== null) {
13907 if (node.id.type !== Identifier) {
13908 node.id.addExportedVariables(systemPatternExports);
13909 }
13910 else if (node.id.variable.exportName) {
13911 code.prependLeft(code.original.indexOf('=', node.id.end) + 1, " exports('" + (node.id.variable.safeExportName || node.id.variable.exportName) + "',");
13912 nextSeparatorString += ')';
13913 }
13914 }
13915 if (isInDeclaration) {
13916 separatorString += ',';
13917 }
13918 else {
13919 if (hasRenderedContent) {
13920 separatorString += ';';
13921 }
13922 leadingString += this.kind + " ";
13923 isInDeclaration = true;
13924 }
13925 }
13926 if (renderedContentEnd === lastSeparatorPos + 1) {
13927 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
13928 }
13929 else {
13930 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
13931 code.appendLeft(renderedContentEnd, leadingString);
13932 }
13933 node.render(code, options);
13934 actualContentEnd = contentEnd;
13935 renderedContentEnd = end_1;
13936 hasRenderedContent = true;
13937 lastSeparatorPos = separator;
13938 separatorString = nextSeparatorString;
13939 }
13940 if (hasRenderedContent) {
13941 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
13942 }
13943 else {
13944 code.remove(start, end);
13945 }
13946 };
13947 return VariableDeclaration;
13948}(NodeBase));
13949
13950var VariableDeclarator = /** @class */ (function (_super) {
13951 __extends(VariableDeclarator, _super);
13952 function VariableDeclarator() {
13953 return _super !== null && _super.apply(this, arguments) || this;
13954 }
13955 VariableDeclarator.prototype.declareDeclarator = function (kind) {
13956 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
13957 };
13958 VariableDeclarator.prototype.deoptimizePath = function (path) {
13959 this.id.deoptimizePath(path);
13960 };
13961 VariableDeclarator.prototype.render = function (code, options) {
13962 // This can happen for hoisted variables in dead branches
13963 if (this.init !== null && !this.init.included) {
13964 code.remove(this.id.end, this.end);
13965 this.id.render(code, options);
13966 }
13967 else {
13968 _super.prototype.render.call(this, code, options);
13969 }
13970 };
13971 return VariableDeclarator;
13972}(NodeBase));
13973
13974var WhileStatement = /** @class */ (function (_super) {
13975 __extends(WhileStatement, _super);
13976 function WhileStatement() {
13977 return _super !== null && _super.apply(this, arguments) || this;
13978 }
13979 WhileStatement.prototype.hasEffects = function (options) {
13980 return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
13981 };
13982 return WhileStatement;
13983}(NodeBase));
13984
13985var YieldExpression = /** @class */ (function (_super) {
13986 __extends(YieldExpression, _super);
13987 function YieldExpression() {
13988 return _super !== null && _super.apply(this, arguments) || this;
13989 }
13990 YieldExpression.prototype.bind = function () {
13991 _super.prototype.bind.call(this);
13992 if (this.argument !== null) {
13993 this.argument.deoptimizePath(UNKNOWN_PATH);
13994 }
13995 };
13996 YieldExpression.prototype.hasEffects = function (options) {
13997 return (!options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)));
13998 };
13999 YieldExpression.prototype.render = function (code, options) {
14000 if (this.argument) {
14001 this.argument.render(code, options);
14002 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
14003 code.prependLeft(this.start + 5, ' ');
14004 }
14005 }
14006 };
14007 return YieldExpression;
14008}(NodeBase));
14009
14010var nodeConstructors = {
14011 ArrayExpression: ArrayExpression,
14012 ArrayPattern: ArrayPattern,
14013 ArrowFunctionExpression: ArrowFunctionExpression,
14014 AssignmentExpression: AssignmentExpression,
14015 AssignmentPattern: AssignmentPattern,
14016 AwaitExpression: AwaitExpression,
14017 BinaryExpression: BinaryExpression,
14018 BlockStatement: BlockStatement$1,
14019 BreakStatement: BreakStatement,
14020 CallExpression: CallExpression$1,
14021 CatchClause: CatchClause,
14022 ClassBody: ClassBody,
14023 ClassDeclaration: ClassDeclaration$1,
14024 ClassExpression: ClassExpression,
14025 ConditionalExpression: ConditionalExpression,
14026 DoWhileStatement: DoWhileStatement,
14027 EmptyStatement: EmptyStatement,
14028 ExportAllDeclaration: ExportAllDeclaration$1,
14029 ExportDefaultDeclaration: ExportDefaultDeclaration$1,
14030 ExportNamedDeclaration: ExportNamedDeclaration,
14031 ExpressionStatement: ExpressionStatement$1,
14032 ForInStatement: ForInStatement,
14033 ForOfStatement: ForOfStatement,
14034 ForStatement: ForStatement,
14035 FunctionDeclaration: FunctionDeclaration$1,
14036 FunctionExpression: FunctionExpression$1,
14037 Identifier: Identifier$1,
14038 IfStatement: IfStatement,
14039 Import: Import,
14040 ImportDeclaration: ImportDeclaration,
14041 LabeledStatement: LabeledStatement,
14042 Literal: Literal$1,
14043 LogicalExpression: LogicalExpression,
14044 MemberExpression: MemberExpression$1,
14045 MetaProperty: MetaProperty,
14046 MethodDefinition: MethodDefinition,
14047 NewExpression: NewExpression,
14048 ObjectExpression: ObjectExpression,
14049 ObjectPattern: ObjectPattern,
14050 Program: Program$1,
14051 Property: Property$1,
14052 RestElement: RestElement,
14053 ReturnStatement: ReturnStatement$1,
14054 SequenceExpression: SequenceExpression,
14055 SpreadElement: SpreadElement,
14056 SwitchCase: SwitchCase,
14057 SwitchStatement: SwitchStatement,
14058 TaggedTemplateExpression: TaggedTemplateExpression,
14059 TemplateElement: TemplateElement,
14060 TemplateLiteral: TemplateLiteral$1,
14061 ThisExpression: ThisExpression,
14062 ThrowStatement: ThrowStatement,
14063 TryStatement: NodeBase,
14064 UnaryExpression: UnaryExpression,
14065 UnknownNode: UnknownNode,
14066 UpdateExpression: UpdateExpression,
14067 VariableDeclaration: VariableDeclaration$1,
14068 VariableDeclarator: VariableDeclarator,
14069 WhileStatement: WhileStatement,
14070 YieldExpression: YieldExpression
14071};
14072
14073function getOriginalLocation(sourcemapChain, location) {
14074 var filteredSourcemapChain = sourcemapChain.filter(function (sourcemap) { return sourcemap.mappings; });
14075 while (filteredSourcemapChain.length > 0) {
14076 var sourcemap = filteredSourcemapChain.pop();
14077 var line = sourcemap.mappings[location.line - 1];
14078 var locationFound = false;
14079 if (line !== undefined) {
14080 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
14081 var segment = line_1[_i];
14082 if (segment[0] >= location.column) {
14083 if (segment.length < 4)
14084 break;
14085 location = {
14086 column: segment[3],
14087 line: segment[2] + 1,
14088 name: sourcemap.names[segment[4]],
14089 source: sourcemap.sources[segment[1]]
14090 };
14091 locationFound = true;
14092 break;
14093 }
14094 }
14095 }
14096 if (!locationFound) {
14097 throw new Error("Can't resolve original location of error.");
14098 }
14099 }
14100 return location;
14101}
14102
14103// AST walker module for Mozilla Parser API compatible trees
14104
14105function skipThrough(node, st, c) { c(node, st); }
14106function ignore(_node, _st, _c) {}
14107
14108// Node walkers.
14109
14110var base$1 = {};
14111
14112base$1.Program = base$1.BlockStatement = function (node, st, c) {
14113 for (var i = 0, list = node.body; i < list.length; i += 1)
14114 {
14115 var stmt = list[i];
14116
14117 c(stmt, st, "Statement");
14118 }
14119};
14120base$1.Statement = skipThrough;
14121base$1.EmptyStatement = ignore;
14122base$1.ExpressionStatement = base$1.ParenthesizedExpression =
14123 function (node, st, c) { return c(node.expression, st, "Expression"); };
14124base$1.IfStatement = function (node, st, c) {
14125 c(node.test, st, "Expression");
14126 c(node.consequent, st, "Statement");
14127 if (node.alternate) { c(node.alternate, st, "Statement"); }
14128};
14129base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
14130base$1.BreakStatement = base$1.ContinueStatement = ignore;
14131base$1.WithStatement = function (node, st, c) {
14132 c(node.object, st, "Expression");
14133 c(node.body, st, "Statement");
14134};
14135base$1.SwitchStatement = function (node, st, c) {
14136 c(node.discriminant, st, "Expression");
14137 for (var i = 0, list = node.cases; i < list.length; i += 1) {
14138 var cs = list[i];
14139
14140 if (cs.test) { c(cs.test, st, "Expression"); }
14141 for (var i$1 = 0, list$1 = cs.consequent; i$1 < list$1.length; i$1 += 1)
14142 {
14143 var cons = list$1[i$1];
14144
14145 c(cons, st, "Statement");
14146 }
14147 }
14148};
14149base$1.SwitchCase = function (node, st, c) {
14150 if (node.test) { c(node.test, st, "Expression"); }
14151 for (var i = 0, list = node.consequent; i < list.length; i += 1)
14152 {
14153 var cons = list[i];
14154
14155 c(cons, st, "Statement");
14156 }
14157};
14158base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
14159 if (node.argument) { c(node.argument, st, "Expression"); }
14160};
14161base$1.ThrowStatement = base$1.SpreadElement =
14162 function (node, st, c) { return c(node.argument, st, "Expression"); };
14163base$1.TryStatement = function (node, st, c) {
14164 c(node.block, st, "Statement");
14165 if (node.handler) { c(node.handler, st); }
14166 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
14167};
14168base$1.CatchClause = function (node, st, c) {
14169 if (node.param) { c(node.param, st, "Pattern"); }
14170 c(node.body, st, "Statement");
14171};
14172base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
14173 c(node.test, st, "Expression");
14174 c(node.body, st, "Statement");
14175};
14176base$1.ForStatement = function (node, st, c) {
14177 if (node.init) { c(node.init, st, "ForInit"); }
14178 if (node.test) { c(node.test, st, "Expression"); }
14179 if (node.update) { c(node.update, st, "Expression"); }
14180 c(node.body, st, "Statement");
14181};
14182base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
14183 c(node.left, st, "ForInit");
14184 c(node.right, st, "Expression");
14185 c(node.body, st, "Statement");
14186};
14187base$1.ForInit = function (node, st, c) {
14188 if (node.type === "VariableDeclaration") { c(node, st); }
14189 else { c(node, st, "Expression"); }
14190};
14191base$1.DebuggerStatement = ignore;
14192
14193base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
14194base$1.VariableDeclaration = function (node, st, c) {
14195 for (var i = 0, list = node.declarations; i < list.length; i += 1)
14196 {
14197 var decl = list[i];
14198
14199 c(decl, st);
14200 }
14201};
14202base$1.VariableDeclarator = function (node, st, c) {
14203 c(node.id, st, "Pattern");
14204 if (node.init) { c(node.init, st, "Expression"); }
14205};
14206
14207base$1.Function = function (node, st, c) {
14208 if (node.id) { c(node.id, st, "Pattern"); }
14209 for (var i = 0, list = node.params; i < list.length; i += 1)
14210 {
14211 var param = list[i];
14212
14213 c(param, st, "Pattern");
14214 }
14215 c(node.body, st, node.expression ? "Expression" : "Statement");
14216};
14217
14218base$1.Pattern = function (node, st, c) {
14219 if (node.type === "Identifier")
14220 { c(node, st, "VariablePattern"); }
14221 else if (node.type === "MemberExpression")
14222 { c(node, st, "MemberPattern"); }
14223 else
14224 { c(node, st); }
14225};
14226base$1.VariablePattern = ignore;
14227base$1.MemberPattern = skipThrough;
14228base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
14229base$1.ArrayPattern = function (node, st, c) {
14230 for (var i = 0, list = node.elements; i < list.length; i += 1) {
14231 var elt = list[i];
14232
14233 if (elt) { c(elt, st, "Pattern"); }
14234 }
14235};
14236base$1.ObjectPattern = function (node, st, c) {
14237 for (var i = 0, list = node.properties; i < list.length; i += 1) {
14238 var prop = list[i];
14239
14240 if (prop.type === "Property") {
14241 if (prop.computed) { c(prop.key, st, "Expression"); }
14242 c(prop.value, st, "Pattern");
14243 } else if (prop.type === "RestElement") {
14244 c(prop.argument, st, "Pattern");
14245 }
14246 }
14247};
14248
14249base$1.Expression = skipThrough;
14250base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
14251base$1.ArrayExpression = function (node, st, c) {
14252 for (var i = 0, list = node.elements; i < list.length; i += 1) {
14253 var elt = list[i];
14254
14255 if (elt) { c(elt, st, "Expression"); }
14256 }
14257};
14258base$1.ObjectExpression = function (node, st, c) {
14259 for (var i = 0, list = node.properties; i < list.length; i += 1)
14260 {
14261 var prop = list[i];
14262
14263 c(prop, st);
14264 }
14265};
14266base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
14267base$1.SequenceExpression = function (node, st, c) {
14268 for (var i = 0, list = node.expressions; i < list.length; i += 1)
14269 {
14270 var expr = list[i];
14271
14272 c(expr, st, "Expression");
14273 }
14274};
14275base$1.TemplateLiteral = function (node, st, c) {
14276 for (var i = 0, list = node.quasis; i < list.length; i += 1)
14277 {
14278 var quasi = list[i];
14279
14280 c(quasi, st);
14281 }
14282
14283 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
14284 {
14285 var expr = list$1[i$1];
14286
14287 c(expr, st, "Expression");
14288 }
14289};
14290base$1.TemplateElement = ignore;
14291base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
14292 c(node.argument, st, "Expression");
14293};
14294base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
14295 c(node.left, st, "Expression");
14296 c(node.right, st, "Expression");
14297};
14298base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
14299 c(node.left, st, "Pattern");
14300 c(node.right, st, "Expression");
14301};
14302base$1.ConditionalExpression = function (node, st, c) {
14303 c(node.test, st, "Expression");
14304 c(node.consequent, st, "Expression");
14305 c(node.alternate, st, "Expression");
14306};
14307base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
14308 c(node.callee, st, "Expression");
14309 if (node.arguments)
14310 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
14311 {
14312 var arg = list[i];
14313
14314 c(arg, st, "Expression");
14315 } }
14316};
14317base$1.MemberExpression = function (node, st, c) {
14318 c(node.object, st, "Expression");
14319 if (node.computed) { c(node.property, st, "Expression"); }
14320};
14321base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
14322 if (node.declaration)
14323 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
14324 if (node.source) { c(node.source, st, "Expression"); }
14325};
14326base$1.ExportAllDeclaration = function (node, st, c) {
14327 c(node.source, st, "Expression");
14328};
14329base$1.ImportDeclaration = function (node, st, c) {
14330 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
14331 {
14332 var spec = list[i];
14333
14334 c(spec, st);
14335 }
14336 c(node.source, st, "Expression");
14337};
14338base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
14339
14340base$1.TaggedTemplateExpression = function (node, st, c) {
14341 c(node.tag, st, "Expression");
14342 c(node.quasi, st, "Expression");
14343};
14344base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
14345base$1.Class = function (node, st, c) {
14346 if (node.id) { c(node.id, st, "Pattern"); }
14347 if (node.superClass) { c(node.superClass, st, "Expression"); }
14348 c(node.body, st);
14349};
14350base$1.ClassBody = function (node, st, c) {
14351 for (var i = 0, list = node.body; i < list.length; i += 1)
14352 {
14353 var elt = list[i];
14354
14355 c(elt, st);
14356 }
14357};
14358base$1.MethodDefinition = base$1.Property = function (node, st, c) {
14359 if (node.computed) { c(node.key, st, "Expression"); }
14360 c(node.value, st, "Expression");
14361};
14362
14363// @ts-ignore
14364function handlePureAnnotationsOfNode(node, state, type) {
14365 if (type === void 0) { type = node.type; }
14366 var commentNode = state.commentNodes[state.commentIndex];
14367 while (commentNode && node.start >= commentNode.end) {
14368 markPureNode(node, commentNode);
14369 commentNode = state.commentNodes[++state.commentIndex];
14370 }
14371 if (commentNode && commentNode.end <= node.end) {
14372 base$1[type](node, state, handlePureAnnotationsOfNode);
14373 }
14374}
14375function markPureNode(node, comment) {
14376 if (node.annotations) {
14377 node.annotations.push(comment);
14378 }
14379 else {
14380 node.annotations = [comment];
14381 }
14382 if (node.type === 'ExpressionStatement') {
14383 node = node.expression;
14384 }
14385 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
14386 node.annotatedPure = true;
14387 }
14388}
14389var pureCommentRegex = /[@#]__PURE__/;
14390var isPureComment = function (comment) { return pureCommentRegex.test(comment.text); };
14391function markPureCallExpressions(comments, esTreeAst) {
14392 handlePureAnnotationsOfNode(esTreeAst, {
14393 commentIndex: 0,
14394 commentNodes: comments.filter(isPureComment)
14395 });
14396}
14397
14398// this looks ridiculous, but it prevents sourcemap tooling from mistaking
14399// this for an actual sourceMappingURL
14400var SOURCEMAPPING_URL = 'sourceMa';
14401SOURCEMAPPING_URL += 'ppingURL';
14402var SOURCEMAPPING_URL_RE = new RegExp("^#\\s+" + SOURCEMAPPING_URL + "=.+\\n?");
14403
14404var NOOP = function () { };
14405var getStartTime = function () { return 0; };
14406var getElapsedTime = function () { return 0; };
14407var getMemory = function () { return 0; };
14408var timers = {};
14409var normalizeHrTime = function (time) { return time[0] * 1e3 + time[1] / 1e6; };
14410function setTimeHelpers() {
14411 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
14412 getStartTime = process.hrtime.bind(process);
14413 getElapsedTime = function (previous) { return normalizeHrTime(process.hrtime(previous)); };
14414 }
14415 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
14416 getStartTime = performance.now.bind(performance);
14417 getElapsedTime = function (previous) { return performance.now() - previous; };
14418 }
14419 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
14420 getMemory = function () { return process.memoryUsage().heapUsed; };
14421 }
14422}
14423function getPersistedLabel(label, level) {
14424 switch (level) {
14425 case 1:
14426 return "# " + label;
14427 case 2:
14428 return "## " + label;
14429 case 3:
14430 return label;
14431 default:
14432 return ' '.repeat(level - 4) + "- " + label;
14433 }
14434}
14435function timeStartImpl(label, level) {
14436 if (level === void 0) { level = 3; }
14437 label = getPersistedLabel(label, level);
14438 if (!timers.hasOwnProperty(label)) {
14439 timers[label] = {
14440 memory: 0,
14441 startMemory: undefined,
14442 startTime: undefined,
14443 time: 0,
14444 totalMemory: 0
14445 };
14446 }
14447 var currentMemory = getMemory();
14448 timers[label].startTime = getStartTime();
14449 timers[label].startMemory = currentMemory;
14450}
14451function timeEndImpl(label, level) {
14452 if (level === void 0) { level = 3; }
14453 label = getPersistedLabel(label, level);
14454 if (timers.hasOwnProperty(label)) {
14455 var currentMemory = getMemory();
14456 timers[label].time += getElapsedTime(timers[label].startTime);
14457 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
14458 timers[label].memory += currentMemory - timers[label].startMemory;
14459 }
14460}
14461function getTimings() {
14462 var newTimings = {};
14463 Object.keys(timers).forEach(function (label) {
14464 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
14465 });
14466 return newTimings;
14467}
14468var timeStart = NOOP, timeEnd = NOOP;
14469var TIMED_PLUGIN_HOOKS = {
14470 load: true,
14471 ongenerate: true,
14472 onwrite: true,
14473 resolveDynamicImport: true,
14474 resolveId: true,
14475 transform: true,
14476 transformBundle: true
14477};
14478function getPluginWithTimers(plugin, index) {
14479 var timedPlugin = {};
14480 var _loop_1 = function (hook) {
14481 if (TIMED_PLUGIN_HOOKS[hook] === true) {
14482 var timerLabel_1 = "plugin " + index;
14483 if (plugin.name) {
14484 timerLabel_1 += " (" + plugin.name + ")";
14485 }
14486 timerLabel_1 += " - " + hook;
14487 timedPlugin[hook] = function () {
14488 timeStart(timerLabel_1, 4);
14489 var result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
14490 timeEnd(timerLabel_1, 4);
14491 if (result && typeof result.then === 'function') {
14492 timeStart(timerLabel_1 + " (async)", 4);
14493 result.then(function () { return timeEnd(timerLabel_1 + " (async)", 4); });
14494 }
14495 return result;
14496 };
14497 }
14498 else {
14499 timedPlugin[hook] = plugin[hook];
14500 }
14501 };
14502 for (var _i = 0, _a = Object.keys(plugin); _i < _a.length; _i++) {
14503 var hook = _a[_i];
14504 _loop_1(hook);
14505 }
14506 return timedPlugin;
14507}
14508function initialiseTimers(inputOptions) {
14509 if (inputOptions.perf) {
14510 timers = {};
14511 setTimeHelpers();
14512 timeStart = timeStartImpl;
14513 timeEnd = timeEndImpl;
14514 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
14515 }
14516 else {
14517 timeStart = NOOP;
14518 timeEnd = NOOP;
14519 }
14520}
14521
14522function visitStaticModuleDependencies(baseModule, areDependenciesSkipped) {
14523 var modules = [baseModule];
14524 var visitedModules = {};
14525 for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
14526 var module = modules_1[_i];
14527 if (areDependenciesSkipped(module) || module instanceof ExternalModule)
14528 continue;
14529 for (var _a = 0, _b = module.dependencies; _a < _b.length; _a++) {
14530 var dependency = _b[_a];
14531 if (!visitedModules[dependency.id]) {
14532 visitedModules[dependency.id] = true;
14533 modules.push(dependency);
14534 }
14535 }
14536 }
14537}
14538
14539var defaultAcornOptions = {
14540 ecmaVersion: 2019,
14541 preserveParens: false,
14542 sourceType: 'module'
14543};
14544function tryParse(module, Parser, acornOptions) {
14545 try {
14546 return Parser.parse(module.code, __assign({}, defaultAcornOptions, acornOptions, { onComment: function (block, text, start, end) {
14547 return module.comments.push({ block: block, text: text, start: start, end: end });
14548 } }));
14549 }
14550 catch (err) {
14551 var message = err.message.replace(/ \(\d+:\d+\)$/, '');
14552 if (module.id.endsWith('.json')) {
14553 message += ' (Note that you need rollup-plugin-json to import JSON files)';
14554 }
14555 else if (!module.id.endsWith('.js')) {
14556 message += ' (Note that you need plugins to import files that are not JavaScript)';
14557 }
14558 module.error({
14559 code: 'PARSE_ERROR',
14560 message: message
14561 }, err.pos);
14562 }
14563}
14564function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
14565 importingModule.error({
14566 code: 'MISSING_EXPORT',
14567 message: "'" + exportName + "' is not exported by " + relativeId(importedModule),
14568 url: "https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-"
14569 }, importerStart);
14570}
14571var MISSING_EXPORT_SHIM_DESCRIPTION = {
14572 localName: MISSING_EXPORT_SHIM_VARIABLE
14573};
14574var Module = /** @class */ (function () {
14575 function Module(graph, id) {
14576 this.chunkAlias = undefined;
14577 this.comments = [];
14578 this.dependencies = [];
14579 this.dynamicallyImportedBy = [];
14580 this.dynamicDependencies = [];
14581 this.dynamicImports = [];
14582 this.entryPointsHash = new Uint8Array(10);
14583 this.execIndex = Infinity;
14584 this.exportAllModules = null;
14585 this.exportAllSources = [];
14586 this.exports = Object.create(null);
14587 this.exportsAll = Object.create(null);
14588 this.exportShimVariable = new ExportShimVariable(this);
14589 this.facadeChunk = null;
14590 this.importDescriptions = Object.create(null);
14591 this.importMetas = [];
14592 this.imports = new Set();
14593 this.isEntryPoint = false;
14594 this.isExecuted = false;
14595 this.reexports = Object.create(null);
14596 this.sources = [];
14597 this.usesTopLevelAwait = false;
14598 this.namespaceVariable = undefined;
14599 this.id = id;
14600 this.graph = graph;
14601 this.excludeFromSourcemap = /\0/.test(id);
14602 this.context = graph.getModuleContext(id);
14603 }
14604 Module.prototype.basename = function () {
14605 var base = basename(this.id);
14606 var ext = extname(this.id);
14607 return makeLegal(ext ? base.slice(0, -ext.length) : base);
14608 };
14609 Module.prototype.bindReferences = function () {
14610 this.ast.bind();
14611 };
14612 Module.prototype.error = function (props, pos) {
14613 if (pos !== undefined) {
14614 props.pos = pos;
14615 var location = locate(this.code, pos, { offsetLine: 1 });
14616 try {
14617 location = getOriginalLocation(this.sourcemapChain, location);
14618 }
14619 catch (e) {
14620 this.warn({
14621 code: 'SOURCEMAP_ERROR',
14622 loc: {
14623 column: location.column,
14624 file: this.id,
14625 line: location.line
14626 },
14627 message: "Error when using sourcemap for reporting an error: " + e.message,
14628 pos: pos
14629 }, undefined);
14630 }
14631 props.loc = {
14632 column: location.column,
14633 file: this.id,
14634 line: location.line
14635 };
14636 props.frame = getCodeFrame(this.originalCode, location.line, location.column);
14637 }
14638 error(props);
14639 };
14640 Module.prototype.getAllExports = function () {
14641 var allExports = Object.assign(Object.create(null), this.exports, this.reexports);
14642 this.exportAllModules.forEach(function (module) {
14643 if (module.isExternal) {
14644 allExports["*" + module.id] = true;
14645 return;
14646 }
14647 for (var _i = 0, _a = module.getAllExports(); _i < _a.length; _i++) {
14648 var name = _a[_i];
14649 if (name !== 'default')
14650 allExports[name] = true;
14651 }
14652 });
14653 return Object.keys(allExports);
14654 };
14655 Module.prototype.getDynamicImportExpressions = function () {
14656 return this.dynamicImports.map(function (_a) {
14657 var node = _a.node;
14658 var importArgument = node.parent.arguments[0];
14659 if (isTemplateLiteral(importArgument)) {
14660 if (importArgument.expressions.length === 0 && importArgument.quasis.length === 1) {
14661 return importArgument.quasis[0].value.cooked;
14662 }
14663 }
14664 else if (isLiteral(importArgument)) {
14665 if (typeof importArgument.value === 'string') {
14666 return importArgument.value;
14667 }
14668 }
14669 else {
14670 return importArgument;
14671 }
14672 });
14673 };
14674 Module.prototype.getExports = function () {
14675 return Object.keys(this.exports);
14676 };
14677 Module.prototype.getOrCreateNamespace = function () {
14678 return (this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext)));
14679 };
14680 Module.prototype.getReexports = function () {
14681 var reexports = Object.create(null);
14682 for (var name in this.reexports) {
14683 reexports[name] = true;
14684 }
14685 this.exportAllModules.forEach(function (module) {
14686 if (module.isExternal) {
14687 reexports["*" + module.id] = true;
14688 return;
14689 }
14690 for (var _i = 0, _a = module.getExports().concat(module.getReexports()); _i < _a.length; _i++) {
14691 var name = _a[_i];
14692 if (name !== 'default')
14693 reexports[name] = true;
14694 }
14695 });
14696 return Object.keys(reexports);
14697 };
14698 Module.prototype.getRenderedExports = function () {
14699 // only direct exports are counted here, not reexports at all
14700 var renderedExports = [];
14701 var removedExports = [];
14702 for (var exportName in this.exports) {
14703 var expt = this.exports[exportName];
14704 (expt.node && expt.node.included ? renderedExports : removedExports).push(exportName);
14705 }
14706 return { renderedExports: renderedExports, removedExports: removedExports };
14707 };
14708 Module.prototype.getVariableForExportName = function (name, isExportAllSearch) {
14709 if (name[0] === '*') {
14710 if (name.length === 1) {
14711 return this.getOrCreateNamespace();
14712 }
14713 else {
14714 // export * from 'external'
14715 var module = this.graph.moduleById.get(name.slice(1));
14716 return module.getVariableForExportName('*');
14717 }
14718 }
14719 // export { foo } from './other'
14720 var reexportDeclaration = this.reexports[name];
14721 if (reexportDeclaration) {
14722 var declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName);
14723 if (!declaration) {
14724 handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
14725 }
14726 return declaration;
14727 }
14728 var exportDeclaration = this.exports[name];
14729 if (exportDeclaration) {
14730 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
14731 return this.exportShimVariable;
14732 }
14733 var name_1 = exportDeclaration.localName;
14734 return this.traceVariable(name_1) || this.graph.scope.findVariable(name_1);
14735 }
14736 if (name !== 'default') {
14737 for (var i = 0; i < this.exportAllModules.length; i += 1) {
14738 var module = this.exportAllModules[i];
14739 var declaration = module.getVariableForExportName(name, true);
14740 if (declaration)
14741 return declaration;
14742 }
14743 }
14744 // we don't want to create shims when we are just
14745 // probing export * modules for exports
14746 if (this.graph.shimMissingExports && !isExportAllSearch) {
14747 this.shimMissingExport(name);
14748 return this.exportShimVariable;
14749 }
14750 };
14751 Module.prototype.include = function () {
14752 if (this.ast.shouldBeIncluded())
14753 this.ast.include(false);
14754 };
14755 Module.prototype.includeAllExports = function () {
14756 if (!this.isExecuted) {
14757 this.graph.needsTreeshakingPass = true;
14758 visitStaticModuleDependencies(this, function (module) {
14759 if (module instanceof ExternalModule || module.isExecuted)
14760 return true;
14761 module.isExecuted = true;
14762 return false;
14763 });
14764 }
14765 for (var _i = 0, _a = this.getExports(); _i < _a.length; _i++) {
14766 var exportName = _a[_i];
14767 var variable = this.getVariableForExportName(exportName);
14768 variable.deoptimizePath(UNKNOWN_PATH);
14769 if (!variable.included) {
14770 variable.include();
14771 this.graph.needsTreeshakingPass = true;
14772 }
14773 }
14774 for (var _b = 0, _c = this.getReexports(); _b < _c.length; _b++) {
14775 var name = _c[_b];
14776 var variable = this.getVariableForExportName(name);
14777 if (variable.isExternal) {
14778 variable.reexported = variable.module.reexported = true;
14779 }
14780 else if (!variable.included) {
14781 variable.include();
14782 variable.deoptimizePath(UNKNOWN_PATH);
14783 this.graph.needsTreeshakingPass = true;
14784 }
14785 }
14786 };
14787 Module.prototype.includeAllInBundle = function () {
14788 this.ast.include(true);
14789 };
14790 Module.prototype.isIncluded = function () {
14791 return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
14792 };
14793 Module.prototype.linkDependencies = function () {
14794 var _this = this;
14795 for (var _i = 0, _a = this.sources; _i < _a.length; _i++) {
14796 var source = _a[_i];
14797 var id = this.resolvedIds[source].id;
14798 if (id) {
14799 var module = this.graph.moduleById.get(id);
14800 this.dependencies.push(module);
14801 }
14802 }
14803 for (var _b = 0, _c = this.dynamicImports; _b < _c.length; _b++) {
14804 var resolution = _c[_b].resolution;
14805 if (resolution instanceof Module || resolution instanceof ExternalModule) {
14806 this.dynamicDependencies.push(resolution);
14807 }
14808 }
14809 this.addModulesToSpecifiers(this.importDescriptions);
14810 this.addModulesToSpecifiers(this.reexports);
14811 this.exportAllModules = this.exportAllSources.map(function (source) {
14812 var id = _this.resolvedIds[source].id;
14813 return _this.graph.moduleById.get(id);
14814 });
14815 };
14816 Module.prototype.render = function (options) {
14817 var magicString = this.magicString.clone();
14818 this.ast.render(magicString, options);
14819 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
14820 return magicString;
14821 };
14822 Module.prototype.setSource = function (_a) {
14823 var _this = this;
14824 var code = _a.code, originalCode = _a.originalCode, originalSourcemap = _a.originalSourcemap, ast = _a.ast, sourcemapChain = _a.sourcemapChain, resolvedIds = _a.resolvedIds, transformDependencies = _a.transformDependencies, customTransformCache = _a.customTransformCache;
14825 this.code = code;
14826 this.originalCode = originalCode;
14827 this.originalSourcemap = originalSourcemap;
14828 this.sourcemapChain = sourcemapChain;
14829 this.transformDependencies = transformDependencies;
14830 this.customTransformCache = customTransformCache;
14831 timeStart('generate ast', 3);
14832 this.esTreeAst = ((ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions)));
14833 markPureCallExpressions(this.comments, this.esTreeAst);
14834 timeEnd('generate ast', 3);
14835 this.resolvedIds = resolvedIds || Object.create(null);
14836 // By default, `id` is the filename. Custom resolvers and loaders
14837 // can change that, but it makes sense to use it for the source filename
14838 var fileName = this.id;
14839 this.magicString = new MagicString(code, {
14840 filename: this.excludeFromSourcemap ? null : fileName,
14841 indentExclusionRanges: []
14842 });
14843 this.removeExistingSourceMap();
14844 timeStart('analyse ast', 3);
14845 this.astContext = {
14846 addDynamicImport: this.addDynamicImport.bind(this),
14847 addExport: this.addExport.bind(this),
14848 addImport: this.addImport.bind(this),
14849 addImportMeta: this.addImportMeta.bind(this),
14850 annotations: this.graph.treeshake && this.graph.treeshakingOptions.annotations,
14851 code: code,
14852 deoptimizationTracker: this.graph.deoptimizationTracker,
14853 error: this.error.bind(this),
14854 fileName: fileName,
14855 getAssetFileName: this.graph.pluginDriver.getAssetFileName,
14856 getExports: this.getExports.bind(this),
14857 getModuleExecIndex: function () { return _this.execIndex; },
14858 getModuleName: this.basename.bind(this),
14859 getReexports: this.getReexports.bind(this),
14860 importDescriptions: this.importDescriptions,
14861 includeDynamicImport: this.includeDynamicImport.bind(this),
14862 includeVariable: this.includeVariable.bind(this),
14863 isCrossChunkImport: function (importDescription) { return importDescription.module.chunk !== _this.chunk; },
14864 magicString: this.magicString,
14865 module: this,
14866 moduleContext: this.context,
14867 nodeConstructors: nodeConstructors,
14868 preserveModules: this.graph.preserveModules,
14869 propertyReadSideEffects: !this.graph.treeshake || this.graph.treeshakingOptions.propertyReadSideEffects,
14870 traceExport: this.getVariableForExportName.bind(this),
14871 traceVariable: this.traceVariable.bind(this),
14872 treeshake: this.graph.treeshake,
14873 usesTopLevelAwait: false,
14874 warn: this.warn.bind(this)
14875 };
14876 this.scope = new ModuleScope(this.graph.scope, this.astContext);
14877 this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
14878 timeEnd('analyse ast', 3);
14879 };
14880 Module.prototype.toJSON = function () {
14881 return {
14882 ast: this.esTreeAst,
14883 code: this.code,
14884 customTransformCache: this.customTransformCache,
14885 dependencies: this.dependencies.map(function (module) { return module.id; }),
14886 id: this.id,
14887 originalCode: this.originalCode,
14888 originalSourcemap: this.originalSourcemap,
14889 resolvedIds: this.resolvedIds,
14890 sourcemapChain: this.sourcemapChain,
14891 transformAssets: this.transformAssets,
14892 transformDependencies: this.transformDependencies
14893 };
14894 };
14895 Module.prototype.traceVariable = function (name) {
14896 if (name in this.scope.variables) {
14897 return this.scope.variables[name];
14898 }
14899 if (name in this.importDescriptions) {
14900 var importDeclaration = this.importDescriptions[name];
14901 var otherModule = importDeclaration.module;
14902 if (!otherModule.isExternal && importDeclaration.name === '*') {
14903 return otherModule.getOrCreateNamespace();
14904 }
14905 var declaration = otherModule.getVariableForExportName(importDeclaration.name);
14906 if (!declaration) {
14907 handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
14908 }
14909 return declaration;
14910 }
14911 return null;
14912 };
14913 Module.prototype.warn = function (warning, pos) {
14914 if (pos !== undefined) {
14915 warning.pos = pos;
14916 var _a = locate(this.code, pos, { offsetLine: 1 }), line = _a.line, column = _a.column; // TODO trace sourcemaps, cf. error()
14917 warning.loc = { file: this.id, line: line, column: column };
14918 warning.frame = getCodeFrame(this.code, line, column);
14919 }
14920 warning.id = this.id;
14921 this.graph.warn(warning);
14922 };
14923 Module.prototype.addDynamicImport = function (node) {
14924 this.dynamicImports.push({ node: node, alias: undefined, resolution: undefined });
14925 };
14926 Module.prototype.addExport = function (node) {
14927 var source = node.source && node.source.value;
14928 // export { name } from './other'
14929 if (source) {
14930 if (this.sources.indexOf(source) === -1)
14931 this.sources.push(source);
14932 if (node.type === ExportAllDeclaration) {
14933 // Store `export * from '...'` statements in an array of delegates.
14934 // When an unknown import is encountered, we see if one of them can satisfy it.
14935 this.exportAllSources.push(source);
14936 }
14937 else {
14938 for (var _i = 0, _a = node.specifiers; _i < _a.length; _i++) {
14939 var specifier = _a[_i];
14940 var name = specifier.exported.name;
14941 if (this.exports[name] || this.reexports[name]) {
14942 this.error({
14943 code: 'DUPLICATE_EXPORT',
14944 message: "A module cannot have multiple exports with the same name ('" + name + "')"
14945 }, specifier.start);
14946 }
14947 this.reexports[name] = {
14948 localName: specifier.local.name,
14949 module: null,
14950 source: source,
14951 start: specifier.start
14952 };
14953 }
14954 }
14955 }
14956 else if (isExportDefaultDeclaration(node)) {
14957 // export default function foo () {}
14958 // export default foo;
14959 // export default 42;
14960 if (this.exports.default) {
14961 this.error({
14962 code: 'DUPLICATE_EXPORT',
14963 message: "A module can only have one default export"
14964 }, node.start);
14965 }
14966 this.exports.default = {
14967 identifier: node.variable.getOriginalVariableName(),
14968 localName: 'default',
14969 node: node
14970 };
14971 }
14972 else if (node.declaration) {
14973 // export var { foo, bar } = ...
14974 // export var foo = 42;
14975 // export var a = 1, b = 2, c = 3;
14976 // export function foo () {}
14977 var declaration = node.declaration;
14978 if (declaration.type === VariableDeclaration) {
14979 for (var _b = 0, _c = declaration.declarations; _b < _c.length; _b++) {
14980 var decl = _c[_b];
14981 for (var _d = 0, _e = extractAssignedNames(decl.id); _d < _e.length; _d++) {
14982 var localName = _e[_d];
14983 this.exports[localName] = { localName: localName, node: node };
14984 }
14985 }
14986 }
14987 else {
14988 // export function foo () {}
14989 var localName = declaration.id.name;
14990 this.exports[localName] = { localName: localName, node: node };
14991 }
14992 }
14993 else {
14994 // export { foo, bar, baz }
14995 for (var _f = 0, _g = node.specifiers; _f < _g.length; _f++) {
14996 var specifier = _g[_f];
14997 var localName = specifier.local.name;
14998 var exportedName = specifier.exported.name;
14999 if (this.exports[exportedName] || this.reexports[exportedName]) {
15000 this.error({
15001 code: 'DUPLICATE_EXPORT',
15002 message: "A module cannot have multiple exports with the same name ('" + exportedName + "')"
15003 }, specifier.start);
15004 }
15005 this.exports[exportedName] = { localName: localName, node: node };
15006 }
15007 }
15008 };
15009 Module.prototype.addImport = function (node) {
15010 var source = node.source.value;
15011 if (this.sources.indexOf(source) === -1)
15012 this.sources.push(source);
15013 for (var _i = 0, _a = node.specifiers; _i < _a.length; _i++) {
15014 var specifier = _a[_i];
15015 var localName = specifier.local.name;
15016 if (this.importDescriptions[localName]) {
15017 this.error({
15018 code: 'DUPLICATE_IMPORT',
15019 message: "Duplicated import '" + localName + "'"
15020 }, specifier.start);
15021 }
15022 var isDefault = specifier.type === ImportDefaultSpecifier;
15023 var isNamespace = specifier.type === ImportNamespaceSpecifier;
15024 var name = isDefault
15025 ? 'default'
15026 : isNamespace
15027 ? '*'
15028 : specifier.imported.name;
15029 this.importDescriptions[localName] = { source: source, start: specifier.start, name: name, module: null };
15030 }
15031 };
15032 Module.prototype.addImportMeta = function (node) {
15033 this.importMetas.push(node);
15034 };
15035 Module.prototype.addModulesToSpecifiers = function (specifiers) {
15036 for (var _i = 0, _a = Object.keys(specifiers); _i < _a.length; _i++) {
15037 var name = _a[_i];
15038 var specifier = specifiers[name];
15039 var id = this.resolvedIds[specifier.source].id;
15040 specifier.module = this.graph.moduleById.get(id);
15041 }
15042 };
15043 Module.prototype.includeDynamicImport = function (node) {
15044 var resolution = this.dynamicImports.find(function (dynamicImport) { return dynamicImport.node === node; })
15045 .resolution;
15046 if (resolution instanceof Module) {
15047 resolution.dynamicallyImportedBy.push(this);
15048 resolution.includeAllExports();
15049 }
15050 };
15051 Module.prototype.includeVariable = function (variable) {
15052 if (!variable.included) {
15053 variable.include();
15054 this.graph.needsTreeshakingPass = true;
15055 }
15056 if (variable.module && variable.module !== this) {
15057 this.imports.add(variable);
15058 }
15059 };
15060 Module.prototype.removeExistingSourceMap = function () {
15061 for (var _i = 0, _a = this.comments; _i < _a.length; _i++) {
15062 var comment = _a[_i];
15063 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
15064 this.magicString.remove(comment.start, comment.end);
15065 }
15066 }
15067 };
15068 Module.prototype.shimMissingExport = function (name) {
15069 if (!this.exports[name]) {
15070 this.graph.warn({
15071 code: 'SHIMMED_EXPORT',
15072 exporter: relativeId(this.id),
15073 exportName: name,
15074 message: "Missing export \"" + name + "\" has been shimmed in module " + relativeId(this.id) + "."
15075 });
15076 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
15077 }
15078 };
15079 return Module;
15080}());
15081
15082var Source = /** @class */ (function () {
15083 function Source(filename, content) {
15084 this.isOriginal = true;
15085 this.filename = filename;
15086 this.content = content;
15087 }
15088 Source.prototype.traceSegment = function (line, column, name) {
15089 return { line: line, column: column, name: name, source: this };
15090 };
15091 return Source;
15092}());
15093var Link = /** @class */ (function () {
15094 function Link(map, sources) {
15095 this.sources = sources;
15096 this.names = map.names;
15097 this.mappings = map.mappings;
15098 }
15099 Link.prototype.traceMappings = function () {
15100 var sources = [];
15101 var sourcesContent = [];
15102 var names = [];
15103 var mappings = [];
15104 for (var _i = 0, _a = this.mappings; _i < _a.length; _i++) {
15105 var line = _a[_i];
15106 var tracedLine = [];
15107 for (var _b = 0, line_1 = line; _b < line_1.length; _b++) {
15108 var segment = line_1[_b];
15109 var source = this.sources[segment[1]];
15110 if (!source)
15111 continue;
15112 var traced = source.traceSegment(segment[2], segment[3], this.names[segment[4]]);
15113 if (traced) {
15114 // newer sources are more likely to be used, so search backwards.
15115 var sourceIndex = sources.lastIndexOf(traced.source.filename);
15116 if (sourceIndex === -1) {
15117 sourceIndex = sources.length;
15118 sources.push(traced.source.filename);
15119 sourcesContent[sourceIndex] = traced.source.content;
15120 }
15121 else if (sourcesContent[sourceIndex] == null) {
15122 sourcesContent[sourceIndex] = traced.source.content;
15123 }
15124 else if (traced.source.content != null &&
15125 sourcesContent[sourceIndex] !== traced.source.content) {
15126 error({
15127 message: "Multiple conflicting contents for sourcemap source " + traced.source.filename
15128 });
15129 }
15130 var tracedSegment = [
15131 segment[0],
15132 sourceIndex,
15133 traced.line,
15134 traced.column
15135 ];
15136 if (traced.name) {
15137 var nameIndex = names.indexOf(traced.name);
15138 if (nameIndex === -1) {
15139 nameIndex = names.length;
15140 names.push(traced.name);
15141 }
15142 tracedSegment[4] = nameIndex;
15143 }
15144 tracedLine.push(tracedSegment);
15145 }
15146 }
15147 mappings.push(tracedLine);
15148 }
15149 return { sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings };
15150 };
15151 Link.prototype.traceSegment = function (line, column, name) {
15152 var segments = this.mappings[line];
15153 if (!segments)
15154 return null;
15155 // binary search through segments for the given column
15156 var i = 0;
15157 var j = segments.length - 1;
15158 while (i <= j) {
15159 var m = (i + j) >> 1;
15160 var segment = segments[m];
15161 if (segment[0] === column) {
15162 var source = this.sources[segment[1]];
15163 if (!source)
15164 return null;
15165 return source.traceSegment(segment[2], segment[3], this.names[segment[4]] || name);
15166 }
15167 if (segment[0] > column) {
15168 j = m - 1;
15169 }
15170 else {
15171 i = m + 1;
15172 }
15173 }
15174 return null;
15175 };
15176 return Link;
15177}());
15178// TODO TypeScript: Fix <any> typecasts
15179function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
15180 function linkMap(source, map) {
15181 if (map.missing) {
15182 bundle.graph.warn({
15183 code: 'SOURCEMAP_BROKEN',
15184 message: "Sourcemap is likely to be incorrect: a plugin" + (map.plugin ? " ('" + map.plugin + "')" : "") + " was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help",
15185 plugin: map.plugin,
15186 url: "https://rollupjs.org/guide/en#warning-sourcemap-is-likely-to-be-incorrect"
15187 });
15188 map = {
15189 mappings: '',
15190 names: []
15191 };
15192 }
15193 return new Link(map, [source]);
15194 }
15195 var moduleSources = modules
15196 .filter(function (module) { return !module.excludeFromSourcemap; })
15197 .map(function (module) {
15198 var sourcemapChain = module.sourcemapChain;
15199 var source;
15200 var originalSourcemap = module.originalSourcemap;
15201 if (!originalSourcemap) {
15202 source = new Source(module.id, module.originalCode);
15203 }
15204 else {
15205 var sources_1 = originalSourcemap.sources;
15206 var sourcesContent_1 = originalSourcemap.sourcesContent || [];
15207 if (sources_1 == null || (sources_1.length <= 1 && sources_1[0] == null)) {
15208 source = new Source(module.id, sourcesContent_1[0]);
15209 sourcemapChain = [originalSourcemap].concat(sourcemapChain);
15210 }
15211 else {
15212 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
15213 var directory_1 = dirname(module.id) || '.';
15214 var sourceRoot_1 = originalSourcemap.sourceRoot || '.';
15215 var baseSources = sources_1.map(function (source, i) {
15216 return new Source(resolve$1(directory_1, sourceRoot_1, source), sourcesContent_1[i]);
15217 });
15218 source = new Link(originalSourcemap, baseSources);
15219 }
15220 }
15221 source = sourcemapChain.reduce(linkMap, source);
15222 return source;
15223 });
15224 var source = new Link(map, moduleSources);
15225 source = bundleSourcemapChain.reduce(linkMap, source);
15226 var _a = source.traceMappings(), sources = _a.sources, sourcesContent = _a.sourcesContent, names = _a.names, mappings = _a.mappings;
15227 if (file) {
15228 var directory_2 = dirname(file);
15229 sources = sources.map(function (source) { return relative(directory_2, source); });
15230 file = basename(file);
15231 }
15232 sourcesContent = excludeContent ? null : sourcesContent;
15233 return new SourceMap({ file: file, sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings });
15234}
15235
15236var _a;
15237var RESERVED_NAMES = Object.assign(Object.create(null), {
15238 await: true,
15239 break: true,
15240 case: true,
15241 catch: true,
15242 class: true,
15243 const: true,
15244 continue: true,
15245 debugger: true,
15246 default: true,
15247 delete: true,
15248 do: true,
15249 else: true,
15250 enum: true,
15251 eval: true,
15252 export: true,
15253 extends: true,
15254 finally: true,
15255 for: true,
15256 function: true,
15257 if: true,
15258 implements: true,
15259 import: true,
15260 in: true,
15261 instanceof: true,
15262 interface: true,
15263 let: true,
15264 new: true,
15265 null: true,
15266 package: true,
15267 private: true,
15268 protected: true,
15269 public: true,
15270 return: true,
15271 static: true,
15272 super: true,
15273 switch: true,
15274 throw: true,
15275 try: true,
15276 typeof: true,
15277 undefined: true,
15278 var: true,
15279 void: true,
15280 while: true,
15281 with: true,
15282 yield: true
15283});
15284var NONE = {};
15285var EXPORTS = { exports: true };
15286var RESERVED_NAMES_BY_FORMAT = {
15287 amd: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES },
15288 cjs: {
15289 forbiddenNames: RESERVED_NAMES,
15290 formatGlobals: (_a = { exports: true, module: true }, _a[INTEROP_DEFAULT_VARIABLE] = true, _a)
15291 },
15292 es: { formatGlobals: NONE, forbiddenNames: RESERVED_NAMES },
15293 iife: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES },
15294 system: {
15295 forbiddenNames: Object.assign(Object.create(null), RESERVED_NAMES, EXPORTS),
15296 formatGlobals: NONE
15297 },
15298 umd: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES }
15299};
15300
15301var DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
15302 amd: deconflictImportsOther,
15303 cjs: deconflictImportsOther,
15304 es: deconflictImportsEsm,
15305 iife: deconflictImportsOther,
15306 system: deconflictImportsEsm,
15307 umd: deconflictImportsOther
15308};
15309function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
15310 var _a = RESERVED_NAMES_BY_FORMAT[format], forbiddenNames = _a.forbiddenNames, formatGlobals = _a.formatGlobals;
15311 Object.assign(usedNames, forbiddenNames);
15312 Object.assign(usedNames, formatGlobals);
15313 addUsedGlobalNames(usedNames, modules);
15314 deconflictTopLevelVariables(usedNames, modules);
15315 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
15316 for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
15317 var module = modules_1[_i];
15318 module.scope.deconflict(forbiddenNames);
15319 }
15320}
15321function addUsedGlobalNames(usedNames, modules) {
15322 var accessedGlobals = Object.assign.apply(Object, [{}].concat(modules.map(function (module) { return module.scope.accessedOutsideVariables; })));
15323 for (var _i = 0, _a = Object.keys(accessedGlobals); _i < _a.length; _i++) {
15324 var name = _a[_i];
15325 var variable = accessedGlobals[name];
15326 if (variable.included) {
15327 usedNames[name] = true;
15328 }
15329 }
15330}
15331function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
15332 for (var _i = 0, _a = Array.from(imports); _i < _a.length; _i++) {
15333 var variable = _a[_i];
15334 var module = variable.module;
15335 var name = variable.name;
15336 var proposedName = void 0;
15337 if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
15338 if (name === 'default' && interop && module.exportsNamespace) {
15339 proposedName = module.variableName + '__default';
15340 }
15341 else {
15342 proposedName = module.variableName;
15343 }
15344 }
15345 else {
15346 proposedName = name;
15347 }
15348 variable.setRenderNames(null, getSafeName(proposedName, usedNames));
15349 }
15350}
15351function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
15352 for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
15353 var chunkOrExternalModule = dependencies_1[_i];
15354 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
15355 }
15356 for (var _a = 0, _b = Array.from(imports); _a < _b.length; _a++) {
15357 var variable = _b[_a];
15358 var module = variable.module;
15359 if (module instanceof ExternalModule) {
15360 var name = variable.name;
15361 if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
15362 variable.setRenderNames(null, module.variableName + '__default');
15363 }
15364 else if (name === '*' || name === 'default') {
15365 variable.setRenderNames(null, module.variableName);
15366 }
15367 else {
15368 variable.setRenderNames(module.variableName, null);
15369 }
15370 }
15371 else {
15372 var chunk = module.chunk;
15373 if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
15374 variable.setRenderNames(null, chunk.variableName);
15375 }
15376 else {
15377 variable.setRenderNames(chunk.variableName, module.chunk.getVariableExportName(variable));
15378 }
15379 }
15380 }
15381}
15382function deconflictTopLevelVariables(usedNames, modules) {
15383 for (var _i = 0, modules_2 = modules; _i < modules_2.length; _i++) {
15384 var module = modules_2[_i];
15385 var moduleVariables = module.scope.variables;
15386 for (var _a = 0, _b = Object.keys(moduleVariables); _a < _b.length; _a++) {
15387 var name = _b[_a];
15388 var variable = moduleVariables[name];
15389 if (variable.included &&
15390 // this will only happen for exports in some formats
15391 !(variable.renderBaseName ||
15392 (variable instanceof ExportDefaultVariable && variable.referencesOriginal()))) {
15393 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
15394 }
15395 }
15396 var namespace = module.getOrCreateNamespace();
15397 if (namespace.included) {
15398 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
15399 }
15400 }
15401}
15402
15403var compareExecIndex = function (unitA, unitB) {
15404 return unitA.execIndex > unitB.execIndex ? 1 : -1;
15405};
15406function sortByExecutionOrder(units) {
15407 units.sort(compareExecIndex);
15408}
15409function analyseModuleExecution(entryModules) {
15410 var nextExecIndex = 0;
15411 var inStaticGraph = true;
15412 var cyclePaths = [];
15413 var analysedModules = {};
15414 var orderedModules = [];
15415 var dynamicImports = [];
15416 var parents = {};
15417 var analyseModule = function (module) {
15418 if (analysedModules[module.id])
15419 return;
15420 if (module instanceof ExternalModule) {
15421 module.execIndex = nextExecIndex++;
15422 analysedModules[module.id] = true;
15423 return;
15424 }
15425 if (inStaticGraph) {
15426 module.isExecuted = true;
15427 }
15428 for (var _i = 0, _a = module.dependencies; _i < _a.length; _i++) {
15429 var dependency = _a[_i];
15430 if (dependency.id in parents) {
15431 if (!analysedModules[dependency.id]) {
15432 cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
15433 }
15434 continue;
15435 }
15436 parents[dependency.id] = module.id;
15437 analyseModule(dependency);
15438 }
15439 for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
15440 var resolution = _c[_b].resolution;
15441 if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
15442 dynamicImports.push(resolution);
15443 }
15444 }
15445 module.execIndex = nextExecIndex++;
15446 analysedModules[module.id] = true;
15447 orderedModules.push(module);
15448 };
15449 for (var _i = 0, entryModules_1 = entryModules; _i < entryModules_1.length; _i++) {
15450 var curEntry = entryModules_1[_i];
15451 curEntry.isEntryPoint = true;
15452 if (!parents[curEntry.id]) {
15453 parents[curEntry.id] = null;
15454 analyseModule(curEntry);
15455 }
15456 }
15457 inStaticGraph = false;
15458 for (var _a = 0, dynamicImports_1 = dynamicImports; _a < dynamicImports_1.length; _a++) {
15459 var curEntry = dynamicImports_1[_a];
15460 if (!parents[curEntry.id]) {
15461 parents[curEntry.id] = null;
15462 analyseModule(curEntry);
15463 }
15464 }
15465 return { orderedModules: orderedModules, cyclePaths: cyclePaths };
15466}
15467function getCyclePath(id, parentId, parents) {
15468 var path = [relativeId(id)];
15469 var curId = parentId;
15470 while (curId !== id) {
15471 path.push(relativeId(curId));
15472 curId = parents[curId];
15473 if (!curId)
15474 break;
15475 }
15476 path.push(path[0]);
15477 path.reverse();
15478 return path;
15479}
15480
15481function guessIndentString(code) {
15482 var lines = code.split('\n');
15483 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
15484 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
15485 if (tabbed.length === 0 && spaced.length === 0) {
15486 return null;
15487 }
15488 // More lines tabbed than spaced? Assume tabs, and
15489 // default to tabs in the case of a tie (or nothing
15490 // to go on)
15491 if (tabbed.length >= spaced.length) {
15492 return '\t';
15493 }
15494 // Otherwise, we need to guess the multiple
15495 var min = spaced.reduce(function (previous, current) {
15496 var numSpaces = /^ +/.exec(current)[0].length;
15497 return Math.min(numSpaces, previous);
15498 }, Infinity);
15499 return new Array(min + 1).join(' ');
15500}
15501function getIndentString(modules, options) {
15502 if (options.indent !== true)
15503 return options.indent || '';
15504 for (var i = 0; i < modules.length; i++) {
15505 var indent = guessIndentString(modules[i].originalCode);
15506 if (indent !== null)
15507 return indent;
15508 }
15509 return '\t';
15510}
15511
15512function renderChunk(_a) {
15513 var graph = _a.graph, chunk = _a.chunk, renderChunk = _a.renderChunk, code = _a.code, sourcemapChain = _a.sourcemapChain, options = _a.options;
15514 var renderChunkReducer = function (code, result, plugin) {
15515 if (result == null)
15516 return code;
15517 if (typeof result === 'string')
15518 result = {
15519 code: result,
15520 map: undefined
15521 };
15522 var map = typeof result.map === 'string' ? JSON.parse(result.map) : result.map;
15523 if (map && typeof map.mappings === 'string')
15524 map.mappings = decode(map.mappings);
15525 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
15526 if (map !== null)
15527 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
15528 return result.code;
15529 };
15530 var inTransformBundle = false;
15531 var inRenderChunk = true;
15532 return graph.pluginDriver
15533 .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
15534 .then(function (code) {
15535 inRenderChunk = false;
15536 return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
15537 })
15538 .then(function (code) {
15539 inTransformBundle = true;
15540 return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
15541 })
15542 .catch(function (err) {
15543 if (inRenderChunk)
15544 throw err;
15545 error(err, {
15546 code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
15547 message: "Error transforming " + ((inTransformBundle ? 'bundle' : 'chunk') +
15548 (err.plugin ? " with '" + err.plugin + "' plugin" : '')) + ": " + err.message,
15549 plugin: err.plugin
15550 });
15551 });
15552}
15553
15554function renderNamePattern(pattern, patternName, getReplacement) {
15555 if (!isPlainName(pattern))
15556 error({
15557 code: 'INVALID_PATTERN',
15558 message: "Invalid output pattern \"" + pattern + "\" for " + patternName + ", cannot be an absolute or relative URL or path."
15559 });
15560 return pattern.replace(/\[(\w+)\]/g, function (_match, type) {
15561 var replacement = getReplacement(type);
15562 if (replacement === undefined)
15563 error({
15564 code: 'INVALID_PATTERN_REPLACEMENT',
15565 message: "\"" + type + "\" is not a valid substitution name in output option " + patternName + " pattern."
15566 });
15567 if (!isPlainName(replacement))
15568 error({
15569 code: 'INVALID_PATTERN_REPLACEMENT',
15570 message: "Invalid replacement \"" + replacement + "\" for \"" + type + "\" in " + patternName + " pattern, must be a plain path name."
15571 });
15572 return replacement;
15573 });
15574}
15575function makeUnique(name, existingNames) {
15576 if (name in existingNames === false)
15577 return name;
15578 var ext = extname(name);
15579 name = name.substr(0, name.length - ext.length);
15580 var uniqueName, uniqueIndex = 1;
15581 while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
15582 ;
15583 return uniqueName;
15584}
15585
15586function sanitizeFileName(name) {
15587 return name.replace(/[\0]/g, '_');
15588}
15589
15590function getGlobalName(module, globals, graph, hasExports) {
15591 var globalName;
15592 if (typeof globals === 'function') {
15593 globalName = globals(module.id);
15594 }
15595 else if (globals) {
15596 globalName = globals[module.id];
15597 }
15598 if (globalName) {
15599 return globalName;
15600 }
15601 if (hasExports) {
15602 graph.warn({
15603 code: 'MISSING_GLOBAL_NAME',
15604 guess: module.variableName,
15605 message: "No name was provided for external module '" + module.id + "' in output.globals \u2013 guessing '" + module.variableName + "'",
15606 source: module.id
15607 });
15608 return module.variableName;
15609 }
15610}
15611var Chunk$1 = /** @class */ (function () {
15612 function Chunk(graph, orderedModules) {
15613 this.entryModules = [];
15614 this.exportMode = 'named';
15615 this.facadeModule = null;
15616 this.hasDynamicImport = false;
15617 this.id = undefined;
15618 this.indentString = undefined;
15619 this.isManualChunk = false;
15620 this.usedModules = undefined;
15621 this.dependencies = undefined;
15622 this.dynamicDependencies = undefined;
15623 this.exportNames = Object.create(null);
15624 this.exports = new Set();
15625 this.imports = new Set();
15626 this.needsExportsShim = false;
15627 this.renderedDeclarations = undefined;
15628 this.renderedHash = undefined;
15629 this.renderedModuleSources = undefined;
15630 this.renderedSource = null;
15631 this.renderedSourceLength = undefined;
15632 this.sortedExportNames = null;
15633 this.graph = graph;
15634 this.orderedModules = orderedModules;
15635 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
15636 this.isEmpty = true;
15637 for (var _i = 0, orderedModules_1 = orderedModules; _i < orderedModules_1.length; _i++) {
15638 var module = orderedModules_1[_i];
15639 if (this.isEmpty && module.isIncluded()) {
15640 this.isEmpty = false;
15641 }
15642 if (module.chunkAlias) {
15643 this.isManualChunk = true;
15644 }
15645 module.chunk = this;
15646 if (module.isEntryPoint ||
15647 module.dynamicallyImportedBy.some(function (module) { return orderedModules.indexOf(module) === -1; })) {
15648 this.entryModules.push(module);
15649 }
15650 }
15651 if (this.entryModules.length > 0) {
15652 this.variableName = makeLegal(basename(this.entryModules.map(function (module) { return module.chunkAlias; }).find(Boolean) ||
15653 this.entryModules[0].id));
15654 }
15655 else
15656 this.variableName = '__chunk_' + ++graph.curChunkIndex;
15657 }
15658 Chunk.prototype.generateEntryExportsOrMarkAsTainted = function () {
15659 var _this = this;
15660 var exportVariableMaps = this.entryModules.map(function (module) { return ({
15661 map: _this.getVariableExportNamesForModule(module),
15662 module: module
15663 }); });
15664 for (var _i = 0, exportVariableMaps_1 = exportVariableMaps; _i < exportVariableMaps_1.length; _i++) {
15665 var map = exportVariableMaps_1[_i].map;
15666 for (var _a = 0, _b = Array.from(map.keys()); _a < _b.length; _a++) {
15667 var exposedVariable = _b[_a];
15668 this.exports.add(exposedVariable);
15669 }
15670 }
15671 var exposedVariables = Array.from(this.exports);
15672 checkNextEntryModule: for (var _c = 0, exportVariableMaps_2 = exportVariableMaps; _c < exportVariableMaps_2.length; _c++) {
15673 var _d = exportVariableMaps_2[_c], map = _d.map, module = _d.module;
15674 if (!this.graph.preserveModules) {
15675 for (var _e = 0, exposedVariables_1 = exposedVariables; _e < exposedVariables_1.length; _e++) {
15676 var exposedVariable = exposedVariables_1[_e];
15677 if (!map.has(exposedVariable)) {
15678 continue checkNextEntryModule;
15679 }
15680 }
15681 }
15682 this.facadeModule = module;
15683 for (var _f = 0, _g = Array.from(map); _f < _g.length; _f++) {
15684 var _h = _g[_f], variable = _h[0], exportNames = _h[1];
15685 for (var _j = 0, exportNames_1 = exportNames; _j < exportNames_1.length; _j++) {
15686 var exportName = exportNames_1[_j];
15687 this.exportNames[exportName] = variable;
15688 }
15689 }
15690 return;
15691 }
15692 };
15693 Chunk.prototype.generateId = function (pattern, patternName, addons, options, existingNames) {
15694 var _this = this;
15695 this.id = makeUnique(renderNamePattern(pattern, patternName, function (type) {
15696 switch (type) {
15697 case 'format':
15698 return options.format === 'es' ? 'esm' : options.format;
15699 case 'hash':
15700 return _this.computeContentHashWithDependencies(addons, options);
15701 case 'name':
15702 return _this.getChunkName();
15703 }
15704 }), existingNames);
15705 };
15706 Chunk.prototype.generateIdPreserveModules = function (preserveModulesRelativeDir, existingNames) {
15707 var sanitizedId = sanitizeFileName(this.orderedModules[0].id);
15708 this.id = makeUnique(normalize(isAbsolute(this.orderedModules[0].id)
15709 ? relative(preserveModulesRelativeDir, sanitizedId)
15710 : '_virtual/' + basename(sanitizedId)), existingNames);
15711 };
15712 Chunk.prototype.generateInternalExports = function (options) {
15713 if (this.facadeModule !== null)
15714 return;
15715 var mangle = options.format === 'system' || options.format === 'es' || options.compact;
15716 var i = 0, safeExportName;
15717 this.exportNames = Object.create(null);
15718 this.sortedExportNames = null;
15719 var exportedVariables = Array.from(this.exports);
15720 if (mangle) {
15721 for (var _i = 0, exportedVariables_1 = exportedVariables; _i < exportedVariables_1.length; _i++) {
15722 var variable = exportedVariables_1[_i];
15723 do {
15724 safeExportName = toBase64(++i);
15725 // skip past leading number identifiers
15726 if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
15727 i += 9 * Math.pow(64, (safeExportName.length - 1));
15728 safeExportName = toBase64(i);
15729 }
15730 } while (RESERVED_NAMES[safeExportName]);
15731 this.exportNames[safeExportName] = variable;
15732 }
15733 }
15734 else {
15735 for (var _a = 0, exportedVariables_2 = exportedVariables; _a < exportedVariables_2.length; _a++) {
15736 var variable = exportedVariables_2[_a];
15737 i = 0;
15738 safeExportName = variable.name;
15739 while (this.exportNames[safeExportName]) {
15740 safeExportName = variable.name + '$' + ++i;
15741 }
15742 this.exportNames[safeExportName] = variable;
15743 }
15744 }
15745 };
15746 Chunk.prototype.getChunkName = function () {
15747 return this.chunkName || (this.chunkName = this.computeChunkName());
15748 };
15749 Chunk.prototype.getDynamicImportIds = function () {
15750 return this.dynamicDependencies.map(function (chunk) { return chunk.id; }).filter(Boolean);
15751 };
15752 Chunk.prototype.getExportNames = function () {
15753 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
15754 };
15755 Chunk.prototype.getImportIds = function () {
15756 return this.dependencies.map(function (chunk) { return chunk.id; });
15757 };
15758 Chunk.prototype.getRenderedHash = function () {
15759 var _this = this;
15760 if (this.renderedHash)
15761 return this.renderedHash;
15762 if (!this.renderedSource)
15763 return '';
15764 var hash = _256();
15765 hash.update(this.renderedSource.toString());
15766 hash.update(this.getExportNames()
15767 .map(function (exportName) {
15768 var variable = _this.exportNames[exportName];
15769 return relativeId(variable.module.id).replace(/\\/g, '/') + ":" + variable.name + ":" + exportName;
15770 })
15771 .join(','));
15772 return (this.renderedHash = hash.digest('hex'));
15773 };
15774 Chunk.prototype.getRenderedSourceLength = function () {
15775 if (this.renderedSourceLength !== undefined)
15776 return this.renderedSourceLength;
15777 return (this.renderedSourceLength = this.renderedSource.length());
15778 };
15779 Chunk.prototype.getVariableExportName = function (variable) {
15780 if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
15781 return '*';
15782 }
15783 for (var _i = 0, _a = Object.keys(this.exportNames); _i < _a.length; _i++) {
15784 var exportName = _a[_i];
15785 if (this.exportNames[exportName] === variable)
15786 return exportName;
15787 }
15788 };
15789 Chunk.prototype.link = function () {
15790 var dependencies = new Set();
15791 var dynamicDependencies = new Set();
15792 for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
15793 var module = _a[_i];
15794 this.addChunksFromDependencies(module.dependencies, dependencies);
15795 this.addChunksFromDependencies(module.dynamicDependencies, dynamicDependencies);
15796 this.setUpModuleImports(module);
15797 }
15798 this.dependencies = Array.from(dependencies);
15799 this.dynamicDependencies = Array.from(dynamicDependencies);
15800 };
15801 /*
15802 * Performs a full merge of another chunk into this chunk
15803 * chunkList allows updating references in other chunks for the merged chunk to this chunk
15804 * A new facade will be added to chunkList if tainting exports of either as an entry point
15805 */
15806 Chunk.prototype.merge = function (chunk, chunkList, options, inputBase) {
15807 var _this = this;
15808 if (this.facadeModule !== null || chunk.facadeModule !== null)
15809 throw new Error('Internal error: Code splitting chunk merges not supported for facades');
15810 for (var _i = 0, _a = chunk.orderedModules; _i < _a.length; _i++) {
15811 var module = _a[_i];
15812 module.chunk = this;
15813 this.orderedModules.push(module);
15814 }
15815 for (var _b = 0, _c = Array.from(chunk.imports); _b < _c.length; _b++) {
15816 var variable = _c[_b];
15817 if (!this.imports.has(variable) && variable.module.chunk !== this) {
15818 this.imports.add(variable);
15819 }
15820 }
15821 // NB detect when exported variables are orphaned by the merge itself
15822 // (involves reverse tracing dependents)
15823 for (var _d = 0, _e = Array.from(chunk.exports); _d < _e.length; _d++) {
15824 var variable = _e[_d];
15825 if (!this.exports.has(variable)) {
15826 this.exports.add(variable);
15827 }
15828 }
15829 var thisOldExportNames = this.exportNames;
15830 // regenerate internal names
15831 this.generateInternalExports(options);
15832 var updateRenderedDeclaration = function (dep, oldExportNames) {
15833 if (dep.imports) {
15834 for (var _i = 0, _a = dep.imports; _i < _a.length; _i++) {
15835 var impt = _a[_i];
15836 impt.imported = _this.getVariableExportName(oldExportNames[impt.imported]);
15837 }
15838 }
15839 if (dep.reexports) {
15840 for (var _b = 0, _c = dep.reexports; _b < _c.length; _b++) {
15841 var reexport = _c[_b];
15842 reexport.imported = _this.getVariableExportName(oldExportNames[reexport.imported]);
15843 }
15844 }
15845 };
15846 var mergeRenderedDeclaration = function (into, from) {
15847 if (from.imports) {
15848 if (!into.imports) {
15849 into.imports = from.imports;
15850 }
15851 else {
15852 into.imports = into.imports.concat(from.imports);
15853 }
15854 }
15855 if (from.reexports) {
15856 if (!into.reexports) {
15857 into.reexports = from.reexports;
15858 }
15859 else {
15860 into.reexports = into.reexports.concat(from.reexports);
15861 }
15862 }
15863 if (!into.exportsNames && from.exportsNames) {
15864 into.exportsNames = true;
15865 }
15866 if (!into.exportsDefault && from.exportsDefault) {
15867 into.exportsDefault = true;
15868 }
15869 into.name = _this.variableName;
15870 };
15871 // go through the other chunks and update their dependencies
15872 // also update their import and reexport names in the process
15873 for (var _f = 0, chunkList_1 = chunkList; _f < chunkList_1.length; _f++) {
15874 var c = chunkList_1[_f];
15875 var includedDeclaration = void 0;
15876 for (var i = 0; i < c.dependencies.length; i++) {
15877 var dep = c.dependencies[i];
15878 if ((dep === chunk || dep === this) && includedDeclaration) {
15879 var duplicateDeclaration = c.renderedDeclarations.dependencies[i];
15880 updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
15881 mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
15882 c.renderedDeclarations.dependencies.splice(i, 1);
15883 c.dependencies.splice(i--, 1);
15884 }
15885 else if (dep === chunk) {
15886 c.dependencies[i] = this;
15887 includedDeclaration = c.renderedDeclarations.dependencies[i];
15888 updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
15889 }
15890 else if (dep === this) {
15891 includedDeclaration = c.renderedDeclarations.dependencies[i];
15892 updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
15893 }
15894 }
15895 }
15896 // re-render the merged chunk
15897 this.preRender(options, inputBase);
15898 };
15899 // prerender allows chunk hashes and names to be generated before finalizing
15900 Chunk.prototype.preRender = function (options, inputBase) {
15901 timeStart('render modules', 3);
15902 var magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
15903 this.usedModules = [];
15904 this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
15905 var n = options.compact ? '' : '\n';
15906 var _ = options.compact ? '' : ' ';
15907 var renderOptions = {
15908 compact: options.compact,
15909 dynamicImportFunction: options.dynamicImportFunction,
15910 format: options.format,
15911 freeze: options.freeze !== false,
15912 indent: this.indentString,
15913 namespaceToStringTag: options.namespaceToStringTag === true,
15914 varOrConst: options.preferConst ? 'const' : 'var'
15915 };
15916 // Make sure the direct dependencies of a chunk are present to maintain execution order
15917 for (var _i = 0, _a = Array.from(this.imports); _i < _a.length; _i++) {
15918 var module = _a[_i].module;
15919 var chunkOrExternal = module instanceof Module ? module.chunk : module;
15920 if (this.dependencies.indexOf(chunkOrExternal) === -1) {
15921 this.dependencies.push(chunkOrExternal);
15922 }
15923 }
15924 // for static and dynamic entry points, inline the execution list to avoid loading latency
15925 if (!this.graph.preserveModules && this.facadeModule !== null) {
15926 for (var _b = 0, _c = this.dependencies; _b < _c.length; _b++) {
15927 var dep = _c[_b];
15928 if (dep instanceof Chunk)
15929 this.inlineChunkDependencies(dep, true);
15930 }
15931 }
15932 // prune empty dependency chunks, inlining their side-effect dependencies
15933 for (var i = 0; i < this.dependencies.length; i++) {
15934 var dep = this.dependencies[i];
15935 if (dep instanceof Chunk && dep.isEmpty) {
15936 this.dependencies.splice(i--, 1);
15937 this.inlineChunkDependencies(dep, false);
15938 }
15939 }
15940 sortByExecutionOrder(this.dependencies);
15941 this.setIdentifierRenderResolutions(options);
15942 this.prepareDynamicImports();
15943 var hoistedSource = '';
15944 this.renderedModules = Object.create(null);
15945 this.renderedModuleSources = [];
15946 for (var i = 0; i < this.orderedModules.length; i++) {
15947 var module = this.orderedModules[i];
15948 var source = module.render(renderOptions);
15949 source.trim();
15950 if (options.compact && source.lastLine().indexOf('//') !== -1)
15951 source.append('\n');
15952 this.renderedModuleSources.push(source);
15953 var _d = module.getRenderedExports(), renderedExports = _d.renderedExports, removedExports = _d.removedExports;
15954 this.renderedModules[module.id] = {
15955 originalLength: module.originalCode.length,
15956 removedExports: removedExports,
15957 renderedExports: renderedExports,
15958 renderedLength: source.length()
15959 };
15960 var namespace = module.getOrCreateNamespace();
15961 if (namespace.included || !source.isEmpty()) {
15962 magicString.addSource(source);
15963 this.usedModules.push(module);
15964 if (namespace.included && !this.graph.preserveModules) {
15965 var rendered = namespace.renderBlock(renderOptions);
15966 if (namespace.renderFirst())
15967 hoistedSource += n + rendered;
15968 else
15969 magicString.addSource(new MagicString(rendered));
15970 }
15971 }
15972 }
15973 if (hoistedSource)
15974 magicString.prepend(hoistedSource + n + n);
15975 if (this.needsExportsShim) {
15976 magicString.prepend("" + n + renderOptions.varOrConst + " " + MISSING_EXPORT_SHIM_VARIABLE + _ + "=" + _ + "void 0;" + n + n);
15977 }
15978 if (options.compact) {
15979 this.renderedSource = magicString;
15980 }
15981 else {
15982 this.renderedSource = magicString.trim();
15983 }
15984 this.renderedSourceLength = undefined;
15985 this.renderedHash = undefined;
15986 if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) {
15987 this.graph.warn({
15988 code: 'EMPTY_BUNDLE',
15989 message: 'Generated an empty bundle'
15990 });
15991 }
15992 this.renderedDeclarations = {
15993 dependencies: this.getChunkDependencyDeclarations(options, inputBase),
15994 exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
15995 };
15996 timeEnd('render modules', 3);
15997 };
15998 Chunk.prototype.render = function (options, addons, outputChunk) {
15999 var _this = this;
16000 timeStart('render format', 3);
16001 if (!this.renderedSource)
16002 throw new Error('Internal error: Chunk render called before preRender');
16003 var finalise = finalisers[options.format];
16004 if (!finalise) {
16005 error({
16006 code: 'INVALID_OPTION',
16007 message: "Invalid format: " + options.format + " - valid options are " + Object.keys(finalisers).join(', ') + "."
16008 });
16009 }
16010 if (options.dynamicImportFunction && options.format !== 'es') {
16011 this.graph.warn({
16012 code: 'INVALID_OPTION',
16013 message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
16014 });
16015 }
16016 // populate ids in the rendered declarations only here
16017 // as chunk ids known only after prerender
16018 for (var i = 0; i < this.dependencies.length; i++) {
16019 var dep = this.dependencies[i];
16020 if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
16021 continue;
16022 var renderedDependency = this.renderedDeclarations.dependencies[i];
16023 var depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
16024 var relPath = this.id ? normalize(relative(dirname(this.id), depId)) : depId;
16025 if (!relPath.startsWith('../'))
16026 relPath = './' + relPath;
16027 if (dep instanceof Chunk)
16028 renderedDependency.namedExportsMode = dep.exportMode !== 'default';
16029 renderedDependency.id = relPath;
16030 }
16031 this.finaliseDynamicImports();
16032 var needsAmdModule = this.finaliseImportMetas(options);
16033 var hasExports = this.renderedDeclarations.exports.length !== 0 ||
16034 this.renderedDeclarations.dependencies.some(function (dep) { return dep.reexports && dep.reexports.length !== 0; });
16035 var usesTopLevelAwait = this.orderedModules.some(function (module) { return module.usesTopLevelAwait; });
16036 if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
16037 error({
16038 code: 'INVALID_TLA_FORMAT',
16039 message: "Module format " + options.format + " does not support top-level await. Use the \"es\" or \"system\" output formats rather."
16040 });
16041 }
16042 var magicString = finalise(this.renderedSource, {
16043 dependencies: this.renderedDeclarations.dependencies,
16044 dynamicImport: this.hasDynamicImport,
16045 exports: this.renderedDeclarations.exports,
16046 hasExports: hasExports,
16047 indentString: this.indentString,
16048 intro: addons.intro,
16049 isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint,
16050 namedExportsMode: this.exportMode !== 'default',
16051 needsAmdModule: needsAmdModule,
16052 outro: addons.outro,
16053 usesTopLevelAwait: usesTopLevelAwait,
16054 varOrConst: options.preferConst ? 'const' : 'var',
16055 warn: this.graph.warn.bind(this.graph)
16056 }, options);
16057 if (addons.banner)
16058 magicString.prepend(addons.banner);
16059 if (addons.footer)
16060 magicString.append(addons.footer);
16061 var prevCode = magicString.toString();
16062 timeEnd('render format', 3);
16063 var map = null;
16064 var chunkSourcemapChain = [];
16065 return renderChunk({
16066 chunk: this,
16067 code: prevCode,
16068 graph: this.graph,
16069 options: options,
16070 renderChunk: outputChunk,
16071 sourcemapChain: chunkSourcemapChain
16072 }).then(function (code) {
16073 if (options.sourcemap) {
16074 timeStart('sourcemap', 3);
16075 var file = void 0;
16076 if (options.file)
16077 file = resolve$1(options.sourcemapFile || options.file);
16078 else if (options.dir)
16079 file = resolve$1(options.dir, _this.id);
16080 else
16081 file = resolve$1(_this.id);
16082 if (_this.graph.pluginDriver.hasLoadersOrTransforms) {
16083 var decodedMap = magicString.generateDecodedMap({});
16084 map = collapseSourcemaps(_this, file, decodedMap, _this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
16085 }
16086 else {
16087 map = magicString.generateMap({ file: file, includeContent: !options.sourcemapExcludeSources });
16088 }
16089 map.sources = map.sources.map(function (sourcePath) {
16090 return normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath);
16091 });
16092 timeEnd('sourcemap', 3);
16093 }
16094 if (options.compact !== true && code[code.length - 1] !== '\n')
16095 code += '\n';
16096 return { code: code, map: map };
16097 });
16098 };
16099 Chunk.prototype.turnIntoFacade = function (facadedModule) {
16100 this.dependencies = [facadedModule.chunk];
16101 this.dynamicDependencies = [];
16102 this.facadeModule = facadedModule;
16103 facadedModule.facadeChunk = this;
16104 for (var _i = 0, _a = facadedModule.getAllExports(); _i < _a.length; _i++) {
16105 var exportName = _a[_i];
16106 var tracedVariable = facadedModule.getVariableForExportName(exportName);
16107 this.exports.add(tracedVariable);
16108 this.exportNames[exportName] = tracedVariable;
16109 }
16110 };
16111 Chunk.prototype.visitDependencies = function (handleDependency) {
16112 var toBeVisited = [this];
16113 var visited = new Set();
16114 for (var _i = 0, toBeVisited_1 = toBeVisited; _i < toBeVisited_1.length; _i++) {
16115 var current = toBeVisited_1[_i];
16116 handleDependency(current);
16117 if (current instanceof ExternalModule)
16118 continue;
16119 for (var _a = 0, _b = current.dependencies.concat(current.dynamicDependencies); _a < _b.length; _a++) {
16120 var dependency = _b[_a];
16121 if (!visited.has(dependency)) {
16122 visited.add(dependency);
16123 toBeVisited.push(dependency);
16124 }
16125 }
16126 }
16127 };
16128 Chunk.prototype.visitStaticDependenciesUntilCondition = function (isConditionSatisfied) {
16129 var seen = new Set();
16130 function visitDep(dep) {
16131 if (seen.has(dep))
16132 return;
16133 seen.add(dep);
16134 if (dep instanceof Chunk) {
16135 for (var _i = 0, _a = dep.dependencies; _i < _a.length; _i++) {
16136 var subDep = _a[_i];
16137 if (visitDep(subDep))
16138 return true;
16139 }
16140 }
16141 return isConditionSatisfied(dep) === true;
16142 }
16143 return visitDep(this);
16144 };
16145 Chunk.prototype.addChunksFromDependencies = function (moduleDependencies, chunkDependencies) {
16146 for (var _i = 0, moduleDependencies_1 = moduleDependencies; _i < moduleDependencies_1.length; _i++) {
16147 var depModule = moduleDependencies_1[_i];
16148 if (depModule.chunk === this) {
16149 continue;
16150 }
16151 var dependency = void 0;
16152 if (depModule instanceof Module) {
16153 dependency = depModule.chunk;
16154 }
16155 else {
16156 if (!depModule.used && this.graph.isPureExternalModule(depModule.id)) {
16157 continue;
16158 }
16159 dependency = depModule;
16160 }
16161 chunkDependencies.add(dependency);
16162 }
16163 };
16164 Chunk.prototype.computeChunkName = function () {
16165 if (this.facadeModule !== null && this.facadeModule.chunkAlias) {
16166 return sanitizeFileName(this.facadeModule.chunkAlias);
16167 }
16168 for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
16169 var module = _a[_i];
16170 if (module.chunkAlias)
16171 return sanitizeFileName(module.chunkAlias);
16172 }
16173 return 'chunk';
16174 };
16175 Chunk.prototype.computeContentHashWithDependencies = function (addons, options) {
16176 var hash = _256();
16177 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(function (addon) { return addon || ''; }).join(':'));
16178 hash.update(options.format);
16179 this.visitDependencies(function (dep) {
16180 if (dep instanceof ExternalModule)
16181 hash.update(':' + dep.renderPath);
16182 else
16183 hash.update(dep.getRenderedHash());
16184 });
16185 return hash.digest('hex').substr(0, 8);
16186 };
16187 Chunk.prototype.finaliseDynamicImports = function () {
16188 for (var i = 0; i < this.orderedModules.length; i++) {
16189 var module = this.orderedModules[i];
16190 var code = this.renderedModuleSources[i];
16191 for (var _i = 0, _a = module.dynamicImports; _i < _a.length; _i++) {
16192 var _b = _a[_i], node = _b.node, resolution = _b.resolution;
16193 if (!resolution)
16194 continue;
16195 if (resolution instanceof Module) {
16196 if (!resolution.chunk.isEmpty && resolution.chunk !== this) {
16197 var resolutionChunk = resolution.facadeChunk || resolution.chunk;
16198 var relPath = normalize(relative(dirname(this.id), resolutionChunk.id));
16199 if (!relPath.startsWith('../'))
16200 relPath = './' + relPath;
16201 node.renderFinalResolution(code, "'" + relPath + "'");
16202 }
16203 }
16204 else if (resolution instanceof ExternalModule) {
16205 node.renderFinalResolution(code, "'" + resolution.id + "'");
16206 }
16207 else {
16208 node.renderFinalResolution(code, resolution);
16209 }
16210 }
16211 }
16212 };
16213 Chunk.prototype.finaliseImportMetas = function (options) {
16214 var usesMechanism = false;
16215 for (var i = 0; i < this.orderedModules.length; i++) {
16216 var module = this.orderedModules[i];
16217 var code = this.renderedModuleSources[i];
16218 for (var _i = 0, _a = module.importMetas; _i < _a.length; _i++) {
16219 var importMeta = _a[_i];
16220 if (importMeta.renderFinalMechanism(code, this.id, options.format, options.compact))
16221 usesMechanism = true;
16222 }
16223 }
16224 return usesMechanism;
16225 };
16226 Chunk.prototype.getChunkDependencyDeclarations = function (options, inputBase) {
16227 var reexportDeclarations = new Map();
16228 for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
16229 var exportName = _a[_i];
16230 var exportModule = void 0;
16231 var importName = void 0;
16232 var needsLiveBinding = false;
16233 if (exportName[0] === '*') {
16234 exportModule = this.graph.moduleById.get(exportName.substr(1));
16235 importName = exportName = '*';
16236 }
16237 else {
16238 var variable = this.exportNames[exportName];
16239 var module = variable.module;
16240 // skip local exports
16241 if (!module || module.chunk === this)
16242 continue;
16243 if (module instanceof Module) {
16244 exportModule = module.chunk;
16245 importName = module.chunk.getVariableExportName(variable);
16246 needsLiveBinding = variable.isReassigned;
16247 }
16248 else {
16249 exportModule = module;
16250 importName = variable.name;
16251 needsLiveBinding = true;
16252 }
16253 }
16254 var exportDeclaration = reexportDeclarations.get(exportModule);
16255 if (!exportDeclaration)
16256 reexportDeclarations.set(exportModule, (exportDeclaration = []));
16257 exportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding: needsLiveBinding });
16258 }
16259 var importsAsArray = Array.from(this.imports);
16260 var renderedImports = new Set();
16261 var dependencies = [];
16262 for (var _b = 0, _c = this.dependencies; _b < _c.length; _b++) {
16263 var dep = _c[_b];
16264 var imports = [];
16265 for (var _d = 0, importsAsArray_1 = importsAsArray; _d < importsAsArray_1.length; _d++) {
16266 var variable = importsAsArray_1[_d];
16267 var renderedVariable = variable instanceof ExportDefaultVariable && variable.referencesOriginal()
16268 ? variable.getOriginalVariable()
16269 : variable;
16270 if ((variable.module instanceof Module
16271 ? variable.module.chunk === dep
16272 : variable.module === dep) &&
16273 !renderedImports.has(renderedVariable)) {
16274 renderedImports.add(renderedVariable);
16275 var local = variable.getName();
16276 var imported = variable.module instanceof ExternalModule
16277 ? variable.name
16278 : variable.module.chunk.getVariableExportName(variable);
16279 imports.push({ local: local, imported: imported });
16280 }
16281 }
16282 var reexports = reexportDeclarations.get(dep);
16283 var exportsNames = void 0, exportsDefault = void 0;
16284 var namedExportsMode = true;
16285 if (dep instanceof ExternalModule) {
16286 exportsNames = dep.exportsNames || dep.exportsNamespace;
16287 exportsDefault = 'default' in dep.declarations;
16288 }
16289 else {
16290 exportsNames = true;
16291 // we don't want any interop patterns to trigger
16292 exportsDefault = false;
16293 namedExportsMode = dep.exportMode !== 'default';
16294 }
16295 var id = void 0;
16296 var globalName = void 0;
16297 if (dep instanceof ExternalModule) {
16298 id = dep.setRenderPath(options, inputBase);
16299 if (options.format === 'umd' || options.format === 'iife') {
16300 globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
16301 }
16302 }
16303 dependencies.push({
16304 exportsDefault: exportsDefault,
16305 exportsNames: exportsNames,
16306 globalName: globalName,
16307 id: id,
16308 imports: imports.length > 0 ? imports : null,
16309 isChunk: !dep.isExternal,
16310 name: dep.variableName,
16311 namedExportsMode: namedExportsMode,
16312 reexports: reexports
16313 });
16314 }
16315 return dependencies;
16316 };
16317 Chunk.prototype.getChunkExportDeclarations = function () {
16318 var exports = [];
16319 var _loop_1 = function (exportName) {
16320 if (exportName[0] === '*')
16321 return "continue";
16322 var variable = this_1.exportNames[exportName];
16323 var module = variable.module;
16324 if (module && module.chunk !== this_1)
16325 return "continue";
16326 var hoisted = false;
16327 var uninitialized = false;
16328 if (variable instanceof LocalVariable) {
16329 if (variable.init === UNDEFINED_EXPRESSION) {
16330 uninitialized = true;
16331 }
16332 variable.declarations.forEach(function (decl) {
16333 if (decl.type === ExportDefaultDeclaration) {
16334 if (decl.declaration.type === FunctionDeclaration)
16335 hoisted = true;
16336 }
16337 else if (decl.parent.type === FunctionDeclaration) {
16338 hoisted = true;
16339 }
16340 });
16341 }
16342 else if (variable instanceof GlobalVariable) {
16343 hoisted = true;
16344 }
16345 var localName = variable.getName();
16346 exports.push({
16347 exported: exportName === '*' ? localName : exportName,
16348 hoisted: hoisted,
16349 local: localName,
16350 uninitialized: uninitialized
16351 });
16352 };
16353 var this_1 = this;
16354 for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
16355 var exportName = _a[_i];
16356 _loop_1(exportName);
16357 }
16358 return exports;
16359 };
16360 Chunk.prototype.getVariableExportNamesForModule = function (module) {
16361 var exportNamesByVariable = new Map();
16362 for (var _i = 0, _a = module.getAllExports(); _i < _a.length; _i++) {
16363 var exportName = _a[_i];
16364 var tracedVariable = module.getVariableForExportName(exportName);
16365 if (!tracedVariable || !(tracedVariable.included || tracedVariable.isExternal)) {
16366 continue;
16367 }
16368 var existingExportNames = exportNamesByVariable.get(tracedVariable);
16369 if (existingExportNames) {
16370 existingExportNames.push(exportName);
16371 }
16372 else {
16373 exportNamesByVariable.set(tracedVariable, [exportName]);
16374 }
16375 var exportingModule = tracedVariable.module;
16376 if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
16377 exportingModule.chunk.exports.add(tracedVariable);
16378 }
16379 }
16380 return exportNamesByVariable;
16381 };
16382 Chunk.prototype.inlineChunkDependencies = function (chunk, deep) {
16383 for (var _i = 0, _a = chunk.dependencies; _i < _a.length; _i++) {
16384 var dep = _a[_i];
16385 if (dep instanceof ExternalModule) {
16386 if (this.dependencies.indexOf(dep) === -1)
16387 this.dependencies.push(dep);
16388 }
16389 else {
16390 if (dep === this || this.dependencies.indexOf(dep) !== -1)
16391 continue;
16392 if (!dep.isEmpty)
16393 this.dependencies.push(dep);
16394 if (deep)
16395 this.inlineChunkDependencies(dep, true);
16396 }
16397 }
16398 };
16399 Chunk.prototype.prepareDynamicImports = function () {
16400 for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
16401 var module = _a[_i];
16402 for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
16403 var _d = _c[_b], node = _d.node, resolution = _d.resolution;
16404 if (!resolution)
16405 continue;
16406 if (resolution instanceof Module) {
16407 if (resolution.chunk === this) {
16408 var namespace = resolution.getOrCreateNamespace();
16409 node.setResolution(false, namespace.getName());
16410 }
16411 else {
16412 node.setResolution(false);
16413 }
16414 }
16415 else if (resolution instanceof ExternalModule) {
16416 node.setResolution(true);
16417 }
16418 else {
16419 node.setResolution(false);
16420 }
16421 }
16422 }
16423 };
16424 Chunk.prototype.setIdentifierRenderResolutions = function (options) {
16425 for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
16426 var exportName = _a[_i];
16427 var exportVariable = this.exportNames[exportName];
16428 if (exportVariable) {
16429 if (exportVariable instanceof ExportShimVariable) {
16430 this.needsExportsShim = true;
16431 }
16432 exportVariable.exportName = exportName;
16433 if (options.format !== 'es' &&
16434 options.format !== 'system' &&
16435 exportVariable.isReassigned &&
16436 !exportVariable.isId &&
16437 (!isExportDefaultVariable(exportVariable) || !exportVariable.hasId)) {
16438 exportVariable.setRenderNames('exports', exportName);
16439 }
16440 else {
16441 exportVariable.setRenderNames(null, null);
16442 }
16443 }
16444 }
16445 var usedNames = Object.create(null);
16446 if (this.needsExportsShim) {
16447 usedNames[MISSING_EXPORT_SHIM_VARIABLE] = true;
16448 }
16449 deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
16450 };
16451 Chunk.prototype.setUpModuleImports = function (module) {
16452 for (var _i = 0, _a = Array.from(module.imports); _i < _a.length; _i++) {
16453 var variable = _a[_i];
16454 if (variable.module.chunk !== this) {
16455 this.imports.add(variable);
16456 if (variable.module instanceof Module) {
16457 variable.module.chunk.exports.add(variable);
16458 }
16459 }
16460 }
16461 if (module.getOrCreateNamespace().included) {
16462 for (var _b = 0, _c = Object.keys(module.reexports); _b < _c.length; _b++) {
16463 var reexportName = _c[_b];
16464 var reexport = module.reexports[reexportName];
16465 var variable = reexport.module.getVariableForExportName(reexport.localName);
16466 if (variable.module.chunk !== this) {
16467 this.imports.add(variable);
16468 if (variable.module instanceof Module) {
16469 variable.module.chunk.exports.add(variable);
16470 }
16471 }
16472 }
16473 }
16474 for (var _d = 0, _e = module.dynamicImports; _d < _e.length; _d++) {
16475 var _f = _e[_d], node = _f.node, resolution = _f.resolution;
16476 if (node.included) {
16477 this.hasDynamicImport = true;
16478 if (resolution instanceof Module && resolution.chunk === this)
16479 resolution.getOrCreateNamespace().include();
16480 }
16481 }
16482 };
16483 return Chunk;
16484}());
16485
16486/*
16487 * Given a chunk list, perform optimizations on that chunk list
16488 * to reduce the mumber of chunks. Mutates the chunks array.
16489 *
16490 * Manual chunks (with chunk.chunkAlias already set) are preserved
16491 * Entry points are carefully preserved as well
16492 *
16493 */
16494function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
16495 var _loop_1 = function (chunkIndex) {
16496 var mainChunk = chunks[chunkIndex];
16497 var execGroup = [];
16498 mainChunk.visitStaticDependenciesUntilCondition(function (dep) {
16499 if (dep instanceof Chunk$1) {
16500 execGroup.push(dep);
16501 }
16502 });
16503 if (execGroup.length < 2) {
16504 return out_chunkIndex_1 = chunkIndex, "continue";
16505 }
16506 var execGroupIndex = 1;
16507 var seekingFirstMergeCandidate = true;
16508 var lastChunk, chunk = execGroup[0], nextChunk = execGroup[1];
16509 var isMergeCandidate = function (chunk) {
16510 if (chunk.facadeModule !== null || chunk.isManualChunk) {
16511 return false;
16512 }
16513 if (!nextChunk || nextChunk.facadeModule !== null) {
16514 return false;
16515 }
16516 if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
16517 return false;
16518 }
16519 // if (!chunk.isPure()) continue;
16520 return true;
16521 };
16522 var _loop_2 = function () {
16523 if (seekingFirstMergeCandidate) {
16524 if (isMergeCandidate(chunk)) {
16525 seekingFirstMergeCandidate = false;
16526 }
16527 return "continue";
16528 }
16529 var remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
16530 if (remainingSize <= 0) {
16531 if (!isMergeCandidate(chunk)) {
16532 seekingFirstMergeCandidate = true;
16533 }
16534 return "continue";
16535 }
16536 // if (!chunk.isPure()) continue;
16537 var chunkDependencies = new Set();
16538 chunk.visitStaticDependenciesUntilCondition(function (dep) { return chunkDependencies.add(dep); });
16539 var ignoreSizeChunks = new Set([chunk, lastChunk]);
16540 if (lastChunk.visitStaticDependenciesUntilCondition(function (dep) {
16541 if (dep === chunk || dep === lastChunk) {
16542 return false;
16543 }
16544 if (chunkDependencies.has(dep)) {
16545 return false;
16546 }
16547 if (dep instanceof ExternalModule) {
16548 return true;
16549 }
16550 remainingSize -= dep.getRenderedSourceLength();
16551 if (remainingSize <= 0) {
16552 return true;
16553 }
16554 ignoreSizeChunks.add(dep);
16555 })) {
16556 if (!isMergeCandidate(chunk)) {
16557 seekingFirstMergeCandidate = true;
16558 }
16559 return "continue";
16560 }
16561 if (chunk.visitStaticDependenciesUntilCondition(function (dep) {
16562 if (ignoreSizeChunks.has(dep)) {
16563 return false;
16564 }
16565 if (dep instanceof ExternalModule) {
16566 return true;
16567 }
16568 remainingSize -= dep.getRenderedSourceLength();
16569 if (remainingSize <= 0) {
16570 return true;
16571 }
16572 })) {
16573 if (!isMergeCandidate(chunk)) {
16574 seekingFirstMergeCandidate = true;
16575 }
16576 return "continue";
16577 }
16578 // within the size limit -> merge!
16579 var optimizedChunkIndex = chunks.indexOf(chunk);
16580 if (optimizedChunkIndex <= chunkIndex)
16581 chunkIndex--;
16582 chunks.splice(optimizedChunkIndex, 1);
16583 lastChunk.merge(chunk, chunks, options, inputBase);
16584 execGroup.splice(--execGroupIndex, 1);
16585 chunk = lastChunk;
16586 // keep going to see if we can merge this with the next again
16587 if (nextChunk && !isMergeCandidate(nextChunk)) {
16588 seekingFirstMergeCandidate = true;
16589 }
16590 };
16591 do {
16592 _loop_2();
16593 } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
16594 out_chunkIndex_1 = chunkIndex;
16595 };
16596 var out_chunkIndex_1;
16597 for (var chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
16598 _loop_1(chunkIndex);
16599 chunkIndex = out_chunkIndex_1;
16600 }
16601 return chunks;
16602}
16603
16604const tt = acorn__default.tokTypes;
16605const isIdentifierStart = acorn__default.isIdentifierStart;
16606
16607var acornBigint = function(Parser) {
16608 return class extends Parser {
16609 parseLiteral(value) {
16610 const node = super.parseLiteral(value);
16611 if (node.raw.charCodeAt(node.raw.length - 1) == 110) node.bigint = this.getNumberInput(node.start, node.end);
16612 return node
16613 }
16614
16615 readRadixNumber(radix) {
16616 let start = this.pos;
16617 this.pos += 2; // 0x
16618 let val = this.readInt(radix);
16619 if (val === null) this.raise(this.start + 2, `Expected number in radix ${radix}`);
16620 if (this.input.charCodeAt(this.pos) == 110) {
16621 let str = this.getNumberInput(start, this.pos);
16622 val = typeof BigInt !== "undefined" ? BigInt(str) : null;
16623 ++this.pos;
16624 } else if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
16625 return this.finishToken(tt.num, val)
16626 }
16627
16628 readNumber(startsWithDot) {
16629 let start = this.pos;
16630
16631 // Not an int
16632 if (startsWithDot) return super.readNumber(startsWithDot)
16633
16634 // Legacy octal
16635 if (this.input.charCodeAt(start) === 48 && this.input.charCodeAt(start + 1) !== 110) {
16636 return super.readNumber(startsWithDot)
16637 }
16638
16639 if (this.readInt(10) === null) this.raise(start, "Invalid number");
16640
16641 // Not a BigInt, reset and parse again
16642 if (this.input.charCodeAt(this.pos) != 110) {
16643 this.pos = start;
16644 return super.readNumber(startsWithDot)
16645 }
16646
16647 let str = this.getNumberInput(start, this.pos);
16648 let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
16649 ++this.pos;
16650 return this.finishToken(tt.num, val)
16651 }
16652
16653 // This is basically a hook for acorn-numeric-separator
16654 getNumberInput(start, end) {
16655 if (super.getNumberInput) return super.getNumberInput(start, end)
16656 return this.input.slice(start, end)
16657 }
16658 }
16659};
16660
16661/* eslint-disable no-underscore-dangle */
16662
16663const DynamicImportKey = 'Import';
16664
16665// NOTE: This allows `yield import()` to parse correctly.
16666tokTypes._import.startsExpr = true;
16667
16668function parseDynamicImport() {
16669 const node = this.startNode();
16670 this.next();
16671 if (this.type !== tokTypes.parenL) {
16672 this.unexpected();
16673 }
16674 return this.finishNode(node, DynamicImportKey);
16675}
16676
16677function parenAfter() {
16678 return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
16679}
16680
16681function dynamicImport(Parser) {
16682 return class extends Parser {
16683 parseStatement(context, topLevel, exports) {
16684 if (this.type === tokTypes._import && parenAfter.call(this)) {
16685 return this.parseExpressionStatement(this.startNode(), this.parseExpression());
16686 }
16687 return super.parseStatement(context, topLevel, exports);
16688 }
16689
16690 parseExprAtom(refDestructuringErrors) {
16691 if (this.type === tokTypes._import) {
16692 return parseDynamicImport.call(this);
16693 }
16694 return super.parseExprAtom(refDestructuringErrors);
16695 }
16696 };
16697}
16698
16699const tt$1 = acorn__default.tokTypes;
16700
16701const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
16702
16703const nextTokenIsDot = parser => {
16704 skipWhiteSpace.lastIndex = parser.pos;
16705 let skip = skipWhiteSpace.exec(parser.input);
16706 let next = parser.pos + skip[0].length;
16707 return parser.input.slice(next, next + 1) === "."
16708};
16709
16710var acornImportMeta = function(Parser) {
16711 return class extends Parser {
16712 parseExprAtom(refDestructuringErrors) {
16713 if (this.type !== tt$1._import || !nextTokenIsDot(this)) return super.parseExprAtom(refDestructuringErrors)
16714
16715 if (!this.options.allowImportExportEverywhere && !this.inModule) {
16716 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
16717 }
16718
16719 let node = this.startNode();
16720 node.meta = this.parseIdent(true);
16721 this.expect(tt$1.dot);
16722 node.property = this.parseIdent(true);
16723 if (node.property.name !== "meta") {
16724 this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
16725 }
16726 if (this.containsEsc) {
16727 this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
16728 }
16729 return this.finishNode(node, "MetaProperty")
16730 }
16731
16732 parseStatement(context, topLevel, exports) {
16733 if (this.type !== tt$1._import || !nextTokenIsDot(this)) {
16734 return super.parseStatement(context, topLevel, exports)
16735 }
16736
16737 let node = this.startNode();
16738 let expr = this.parseExpression();
16739 return this.parseExpressionStatement(node, expr)
16740 }
16741 }
16742};
16743
16744var UndefinedVariable = /** @class */ (function (_super) {
16745 __extends(UndefinedVariable, _super);
16746 function UndefinedVariable() {
16747 return _super.call(this, 'undefined') || this;
16748 }
16749 UndefinedVariable.prototype.getLiteralValueAtPath = function () {
16750 return undefined;
16751 };
16752 return UndefinedVariable;
16753}(Variable));
16754
16755var GlobalScope = /** @class */ (function (_super) {
16756 __extends(GlobalScope, _super);
16757 function GlobalScope() {
16758 var _this = _super.call(this) || this;
16759 _this.variables.undefined = new UndefinedVariable();
16760 return _this;
16761 }
16762 GlobalScope.prototype.findVariable = function (name) {
16763 if (!this.variables[name])
16764 return (this.variables[name] = new GlobalVariable(name));
16765 return this.variables[name];
16766 };
16767 return GlobalScope;
16768}(Scope));
16769
16770var getNewTrackedPaths = function () { return ({
16771 paths: Object.create(null),
16772 tracked: false,
16773 unknownPath: null
16774}); };
16775var EntityPathTracker = /** @class */ (function () {
16776 function EntityPathTracker() {
16777 this.entityPaths = new Map();
16778 }
16779 EntityPathTracker.prototype.track = function (entity, path) {
16780 var trackedPaths = this.entityPaths.get(entity);
16781 if (!trackedPaths) {
16782 trackedPaths = getNewTrackedPaths();
16783 this.entityPaths.set(entity, trackedPaths);
16784 }
16785 var pathIndex = 0, trackedSubPaths;
16786 while (pathIndex < path.length) {
16787 var key = path[pathIndex];
16788 if (typeof key === 'string') {
16789 trackedSubPaths = trackedPaths.paths[key];
16790 if (!trackedSubPaths) {
16791 trackedSubPaths = getNewTrackedPaths();
16792 trackedPaths.paths[key] = trackedSubPaths;
16793 }
16794 }
16795 else {
16796 trackedSubPaths = trackedPaths.unknownPath;
16797 if (!trackedSubPaths) {
16798 trackedSubPaths = getNewTrackedPaths();
16799 trackedPaths.unknownPath = trackedSubPaths;
16800 }
16801 }
16802 trackedPaths = trackedSubPaths;
16803 pathIndex++;
16804 }
16805 var found = trackedPaths.tracked;
16806 trackedPaths.tracked = true;
16807 return found;
16808 };
16809 return EntityPathTracker;
16810}());
16811
16812function getAssetFileName(asset, existingNames, assetFileNames) {
16813 if (asset.source === undefined)
16814 error({
16815 code: 'ASSET_SOURCE_NOT_FOUND',
16816 message: "Plugin error creating asset " + asset.name + " - no asset source set."
16817 });
16818 if (asset.fileName)
16819 return asset.fileName;
16820 return makeUnique(renderNamePattern(assetFileNames, 'assetFileNames', function (name) {
16821 switch (name) {
16822 case 'hash':
16823 var hash = _256();
16824 hash.update(name);
16825 hash.update(':');
16826 hash.update(asset.source);
16827 return hash.digest('hex').substr(0, 8);
16828 case 'name':
16829 return asset.name.substr(0, asset.name.length - extname(asset.name).length);
16830 case 'extname':
16831 return extname(asset.name);
16832 case 'ext':
16833 return extname(asset.name).substr(1);
16834 }
16835 }), existingNames);
16836}
16837function createAssetPluginHooks(assetsById, outputBundle, assetFileNames) {
16838 return {
16839 emitAsset: function (name, source) {
16840 if (typeof name !== 'string' || !isPlainName(name))
16841 error({
16842 code: 'INVALID_ASSET_NAME',
16843 message: "Plugin error creating asset, name is not a plain (non relative or absolute URL) string name."
16844 });
16845 var assetId;
16846 do {
16847 var assetHash = _256();
16848 if (assetId) {
16849 // if there is a collision, chain until there isn't
16850 assetHash.update(assetId);
16851 }
16852 else {
16853 assetHash.update(name);
16854 }
16855 assetId = assetHash.digest('hex').substr(0, 8);
16856 } while (assetsById.has(assetId));
16857 var asset = { name: name, source: source, fileName: undefined };
16858 if (outputBundle && source !== undefined)
16859 finaliseAsset(asset, outputBundle, assetFileNames);
16860 assetsById.set(assetId, asset);
16861 return assetId;
16862 },
16863 setAssetSource: function (assetId, source) {
16864 var asset = assetsById.get(assetId);
16865 if (!asset)
16866 error({
16867 code: 'ASSET_NOT_FOUND',
16868 message: "Plugin error - Unable to set asset source for unknown asset " + assetId + "."
16869 });
16870 if (asset.source !== undefined)
16871 error({
16872 code: 'ASSET_SOURCE_ALREADY_SET',
16873 message: "Plugin error - Unable to set asset source for " + asset.name + ", source already set."
16874 });
16875 if (typeof source !== 'string' && !source)
16876 error({
16877 code: 'ASSET_SOURCE_MISSING',
16878 message: "Plugin error creating asset " + name + ", setAssetSource call without a source."
16879 });
16880 asset.source = source;
16881 if (outputBundle)
16882 finaliseAsset(asset, outputBundle, assetFileNames);
16883 },
16884 getAssetFileName: function (assetId) {
16885 var asset = assetsById.get(assetId);
16886 if (!asset)
16887 error({
16888 code: 'ASSET_NOT_FOUND',
16889 message: "Plugin error - Unable to get asset filename for unknown asset " + assetId + "."
16890 });
16891 if (asset.fileName === undefined)
16892 error({
16893 code: 'ASSET_NOT_FINALISED',
16894 message: "Plugin error - Unable to get asset file name for asset " + assetId + ". Ensure that the source is set and that generate is called first."
16895 });
16896 return asset.fileName;
16897 }
16898 };
16899}
16900function finaliseAsset(asset, outputBundle, assetFileNames) {
16901 var fileName = getAssetFileName(asset, outputBundle, assetFileNames);
16902 asset.fileName = fileName;
16903 outputBundle[fileName] = {
16904 fileName: fileName,
16905 isAsset: true,
16906 source: asset.source
16907 };
16908}
16909function createTransformEmitAsset(assetsById, emitAsset) {
16910 var assets = [];
16911 return {
16912 assets: assets,
16913 emitAsset: function (name, source) {
16914 var assetId = emitAsset(name, source);
16915 var asset = assetsById.get(assetId);
16916 // distinguish transform assets
16917 assets.push({
16918 fileName: undefined,
16919 name: asset.name,
16920 source: asset.source
16921 });
16922 return assetId;
16923 }
16924 };
16925}
16926
16927var CHAR_CODE_A = 97;
16928var CHAR_CODE_0 = 48;
16929function intToHex(num) {
16930 if (num < 10)
16931 return String.fromCharCode(CHAR_CODE_0 + num);
16932 else
16933 return String.fromCharCode(CHAR_CODE_A + (num - 10));
16934}
16935function Uint8ArrayToHexString(buffer) {
16936 var str = '';
16937 // hex conversion - 2 chars per 8 bit component
16938 for (var i = 0; i < buffer.length; i++) {
16939 var num = buffer[i];
16940 // big endian conversion, but whatever
16941 str += intToHex(num >> 4);
16942 str += intToHex(num & 0xf);
16943 }
16944 return str;
16945}
16946function Uint8ArrayXor(to, from) {
16947 for (var i = 0; i < to.length; i++)
16948 to[i] = to[i] ^ from[i];
16949 return to;
16950}
16951function randomUint8Array(len) {
16952 var buffer = new Uint8Array(len);
16953 for (var i = 0; i < buffer.length; i++)
16954 buffer[i] = Math.random() * (2 << 8);
16955 return buffer;
16956}
16957
16958function assignChunkColouringHashes(entryModules, manualChunkModules) {
16959 var _a, _b, _c;
16960 var currentEntry, currentEntryHash;
16961 var modulesVisitedForCurrentEntry;
16962 var handledEntryPoints = {};
16963 var dynamicImports = [];
16964 var addCurrentEntryColourToModule = function (module) {
16965 if (currentEntry.chunkAlias) {
16966 module.chunkAlias = currentEntry.chunkAlias;
16967 module.entryPointsHash = currentEntryHash;
16968 }
16969 else {
16970 Uint8ArrayXor(module.entryPointsHash, currentEntryHash);
16971 }
16972 for (var _i = 0, _a = module.dependencies; _i < _a.length; _i++) {
16973 var dependency = _a[_i];
16974 if (dependency instanceof ExternalModule || dependency.id in modulesVisitedForCurrentEntry) {
16975 continue;
16976 }
16977 modulesVisitedForCurrentEntry[dependency.id] = true;
16978 if (!handledEntryPoints[dependency.id] && !dependency.chunkAlias)
16979 addCurrentEntryColourToModule(dependency);
16980 }
16981 for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
16982 var resolution = _c[_b].resolution;
16983 if (resolution instanceof Module &&
16984 resolution.dynamicallyImportedBy.length > 0 &&
16985 !resolution.chunkAlias) {
16986 dynamicImports.push(resolution);
16987 }
16988 }
16989 };
16990 if (manualChunkModules) {
16991 for (var _i = 0, _d = Object.keys(manualChunkModules); _i < _d.length; _i++) {
16992 var chunkName = _d[_i];
16993 currentEntryHash = randomUint8Array(10);
16994 for (var _e = 0, _f = manualChunkModules[chunkName]; _e < _f.length; _e++) {
16995 currentEntry = _f[_e];
16996 if (currentEntry.chunkAlias) {
16997 error({
16998 code: 'INVALID_CHUNK',
16999 message: "Cannot assign " + relative(process.cwd(), currentEntry.id) + " to the \"" + chunkName + "\" chunk as it is already in the \"" + currentEntry.chunkAlias + "\" chunk.\nTry defining \"" + chunkName + "\" first in the manualChunks definitions of the Rollup configuration."
17000 });
17001 }
17002 currentEntry.chunkAlias = chunkName;
17003 modulesVisitedForCurrentEntry = (_a = {}, _a[currentEntry.id] = true, _a);
17004 addCurrentEntryColourToModule(currentEntry);
17005 }
17006 }
17007 }
17008 for (var _g = 0, entryModules_1 = entryModules; _g < entryModules_1.length; _g++) {
17009 currentEntry = entryModules_1[_g];
17010 handledEntryPoints[currentEntry.id] = true;
17011 currentEntryHash = randomUint8Array(10);
17012 modulesVisitedForCurrentEntry = (_b = {}, _b[currentEntry.id] = null, _b);
17013 addCurrentEntryColourToModule(currentEntry);
17014 }
17015 for (var _h = 0, dynamicImports_1 = dynamicImports; _h < dynamicImports_1.length; _h++) {
17016 currentEntry = dynamicImports_1[_h];
17017 if (handledEntryPoints[currentEntry.id]) {
17018 continue;
17019 }
17020 handledEntryPoints[currentEntry.id] = true;
17021 currentEntryHash = randomUint8Array(10);
17022 modulesVisitedForCurrentEntry = (_c = {}, _c[currentEntry.id] = null, _c);
17023 addCurrentEntryColourToModule(currentEntry);
17024 }
17025}
17026
17027function mkdirpath(path) {
17028 var dir = dirname(path);
17029 try {
17030 readdirSync(dir);
17031 }
17032 catch (err) {
17033 mkdirpath(dir);
17034 try {
17035 mkdirSync(dir);
17036 }
17037 catch (err2) {
17038 if (err2.code !== 'EEXIST') {
17039 throw err2;
17040 }
17041 }
17042 }
17043}
17044function writeFile(dest, data) {
17045 return new Promise(function (fulfil, reject) {
17046 mkdirpath(dest);
17047 writeFile$1(dest, data, function (err) {
17048 if (err) {
17049 reject(err);
17050 }
17051 else {
17052 fulfil();
17053 }
17054 });
17055 });
17056}
17057
17058function getRollupDefaultPlugin(options) {
17059 return {
17060 name: 'Rollup Core',
17061 resolveId: createResolveId(options),
17062 load: function (id) {
17063 return readFileSync(id, 'utf-8');
17064 },
17065 resolveDynamicImport: function (specifier, parentId) {
17066 if (typeof specifier === 'string' && !this.isExternal(specifier, parentId, false))
17067 return this.resolveId(specifier, parentId);
17068 }
17069 };
17070}
17071function findFile(file, preserveSymlinks) {
17072 try {
17073 var stats = lstatSync(file);
17074 if (!preserveSymlinks && stats.isSymbolicLink())
17075 return findFile(realpathSync(file), preserveSymlinks);
17076 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
17077 // check case
17078 var name = basename(file);
17079 var files = readdirSync(dirname(file));
17080 if (files.indexOf(name) !== -1)
17081 return file;
17082 }
17083 }
17084 catch (err) {
17085 // suppress
17086 }
17087}
17088function addJsExtensionIfNecessary(file, preserveSymlinks) {
17089 var found = findFile(file, preserveSymlinks);
17090 if (found)
17091 return found;
17092 found = findFile(file + '.mjs', preserveSymlinks);
17093 if (found)
17094 return found;
17095 found = findFile(file + '.js', preserveSymlinks);
17096 return found;
17097}
17098function createResolveId(options) {
17099 return function (importee, importer) {
17100 if (typeof process === 'undefined') {
17101 error({
17102 code: 'MISSING_PROCESS',
17103 message: "It looks like you're using Rollup in a non-Node.js environment. This means you must supply a plugin with custom resolveId and load functions",
17104 url: 'https://rollupjs.org/guide/en#a-simple-example'
17105 });
17106 }
17107 // external modules (non-entry modules that start with neither '.' or '/')
17108 // are skipped at this stage.
17109 if (importer !== undefined && !isAbsolute(importee) && importee[0] !== '.')
17110 return null;
17111 // `resolve` processes paths from right to left, prepending them until an
17112 // absolute path is created. Absolute importees therefore shortcircuit the
17113 // resolve call and require no special handing on our part.
17114 // See https://nodejs.org/api/path.html#path_path_resolve_paths
17115 return addJsExtensionIfNecessary(resolve$1(importer ? dirname(importer) : resolve$1(), importee), options.preserveSymlinks);
17116 };
17117}
17118
17119var deprecatedHookNames = {
17120 ongenerate: 'generateBundle',
17121 onwrite: 'generateBundle',
17122 transformBundle: 'renderChunk',
17123 transformChunk: 'renderChunk'
17124};
17125function createPluginDriver(graph, options, pluginCache, watcher) {
17126 var plugins = (options.plugins || []).concat([getRollupDefaultPlugin(options)]);
17127 var _a = createAssetPluginHooks(graph.assetsById), emitAsset = _a.emitAsset, getAssetFileName = _a.getAssetFileName, setAssetSource = _a.setAssetSource;
17128 var existingPluginKeys = {};
17129 var hasLoadersOrTransforms = false;
17130 var pluginContexts = plugins.map(function (plugin, pidx) {
17131 var cacheable = true;
17132 if (typeof plugin.cacheKey !== 'string') {
17133 if (typeof plugin.name !== 'string' || existingPluginKeys[plugin.name]) {
17134 cacheable = false;
17135 }
17136 else {
17137 existingPluginKeys[plugin.name] = true;
17138 }
17139 }
17140 if (!hasLoadersOrTransforms &&
17141 (plugin.load || plugin.transform || plugin.transformBundle || plugin.transformChunk))
17142 hasLoadersOrTransforms = true;
17143 var cacheInstance;
17144 if (!pluginCache) {
17145 cacheInstance = noCache;
17146 }
17147 else if (cacheable) {
17148 var cacheKey = plugin.cacheKey || plugin.name;
17149 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
17150 }
17151 else {
17152 cacheInstance = uncacheablePlugin(plugin.name);
17153 }
17154 var watcherDeprecationWarningShown = false;
17155 function deprecatedWatchListener(event, handler) {
17156 if (!watcherDeprecationWarningShown) {
17157 context.warn({
17158 code: 'PLUGIN_WATCHER_DEPRECATED',
17159 message: "this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead."
17160 });
17161 watcherDeprecationWarningShown = true;
17162 }
17163 return watcher.on(event, handler);
17164 }
17165 var context = {
17166 addWatchFile: function (id) {
17167 if (graph.finished)
17168 this.error('addWatchFile can only be called during the build.');
17169 graph.watchFiles[id] = true;
17170 },
17171 cache: cacheInstance,
17172 emitAsset: emitAsset,
17173 error: function (err) {
17174 if (typeof err === 'string')
17175 err = { message: err };
17176 if (err.code)
17177 err.pluginCode = err.code;
17178 err.code = 'PLUGIN_ERROR';
17179 err.plugin = plugin.name || "Plugin at position " + (pidx + 1);
17180 error(err);
17181 },
17182 isExternal: function (id, parentId, isResolved) {
17183 if (isResolved === void 0) { isResolved = false; }
17184 return graph.isExternal(id, parentId, isResolved);
17185 },
17186 getAssetFileName: getAssetFileName,
17187 getModuleInfo: function (moduleId) {
17188 var foundModule = graph.moduleById.get(moduleId);
17189 if (foundModule == null) {
17190 throw new Error("Unable to find module " + moduleId);
17191 }
17192 return {
17193 id: foundModule.id,
17194 importedIds: foundModule.isExternal
17195 ? []
17196 : foundModule.sources.map(function (id) { return foundModule.resolvedIds[id].id; }),
17197 isExternal: !!foundModule.isExternal
17198 };
17199 },
17200 meta: {
17201 rollupVersion: version
17202 },
17203 moduleIds: graph.moduleById.keys(),
17204 parse: graph.contextParse,
17205 resolveId: function (id, parent) {
17206 return pluginDriver.hookFirst('resolveId', [id, parent]);
17207 },
17208 setAssetSource: setAssetSource,
17209 warn: function (warning) {
17210 if (typeof warning === 'string')
17211 warning = { message: warning };
17212 if (warning.code)
17213 warning.pluginCode = warning.code;
17214 warning.code = 'PLUGIN_WARNING';
17215 warning.plugin = plugin.name || "Plugin at position " + (pidx + 1);
17216 graph.warn(warning);
17217 },
17218 watcher: watcher
17219 ? __assign({}, watcher, { addListener: deprecatedWatchListener, on: deprecatedWatchListener })
17220 : undefined
17221 };
17222 return context;
17223 });
17224 function runHookSync(hookName, args, pidx, permitValues, hookContext) {
17225 if (permitValues === void 0) { permitValues = false; }
17226 var plugin = plugins[pidx];
17227 var context = pluginContexts[pidx];
17228 var hook = plugin[hookName];
17229 if (!hook)
17230 return;
17231 var deprecatedHookNewName = deprecatedHookNames[hookName];
17232 if (deprecatedHookNewName)
17233 context.warn(hookDeprecationWarning(hookName, deprecatedHookNewName, plugin, pidx));
17234 if (hookContext) {
17235 context = hookContext(context, plugin);
17236 if (!context || context === pluginContexts[pidx])
17237 throw new Error('Internal Rollup error: hookContext must return a new context object.');
17238 }
17239 try {
17240 // permit values allows values to be returned instead of a functional hook
17241 if (typeof hook !== 'function') {
17242 if (permitValues)
17243 return hook;
17244 error({
17245 code: 'INVALID_PLUGIN_HOOK',
17246 message: "Error running plugin hook " + hookName + " for " + (plugin.name ||
17247 "Plugin at position " + (pidx + 1)) + ", expected a function hook."
17248 });
17249 }
17250 return hook.apply(context, args);
17251 }
17252 catch (err) {
17253 if (typeof err === 'string')
17254 err = { message: err };
17255 if (err.code !== 'PLUGIN_ERROR') {
17256 if (err.code)
17257 err.pluginCode = err.code;
17258 err.code = 'PLUGIN_ERROR';
17259 }
17260 err.plugin = plugin.name || "Plugin at position " + (pidx + 1);
17261 err.hook = hookName;
17262 error(err);
17263 }
17264 }
17265 function runHook(hookName, args, pidx, permitValues, hookContext) {
17266 if (permitValues === void 0) { permitValues = false; }
17267 var plugin = plugins[pidx];
17268 var context = pluginContexts[pidx];
17269 var hook = plugin[hookName];
17270 if (!hook)
17271 return;
17272 var deprecatedHookNewName = deprecatedHookNames[hookName];
17273 if (deprecatedHookNewName)
17274 context.warn(hookDeprecationWarning(hookName, deprecatedHookNewName, plugin, pidx));
17275 if (hookContext) {
17276 context = hookContext(context, plugin);
17277 if (!context || context === pluginContexts[pidx])
17278 throw new Error('Internal Rollup error: hookContext must return a new context object.');
17279 }
17280 return Promise.resolve()
17281 .then(function () {
17282 // permit values allows values to be returned instead of a functional hook
17283 if (typeof hook !== 'function') {
17284 if (permitValues)
17285 return hook;
17286 error({
17287 code: 'INVALID_PLUGIN_HOOK',
17288 message: "Error running plugin hook " + hookName + " for " + (plugin.name ||
17289 "Plugin at position " + (pidx + 1)) + ", expected a function hook."
17290 });
17291 }
17292 return hook.apply(context, args);
17293 })
17294 .catch(function (err) {
17295 if (typeof err === 'string')
17296 err = { message: err };
17297 if (err.code !== 'PLUGIN_ERROR') {
17298 if (err.code)
17299 err.pluginCode = err.code;
17300 err.code = 'PLUGIN_ERROR';
17301 }
17302 err.plugin = plugin.name || "Plugin at position " + (pidx + 1);
17303 err.hook = hookName;
17304 error(err);
17305 });
17306 }
17307 var pluginDriver = {
17308 emitAsset: emitAsset,
17309 getAssetFileName: getAssetFileName,
17310 hasLoadersOrTransforms: hasLoadersOrTransforms,
17311 // chains, ignores returns
17312 hookSeq: function (name, args, hookContext) {
17313 var promise = Promise.resolve();
17314 var _loop_1 = function (i) {
17315 promise = promise.then(function () {
17316 return runHook(name, args, i, false, hookContext);
17317 });
17318 };
17319 for (var i = 0; i < plugins.length; i++) {
17320 _loop_1(i);
17321 }
17322 return promise;
17323 },
17324 // chains, ignores returns
17325 hookSeqSync: function (name, args, hookContext) {
17326 for (var i = 0; i < plugins.length; i++)
17327 runHookSync(name, args, i, false, hookContext);
17328 },
17329 // chains, first non-null result stops and returns
17330 hookFirst: function (name, args, hookContext) {
17331 var promise = Promise.resolve();
17332 var _loop_2 = function (i) {
17333 promise = promise.then(function (result) {
17334 if (result != null)
17335 return result;
17336 return runHook(name, args, i, false, hookContext);
17337 });
17338 };
17339 for (var i = 0; i < plugins.length; i++) {
17340 _loop_2(i);
17341 }
17342 return promise;
17343 },
17344 // parallel, ignores returns
17345 hookParallel: function (name, args, hookContext) {
17346 var promises = [];
17347 for (var i = 0; i < plugins.length; i++) {
17348 var hookPromise = runHook(name, args, i, false, hookContext);
17349 if (!hookPromise)
17350 continue;
17351 promises.push(hookPromise);
17352 }
17353 return Promise.all(promises).then(function () { });
17354 },
17355 // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
17356 hookReduceArg0: function (name, _a, reduce, hookContext) {
17357 var arg0 = _a[0], args = _a.slice(1);
17358 var promise = Promise.resolve(arg0);
17359 var _loop_3 = function (i) {
17360 promise = promise.then(function (arg0) {
17361 var hookPromise = runHook(name, [arg0].concat(args), i, false, hookContext);
17362 if (!hookPromise)
17363 return arg0;
17364 return hookPromise.then(function (result) {
17365 return reduce.call(pluginContexts[i], arg0, result, plugins[i]);
17366 });
17367 });
17368 };
17369 for (var i = 0; i < plugins.length; i++) {
17370 _loop_3(i);
17371 }
17372 return promise;
17373 },
17374 // chains, synchronically reduces returns of type R, to type T, handling the reduced value as the first hook argument
17375 hookReduceArg0Sync: function (name, _a, reduce, hookContext) {
17376 var arg0 = _a[0], args = _a.slice(1);
17377 for (var i = 0; i < plugins.length; i++) {
17378 var result = runHookSync(name, [arg0].concat(args), i, false, hookContext);
17379 arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]);
17380 }
17381 return arg0;
17382 },
17383 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
17384 hookReduceValue: function (name, initial, args, reduce, hookContext) {
17385 var promise = Promise.resolve(initial);
17386 var _loop_4 = function (i) {
17387 promise = promise.then(function (value) {
17388 var hookPromise = runHook(name, args, i, true, hookContext);
17389 if (!hookPromise)
17390 return value;
17391 return hookPromise.then(function (result) {
17392 return reduce.call(pluginContexts[i], value, result, plugins[i]);
17393 });
17394 });
17395 };
17396 for (var i = 0; i < plugins.length; i++) {
17397 _loop_4(i);
17398 }
17399 return promise;
17400 }
17401 };
17402 return pluginDriver;
17403}
17404function createPluginCache(cache) {
17405 return {
17406 has: function (id) {
17407 var item = cache[id];
17408 if (!item)
17409 return false;
17410 item[0] = 0;
17411 return true;
17412 },
17413 get: function (id) {
17414 var item = cache[id];
17415 if (!item)
17416 return undefined;
17417 item[0] = 0;
17418 return item[1];
17419 },
17420 set: function (id, value) {
17421 cache[id] = [0, value];
17422 },
17423 delete: function (id) {
17424 return delete cache[id];
17425 }
17426 };
17427}
17428function trackPluginCache(pluginCache) {
17429 var result = { used: false, cache: undefined };
17430 result.cache = {
17431 has: function (id) {
17432 result.used = true;
17433 return pluginCache.has(id);
17434 },
17435 get: function (id) {
17436 result.used = true;
17437 return pluginCache.get(id);
17438 },
17439 set: function (id, value) {
17440 result.used = true;
17441 return pluginCache.set(id, value);
17442 },
17443 delete: function (id) {
17444 result.used = true;
17445 return pluginCache.delete(id);
17446 }
17447 };
17448 return result;
17449}
17450var noCache = {
17451 has: function () {
17452 return false;
17453 },
17454 get: function () {
17455 return undefined;
17456 },
17457 set: function () { },
17458 delete: function () {
17459 return false;
17460 }
17461};
17462function uncacheablePluginError(pluginName) {
17463 if (!pluginName)
17464 error({
17465 code: 'ANONYMOUS_PLUGIN_CACHE',
17466 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
17467 });
17468 else
17469 error({
17470 code: 'DUPLICATE_PLUGIN_NAME',
17471 message: "The plugin name " + pluginName + " is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user)."
17472 });
17473}
17474var uncacheablePlugin = function (pluginName) { return ({
17475 has: function () {
17476 uncacheablePluginError(pluginName);
17477 return false;
17478 },
17479 get: function () {
17480 uncacheablePluginError(pluginName);
17481 return undefined;
17482 },
17483 set: function () {
17484 uncacheablePluginError(pluginName);
17485 },
17486 delete: function () {
17487 uncacheablePluginError(pluginName);
17488 return false;
17489 }
17490}); };
17491function hookDeprecationWarning(name, newName, plugin, pidx) {
17492 return {
17493 code: name.toUpperCase() + '_HOOK_DEPRECATED',
17494 message: "The " + name + " hook used by plugin " + (plugin.name ||
17495 "at position " + (pidx + 1)) + " is deprecated. The " + newName + " hook should be used instead."
17496 };
17497}
17498
17499function transform(graph, source, module) {
17500 var id = module.id;
17501 var sourcemapChain = [];
17502 var originalSourcemap = typeof source.map === 'string' ? JSON.parse(source.map) : source.map;
17503 if (originalSourcemap && typeof originalSourcemap.mappings === 'string')
17504 originalSourcemap.mappings = decode(originalSourcemap.mappings);
17505 var baseEmitAsset = graph.pluginDriver.emitAsset;
17506 var originalCode = source.code;
17507 var ast = source.ast;
17508 var transformDependencies;
17509 var assets;
17510 var customTransformCache = false;
17511 var trackedPluginCache;
17512 var curPlugin;
17513 var curSource = source.code;
17514 function transformReducer(code, result, plugin) {
17515 // track which plugins use the custom this.cache to opt-out of transform caching
17516 if (!customTransformCache && trackedPluginCache.used)
17517 customTransformCache = true;
17518 if (customTransformCache) {
17519 if (result && Array.isArray(result.dependencies)) {
17520 for (var _i = 0, _a = result.dependencies; _i < _a.length; _i++) {
17521 var dep = _a[_i];
17522 var depId = resolve$1(dirname(id), dep);
17523 if (!graph.watchFiles[depId])
17524 graph.watchFiles[depId] = true;
17525 }
17526 }
17527 }
17528 else {
17529 // assets emitted by transform are transformDependencies
17530 if (assets.length)
17531 module.transformAssets = assets;
17532 if (result && Array.isArray(result.dependencies)) {
17533 // not great, but a useful way to track this without assuming WeakMap
17534 if (!curPlugin.warnedTransformDependencies)
17535 this.warn({
17536 code: 'TRANSFORM_DEPENDENCIES_DEPRECATED',
17537 message: "Returning \"dependencies\" from plugin transform hook is deprecated for using this.addWatchFile() instead."
17538 });
17539 curPlugin.warnedTransformDependencies = true;
17540 if (!transformDependencies)
17541 transformDependencies = [];
17542 for (var _b = 0, _c = result.dependencies; _b < _c.length; _b++) {
17543 var dep = _c[_b];
17544 transformDependencies.push(resolve$1(dirname(id), dep));
17545 }
17546 }
17547 }
17548 if (result == null)
17549 return code;
17550 if (typeof result === 'string') {
17551 result = {
17552 ast: undefined,
17553 code: result,
17554 map: undefined
17555 };
17556 }
17557 else if (typeof result.map === 'string') {
17558 // `result.map` can only be a string if `result` isn't
17559 result.map = JSON.parse(result.map);
17560 }
17561 if (result.map && typeof result.map.mappings === 'string') {
17562 result.map.mappings = decode(result.map.mappings);
17563 }
17564 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
17565 if (result.map !== null) {
17566 sourcemapChain.push(result.map || { missing: true, plugin: plugin.name });
17567 }
17568 ast = result.ast;
17569 return result.code;
17570 }
17571 var setAssetSourceErr;
17572 return graph.pluginDriver
17573 .hookReduceArg0('transform', [curSource, id], transformReducer, function (pluginContext, plugin) {
17574 var _a;
17575 curPlugin = plugin;
17576 if (plugin.cacheKey)
17577 customTransformCache = true;
17578 else
17579 trackedPluginCache = trackPluginCache(pluginContext.cache);
17580 var emitAsset;
17581 (_a = createTransformEmitAsset(graph.assetsById, baseEmitAsset), assets = _a.assets, emitAsset = _a.emitAsset);
17582 return __assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn: function (warning, pos) {
17583 if (typeof warning === 'string')
17584 warning = { message: warning };
17585 if (pos)
17586 augmentCodeLocation(warning, pos, curSource, id);
17587 warning.id = id;
17588 warning.hook = 'transform';
17589 pluginContext.warn(warning);
17590 },
17591 error: function (err, pos) {
17592 if (typeof err === 'string')
17593 err = { message: err };
17594 if (pos)
17595 augmentCodeLocation(err, pos, curSource, id);
17596 err.id = id;
17597 err.hook = 'transform';
17598 pluginContext.error(err);
17599 },
17600 emitAsset: emitAsset,
17601 addWatchFile: function (id) {
17602 if (!transformDependencies)
17603 transformDependencies = [];
17604 transformDependencies.push(id);
17605 pluginContext.addWatchFile(id);
17606 },
17607 setAssetSource: function (assetId, source) {
17608 pluginContext.setAssetSource(assetId, source);
17609 if (!customTransformCache && !setAssetSourceErr) {
17610 try {
17611 this.error({
17612 code: 'INVALID_SETASSETSOURCE',
17613 message: "setAssetSource cannot be called in transform for caching reasons. Use emitAsset with a source, or call setAssetSource in another hook."
17614 });
17615 }
17616 catch (err) {
17617 setAssetSourceErr = err;
17618 }
17619 }
17620 } });
17621 })
17622 .catch(function (err) {
17623 if (typeof err === 'string')
17624 err = { message: err };
17625 if (err.code !== 'PLUGIN_ERROR') {
17626 if (err.code)
17627 err.pluginCode = err.code;
17628 err.code = 'PLUGIN_ERROR';
17629 }
17630 err.id = id;
17631 error(err);
17632 })
17633 .then(function (code) {
17634 if (!customTransformCache && setAssetSourceErr)
17635 throw setAssetSourceErr;
17636 return {
17637 ast: ast,
17638 code: code,
17639 customTransformCache: customTransformCache,
17640 originalCode: originalCode,
17641 originalSourcemap: originalSourcemap,
17642 sourcemapChain: sourcemapChain,
17643 transformDependencies: transformDependencies
17644 };
17645 });
17646}
17647
17648function makeOnwarn() {
17649 var warned = Object.create(null);
17650 return function (warning) {
17651 var str = warning.toString();
17652 if (str in warned)
17653 return;
17654 console.error(str); //eslint-disable-line no-console
17655 warned[str] = true;
17656 };
17657}
17658function normalizeRelativeExternalId(importee, source) {
17659 return isRelative(source) ? resolve$1(importee, '..', source) : source;
17660}
17661var Graph = /** @class */ (function () {
17662 function Graph(options, watcher) {
17663 var _this = this;
17664 var _a;
17665 this.assetsById = new Map();
17666 this.curChunkIndex = 0;
17667 // track graph build status as each graph instance is used only once
17668 this.finished = false;
17669 this.moduleById = new Map();
17670 this.needsTreeshakingPass = false;
17671 this.watchFiles = Object.create(null);
17672 this.externalModules = [];
17673 this.modules = [];
17674 this.curChunkIndex = 0;
17675 this.deoptimizationTracker = new EntityPathTracker();
17676 this.cachedModules = new Map();
17677 if (options.cache) {
17678 if (options.cache.modules)
17679 for (var _i = 0, _b = options.cache.modules; _i < _b.length; _i++) {
17680 var module = _b[_i];
17681 this.cachedModules.set(module.id, module);
17682 }
17683 }
17684 if (options.cache !== false) {
17685 this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
17686 // increment access counter
17687 for (var name in this.pluginCache) {
17688 var cache = this.pluginCache[name];
17689 for (var _c = 0, _d = Object.keys(cache); _c < _d.length; _c++) {
17690 var key = _d[_c];
17691 cache[key][0]++;
17692 }
17693 }
17694 }
17695 this.preserveModules = options.preserveModules;
17696 this.cacheExpiry = options.experimentalCacheExpiry;
17697 if (!options.input) {
17698 throw new Error('You must supply options.input to rollup');
17699 }
17700 this.treeshake = options.treeshake !== false;
17701 if (this.treeshake) {
17702 this.treeshakingOptions = options.treeshake
17703 ? {
17704 annotations: options.treeshake.annotations !== false,
17705 propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
17706 pureExternalModules: options.treeshake.pureExternalModules
17707 }
17708 : { propertyReadSideEffects: true, annotations: true, pureExternalModules: false };
17709 if (this.treeshakingOptions.pureExternalModules === true) {
17710 this.isPureExternalModule = function () { return true; };
17711 }
17712 else if (typeof this.treeshakingOptions.pureExternalModules === 'function') {
17713 this.isPureExternalModule = this.treeshakingOptions.pureExternalModules;
17714 }
17715 else if (Array.isArray(this.treeshakingOptions.pureExternalModules)) {
17716 var pureExternalModules_1 = new Set(this.treeshakingOptions.pureExternalModules);
17717 this.isPureExternalModule = function (id) { return pureExternalModules_1.has(id); };
17718 }
17719 else {
17720 this.isPureExternalModule = function () { return false; };
17721 }
17722 }
17723 else {
17724 this.isPureExternalModule = function () { return false; };
17725 }
17726 this.contextParse = function (code, options) {
17727 if (options === void 0) { options = {}; }
17728 return _this.acornParser.parse(code, __assign({}, defaultAcornOptions, options, _this.acornOptions));
17729 };
17730 this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher);
17731 if (watcher) {
17732 var handleChange_1 = function (id) { return _this.pluginDriver.hookSeqSync('watchChange', [id]); };
17733 watcher.on('change', handleChange_1);
17734 watcher.once('restart', function () {
17735 watcher.removeListener('change', handleChange_1);
17736 });
17737 }
17738 if (typeof options.external === 'function') {
17739 var external_1 = options.external;
17740 this.isExternal = function (id, parentId, isResolved) {
17741 return !id.startsWith('\0') && external_1(id, parentId, isResolved);
17742 };
17743 }
17744 else {
17745 var external = options.external;
17746 var ids_1 = new Set(Array.isArray(external) ? external : external ? [external] : []);
17747 this.isExternal = function (id) { return ids_1.has(id); };
17748 }
17749 this.shimMissingExports = options.shimMissingExports;
17750 this.scope = new GlobalScope();
17751 this.context = String(options.context);
17752 var optionsModuleContext = options.moduleContext;
17753 if (typeof optionsModuleContext === 'function') {
17754 this.getModuleContext = function (id) { return optionsModuleContext(id) || _this.context; };
17755 }
17756 else if (typeof optionsModuleContext === 'object') {
17757 var moduleContext_1 = new Map();
17758 for (var key in optionsModuleContext) {
17759 moduleContext_1.set(resolve$1(key), optionsModuleContext[key]);
17760 }
17761 this.getModuleContext = function (id) { return moduleContext_1.get(id) || _this.context; };
17762 }
17763 else {
17764 this.getModuleContext = function () { return _this.context; };
17765 }
17766 this.onwarn = options.onwarn || makeOnwarn();
17767 this.acornOptions = options.acorn || {};
17768 var acornPluginsToInject = [];
17769 acornPluginsToInject.push(dynamicImport);
17770 acornPluginsToInject.push(acornImportMeta);
17771 acornPluginsToInject.push(acornBigint);
17772 if (options.experimentalTopLevelAwait) {
17773 this.acornOptions.allowAwaitOutsideFunction = true;
17774 }
17775 var acornInjectPlugins = options.acornInjectPlugins;
17776 acornPluginsToInject.push.apply(acornPluginsToInject, (Array.isArray(acornInjectPlugins)
17777 ? acornInjectPlugins
17778 : acornInjectPlugins
17779 ? [acornInjectPlugins]
17780 : []));
17781 this.acornParser = (_a = Parser$1).extend.apply(_a, acornPluginsToInject);
17782 }
17783 Graph.prototype.build = function (entryModules, manualChunks, inlineDynamicImports) {
17784 // Phase 1 – discovery. We load the entry module and find which
17785 // modules it imports, and import those, until we have all
17786 // of the entry module's dependencies
17787 var _this = this;
17788 timeStart('parse modules', 2);
17789 return this.loadEntryModules(entryModules, manualChunks).then(function (_a) {
17790 var entryModules = _a.entryModules, entryModuleAliases = _a.entryModuleAliases, manualChunkModules = _a.manualChunkModules;
17791 timeEnd('parse modules', 2);
17792 // Phase 2 - linking. We populate the module dependency links and
17793 // determine the topological execution order for the bundle
17794 timeStart('analyse dependency graph', 2);
17795 for (var i = 0; i < entryModules.length; i++) {
17796 var entryModule = entryModules[i];
17797 var duplicateIndex = entryModules.indexOf(entryModule, i + 1);
17798 if (duplicateIndex !== -1) {
17799 error({
17800 code: 'DUPLICATE_ENTRY_POINTS',
17801 message: "Duplicate entry points detected. The input entries " + entryModuleAliases[i] + " and " + entryModuleAliases[duplicateIndex] + " both point to the same module, " + entryModule.id
17802 });
17803 }
17804 }
17805 _this.link(entryModules);
17806 timeEnd('analyse dependency graph', 2);
17807 // Phase 3 – marking. We include all statements that should be included
17808 timeStart('mark included statements', 2);
17809 if (inlineDynamicImports) {
17810 if (entryModules.length > 1)
17811 throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
17812 }
17813 for (var _i = 0, entryModules_1 = entryModules; _i < entryModules_1.length; _i++) {
17814 var entryModule = entryModules_1[_i];
17815 entryModule.includeAllExports();
17816 }
17817 _this.includeMarked(_this.modules);
17818 // check for unused external imports
17819 for (var _b = 0, _c = _this.externalModules; _b < _c.length; _b++) {
17820 var externalModule = _c[_b];
17821 externalModule.warnUnusedImports();
17822 }
17823 timeEnd('mark included statements', 2);
17824 // Phase 4 – we construct the chunks, working out the optimal chunking using
17825 // entry point graph colouring, before generating the import and export facades
17826 timeStart('generate chunks', 2);
17827 if (!_this.preserveModules && !inlineDynamicImports) {
17828 assignChunkColouringHashes(entryModules, manualChunkModules);
17829 }
17830 if (entryModuleAliases) {
17831 for (var i = entryModules.length - 1; i >= 0; i--) {
17832 entryModules[i].chunkAlias = entryModuleAliases[i];
17833 }
17834 }
17835 // TODO: there is one special edge case unhandled here and that is that any module
17836 // exposed as an unresolvable export * (to a graph external export *,
17837 // either as a namespace import reexported or top-level export *)
17838 // should be made to be its own entry point module before chunking
17839 var chunks = [];
17840 if (_this.preserveModules) {
17841 for (var _d = 0, _e = _this.modules; _d < _e.length; _d++) {
17842 var module = _e[_d];
17843 var chunk = new Chunk$1(_this, [module]);
17844 if (module.isEntryPoint || !chunk.isEmpty) {
17845 chunk.entryModules = [module];
17846 }
17847 chunks.push(chunk);
17848 }
17849 }
17850 else {
17851 var chunkModules = {};
17852 for (var _f = 0, _g = _this.modules; _f < _g.length; _f++) {
17853 var module = _g[_f];
17854 var entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
17855 var curChunk = chunkModules[entryPointsHashStr];
17856 if (curChunk) {
17857 curChunk.push(module);
17858 }
17859 else {
17860 chunkModules[entryPointsHashStr] = [module];
17861 }
17862 }
17863 for (var entryHashSum in chunkModules) {
17864 var chunkModulesOrdered = chunkModules[entryHashSum];
17865 sortByExecutionOrder(chunkModulesOrdered);
17866 var chunk = new Chunk$1(_this, chunkModulesOrdered);
17867 chunks.push(chunk);
17868 }
17869 }
17870 // for each chunk module, set up its imports to other
17871 // chunks, if those variables are included after treeshaking
17872 for (var _h = 0, chunks_1 = chunks; _h < chunks_1.length; _h++) {
17873 var chunk = chunks_1[_h];
17874 chunk.link();
17875 }
17876 // filter out empty dependencies
17877 chunks = chunks.filter(function (chunk) { return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.isManualChunk; });
17878 // then go over and ensure all entry chunks export their variables
17879 for (var _j = 0, chunks_2 = chunks; _j < chunks_2.length; _j++) {
17880 var chunk = chunks_2[_j];
17881 if (_this.preserveModules || chunk.entryModules.length > 0) {
17882 chunk.generateEntryExportsOrMarkAsTainted();
17883 }
17884 }
17885 // create entry point facades for entry module chunks that have tainted exports
17886 var facades = [];
17887 if (!_this.preserveModules) {
17888 for (var _k = 0, chunks_3 = chunks; _k < chunks_3.length; _k++) {
17889 var chunk = chunks_3[_k];
17890 for (var _l = 0, _m = chunk.entryModules; _l < _m.length; _l++) {
17891 var entryModule = _m[_l];
17892 if (chunk.facadeModule !== entryModule) {
17893 var entryPointFacade = new Chunk$1(_this, []);
17894 entryPointFacade.turnIntoFacade(entryModule);
17895 facades.push(entryPointFacade);
17896 }
17897 }
17898 }
17899 }
17900 timeEnd('generate chunks', 2);
17901 _this.finished = true;
17902 return chunks.concat(facades);
17903 });
17904 };
17905 Graph.prototype.finaliseAssets = function (assetFileNames) {
17906 var outputBundle = Object.create(null);
17907 this.assetsById.forEach(function (asset) {
17908 if (asset.source !== undefined)
17909 finaliseAsset(asset, outputBundle, assetFileNames);
17910 });
17911 return outputBundle;
17912 };
17913 Graph.prototype.getCache = function () {
17914 // handle plugin cache eviction
17915 for (var name in this.pluginCache) {
17916 var cache = this.pluginCache[name];
17917 var allDeleted = true;
17918 for (var _i = 0, _a = Object.keys(cache); _i < _a.length; _i++) {
17919 var key = _a[_i];
17920 if (cache[key][0] >= this.cacheExpiry)
17921 delete cache[key];
17922 else
17923 allDeleted = false;
17924 }
17925 if (allDeleted)
17926 delete this.pluginCache[name];
17927 }
17928 return {
17929 modules: this.modules.map(function (module) { return module.toJSON(); }),
17930 plugins: this.pluginCache
17931 };
17932 };
17933 Graph.prototype.includeMarked = function (modules) {
17934 if (this.treeshake) {
17935 var treeshakingPass = 1;
17936 do {
17937 timeStart("treeshaking pass " + treeshakingPass, 3);
17938 this.needsTreeshakingPass = false;
17939 for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
17940 var module = modules_1[_i];
17941 if (module.isExecuted)
17942 module.include();
17943 }
17944 timeEnd("treeshaking pass " + treeshakingPass++, 3);
17945 } while (this.needsTreeshakingPass);
17946 }
17947 else {
17948 // Necessary to properly replace namespace imports
17949 for (var _a = 0, modules_2 = modules; _a < modules_2.length; _a++) {
17950 var module = modules_2[_a];
17951 module.includeAllInBundle();
17952 }
17953 }
17954 };
17955 Graph.prototype.warn = function (warning) {
17956 warning.toString = function () {
17957 var str = '';
17958 if (warning.plugin)
17959 str += "(" + warning.plugin + " plugin) ";
17960 if (warning.loc)
17961 str += relativeId(warning.loc.file) + " (" + warning.loc.line + ":" + warning.loc.column + ") ";
17962 str += warning.message;
17963 return str;
17964 };
17965 this.onwarn(warning);
17966 };
17967 Graph.prototype.fetchAllDependencies = function (module) {
17968 var _this = this;
17969 var fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map(function (dynamicImportExpression, index) {
17970 return _this.pluginDriver
17971 .hookFirst('resolveDynamicImport', [dynamicImportExpression, module.id])
17972 .then(function (replacement) {
17973 if (!replacement)
17974 return;
17975 var dynamicImport = module.dynamicImports[index];
17976 dynamicImport.alias = getAliasName(replacement, typeof dynamicImportExpression === 'string' ? dynamicImportExpression : undefined);
17977 if (typeof dynamicImportExpression !== 'string') {
17978 dynamicImport.resolution = replacement;
17979 }
17980 else if (_this.isExternal(replacement, module.id, true)) {
17981 var externalModule = void 0;
17982 if (!_this.moduleById.has(replacement)) {
17983 externalModule = new ExternalModule({
17984 graph: _this,
17985 id: replacement
17986 });
17987 _this.externalModules.push(externalModule);
17988 _this.moduleById.set(replacement, module);
17989 }
17990 else {
17991 externalModule = _this.moduleById.get(replacement);
17992 }
17993 dynamicImport.resolution = externalModule;
17994 externalModule.exportsNamespace = true;
17995 }
17996 else {
17997 return _this.fetchModule(replacement, module.id).then(function (depModule) {
17998 dynamicImport.resolution = depModule;
17999 });
18000 }
18001 });
18002 }));
18003 fetchDynamicImportsPromise.catch(function () { });
18004 return Promise.all(module.sources.map(function (source) { return _this.resolveAndFetchDependency(module, source); })).then(function () { return fetchDynamicImportsPromise; });
18005 };
18006 Graph.prototype.fetchModule = function (id, importer) {
18007 var _this = this;
18008 // short-circuit cycles
18009 var existingModule = this.moduleById.get(id);
18010 if (existingModule) {
18011 if (existingModule.isExternal)
18012 throw new Error("Cannot fetch external module " + id);
18013 return Promise.resolve(existingModule);
18014 }
18015 var module = new Module(this, id);
18016 this.moduleById.set(id, module);
18017 this.watchFiles[id] = true;
18018 timeStart('load modules', 3);
18019 return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
18020 .catch(function (err) {
18021 timeEnd('load modules', 3);
18022 var msg = "Could not load " + id;
18023 if (importer)
18024 msg += " (imported by " + importer + ")";
18025 msg += ": " + err.message;
18026 throw new Error(msg);
18027 })
18028 .then(function (source) {
18029 timeEnd('load modules', 3);
18030 if (typeof source === 'string')
18031 return source;
18032 if (source && typeof source === 'object' && typeof source.code === 'string')
18033 return source;
18034 // TODO report which plugin failed
18035 error({
18036 code: 'BAD_LOADER',
18037 message: "Error loading " + relativeId(id) + ": plugin load hook should return a string, a { code, map } object, or nothing/null"
18038 });
18039 })
18040 .then(function (source) {
18041 var sourceDescription = typeof source === 'string'
18042 ? {
18043 ast: null,
18044 code: source
18045 }
18046 : source;
18047 var cachedModule = _this.cachedModules.get(id);
18048 if (cachedModule &&
18049 !cachedModule.customTransformCache &&
18050 cachedModule.originalCode === sourceDescription.code) {
18051 // re-emit transform assets
18052 if (cachedModule.transformAssets) {
18053 for (var _i = 0, _a = cachedModule.transformAssets; _i < _a.length; _i++) {
18054 var asset = _a[_i];
18055 _this.pluginDriver.emitAsset(asset.name, asset.source);
18056 }
18057 }
18058 return cachedModule;
18059 }
18060 return transform(_this, sourceDescription, module);
18061 })
18062 .then(function (source) {
18063 module.setSource(source);
18064 _this.modules.push(module);
18065 _this.moduleById.set(id, module);
18066 return _this.fetchAllDependencies(module).then(function () {
18067 for (var name in module.exports) {
18068 if (name !== 'default') {
18069 module.exportsAll[name] = module.id;
18070 }
18071 }
18072 module.exportAllSources.forEach(function (source) {
18073 var id = module.resolvedIds[source].id;
18074 var exportAllModule = _this.moduleById.get(id);
18075 if (exportAllModule.isExternal)
18076 return;
18077 for (var name in exportAllModule.exportsAll) {
18078 if (name in module.exportsAll) {
18079 _this.warn({
18080 code: 'NAMESPACE_CONFLICT',
18081 message: "Conflicting namespaces: " + relativeId(module.id) + " re-exports '" + name + "' from both " + relativeId(module.exportsAll[name]) + " and " + relativeId(exportAllModule.exportsAll[name]) + " (will be ignored)",
18082 name: name,
18083 reexporter: module.id,
18084 sources: [module.exportsAll[name], exportAllModule.exportsAll[name]]
18085 });
18086 }
18087 else {
18088 module.exportsAll[name] = exportAllModule.exportsAll[name];
18089 }
18090 }
18091 });
18092 return module;
18093 });
18094 });
18095 };
18096 Graph.prototype.link = function (entryModules) {
18097 for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
18098 var module = _a[_i];
18099 module.linkDependencies();
18100 }
18101 var _b = analyseModuleExecution(entryModules), orderedModules = _b.orderedModules, cyclePaths = _b.cyclePaths;
18102 for (var _c = 0, cyclePaths_1 = cyclePaths; _c < cyclePaths_1.length; _c++) {
18103 var cyclePath = cyclePaths_1[_c];
18104 this.warn({
18105 code: 'CIRCULAR_DEPENDENCY',
18106 importer: cyclePath[0],
18107 message: "Circular dependency: " + cyclePath.join(' -> ')
18108 });
18109 }
18110 this.modules = orderedModules;
18111 for (var _d = 0, _e = this.modules; _d < _e.length; _d++) {
18112 var module = _e[_d];
18113 module.bindReferences();
18114 }
18115 this.warnForMissingExports();
18116 };
18117 Graph.prototype.loadEntryModules = function (entryModules, manualChunks) {
18118 var _this = this;
18119 var removeAliasExtensions = false;
18120 var entryModuleIds;
18121 var entryModuleAliases;
18122 if (typeof entryModules === 'string')
18123 entryModules = [entryModules];
18124 if (Array.isArray(entryModules)) {
18125 removeAliasExtensions = true;
18126 entryModuleAliases = entryModules.concat([]);
18127 entryModuleIds = entryModules;
18128 }
18129 else {
18130 entryModuleAliases = Object.keys(entryModules);
18131 entryModuleIds = entryModuleAliases.map(function (name) { return entryModules[name]; });
18132 }
18133 var entryAndManualChunkIds = entryModuleIds.concat([]);
18134 if (manualChunks) {
18135 Object.keys(manualChunks).forEach(function (name) {
18136 var manualChunkIds = manualChunks[name];
18137 manualChunkIds.forEach(function (id) {
18138 if (entryAndManualChunkIds.indexOf(id) === -1)
18139 entryAndManualChunkIds.push(id);
18140 });
18141 });
18142 }
18143 return Promise.all(entryAndManualChunkIds.map(function (id) { return _this.loadModule(id); })).then(function (entryAndChunkModules) {
18144 if (removeAliasExtensions) {
18145 for (var i = 0; i < entryModuleAliases.length; i++)
18146 entryModuleAliases[i] = getAliasName(entryAndChunkModules[i].id, entryModuleAliases[i]);
18147 }
18148 var entryModules = entryAndChunkModules.slice(0, entryModuleIds.length);
18149 var manualChunkModules;
18150 if (manualChunks) {
18151 manualChunkModules = {};
18152 for (var _i = 0, _a = Object.keys(manualChunks); _i < _a.length; _i++) {
18153 var chunkName = _a[_i];
18154 var chunk = manualChunks[chunkName];
18155 manualChunkModules[chunkName] = chunk.map(function (entryId) {
18156 var entryIndex = entryAndManualChunkIds.indexOf(entryId);
18157 return entryAndChunkModules[entryIndex];
18158 });
18159 }
18160 }
18161 return { entryModules: entryModules, entryModuleAliases: entryModuleAliases, manualChunkModules: manualChunkModules };
18162 });
18163 };
18164 Graph.prototype.loadModule = function (entryName) {
18165 var _this = this;
18166 return this.pluginDriver
18167 .hookFirst('resolveId', [entryName, undefined])
18168 .then(function (id) {
18169 if (id === false) {
18170 error({
18171 code: 'UNRESOLVED_ENTRY',
18172 message: "Entry module cannot be external"
18173 });
18174 }
18175 if (id == null) {
18176 error({
18177 code: 'UNRESOLVED_ENTRY',
18178 message: "Could not resolve entry (" + entryName + ")"
18179 });
18180 }
18181 return _this.fetchModule(id, undefined);
18182 });
18183 };
18184 Graph.prototype.normalizeResolveIdResult = function (resolveIdResult, module, source) {
18185 var id = '';
18186 var external = false;
18187 if (resolveIdResult) {
18188 if (typeof resolveIdResult === 'object') {
18189 id = resolveIdResult.id;
18190 if (resolveIdResult.external) {
18191 external = true;
18192 }
18193 }
18194 else {
18195 id = resolveIdResult;
18196 if (this.isExternal(id, module.id, true)) {
18197 external = true;
18198 }
18199 }
18200 if (external) {
18201 id = normalizeRelativeExternalId(module.id, id);
18202 }
18203 }
18204 else {
18205 id = normalizeRelativeExternalId(module.id, source);
18206 external = true;
18207 if (resolveIdResult !== false && !this.isExternal(id, module.id, true)) {
18208 if (isRelative(source)) {
18209 error({
18210 code: 'UNRESOLVED_IMPORT',
18211 message: "Could not resolve '" + source + "' from " + relativeId(module.id)
18212 });
18213 }
18214 this.warn({
18215 code: 'UNRESOLVED_IMPORT',
18216 importer: relativeId(module.id),
18217 message: "'" + source + "' is imported by " + relativeId(module.id) + ", but could not be resolved \u2013 treating it as an external dependency",
18218 source: source,
18219 url: 'https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency'
18220 });
18221 }
18222 }
18223 return { id: id, external: external };
18224 };
18225 Graph.prototype.resolveAndFetchDependency = function (module, source) {
18226 var _this = this;
18227 return Promise.resolve(module.resolvedIds[source] ||
18228 Promise.resolve(this.isExternal(source, module.id, false)
18229 ? { id: source, external: true }
18230 : this.pluginDriver.hookFirst('resolveId', [source, module.id])).then(function (result) { return _this.normalizeResolveIdResult(result, module, source); })).then(function (resolvedId) {
18231 module.resolvedIds[source] = resolvedId;
18232 if (resolvedId.external) {
18233 if (!_this.moduleById.has(resolvedId.id)) {
18234 var module_1 = new ExternalModule({ graph: _this, id: resolvedId.id });
18235 _this.externalModules.push(module_1);
18236 _this.moduleById.set(resolvedId.id, module_1);
18237 }
18238 var externalModule = _this.moduleById.get(resolvedId.id);
18239 if (externalModule instanceof ExternalModule === false) {
18240 error({
18241 code: 'INVALID_EXTERNAL_ID',
18242 message: "'" + source + "' is imported as an external by " + relativeId(module.id) + ", but is already an existing non-external module id."
18243 });
18244 }
18245 }
18246 else {
18247 return _this.fetchModule(resolvedId.id, module.id);
18248 }
18249 });
18250 };
18251 Graph.prototype.warnForMissingExports = function () {
18252 for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
18253 var module = _a[_i];
18254 for (var _b = 0, _c = Object.keys(module.importDescriptions); _b < _c.length; _b++) {
18255 var importName = _c[_b];
18256 var importDescription = module.importDescriptions[importName];
18257 if (importDescription.name !== '*' &&
18258 !importDescription.module.getVariableForExportName(importDescription.name)) {
18259 module.warn({
18260 code: 'NON_EXISTENT_EXPORT',
18261 message: "Non-existent export '" + importDescription.name + "' is imported from " + relativeId(importDescription.module.id),
18262 name: importDescription.name,
18263 source: importDescription.module.id
18264 }, importDescription.start);
18265 }
18266 }
18267 }
18268 };
18269 return Graph;
18270}());
18271
18272function evalIfFn(strOrFn) {
18273 switch (typeof strOrFn) {
18274 case 'function':
18275 return strOrFn();
18276 case 'string':
18277 return strOrFn;
18278 default:
18279 return '';
18280 }
18281}
18282var concatSep = function (out, next) { return (next ? out + "\n" + next : out); };
18283var concatDblSep = function (out, next) { return (next ? out + "\n\n" + next : out); };
18284function createAddons(graph, options) {
18285 var pluginDriver = graph.pluginDriver;
18286 return Promise.all([
18287 pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
18288 pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
18289 pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
18290 pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
18291 ])
18292 .then(function (_a) {
18293 var banner = _a[0], footer = _a[1], intro = _a[2], outro = _a[3];
18294 if (intro)
18295 intro += '\n\n';
18296 if (outro)
18297 outro = "\n\n" + outro;
18298 if (banner.length)
18299 banner += '\n';
18300 if (footer.length)
18301 footer = '\n' + footer;
18302 return { intro: intro, outro: outro, banner: banner, footer: footer };
18303 })
18304 .catch(function (err) {
18305 error({
18306 code: 'ADDON_ERROR',
18307 message: "Could not retrieve " + err.hook + ". Check configuration of " + err.plugin + ".\n\tError Message: " + err.message
18308 });
18309 });
18310}
18311
18312function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons) {
18313 var usedIds = {};
18314 var _a = chunks.reduce(function (_a, chunk) {
18315 var entryChunks = _a[0], otherChunks = _a[1];
18316 (chunk.facadeModule && chunk.facadeModule.isEntryPoint ? entryChunks : otherChunks).push(chunk);
18317 return [entryChunks, otherChunks];
18318 }, [[], []]), entryChunks = _a[0], otherChunks = _a[1];
18319 // make sure entry chunk names take precedence with regard to deconflicting
18320 var chunksForNaming = entryChunks.concat(otherChunks);
18321 for (var i = 0; i < chunksForNaming.length; i++) {
18322 var chunk = chunksForNaming[i];
18323 if (outputOptions.file) {
18324 chunk.id = basename(outputOptions.file);
18325 }
18326 else if (inputOptions.preserveModules) {
18327 chunk.generateIdPreserveModules(inputBase, usedIds);
18328 }
18329 else {
18330 var pattern = void 0, patternName = void 0;
18331 if (chunk.facadeModule && chunk.facadeModule.isEntryPoint) {
18332 pattern = outputOptions.entryFileNames || '[name].js';
18333 patternName = 'output.entryFileNames';
18334 }
18335 else {
18336 pattern = outputOptions.chunkFileNames || '[name]-[hash].js';
18337 patternName = 'output.chunkFileNames';
18338 }
18339 chunk.generateId(pattern, patternName, addons, outputOptions, usedIds);
18340 }
18341 usedIds[chunk.id] = true;
18342 }
18343}
18344
18345// ported from https://github.com/substack/node-commondir
18346function commondir(files) {
18347 if (files.length === 0)
18348 return '/';
18349 if (files.length === 1)
18350 return dirname(files[0]);
18351 var commonSegments = files.slice(1).reduce(function (commonSegments, file) {
18352 var pathSegements = file.split(/\/+|\\+/);
18353 var i;
18354 for (i = 0; commonSegments[i] === pathSegements[i] &&
18355 i < Math.min(commonSegments.length, pathSegements.length); i++)
18356 ;
18357 return commonSegments.slice(0, i);
18358 }, files[0].split(/\/+|\\+/));
18359 // Windows correctly handles paths with forward-slashes
18360 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
18361}
18362
18363function badExports(option, keys) {
18364 error({
18365 code: 'INVALID_EXPORT_OPTION',
18366 message: "'" + option + "' was specified for output.exports, but entry module has following exports: " + keys.join(', ')
18367 });
18368}
18369function getExportMode(chunk, _a) {
18370 var exportMode = _a.exports, name = _a.name, format = _a.format;
18371 var exportKeys = chunk.getExportNames();
18372 if (exportMode === 'default') {
18373 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
18374 badExports('default', exportKeys);
18375 }
18376 }
18377 else if (exportMode === 'none' && exportKeys.length) {
18378 badExports('none', exportKeys);
18379 }
18380 if (!exportMode || exportMode === 'auto') {
18381 if (exportKeys.length === 0) {
18382 exportMode = 'none';
18383 }
18384 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
18385 exportMode = 'default';
18386 }
18387 else {
18388 if (chunk.facadeModule !== null &&
18389 chunk.facadeModule.isEntryPoint &&
18390 format !== 'es' &&
18391 exportKeys.indexOf('default') !== -1) {
18392 chunk.graph.warn({
18393 code: 'MIXED_EXPORTS',
18394 message: "Using named and default exports together. Consumers of your bundle will have to use " + (name ||
18395 'bundle') + "['default'] to access the default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning",
18396 url: "https://rollupjs.org/guide/en#output-exports"
18397 });
18398 }
18399 exportMode = 'named';
18400 }
18401 }
18402 if (!/(?:default|named|none)/.test(exportMode)) {
18403 error({
18404 code: 'INVALID_EXPORT_OPTION',
18405 message: "output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')",
18406 url: "https://rollupjs.org/guide/en#output-exports"
18407 });
18408 }
18409 return exportMode;
18410}
18411
18412var createGetOption = function (config, command) { return function (name, defaultValue) {
18413 return command[name] !== undefined
18414 ? command[name]
18415 : config[name] !== undefined
18416 ? config[name]
18417 : defaultValue;
18418}; };
18419var normalizeObjectOptionValue = function (optionValue) {
18420 if (!optionValue) {
18421 return optionValue;
18422 }
18423 if (typeof optionValue !== 'object') {
18424 return {};
18425 }
18426 return optionValue;
18427};
18428var getObjectOption = function (config, command, name) {
18429 var commandOption = normalizeObjectOptionValue(command[name]);
18430 var configOption = normalizeObjectOptionValue(config[name]);
18431 if (commandOption !== undefined) {
18432 return commandOption && configOption ? __assign({}, configOption, commandOption) : commandOption;
18433 }
18434 return configOption;
18435};
18436var defaultOnWarn = function (warning) {
18437 if (typeof warning === 'string') {
18438 console.warn(warning); // eslint-disable-line no-console
18439 }
18440 else {
18441 console.warn(warning.message); // eslint-disable-line no-console
18442 }
18443};
18444var getOnWarn = function (config, command, defaultOnWarnHandler) {
18445 if (defaultOnWarnHandler === void 0) { defaultOnWarnHandler = defaultOnWarn; }
18446 return command.silent
18447 ? function () { }
18448 : config.onwarn
18449 ? function (warning) { return config.onwarn(warning, defaultOnWarnHandler); }
18450 : defaultOnWarnHandler;
18451};
18452var getExternal = function (config, command) {
18453 var configExternal = config.external;
18454 return typeof configExternal === 'function'
18455 ? function (id) {
18456 var rest = [];
18457 for (var _i = 1; _i < arguments.length; _i++) {
18458 rest[_i - 1] = arguments[_i];
18459 }
18460 return configExternal.apply(void 0, [id].concat(rest)) || command.external.indexOf(id) !== -1;
18461 }
18462 : (configExternal || []).concat(command.external);
18463};
18464var commandAliases = {
18465 c: 'config',
18466 d: 'dir',
18467 e: 'external',
18468 f: 'format',
18469 g: 'globals',
18470 h: 'help',
18471 i: 'input',
18472 m: 'sourcemap',
18473 n: 'name',
18474 o: 'file',
18475 v: 'version',
18476 w: 'watch'
18477};
18478function mergeOptions(_a) {
18479 var _b = _a.config, config = _b === void 0 ? {} : _b, _c = _a.command, rawCommandOptions = _c === void 0 ? {} : _c, defaultOnWarnHandler = _a.defaultOnWarnHandler;
18480 var command = getCommandOptions(rawCommandOptions);
18481 var inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
18482 if (command.output) {
18483 Object.assign(command, command.output);
18484 }
18485 var output = config.output;
18486 var normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
18487 if (normalizedOutputOptions.length === 0)
18488 normalizedOutputOptions.push({});
18489 var outputOptions = normalizedOutputOptions.map(function (singleOutputOptions) {
18490 return getOutputOptions(singleOutputOptions, command);
18491 });
18492 var unknownOptionErrors = [];
18493 var validInputOptions = Object.keys(inputOptions);
18494 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
18495 var validOutputOptions = Object.keys(outputOptions[0]);
18496 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce(function (allKeys, options) { return allKeys.concat(Object.keys(options)); }, []), validOutputOptions, 'output option');
18497 var validCliOutputOptions = validOutputOptions.filter(function (option) { return option !== 'sourcemapPathTransform'; });
18498 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
18499 return {
18500 inputOptions: inputOptions,
18501 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
18502 outputOptions: outputOptions
18503 };
18504}
18505function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys) {
18506 if (ignoredKeys === void 0) { ignoredKeys = /$./; }
18507 var unknownOptions = options.filter(function (key) { return validOptions.indexOf(key) === -1 && !ignoredKeys.test(key); });
18508 if (unknownOptions.length > 0)
18509 errors.push("Unknown " + optionType + ": " + unknownOptions.join(', ') + ". Allowed options: " + validOptions.sort().join(', '));
18510}
18511function getCommandOptions(rawCommandOptions) {
18512 var command = __assign({}, rawCommandOptions);
18513 command.external = rawCommandOptions.external ? rawCommandOptions.external.split(',') : [];
18514 if (rawCommandOptions.globals) {
18515 command.globals = Object.create(null);
18516 rawCommandOptions.globals.split(',').forEach(function (str) {
18517 var names = str.split(':');
18518 command.globals[names[0]] = names[1];
18519 // Add missing Module IDs to external.
18520 if (command.external.indexOf(names[0]) === -1) {
18521 command.external.push(names[0]);
18522 }
18523 });
18524 }
18525 return command;
18526}
18527function getInputOptions(config, command, defaultOnWarnHandler) {
18528 if (command === void 0) { command = {}; }
18529 var getOption = createGetOption(config, command);
18530 var inputOptions = {
18531 acorn: config.acorn,
18532 acornInjectPlugins: config.acornInjectPlugins,
18533 cache: getOption('cache'),
18534 chunkGroupingSize: getOption('chunkGroupingSize', 5000),
18535 context: config.context,
18536 experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
18537 experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
18538 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
18539 external: getExternal(config, command),
18540 inlineDynamicImports: getOption('inlineDynamicImports', false),
18541 input: getOption('input'),
18542 manualChunks: getOption('manualChunks'),
18543 moduleContext: config.moduleContext,
18544 onwarn: getOnWarn(config, command, defaultOnWarnHandler),
18545 perf: getOption('perf', false),
18546 plugins: config.plugins,
18547 preserveModules: getOption('preserveModules'),
18548 preserveSymlinks: getOption('preserveSymlinks'),
18549 shimMissingExports: getOption('shimMissingExports'),
18550 treeshake: getObjectOption(config, command, 'treeshake'),
18551 watch: config.watch
18552 };
18553 // support rollup({ cache: prevBuildObject })
18554 if (inputOptions.cache && inputOptions.cache.cache)
18555 inputOptions.cache = inputOptions.cache.cache;
18556 return inputOptions;
18557}
18558function getOutputOptions(config, command) {
18559 if (command === void 0) { command = {}; }
18560 var getOption = createGetOption(config, command);
18561 var format = getOption('format');
18562 // Handle format aliases
18563 switch (format) {
18564 case 'esm':
18565 case 'module':
18566 format = 'es';
18567 break;
18568 case 'commonjs':
18569 format = 'cjs';
18570 }
18571 return {
18572 amd: __assign({}, config.amd, command.amd),
18573 assetFileNames: getOption('assetFileNames'),
18574 banner: getOption('banner'),
18575 chunkFileNames: getOption('chunkFileNames'),
18576 compact: getOption('compact', false),
18577 dir: getOption('dir'),
18578 dynamicImportFunction: getOption('dynamicImportFunction'),
18579 entryFileNames: getOption('entryFileNames'),
18580 esModule: getOption('esModule', true),
18581 exports: getOption('exports'),
18582 extend: getOption('extend'),
18583 file: getOption('file'),
18584 footer: getOption('footer'),
18585 format: format === 'esm' ? 'es' : format,
18586 freeze: getOption('freeze', true),
18587 globals: getOption('globals'),
18588 indent: getOption('indent', true),
18589 interop: getOption('interop', true),
18590 intro: getOption('intro'),
18591 name: getOption('name'),
18592 namespaceToStringTag: getOption('namespaceToStringTag', false),
18593 noConflict: getOption('noConflict'),
18594 outro: getOption('outro'),
18595 paths: getOption('paths'),
18596 preferConst: getOption('preferConst'),
18597 sourcemap: getOption('sourcemap'),
18598 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
18599 sourcemapFile: getOption('sourcemapFile'),
18600 sourcemapPathTransform: getOption('sourcemapPathTransform'),
18601 strict: getOption('strict', true)
18602 };
18603}
18604
18605function checkOutputOptions(options) {
18606 if (options.format === 'es6') {
18607 error({
18608 message: 'The "es6" output format is deprecated – use "esm" instead',
18609 url: "https://rollupjs.org/guide/en#output-format"
18610 });
18611 }
18612 if (!options.format) {
18613 error({
18614 message: "You must specify \"output.format\", which can be one of \"amd\", \"cjs\", \"system\", \"esm\", \"iife\" or \"umd\".",
18615 url: "https://rollupjs.org/guide/en#output-format"
18616 });
18617 }
18618}
18619function getAbsoluteEntryModulePaths(chunks) {
18620 var absoluteEntryModulePaths = [];
18621 for (var _i = 0, chunks_1 = chunks; _i < chunks_1.length; _i++) {
18622 var chunk = chunks_1[_i];
18623 for (var _a = 0, _b = chunk.entryModules; _a < _b.length; _a++) {
18624 var entryModule = _b[_a];
18625 if (isAbsolute(entryModule.id)) {
18626 absoluteEntryModulePaths.push(entryModule.id);
18627 }
18628 }
18629 }
18630 return absoluteEntryModulePaths;
18631}
18632var throwAsyncGenerateError = {
18633 get: function () {
18634 throw new Error("bundle.generate(...) now returns a Promise instead of a { code, map } object");
18635 }
18636};
18637function applyOptionHook(inputOptions, plugin) {
18638 if (plugin.options)
18639 return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions;
18640 return inputOptions;
18641}
18642function getInputOptions$1(rawInputOptions) {
18643 if (!rawInputOptions) {
18644 throw new Error('You must supply an options object to rollup');
18645 }
18646 var _a = mergeOptions({
18647 config: rawInputOptions
18648 }), inputOptions = _a.inputOptions, optionError = _a.optionError;
18649 if (optionError)
18650 inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
18651 var plugins = inputOptions.plugins;
18652 inputOptions.plugins = Array.isArray(plugins)
18653 ? plugins.filter(Boolean)
18654 : plugins
18655 ? [plugins]
18656 : [];
18657 inputOptions = inputOptions.plugins.reduce(applyOptionHook, inputOptions);
18658 if (inputOptions.inlineDynamicImports) {
18659 if (inputOptions.preserveModules)
18660 error({
18661 code: 'INVALID_OPTION',
18662 message: "\"preserveModules\" does not support the \"inlineDynamicImports\" option."
18663 });
18664 if (inputOptions.manualChunks)
18665 error({
18666 code: 'INVALID_OPTION',
18667 message: '"manualChunks" option is not supported for "inlineDynamicImports".'
18668 });
18669 if (inputOptions.experimentalOptimizeChunks)
18670 error({
18671 code: 'INVALID_OPTION',
18672 message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
18673 });
18674 if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
18675 (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
18676 error({
18677 code: 'INVALID_OPTION',
18678 message: 'Multiple inputs are not supported for "inlineDynamicImports".'
18679 });
18680 }
18681 else if (inputOptions.preserveModules) {
18682 if (inputOptions.manualChunks)
18683 error({
18684 code: 'INVALID_OPTION',
18685 message: '"preserveModules" does not support the "manualChunks" option.'
18686 });
18687 if (inputOptions.experimentalOptimizeChunks)
18688 error({
18689 code: 'INVALID_OPTION',
18690 message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
18691 });
18692 }
18693 return inputOptions;
18694}
18695var curWatcher;
18696function setWatcher(watcher) {
18697 curWatcher = watcher;
18698}
18699function rollup(rawInputOptions) {
18700 try {
18701 var inputOptions_1 = getInputOptions$1(rawInputOptions);
18702 initialiseTimers(inputOptions_1);
18703 var graph_1 = new Graph(inputOptions_1, curWatcher);
18704 curWatcher = undefined;
18705 // remove the cache option from the memory after graph creation (cache is not used anymore)
18706 var useCache_1 = rawInputOptions.cache !== false;
18707 delete inputOptions_1.cache;
18708 delete rawInputOptions.cache;
18709 timeStart('BUILD', 1);
18710 return graph_1.pluginDriver
18711 .hookParallel('buildStart', [inputOptions_1])
18712 .then(function () {
18713 return graph_1.build(inputOptions_1.input, inputOptions_1.manualChunks, inputOptions_1.inlineDynamicImports);
18714 })
18715 .then(function (chunks) {
18716 return graph_1.pluginDriver.hookParallel('buildEnd').then(function () {
18717 return chunks;
18718 });
18719 }, function (err) {
18720 return graph_1.pluginDriver.hookParallel('buildEnd', [err]).then(function () {
18721 throw err;
18722 });
18723 })
18724 .then(function (chunks) {
18725 timeEnd('BUILD', 1);
18726 // ensure we only do one optimization pass per build
18727 var optimized = false;
18728 function getOutputOptions(rawOutputOptions) {
18729 return normalizeOutputOptions(inputOptions_1, rawOutputOptions, chunks.length > 1, graph_1.pluginDriver);
18730 }
18731 function generate(outputOptions, isWrite) {
18732 timeStart('GENERATE', 1);
18733 var assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
18734 var outputBundle = graph_1.finaliseAssets(assetFileNames);
18735 var inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
18736 return graph_1.pluginDriver
18737 .hookParallel('renderStart')
18738 .then(function () { return createAddons(graph_1, outputOptions); })
18739 .then(function (addons) {
18740 // pre-render all chunks
18741 for (var _i = 0, chunks_2 = chunks; _i < chunks_2.length; _i++) {
18742 var chunk = chunks_2[_i];
18743 if (!inputOptions_1.preserveModules)
18744 chunk.generateInternalExports(outputOptions);
18745 if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
18746 chunk.exportMode = getExportMode(chunk, outputOptions);
18747 }
18748 for (var _a = 0, chunks_3 = chunks; _a < chunks_3.length; _a++) {
18749 var chunk = chunks_3[_a];
18750 chunk.preRender(outputOptions, inputBase);
18751 }
18752 if (!optimized && inputOptions_1.experimentalOptimizeChunks) {
18753 optimizeChunks(chunks, outputOptions, inputOptions_1.chunkGroupingSize, inputBase);
18754 optimized = true;
18755 }
18756 assignChunkIds(chunks, inputOptions_1, outputOptions, inputBase, addons);
18757 var _loop_1 = function (i) {
18758 var chunk = chunks[i];
18759 var facadeModule = chunk.facadeModule;
18760 outputBundle[chunk.id] = {
18761 code: undefined,
18762 dynamicImports: chunk.getDynamicImportIds(),
18763 exports: chunk.getExportNames(),
18764 facadeModuleId: facadeModule && facadeModule.id,
18765 fileName: chunk.id,
18766 imports: chunk.getImportIds(),
18767 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
18768 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
18769 map: undefined,
18770 modules: chunk.renderedModules,
18771 get name() {
18772 return chunk.getChunkName();
18773 }
18774 };
18775 };
18776 // assign to outputBundle
18777 for (var i = 0; i < chunks.length; i++) {
18778 _loop_1(i);
18779 }
18780 return Promise.all(chunks.map(function (chunk) {
18781 var outputChunk = outputBundle[chunk.id];
18782 return chunk.render(outputOptions, addons, outputChunk).then(function (rendered) {
18783 outputChunk.code = rendered.code;
18784 outputChunk.map = rendered.map;
18785 return graph_1.pluginDriver.hookParallel('ongenerate', [
18786 __assign({ bundle: outputChunk }, outputOptions),
18787 outputChunk
18788 ]);
18789 });
18790 })).then(function () { });
18791 })
18792 .catch(function (error) {
18793 return graph_1.pluginDriver.hookParallel('renderError', [error]).then(function () {
18794 throw error;
18795 });
18796 })
18797 .then(function () {
18798 // run generateBundle hook
18799 // assets emitted during generateBundle are unique to that specific generate call
18800 var assets = new Map(graph_1.assetsById);
18801 var generateAssetPluginHooks = createAssetPluginHooks(assets, outputBundle, assetFileNames);
18802 return graph_1.pluginDriver
18803 .hookSeq('generateBundle', [outputOptions, outputBundle, isWrite], function (context) { return (__assign({}, context, generateAssetPluginHooks)); })
18804 .then(function () {
18805 // throw errors for assets not finalised with a source
18806 assets.forEach(function (asset) {
18807 if (asset.fileName === undefined)
18808 finaliseAsset(asset, outputBundle, assetFileNames);
18809 });
18810 });
18811 })
18812 .then(function () {
18813 timeEnd('GENERATE', 1);
18814 return outputBundle;
18815 });
18816 }
18817 var cache = useCache_1 ? graph_1.getCache() : undefined;
18818 var result = {
18819 cache: cache,
18820 generate: (function (rawOutputOptions) {
18821 var promise = generate(getOutputOptions(rawOutputOptions), false).then(function (result) {
18822 return createOutput(result);
18823 });
18824 Object.defineProperty(promise, 'code', throwAsyncGenerateError);
18825 Object.defineProperty(promise, 'map', throwAsyncGenerateError);
18826 return promise;
18827 }),
18828 watchFiles: Object.keys(graph_1.watchFiles),
18829 write: (function (rawOutputOptions) {
18830 var outputOptions = getOutputOptions(rawOutputOptions);
18831 if (!outputOptions.dir && !outputOptions.file) {
18832 error({
18833 code: 'MISSING_OPTION',
18834 message: 'You must specify "output.file" or "output.dir" for the build.'
18835 });
18836 }
18837 return generate(outputOptions, true).then(function (bundle) {
18838 var chunkCnt = 0;
18839 for (var _i = 0, _a = Object.keys(bundle); _i < _a.length; _i++) {
18840 var fileName = _a[_i];
18841 var file = bundle[fileName];
18842 if (file.isAsset)
18843 continue;
18844 chunkCnt++;
18845 if (chunkCnt > 1)
18846 break;
18847 }
18848 if (chunkCnt > 1) {
18849 if (outputOptions.sourcemapFile)
18850 error({
18851 code: 'INVALID_OPTION',
18852 message: '"output.sourcemapFile" is only supported for single-file builds.'
18853 });
18854 if (typeof outputOptions.file === 'string')
18855 error({
18856 code: 'INVALID_OPTION',
18857 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
18858 (typeof inputOptions_1.input !== 'string' ||
18859 inputOptions_1.inlineDynamicImports === true
18860 ? ''
18861 : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
18862 });
18863 }
18864 return Promise.all(Object.keys(bundle).map(function (chunkId) {
18865 return writeOutputFile(graph_1, result, bundle[chunkId], outputOptions);
18866 }))
18867 .then(function () { return graph_1.pluginDriver.hookParallel('writeBundle', [bundle]); })
18868 .then(function () { return createOutput(bundle); });
18869 });
18870 })
18871 };
18872 if (inputOptions_1.perf === true)
18873 result.getTimings = getTimings;
18874 return result;
18875 });
18876 }
18877 catch (err) {
18878 return Promise.reject(err);
18879 }
18880}
18881var SortingFileType;
18882(function (SortingFileType) {
18883 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
18884 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
18885 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
18886})(SortingFileType || (SortingFileType = {}));
18887function getSortingFileType(file) {
18888 if (file.isAsset) {
18889 return SortingFileType.ASSET;
18890 }
18891 if (file.isEntry) {
18892 return SortingFileType.ENTRY_CHUNK;
18893 }
18894 return SortingFileType.SECONDARY_CHUNK;
18895}
18896function createOutput(outputBundle) {
18897 return {
18898 output: Object.keys(outputBundle)
18899 .map(function (fileName) { return outputBundle[fileName]; })
18900 .sort(function (outputFileA, outputFileB) {
18901 var fileTypeA = getSortingFileType(outputFileA);
18902 var fileTypeB = getSortingFileType(outputFileB);
18903 if (fileTypeA === fileTypeB)
18904 return 0;
18905 return fileTypeA < fileTypeB ? -1 : 1;
18906 })
18907 };
18908}
18909function isOutputAsset(file) {
18910 return file.isAsset === true;
18911}
18912function writeOutputFile(graph, build, outputFile, outputOptions) {
18913 var filename = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
18914 var writeSourceMapPromise;
18915 var source;
18916 if (isOutputAsset(outputFile)) {
18917 source = outputFile.source;
18918 }
18919 else {
18920 source = outputFile.code;
18921 if (outputOptions.sourcemap && outputFile.map) {
18922 var url = void 0;
18923 if (outputOptions.sourcemap === 'inline') {
18924 url = outputFile.map.toUrl();
18925 }
18926 else {
18927 url = basename(outputFile.fileName) + ".map";
18928 writeSourceMapPromise = writeFile(filename + ".map", outputFile.map.toString());
18929 }
18930 source += "//# " + SOURCEMAPPING_URL + "=" + url + "\n";
18931 }
18932 }
18933 return writeFile(filename, source)
18934 .then(function () { return writeSourceMapPromise; })
18935 .then(function () {
18936 return !isOutputAsset(outputFile) &&
18937 graph.pluginDriver.hookSeq('onwrite', [
18938 __assign({ bundle: build }, outputOptions),
18939 outputFile
18940 ]);
18941 })
18942 .then(function () { });
18943}
18944function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
18945 if (!rawOutputOptions) {
18946 throw new Error('You must supply an options object');
18947 }
18948 var mergedOptions = mergeOptions({
18949 config: {
18950 output: __assign({}, rawOutputOptions, rawOutputOptions.output, inputOptions.output)
18951 }
18952 });
18953 if (mergedOptions.optionError)
18954 throw new Error(mergedOptions.optionError);
18955 // now outputOptions is an array, but rollup.rollup API doesn't support arrays
18956 var mergedOutputOptions = mergedOptions.outputOptions[0];
18957 var outputOptionsReducer = function (outputOptions, result) {
18958 return result || outputOptions;
18959 };
18960 var outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer);
18961 checkOutputOptions(outputOptions);
18962 if (typeof outputOptions.file === 'string') {
18963 if (typeof outputOptions.dir === 'string')
18964 error({
18965 code: 'INVALID_OPTION',
18966 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
18967 });
18968 if (inputOptions.preserveModules) {
18969 error({
18970 code: 'INVALID_OPTION',
18971 message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
18972 });
18973 }
18974 if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
18975 error({
18976 code: 'INVALID_OPTION',
18977 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
18978 });
18979 }
18980 if (hasMultipleChunks) {
18981 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
18982 error({
18983 code: 'INVALID_OPTION',
18984 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
18985 });
18986 if (typeof outputOptions.file === 'string')
18987 error({
18988 code: 'INVALID_OPTION',
18989 message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
18990 });
18991 }
18992 return outputOptions;
18993}
18994
18995var types = {
18996 ROOT : 0,
18997 GROUP : 1,
18998 POSITION : 2,
18999 SET : 3,
19000 RANGE : 4,
19001 REPETITION : 5,
19002 REFERENCE : 6,
19003 CHAR : 7,
19004};
19005
19006var INTS = function() {
19007 return [{ type: types.RANGE , from: 48, to: 57 }];
19008};
19009
19010var WORDS = function() {
19011 return [
19012 { type: types.CHAR, value: 95 },
19013 { type: types.RANGE, from: 97, to: 122 },
19014 { type: types.RANGE, from: 65, to: 90 }
19015 ].concat(INTS());
19016};
19017
19018var WHITESPACE$1 = function() {
19019 return [
19020 { type: types.CHAR, value: 9 },
19021 { type: types.CHAR, value: 10 },
19022 { type: types.CHAR, value: 11 },
19023 { type: types.CHAR, value: 12 },
19024 { type: types.CHAR, value: 13 },
19025 { type: types.CHAR, value: 32 },
19026 { type: types.CHAR, value: 160 },
19027 { type: types.CHAR, value: 5760 },
19028 { type: types.CHAR, value: 6158 },
19029 { type: types.CHAR, value: 8192 },
19030 { type: types.CHAR, value: 8193 },
19031 { type: types.CHAR, value: 8194 },
19032 { type: types.CHAR, value: 8195 },
19033 { type: types.CHAR, value: 8196 },
19034 { type: types.CHAR, value: 8197 },
19035 { type: types.CHAR, value: 8198 },
19036 { type: types.CHAR, value: 8199 },
19037 { type: types.CHAR, value: 8200 },
19038 { type: types.CHAR, value: 8201 },
19039 { type: types.CHAR, value: 8202 },
19040 { type: types.CHAR, value: 8232 },
19041 { type: types.CHAR, value: 8233 },
19042 { type: types.CHAR, value: 8239 },
19043 { type: types.CHAR, value: 8287 },
19044 { type: types.CHAR, value: 12288 },
19045 { type: types.CHAR, value: 65279 }
19046 ];
19047};
19048
19049var NOTANYCHAR = function() {
19050 return [
19051 { type: types.CHAR, value: 10 },
19052 { type: types.CHAR, value: 13 },
19053 { type: types.CHAR, value: 8232 },
19054 { type: types.CHAR, value: 8233 },
19055 ];
19056};
19057
19058// Predefined class objects.
19059var words = function() {
19060 return { type: types.SET, set: WORDS(), not: false };
19061};
19062
19063var notWords = function() {
19064 return { type: types.SET, set: WORDS(), not: true };
19065};
19066
19067var ints = function() {
19068 return { type: types.SET, set: INTS(), not: false };
19069};
19070
19071var notInts = function() {
19072 return { type: types.SET, set: INTS(), not: true };
19073};
19074
19075var whitespace = function() {
19076 return { type: types.SET, set: WHITESPACE$1(), not: false };
19077};
19078
19079var notWhitespace = function() {
19080 return { type: types.SET, set: WHITESPACE$1(), not: true };
19081};
19082
19083var anyChar = function() {
19084 return { type: types.SET, set: NOTANYCHAR(), not: true };
19085};
19086
19087var sets = {
19088 words: words,
19089 notWords: notWords,
19090 ints: ints,
19091 notInts: notInts,
19092 whitespace: whitespace,
19093 notWhitespace: notWhitespace,
19094 anyChar: anyChar
19095};
19096
19097var util = createCommonjsModule(function (module, exports) {
19098// All of these are private and only used by randexp.
19099// It's assumed that they will always be called with the correct input.
19100
19101var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
19102var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
19103
19104/**
19105 * Finds character representations in str and convert all to
19106 * their respective characters
19107 *
19108 * @param {String} str
19109 * @return {String}
19110 */
19111exports.strToChars = function(str) {
19112 /* jshint maxlen: false */
19113 var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g;
19114 str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
19115 if (lbs) {
19116 return s;
19117 }
19118
19119 var code = b ? 8 :
19120 a16 ? parseInt(a16, 16) :
19121 b16 ? parseInt(b16, 16) :
19122 c8 ? parseInt(c8, 8) :
19123 dctrl ? CTRL.indexOf(dctrl) :
19124 SLSH[eslsh];
19125
19126 var c = String.fromCharCode(code);
19127
19128 // Escape special regex characters.
19129 if (/[\[\]{}\^$.|?*+()]/.test(c)) {
19130 c = '\\' + c;
19131 }
19132
19133 return c;
19134 });
19135
19136 return str;
19137};
19138
19139
19140/**
19141 * turns class into tokens
19142 * reads str until it encounters a ] not preceeded by a \
19143 *
19144 * @param {String} str
19145 * @param {String} regexpStr
19146 * @return {Array.<Array.<Object>, Number>}
19147 */
19148exports.tokenizeClass = function(str, regexpStr) {
19149 /* jshint maxlen: false */
19150 var tokens = [];
19151 var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g;
19152 var rs, c;
19153
19154
19155 while ((rs = regexp.exec(str)) != null) {
19156 if (rs[1]) {
19157 tokens.push(sets.words());
19158
19159 } else if (rs[2]) {
19160 tokens.push(sets.ints());
19161
19162 } else if (rs[3]) {
19163 tokens.push(sets.whitespace());
19164
19165 } else if (rs[4]) {
19166 tokens.push(sets.notWords());
19167
19168 } else if (rs[5]) {
19169 tokens.push(sets.notInts());
19170
19171 } else if (rs[6]) {
19172 tokens.push(sets.notWhitespace());
19173
19174 } else if (rs[7]) {
19175 tokens.push({
19176 type: types.RANGE,
19177 from: (rs[8] || rs[9]).charCodeAt(0),
19178 to: rs[10].charCodeAt(0),
19179 });
19180
19181 } else if (c = rs[12]) {
19182 tokens.push({
19183 type: types.CHAR,
19184 value: c.charCodeAt(0),
19185 });
19186
19187 } else {
19188 return [tokens, regexp.lastIndex];
19189 }
19190 }
19191
19192 exports.error(regexpStr, 'Unterminated character class');
19193};
19194
19195
19196/**
19197 * Shortcut to throw errors.
19198 *
19199 * @param {String} regexp
19200 * @param {String} msg
19201 */
19202exports.error = function(regexp, msg) {
19203 throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
19204};
19205});
19206
19207var wordBoundary = function() {
19208 return { type: types.POSITION, value: 'b' };
19209};
19210
19211var nonWordBoundary = function() {
19212 return { type: types.POSITION, value: 'B' };
19213};
19214
19215var begin = function() {
19216 return { type: types.POSITION, value: '^' };
19217};
19218
19219var end = function() {
19220 return { type: types.POSITION, value: '$' };
19221};
19222
19223var positions = {
19224 wordBoundary: wordBoundary,
19225 nonWordBoundary: nonWordBoundary,
19226 begin: begin,
19227 end: end
19228};
19229
19230var lib = function(regexpStr) {
19231 var i = 0, l, c,
19232 start = { type: types.ROOT, stack: []},
19233
19234 // Keep track of last clause/group and stack.
19235 lastGroup = start,
19236 last = start.stack,
19237 groupStack = [];
19238
19239
19240 var repeatErr = function(i) {
19241 util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));
19242 };
19243
19244 // Decode a few escaped characters.
19245 var str = util.strToChars(regexpStr);
19246 l = str.length;
19247
19248 // Iterate through each character in string.
19249 while (i < l) {
19250 c = str[i++];
19251
19252 switch (c) {
19253 // Handle escaped characters, inclues a few sets.
19254 case '\\':
19255 c = str[i++];
19256
19257 switch (c) {
19258 case 'b':
19259 last.push(positions.wordBoundary());
19260 break;
19261
19262 case 'B':
19263 last.push(positions.nonWordBoundary());
19264 break;
19265
19266 case 'w':
19267 last.push(sets.words());
19268 break;
19269
19270 case 'W':
19271 last.push(sets.notWords());
19272 break;
19273
19274 case 'd':
19275 last.push(sets.ints());
19276 break;
19277
19278 case 'D':
19279 last.push(sets.notInts());
19280 break;
19281
19282 case 's':
19283 last.push(sets.whitespace());
19284 break;
19285
19286 case 'S':
19287 last.push(sets.notWhitespace());
19288 break;
19289
19290 default:
19291 // Check if c is integer.
19292 // In which case it's a reference.
19293 if (/\d/.test(c)) {
19294 last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
19295
19296 // Escaped character.
19297 } else {
19298 last.push({ type: types.CHAR, value: c.charCodeAt(0) });
19299 }
19300 }
19301
19302 break;
19303
19304
19305 // Positionals.
19306 case '^':
19307 last.push(positions.begin());
19308 break;
19309
19310 case '$':
19311 last.push(positions.end());
19312 break;
19313
19314
19315 // Handle custom sets.
19316 case '[':
19317 // Check if this class is 'anti' i.e. [^abc].
19318 var not;
19319 if (str[i] === '^') {
19320 not = true;
19321 i++;
19322 } else {
19323 not = false;
19324 }
19325
19326 // Get all the characters in class.
19327 var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
19328
19329 // Increase index by length of class.
19330 i += classTokens[1];
19331 last.push({
19332 type: types.SET,
19333 set: classTokens[0],
19334 not: not,
19335 });
19336
19337 break;
19338
19339
19340 // Class of any character except \n.
19341 case '.':
19342 last.push(sets.anyChar());
19343 break;
19344
19345
19346 // Push group onto stack.
19347 case '(':
19348 // Create group.
19349 var group = {
19350 type: types.GROUP,
19351 stack: [],
19352 remember: true,
19353 };
19354
19355 c = str[i];
19356
19357 // If if this is a special kind of group.
19358 if (c === '?') {
19359 c = str[i + 1];
19360 i += 2;
19361
19362 // Match if followed by.
19363 if (c === '=') {
19364 group.followedBy = true;
19365
19366 // Match if not followed by.
19367 } else if (c === '!') {
19368 group.notFollowedBy = true;
19369
19370 } else if (c !== ':') {
19371 util.error(regexpStr,
19372 'Invalid group, character \'' + c +
19373 '\' after \'?\' at column ' + (i - 1));
19374 }
19375
19376 group.remember = false;
19377 }
19378
19379 // Insert subgroup into current group stack.
19380 last.push(group);
19381
19382 // Remember the current group for when the group closes.
19383 groupStack.push(lastGroup);
19384
19385 // Make this new group the current group.
19386 lastGroup = group;
19387 last = group.stack;
19388 break;
19389
19390
19391 // Pop group out of stack.
19392 case ')':
19393 if (groupStack.length === 0) {
19394 util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));
19395 }
19396 lastGroup = groupStack.pop();
19397
19398 // Check if this group has a PIPE.
19399 // To get back the correct last stack.
19400 last = lastGroup.options ?
19401 lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
19402 break;
19403
19404
19405 // Use pipe character to give more choices.
19406 case '|':
19407 // Create array where options are if this is the first PIPE
19408 // in this clause.
19409 if (!lastGroup.options) {
19410 lastGroup.options = [lastGroup.stack];
19411 delete lastGroup.stack;
19412 }
19413
19414 // Create a new stack and add to options for rest of clause.
19415 var stack = [];
19416 lastGroup.options.push(stack);
19417 last = stack;
19418 break;
19419
19420
19421 // Repetition.
19422 // For every repetition, remove last element from last stack
19423 // then insert back a RANGE object.
19424 // This design is chosen because there could be more than
19425 // one repetition symbols in a regex i.e. `a?+{2,3}`.
19426 case '{':
19427 var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
19428 if (rs !== null) {
19429 if (last.length === 0) {
19430 repeatErr(i);
19431 }
19432 min = parseInt(rs[1], 10);
19433 max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
19434 i += rs[0].length;
19435
19436 last.push({
19437 type: types.REPETITION,
19438 min: min,
19439 max: max,
19440 value: last.pop(),
19441 });
19442 } else {
19443 last.push({
19444 type: types.CHAR,
19445 value: 123,
19446 });
19447 }
19448 break;
19449
19450 case '?':
19451 if (last.length === 0) {
19452 repeatErr(i);
19453 }
19454 last.push({
19455 type: types.REPETITION,
19456 min: 0,
19457 max: 1,
19458 value: last.pop(),
19459 });
19460 break;
19461
19462 case '+':
19463 if (last.length === 0) {
19464 repeatErr(i);
19465 }
19466 last.push({
19467 type: types.REPETITION,
19468 min: 1,
19469 max: Infinity,
19470 value: last.pop(),
19471 });
19472 break;
19473
19474 case '*':
19475 if (last.length === 0) {
19476 repeatErr(i);
19477 }
19478 last.push({
19479 type: types.REPETITION,
19480 min: 0,
19481 max: Infinity,
19482 value: last.pop(),
19483 });
19484 break;
19485
19486
19487 // Default is a character that is not `\[](){}?+*^$`.
19488 default:
19489 last.push({
19490 type: types.CHAR,
19491 value: c.charCodeAt(0),
19492 });
19493 }
19494
19495 }
19496
19497 // Check if any groups have not been closed.
19498 if (groupStack.length !== 0) {
19499 util.error(regexpStr, 'Unterminated group');
19500 }
19501
19502 return start;
19503};
19504
19505var types_1 = types;
19506lib.types = types_1;
19507
19508var types$1 = lib.types;
19509
19510var safeRegex = function (re, opts) {
19511 if (!opts) opts = {};
19512 var replimit = opts.limit === undefined ? 25 : opts.limit;
19513
19514 if (isRegExp(re)) re = re.source;
19515 else if (typeof re !== 'string') re = String(re);
19516
19517 try { re = lib(re); }
19518 catch (err) { return false }
19519
19520 var reps = 0;
19521 return (function walk (node, starHeight) {
19522 if (node.type === types$1.REPETITION) {
19523 starHeight ++;
19524 reps ++;
19525 if (starHeight > 1) return false;
19526 if (reps > replimit) return false;
19527 }
19528
19529 if (node.options) {
19530 for (var i = 0, len = node.options.length; i < len; i++) {
19531 var ok = walk({ stack: node.options[i] }, starHeight);
19532 if (!ok) return false;
19533 }
19534 }
19535 var stack = node.stack || (node.value && node.value.stack);
19536 if (!stack) return true;
19537
19538 for (var i = 0; i < stack.length; i++) {
19539 var ok = walk(stack[i], starHeight);
19540 if (!ok) return false;
19541 }
19542
19543 return true;
19544 })(re, 0);
19545};
19546
19547function isRegExp (x) {
19548 return {}.toString.call(x) === '[object RegExp]';
19549}
19550
19551/*!
19552 * isobject <https://github.com/jonschlinkert/isobject>
19553 *
19554 * Copyright (c) 2014-2017, Jon Schlinkert.
19555 * Released under the MIT License.
19556 */
19557
19558var isobject = function isObject(val) {
19559 return val != null && typeof val === 'object' && Array.isArray(val) === false;
19560};
19561
19562var toString$1 = Object.prototype.toString;
19563
19564var kindOf = function kindOf(val) {
19565 if (val === void 0) return 'undefined';
19566 if (val === null) return 'null';
19567
19568 var type = typeof val;
19569 if (type === 'boolean') return 'boolean';
19570 if (type === 'string') return 'string';
19571 if (type === 'number') return 'number';
19572 if (type === 'symbol') return 'symbol';
19573 if (type === 'function') {
19574 return isGeneratorFn(val) ? 'generatorfunction' : 'function';
19575 }
19576
19577 if (isArray(val)) return 'array';
19578 if (isBuffer(val)) return 'buffer';
19579 if (isArguments(val)) return 'arguments';
19580 if (isDate(val)) return 'date';
19581 if (isError(val)) return 'error';
19582 if (isRegexp(val)) return 'regexp';
19583
19584 switch (ctorName(val)) {
19585 case 'Symbol': return 'symbol';
19586 case 'Promise': return 'promise';
19587
19588 // Set, Map, WeakSet, WeakMap
19589 case 'WeakMap': return 'weakmap';
19590 case 'WeakSet': return 'weakset';
19591 case 'Map': return 'map';
19592 case 'Set': return 'set';
19593
19594 // 8-bit typed arrays
19595 case 'Int8Array': return 'int8array';
19596 case 'Uint8Array': return 'uint8array';
19597 case 'Uint8ClampedArray': return 'uint8clampedarray';
19598
19599 // 16-bit typed arrays
19600 case 'Int16Array': return 'int16array';
19601 case 'Uint16Array': return 'uint16array';
19602
19603 // 32-bit typed arrays
19604 case 'Int32Array': return 'int32array';
19605 case 'Uint32Array': return 'uint32array';
19606 case 'Float32Array': return 'float32array';
19607 case 'Float64Array': return 'float64array';
19608 }
19609
19610 if (isGeneratorObj(val)) {
19611 return 'generator';
19612 }
19613
19614 // Non-plain objects
19615 type = toString$1.call(val);
19616 switch (type) {
19617 case '[object Object]': return 'object';
19618 // iterators
19619 case '[object Map Iterator]': return 'mapiterator';
19620 case '[object Set Iterator]': return 'setiterator';
19621 case '[object String Iterator]': return 'stringiterator';
19622 case '[object Array Iterator]': return 'arrayiterator';
19623 }
19624
19625 // other
19626 return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
19627};
19628
19629function ctorName(val) {
19630 return val.constructor ? val.constructor.name : null;
19631}
19632
19633function isArray(val) {
19634 if (Array.isArray) return Array.isArray(val);
19635 return val instanceof Array;
19636}
19637
19638function isError(val) {
19639 return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');
19640}
19641
19642function isDate(val) {
19643 if (val instanceof Date) return true;
19644 return typeof val.toDateString === 'function'
19645 && typeof val.getDate === 'function'
19646 && typeof val.setDate === 'function';
19647}
19648
19649function isRegexp(val) {
19650 if (val instanceof RegExp) return true;
19651 return typeof val.flags === 'string'
19652 && typeof val.ignoreCase === 'boolean'
19653 && typeof val.multiline === 'boolean'
19654 && typeof val.global === 'boolean';
19655}
19656
19657function isGeneratorFn(name, val) {
19658 return ctorName(name) === 'GeneratorFunction';
19659}
19660
19661function isGeneratorObj(val) {
19662 return typeof val.throw === 'function'
19663 && typeof val.return === 'function'
19664 && typeof val.next === 'function';
19665}
19666
19667function isArguments(val) {
19668 try {
19669 if (typeof val.length === 'number' && typeof val.callee === 'function') {
19670 return true;
19671 }
19672 } catch (err) {
19673 if (err.message.indexOf('callee') !== -1) {
19674 return true;
19675 }
19676 }
19677 return false;
19678}
19679
19680/**
19681 * If you need to support Safari 5-7 (8-10 yr-old browser),
19682 * take a look at https://github.com/feross/is-buffer
19683 */
19684
19685function isBuffer(val) {
19686 if (val.constructor && typeof val.constructor.isBuffer === 'function') {
19687 return val.constructor.isBuffer(val);
19688 }
19689 return false;
19690}
19691
19692// accessor descriptor properties
19693var accessor = {
19694 get: 'function',
19695 set: 'function',
19696 configurable: 'boolean',
19697 enumerable: 'boolean'
19698};
19699
19700function isAccessorDescriptor(obj, prop) {
19701 if (typeof prop === 'string') {
19702 var val = Object.getOwnPropertyDescriptor(obj, prop);
19703 return typeof val !== 'undefined';
19704 }
19705
19706 if (kindOf(obj) !== 'object') {
19707 return false;
19708 }
19709
19710 if (has$1(obj, 'value') || has$1(obj, 'writable')) {
19711 return false;
19712 }
19713
19714 if (!has$1(obj, 'get') || typeof obj.get !== 'function') {
19715 return false;
19716 }
19717
19718 // tldr: it's valid to have "set" be undefined
19719 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
19720 // was used to get the value, and only `get` was defined by the user
19721 if (has$1(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
19722 return false;
19723 }
19724
19725 for (var key in obj) {
19726 if (!accessor.hasOwnProperty(key)) {
19727 continue;
19728 }
19729
19730 if (kindOf(obj[key]) === accessor[key]) {
19731 continue;
19732 }
19733
19734 if (typeof obj[key] !== 'undefined') {
19735 return false;
19736 }
19737 }
19738 return true;
19739}
19740
19741function has$1(obj, key) {
19742 return {}.hasOwnProperty.call(obj, key);
19743}
19744
19745/**
19746 * Expose `isAccessorDescriptor`
19747 */
19748
19749var isAccessorDescriptor_1 = isAccessorDescriptor;
19750
19751var isDataDescriptor = function isDataDescriptor(obj, prop) {
19752 // data descriptor properties
19753 var data = {
19754 configurable: 'boolean',
19755 enumerable: 'boolean',
19756 writable: 'boolean'
19757 };
19758
19759 if (kindOf(obj) !== 'object') {
19760 return false;
19761 }
19762
19763 if (typeof prop === 'string') {
19764 var val = Object.getOwnPropertyDescriptor(obj, prop);
19765 return typeof val !== 'undefined';
19766 }
19767
19768 if (!('value' in obj) && !('writable' in obj)) {
19769 return false;
19770 }
19771
19772 for (var key in obj) {
19773 if (key === 'value') continue;
19774
19775 if (!data.hasOwnProperty(key)) {
19776 continue;
19777 }
19778
19779 if (kindOf(obj[key]) === data[key]) {
19780 continue;
19781 }
19782
19783 if (typeof obj[key] !== 'undefined') {
19784 return false;
19785 }
19786 }
19787 return true;
19788};
19789
19790var isDescriptor = function isDescriptor(obj, key) {
19791 if (kindOf(obj) !== 'object') {
19792 return false;
19793 }
19794 if ('get' in obj) {
19795 return isAccessorDescriptor_1(obj, key);
19796 }
19797 return isDataDescriptor(obj, key);
19798};
19799
19800var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty)
19801 ? Reflect.defineProperty
19802 : Object.defineProperty;
19803
19804var defineProperty = function defineProperty(obj, key, val) {
19805 if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) {
19806 throw new TypeError('expected an object, function, or array');
19807 }
19808
19809 if (typeof key !== 'string') {
19810 throw new TypeError('expected "key" to be a string');
19811 }
19812
19813 if (isDescriptor(val)) {
19814 define(obj, key, val);
19815 return obj;
19816 }
19817
19818 define(obj, key, {
19819 configurable: true,
19820 enumerable: false,
19821 writable: true,
19822 value: val
19823 });
19824
19825 return obj;
19826};
19827
19828function isObjectObject(o) {
19829 return isobject(o) === true
19830 && Object.prototype.toString.call(o) === '[object Object]';
19831}
19832
19833var isPlainObject = function isPlainObject(o) {
19834 var ctor,prot;
19835
19836 if (isObjectObject(o) === false) return false;
19837
19838 // If has modified constructor
19839 ctor = o.constructor;
19840 if (typeof ctor !== 'function') return false;
19841
19842 // If has modified prototype
19843 prot = ctor.prototype;
19844 if (isObjectObject(prot) === false) return false;
19845
19846 // If constructor does not have an Object-specific method
19847 if (prot.hasOwnProperty('isPrototypeOf') === false) {
19848 return false;
19849 }
19850
19851 // Most likely a plain Object
19852 return true;
19853};
19854
19855var isExtendable = function isExtendable(val) {
19856 return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);
19857};
19858
19859/*!
19860 * assign-symbols <https://github.com/jonschlinkert/assign-symbols>
19861 *
19862 * Copyright (c) 2015, Jon Schlinkert.
19863 * Licensed under the MIT License.
19864 */
19865
19866var assignSymbols = function(receiver, objects) {
19867 if (receiver === null || typeof receiver === 'undefined') {
19868 throw new TypeError('expected first argument to be an object.');
19869 }
19870
19871 if (typeof objects === 'undefined' || typeof Symbol === 'undefined') {
19872 return receiver;
19873 }
19874
19875 if (typeof Object.getOwnPropertySymbols !== 'function') {
19876 return receiver;
19877 }
19878
19879 var isEnumerable = Object.prototype.propertyIsEnumerable;
19880 var target = Object(receiver);
19881 var len = arguments.length, i = 0;
19882
19883 while (++i < len) {
19884 var provider = Object(arguments[i]);
19885 var names = Object.getOwnPropertySymbols(provider);
19886
19887 for (var j = 0; j < names.length; j++) {
19888 var key = names[j];
19889
19890 if (isEnumerable.call(provider, key)) {
19891 target[key] = provider[key];
19892 }
19893 }
19894 }
19895 return target;
19896};
19897
19898var extendShallow = Object.assign || function(obj/*, objects*/) {
19899 if (obj === null || typeof obj === 'undefined') {
19900 throw new TypeError('Cannot convert undefined or null to object');
19901 }
19902 if (!isObject$1(obj)) {
19903 obj = {};
19904 }
19905 for (var i = 1; i < arguments.length; i++) {
19906 var val = arguments[i];
19907 if (isString(val)) {
19908 val = toObject$1(val);
19909 }
19910 if (isObject$1(val)) {
19911 assign(obj, val);
19912 assignSymbols(obj, val);
19913 }
19914 }
19915 return obj;
19916};
19917
19918function assign(a, b) {
19919 for (var key in b) {
19920 if (hasOwn(b, key)) {
19921 a[key] = b[key];
19922 }
19923 }
19924}
19925
19926function isString(val) {
19927 return (val && typeof val === 'string');
19928}
19929
19930function toObject$1(str) {
19931 var obj = {};
19932 for (var i in str) {
19933 obj[i] = str[i];
19934 }
19935 return obj;
19936}
19937
19938function isObject$1(val) {
19939 return (val && typeof val === 'object') || isExtendable(val);
19940}
19941
19942/**
19943 * Returns true if the given `key` is an own property of `obj`.
19944 */
19945
19946function hasOwn(obj, key) {
19947 return Object.prototype.hasOwnProperty.call(obj, key);
19948}
19949
19950/**
19951 * The main export is a function that takes a `pattern` string and an `options` object.
19952 *
19953 * ```js
19954 & var not = require('regex-not');
19955 & console.log(not('foo'));
19956 & //=> /^(?:(?!^(?:foo)$).)*$/
19957 * ```
19958 *
19959 * @param {String} `pattern`
19960 * @param {Object} `options`
19961 * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`.
19962 * @api public
19963 */
19964
19965function toRegex(pattern, options) {
19966 return new RegExp(toRegex.create(pattern, options));
19967}
19968
19969/**
19970 * Create a regex-compatible string from the given `pattern` and `options`.
19971 *
19972 * ```js
19973 & var not = require('regex-not');
19974 & console.log(not.create('foo'));
19975 & //=> '^(?:(?!^(?:foo)$).)*$'
19976 * ```
19977 * @param {String} `pattern`
19978 * @param {Object} `options`
19979 * @return {String}
19980 * @api public
19981 */
19982
19983toRegex.create = function(pattern, options) {
19984 if (typeof pattern !== 'string') {
19985 throw new TypeError('expected a string');
19986 }
19987
19988 var opts = extendShallow({}, options);
19989 if (opts.contains === true) {
19990 opts.strictNegate = false;
19991 }
19992
19993 var open = opts.strictOpen !== false ? '^' : '';
19994 var close = opts.strictClose !== false ? '$' : '';
19995 var endChar = opts.endChar ? opts.endChar : '+';
19996 var str = pattern;
19997
19998 if (opts.strictNegate === false) {
19999 str = '(?:(?!(?:' + pattern + ')).)' + endChar;
20000 } else {
20001 str = '(?:(?!^(?:' + pattern + ')$).)' + endChar;
20002 }
20003
20004 var res = open + str + close;
20005 if (opts.safe === true && safeRegex(res) === false) {
20006 throw new Error('potentially unsafe regular expression: ' + res);
20007 }
20008
20009 return res;
20010};
20011
20012/**
20013 * Expose `toRegex`
20014 */
20015
20016var regexNot = toRegex;
20017
20018var MAX_LENGTH = 1024 * 64;
20019
20020/**
20021 * Session cache
20022 */
20023
20024var cache = {};
20025
20026/**
20027 * Create a regular expression from the given `pattern` string.
20028 *
20029 * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.
20030 * @param {Object} `options`
20031 * @return {RegExp}
20032 * @api public
20033 */
20034
20035var toRegex$1 = function(patterns, options) {
20036 if (!Array.isArray(patterns)) {
20037 return makeRe(patterns, options);
20038 }
20039 return makeRe(patterns.join('|'), options);
20040};
20041
20042/**
20043 * Create a regular expression from the given `pattern` string.
20044 *
20045 * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.
20046 * @param {Object} `options`
20047 * @return {RegExp}
20048 * @api public
20049 */
20050
20051function makeRe(pattern, options) {
20052 if (pattern instanceof RegExp) {
20053 return pattern;
20054 }
20055
20056 if (typeof pattern !== 'string') {
20057 throw new TypeError('expected a string');
20058 }
20059
20060 if (pattern.length > MAX_LENGTH) {
20061 throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
20062 }
20063
20064 var key = pattern;
20065 // do this before shallow cloning options, it's a lot faster
20066 if (!options || (options && options.cache !== false)) {
20067 key = createKey(pattern, options);
20068
20069 if (cache.hasOwnProperty(key)) {
20070 return cache[key];
20071 }
20072 }
20073
20074 var opts = extendShallow({}, options);
20075 if (opts.contains === true) {
20076 if (opts.negate === true) {
20077 opts.strictNegate = false;
20078 } else {
20079 opts.strict = false;
20080 }
20081 }
20082
20083 if (opts.strict === false) {
20084 opts.strictOpen = false;
20085 opts.strictClose = false;
20086 }
20087
20088 var open = opts.strictOpen !== false ? '^' : '';
20089 var close = opts.strictClose !== false ? '$' : '';
20090 var flags = opts.flags || '';
20091 var regex;
20092
20093 if (opts.nocase === true && !/i/.test(flags)) {
20094 flags += 'i';
20095 }
20096
20097 try {
20098 if (opts.negate || typeof opts.strictNegate === 'boolean') {
20099 pattern = regexNot.create(pattern, opts);
20100 }
20101
20102 var str = open + '(?:' + pattern + ')' + close;
20103 regex = new RegExp(str, flags);
20104
20105 if (opts.safe === true && safeRegex(regex) === false) {
20106 throw new Error('potentially unsafe regular expression: ' + regex.source);
20107 }
20108
20109 } catch (err) {
20110 if (opts.strictErrors === true || opts.safe === true) {
20111 err.key = key;
20112 err.pattern = pattern;
20113 err.originalOptions = options;
20114 err.createdOptions = opts;
20115 throw err;
20116 }
20117
20118 try {
20119 regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$');
20120 } catch (err) {
20121 regex = /.^/; //<= match nothing
20122 }
20123 }
20124
20125 if (opts.cache !== false) {
20126 memoize(regex, key, pattern, opts);
20127 }
20128 return regex;
20129}
20130
20131/**
20132 * Memoize generated regex. This can result in dramatic speed improvements
20133 * and simplify debugging by adding options and pattern to the regex. It can be
20134 * disabled by passing setting `options.cache` to false.
20135 */
20136
20137function memoize(regex, key, pattern, options) {
20138 defineProperty(regex, 'cached', true);
20139 defineProperty(regex, 'pattern', pattern);
20140 defineProperty(regex, 'options', options);
20141 defineProperty(regex, 'key', key);
20142 cache[key] = regex;
20143}
20144
20145/**
20146 * Create the key to use for memoization. The key is generated
20147 * by iterating over the options and concatenating key-value pairs
20148 * to the pattern string.
20149 */
20150
20151function createKey(pattern, options) {
20152 if (!options) return pattern;
20153 var key = pattern;
20154 for (var prop in options) {
20155 if (options.hasOwnProperty(prop)) {
20156 key += ';' + prop + '=' + String(options[prop]);
20157 }
20158 }
20159 return key;
20160}
20161
20162/**
20163 * Expose `makeRe`
20164 */
20165
20166var makeRe_1 = makeRe;
20167toRegex$1.makeRe = makeRe_1;
20168
20169var arrayUnique = createCommonjsModule(function (module) {
20170
20171module.exports = function unique(arr) {
20172 if (!Array.isArray(arr)) {
20173 throw new TypeError('array-unique expects an array.');
20174 }
20175
20176 var len = arr.length;
20177 var i = -1;
20178
20179 while (i++ < len) {
20180 var j = i + 1;
20181
20182 for (; j < arr.length; ++j) {
20183 if (arr[i] === arr[j]) {
20184 arr.splice(j--, 1);
20185 }
20186 }
20187 }
20188 return arr;
20189};
20190
20191module.exports.immutable = function uniqueImmutable(arr) {
20192 if (!Array.isArray(arr)) {
20193 throw new TypeError('array-unique expects an array.');
20194 }
20195
20196 var arrLen = arr.length;
20197 var newArr = new Array(arrLen);
20198
20199 for (var i = 0; i < arrLen; i++) {
20200 newArr[i] = arr[i];
20201 }
20202
20203 return module.exports(newArr);
20204};
20205});
20206
20207/*!
20208 * is-extendable <https://github.com/jonschlinkert/is-extendable>
20209 *
20210 * Copyright (c) 2015, Jon Schlinkert.
20211 * Licensed under the MIT License.
20212 */
20213
20214var isExtendable$1 = function isExtendable(val) {
20215 return typeof val !== 'undefined' && val !== null
20216 && (typeof val === 'object' || typeof val === 'function');
20217};
20218
20219var extendShallow$1 = function extend(o/*, objects*/) {
20220 if (!isExtendable$1(o)) { o = {}; }
20221
20222 var len = arguments.length;
20223 for (var i = 1; i < len; i++) {
20224 var obj = arguments[i];
20225
20226 if (isExtendable$1(obj)) {
20227 assign$1(o, obj);
20228 }
20229 }
20230 return o;
20231};
20232
20233function assign$1(a, b) {
20234 for (var key in b) {
20235 if (hasOwn$1(b, key)) {
20236 a[key] = b[key];
20237 }
20238 }
20239}
20240
20241/**
20242 * Returns true if the given `key` is an own property of `obj`.
20243 */
20244
20245function hasOwn$1(obj, key) {
20246 return Object.prototype.hasOwnProperty.call(obj, key);
20247}
20248
20249var splitString = function(str, options, fn) {
20250 if (typeof str !== 'string') {
20251 throw new TypeError('expected a string');
20252 }
20253
20254 if (typeof options === 'function') {
20255 fn = options;
20256 options = null;
20257 }
20258
20259 // allow separator to be defined as a string
20260 if (typeof options === 'string') {
20261 options = { sep: options };
20262 }
20263
20264 var opts = extendShallow({sep: '.'}, options);
20265 var quotes = opts.quotes || ['"', "'", '`'];
20266 var brackets;
20267
20268 if (opts.brackets === true) {
20269 brackets = {
20270 '<': '>',
20271 '(': ')',
20272 '[': ']',
20273 '{': '}'
20274 };
20275 } else if (opts.brackets) {
20276 brackets = opts.brackets;
20277 }
20278
20279 var tokens = [];
20280 var stack = [];
20281 var arr = [''];
20282 var sep = opts.sep;
20283 var len = str.length;
20284 var idx = -1;
20285 var closeIdx;
20286
20287 function expected() {
20288 if (brackets && stack.length) {
20289 return brackets[stack[stack.length - 1]];
20290 }
20291 }
20292
20293 while (++idx < len) {
20294 var ch = str[idx];
20295 var next = str[idx + 1];
20296 var tok = { val: ch, idx: idx, arr: arr, str: str };
20297 tokens.push(tok);
20298
20299 if (ch === '\\') {
20300 tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next;
20301 tok.escaped = true;
20302 if (typeof fn === 'function') {
20303 fn(tok);
20304 }
20305 arr[arr.length - 1] += tok.val;
20306 idx++;
20307 continue;
20308 }
20309
20310 if (brackets && brackets[ch]) {
20311 stack.push(ch);
20312 var e = expected();
20313 var i = idx + 1;
20314
20315 if (str.indexOf(e, i + 1) !== -1) {
20316 while (stack.length && i < len) {
20317 var s = str[++i];
20318 if (s === '\\') {
20319 s++;
20320 continue;
20321 }
20322
20323 if (quotes.indexOf(s) !== -1) {
20324 i = getClosingQuote(str, s, i + 1);
20325 continue;
20326 }
20327
20328 e = expected();
20329 if (stack.length && str.indexOf(e, i + 1) === -1) {
20330 break;
20331 }
20332
20333 if (brackets[s]) {
20334 stack.push(s);
20335 continue;
20336 }
20337
20338 if (e === s) {
20339 stack.pop();
20340 }
20341 }
20342 }
20343
20344 closeIdx = i;
20345 if (closeIdx === -1) {
20346 arr[arr.length - 1] += ch;
20347 continue;
20348 }
20349
20350 ch = str.slice(idx, closeIdx + 1);
20351 tok.val = ch;
20352 tok.idx = idx = closeIdx;
20353 }
20354
20355 if (quotes.indexOf(ch) !== -1) {
20356 closeIdx = getClosingQuote(str, ch, idx + 1);
20357 if (closeIdx === -1) {
20358 arr[arr.length - 1] += ch;
20359 continue;
20360 }
20361
20362 if (keepQuotes(ch, opts) === true) {
20363 ch = str.slice(idx, closeIdx + 1);
20364 } else {
20365 ch = str.slice(idx + 1, closeIdx);
20366 }
20367
20368 tok.val = ch;
20369 tok.idx = idx = closeIdx;
20370 }
20371
20372 if (typeof fn === 'function') {
20373 fn(tok, tokens);
20374 ch = tok.val;
20375 idx = tok.idx;
20376 }
20377
20378 if (tok.val === sep && tok.split !== false) {
20379 arr.push('');
20380 continue;
20381 }
20382
20383 arr[arr.length - 1] += tok.val;
20384 }
20385
20386 return arr;
20387};
20388
20389function getClosingQuote(str, ch, i, brackets) {
20390 var idx = str.indexOf(ch, i);
20391 if (str.charAt(idx - 1) === '\\') {
20392 return getClosingQuote(str, ch, idx + 1);
20393 }
20394 return idx;
20395}
20396
20397function keepQuotes(ch, opts) {
20398 if (opts.keepDoubleQuotes === true && ch === '"') return true;
20399 if (opts.keepSingleQuotes === true && ch === "'") return true;
20400 return opts.keepQuotes;
20401}
20402
20403function keepEscaping(opts, str, idx) {
20404 if (typeof opts.keepEscaping === 'function') {
20405 return opts.keepEscaping(str, idx);
20406 }
20407 return opts.keepEscaping === true || str[idx + 1] === '\\';
20408}
20409
20410/*!
20411 * arr-flatten <https://github.com/jonschlinkert/arr-flatten>
20412 *
20413 * Copyright (c) 2014-2017, Jon Schlinkert.
20414 * Released under the MIT License.
20415 */
20416
20417var arrFlatten = function (arr) {
20418 return flat(arr, []);
20419};
20420
20421function flat(arr, res) {
20422 var i = 0, cur;
20423 var len = arr.length;
20424 for (; i < len; i++) {
20425 cur = arr[i];
20426 Array.isArray(cur) ? flat(cur, res) : res.push(cur);
20427 }
20428 return res;
20429}
20430
20431/*!
20432 * Determine if an object is a Buffer
20433 *
20434 * @author Feross Aboukhadijeh <https://feross.org>
20435 * @license MIT
20436 */
20437
20438// The _isBuffer check is for Safari 5-7 support, because it's missing
20439// Object.prototype.constructor. Remove this eventually
20440var isBuffer_1 = function (obj) {
20441 return obj != null && (isBuffer$1(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
20442};
20443
20444function isBuffer$1 (obj) {
20445 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
20446}
20447
20448// For Node v0.10 support. Remove this eventually.
20449function isSlowBuffer (obj) {
20450 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer$1(obj.slice(0, 0))
20451}
20452
20453var toString$2 = Object.prototype.toString;
20454
20455/**
20456 * Get the native `typeof` a value.
20457 *
20458 * @param {*} `val`
20459 * @return {*} Native javascript type
20460 */
20461
20462var kindOf$1 = function kindOf(val) {
20463 // primitivies
20464 if (typeof val === 'undefined') {
20465 return 'undefined';
20466 }
20467 if (val === null) {
20468 return 'null';
20469 }
20470 if (val === true || val === false || val instanceof Boolean) {
20471 return 'boolean';
20472 }
20473 if (typeof val === 'string' || val instanceof String) {
20474 return 'string';
20475 }
20476 if (typeof val === 'number' || val instanceof Number) {
20477 return 'number';
20478 }
20479
20480 // functions
20481 if (typeof val === 'function' || val instanceof Function) {
20482 return 'function';
20483 }
20484
20485 // array
20486 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
20487 return 'array';
20488 }
20489
20490 // check for instances of RegExp and Date before calling `toString`
20491 if (val instanceof RegExp) {
20492 return 'regexp';
20493 }
20494 if (val instanceof Date) {
20495 return 'date';
20496 }
20497
20498 // other objects
20499 var type = toString$2.call(val);
20500
20501 if (type === '[object RegExp]') {
20502 return 'regexp';
20503 }
20504 if (type === '[object Date]') {
20505 return 'date';
20506 }
20507 if (type === '[object Arguments]') {
20508 return 'arguments';
20509 }
20510 if (type === '[object Error]') {
20511 return 'error';
20512 }
20513
20514 // buffer
20515 if (isBuffer_1(val)) {
20516 return 'buffer';
20517 }
20518
20519 // es6: Map, WeakMap, Set, WeakSet
20520 if (type === '[object Set]') {
20521 return 'set';
20522 }
20523 if (type === '[object WeakSet]') {
20524 return 'weakset';
20525 }
20526 if (type === '[object Map]') {
20527 return 'map';
20528 }
20529 if (type === '[object WeakMap]') {
20530 return 'weakmap';
20531 }
20532 if (type === '[object Symbol]') {
20533 return 'symbol';
20534 }
20535
20536 // typed arrays
20537 if (type === '[object Int8Array]') {
20538 return 'int8array';
20539 }
20540 if (type === '[object Uint8Array]') {
20541 return 'uint8array';
20542 }
20543 if (type === '[object Uint8ClampedArray]') {
20544 return 'uint8clampedarray';
20545 }
20546 if (type === '[object Int16Array]') {
20547 return 'int16array';
20548 }
20549 if (type === '[object Uint16Array]') {
20550 return 'uint16array';
20551 }
20552 if (type === '[object Int32Array]') {
20553 return 'int32array';
20554 }
20555 if (type === '[object Uint32Array]') {
20556 return 'uint32array';
20557 }
20558 if (type === '[object Float32Array]') {
20559 return 'float32array';
20560 }
20561 if (type === '[object Float64Array]') {
20562 return 'float64array';
20563 }
20564
20565 // must be a plain object
20566 return 'object';
20567};
20568
20569var isNumber = function isNumber(num) {
20570 var type = kindOf$1(num);
20571
20572 if (type === 'string') {
20573 if (!num.trim()) return false;
20574 } else if (type !== 'number') {
20575 return false;
20576 }
20577
20578 return (num - num + 1) >= 0;
20579};
20580
20581var extendShallow$2 = function extend(o/*, objects*/) {
20582 if (!isExtendable$1(o)) { o = {}; }
20583
20584 var len = arguments.length;
20585 for (var i = 1; i < len; i++) {
20586 var obj = arguments[i];
20587
20588 if (isExtendable$1(obj)) {
20589 assign$2(o, obj);
20590 }
20591 }
20592 return o;
20593};
20594
20595function assign$2(a, b) {
20596 for (var key in b) {
20597 if (hasOwn$2(b, key)) {
20598 a[key] = b[key];
20599 }
20600 }
20601}
20602
20603/**
20604 * Returns true if the given `key` is an own property of `obj`.
20605 */
20606
20607function hasOwn$2(obj, key) {
20608 return Object.prototype.hasOwnProperty.call(obj, key);
20609}
20610
20611/*!
20612 * repeat-string <https://github.com/jonschlinkert/repeat-string>
20613 *
20614 * Copyright (c) 2014-2015, Jon Schlinkert.
20615 * Licensed under the MIT License.
20616 */
20617
20618/**
20619 * Results cache
20620 */
20621
20622var res = '';
20623var cache$1;
20624
20625/**
20626 * Expose `repeat`
20627 */
20628
20629var repeatString = repeat;
20630
20631/**
20632 * Repeat the given `string` the specified `number`
20633 * of times.
20634 *
20635 * **Example:**
20636 *
20637 * ```js
20638 * var repeat = require('repeat-string');
20639 * repeat('A', 5);
20640 * //=> AAAAA
20641 * ```
20642 *
20643 * @param {String} `string` The string to repeat
20644 * @param {Number} `number` The number of times to repeat the string
20645 * @return {String} Repeated string
20646 * @api public
20647 */
20648
20649function repeat(str, num) {
20650 if (typeof str !== 'string') {
20651 throw new TypeError('expected a string');
20652 }
20653
20654 // cover common, quick use cases
20655 if (num === 1) return str;
20656 if (num === 2) return str + str;
20657
20658 var max = str.length * num;
20659 if (cache$1 !== str || typeof cache$1 === 'undefined') {
20660 cache$1 = str;
20661 res = '';
20662 } else if (res.length >= max) {
20663 return res.substr(0, max);
20664 }
20665
20666 while (max > res.length && num > 1) {
20667 if (num & 1) {
20668 res += str;
20669 }
20670
20671 num >>= 1;
20672 str += str;
20673 }
20674
20675 res += str;
20676 res = res.substr(0, max);
20677 return res;
20678}
20679
20680var cache$2 = {};
20681
20682function toRegexRange(min, max, options) {
20683 if (isNumber(min) === false) {
20684 throw new RangeError('toRegexRange: first argument is invalid.');
20685 }
20686
20687 if (typeof max === 'undefined' || min === max) {
20688 return String(min);
20689 }
20690
20691 if (isNumber(max) === false) {
20692 throw new RangeError('toRegexRange: second argument is invalid.');
20693 }
20694
20695 options = options || {};
20696 var relax = String(options.relaxZeros);
20697 var shorthand = String(options.shorthand);
20698 var capture = String(options.capture);
20699 var key = min + ':' + max + '=' + relax + shorthand + capture;
20700 if (cache$2.hasOwnProperty(key)) {
20701 return cache$2[key].result;
20702 }
20703
20704 var a = Math.min(min, max);
20705 var b = Math.max(min, max);
20706
20707 if (Math.abs(a - b) === 1) {
20708 var result = min + '|' + max;
20709 if (options.capture) {
20710 return '(' + result + ')';
20711 }
20712 return result;
20713 }
20714
20715 var isPadded = padding(min) || padding(max);
20716 var positives = [];
20717 var negatives = [];
20718
20719 var tok = {min: min, max: max, a: a, b: b};
20720 if (isPadded) {
20721 tok.isPadded = isPadded;
20722 tok.maxLen = String(tok.max).length;
20723 }
20724
20725 if (a < 0) {
20726 var newMin = b < 0 ? Math.abs(b) : 1;
20727 var newMax = Math.abs(a);
20728 negatives = splitToPatterns(newMin, newMax, tok, options);
20729 a = tok.a = 0;
20730 }
20731
20732 if (b >= 0) {
20733 positives = splitToPatterns(a, b, tok, options);
20734 }
20735
20736 tok.negatives = negatives;
20737 tok.positives = positives;
20738 tok.result = siftPatterns(negatives, positives, options);
20739
20740 if (options.capture && (positives.length + negatives.length) > 1) {
20741 tok.result = '(' + tok.result + ')';
20742 }
20743
20744 cache$2[key] = tok;
20745 return tok.result;
20746}
20747
20748function siftPatterns(neg, pos, options) {
20749 var onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
20750 var onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
20751 var intersected = filterPatterns(neg, pos, '-?', true, options) || [];
20752 var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
20753 return subpatterns.join('|');
20754}
20755
20756function splitToRanges(min, max) {
20757 min = Number(min);
20758 max = Number(max);
20759
20760 var nines = 1;
20761 var stops = [max];
20762 var stop = +countNines(min, nines);
20763
20764 while (min <= stop && stop <= max) {
20765 stops = push(stops, stop);
20766 nines += 1;
20767 stop = +countNines(min, nines);
20768 }
20769
20770 var zeros = 1;
20771 stop = countZeros(max + 1, zeros) - 1;
20772
20773 while (min < stop && stop <= max) {
20774 stops = push(stops, stop);
20775 zeros += 1;
20776 stop = countZeros(max + 1, zeros) - 1;
20777 }
20778
20779 stops.sort(compare);
20780 return stops;
20781}
20782
20783/**
20784 * Convert a range to a regex pattern
20785 * @param {Number} `start`
20786 * @param {Number} `stop`
20787 * @return {String}
20788 */
20789
20790function rangeToPattern(start, stop, options) {
20791 if (start === stop) {
20792 return {pattern: String(start), digits: []};
20793 }
20794
20795 var zipped = zip(String(start), String(stop));
20796 var len = zipped.length, i = -1;
20797
20798 var pattern = '';
20799 var digits = 0;
20800
20801 while (++i < len) {
20802 var numbers = zipped[i];
20803 var startDigit = numbers[0];
20804 var stopDigit = numbers[1];
20805
20806 if (startDigit === stopDigit) {
20807 pattern += startDigit;
20808
20809 } else if (startDigit !== '0' || stopDigit !== '9') {
20810 pattern += toCharacterClass(startDigit, stopDigit);
20811
20812 } else {
20813 digits += 1;
20814 }
20815 }
20816
20817 if (digits) {
20818 pattern += options.shorthand ? '\\d' : '[0-9]';
20819 }
20820
20821 return { pattern: pattern, digits: [digits] };
20822}
20823
20824function splitToPatterns(min, max, tok, options) {
20825 var ranges = splitToRanges(min, max);
20826 var len = ranges.length;
20827 var idx = -1;
20828
20829 var tokens = [];
20830 var start = min;
20831 var prev;
20832
20833 while (++idx < len) {
20834 var range = ranges[idx];
20835 var obj = rangeToPattern(start, range, options);
20836 var zeros = '';
20837
20838 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
20839 if (prev.digits.length > 1) {
20840 prev.digits.pop();
20841 }
20842 prev.digits.push(obj.digits[0]);
20843 prev.string = prev.pattern + toQuantifier(prev.digits);
20844 start = range + 1;
20845 continue;
20846 }
20847
20848 if (tok.isPadded) {
20849 zeros = padZeros(range, tok);
20850 }
20851
20852 obj.string = zeros + obj.pattern + toQuantifier(obj.digits);
20853 tokens.push(obj);
20854 start = range + 1;
20855 prev = obj;
20856 }
20857
20858 return tokens;
20859}
20860
20861function filterPatterns(arr, comparison, prefix, intersection, options) {
20862 var res = [];
20863
20864 for (var i = 0; i < arr.length; i++) {
20865 var tok = arr[i];
20866 var ele = tok.string;
20867
20868 if (options.relaxZeros !== false) {
20869 if (prefix === '-' && ele.charAt(0) === '0') {
20870 if (ele.charAt(1) === '{') {
20871 ele = '0*' + ele.replace(/^0\{\d+\}/, '');
20872 } else {
20873 ele = '0*' + ele.slice(1);
20874 }
20875 }
20876 }
20877
20878 if (!intersection && !contains(comparison, 'string', ele)) {
20879 res.push(prefix + ele);
20880 }
20881
20882 if (intersection && contains(comparison, 'string', ele)) {
20883 res.push(prefix + ele);
20884 }
20885 }
20886 return res;
20887}
20888
20889/**
20890 * Zip strings (`for in` can be used on string characters)
20891 */
20892
20893function zip(a, b) {
20894 var arr = [];
20895 for (var ch in a) arr.push([a[ch], b[ch]]);
20896 return arr;
20897}
20898
20899function compare(a, b) {
20900 return a > b ? 1 : b > a ? -1 : 0;
20901}
20902
20903function push(arr, ele) {
20904 if (arr.indexOf(ele) === -1) arr.push(ele);
20905 return arr;
20906}
20907
20908function contains(arr, key, val) {
20909 for (var i = 0; i < arr.length; i++) {
20910 if (arr[i][key] === val) {
20911 return true;
20912 }
20913 }
20914 return false;
20915}
20916
20917function countNines(min, len) {
20918 return String(min).slice(0, -len) + repeatString('9', len);
20919}
20920
20921function countZeros(integer, zeros) {
20922 return integer - (integer % Math.pow(10, zeros));
20923}
20924
20925function toQuantifier(digits) {
20926 var start = digits[0];
20927 var stop = digits[1] ? (',' + digits[1]) : '';
20928 if (!stop && (!start || start === 1)) {
20929 return '';
20930 }
20931 return '{' + start + stop + '}';
20932}
20933
20934function toCharacterClass(a, b) {
20935 return '[' + a + ((b - a === 1) ? '' : '-') + b + ']';
20936}
20937
20938function padding(str) {
20939 return /^-?(0+)\d/.exec(str);
20940}
20941
20942function padZeros(val, tok) {
20943 if (tok.isPadded) {
20944 var diff = Math.abs(tok.maxLen - String(val).length);
20945 switch (diff) {
20946 case 0:
20947 return '';
20948 case 1:
20949 return '0';
20950 default: {
20951 return '0{' + diff + '}';
20952 }
20953 }
20954 }
20955 return val;
20956}
20957
20958/**
20959 * Expose `toRegexRange`
20960 */
20961
20962var toRegexRange_1 = toRegexRange;
20963
20964/**
20965 * Return a range of numbers or letters.
20966 *
20967 * @param {String} `start` Start of the range
20968 * @param {String} `stop` End of the range
20969 * @param {String} `step` Increment or decrement to use.
20970 * @param {Function} `fn` Custom function to modify each element in the range.
20971 * @return {Array}
20972 */
20973
20974function fillRange(start, stop, step, options) {
20975 if (typeof start === 'undefined') {
20976 return [];
20977 }
20978
20979 if (typeof stop === 'undefined' || start === stop) {
20980 // special case, for handling negative zero
20981 var isString = typeof start === 'string';
20982 if (isNumber(start) && !toNumber(start)) {
20983 return [isString ? '0' : 0];
20984 }
20985 return [start];
20986 }
20987
20988 if (typeof step !== 'number' && typeof step !== 'string') {
20989 options = step;
20990 step = undefined;
20991 }
20992
20993 if (typeof options === 'function') {
20994 options = { transform: options };
20995 }
20996
20997 var opts = extendShallow$2({step: step}, options);
20998 if (opts.step && !isValidNumber(opts.step)) {
20999 if (opts.strictRanges === true) {
21000 throw new TypeError('expected options.step to be a number');
21001 }
21002 return [];
21003 }
21004
21005 opts.isNumber = isValidNumber(start) && isValidNumber(stop);
21006 if (!opts.isNumber && !isValid(start, stop)) {
21007 if (opts.strictRanges === true) {
21008 throw new RangeError('invalid range arguments: ' + util$2.inspect([start, stop]));
21009 }
21010 return [];
21011 }
21012
21013 opts.isPadded = isPadded(start) || isPadded(stop);
21014 opts.toString = opts.stringify
21015 || typeof opts.step === 'string'
21016 || typeof start === 'string'
21017 || typeof stop === 'string'
21018 || !opts.isNumber;
21019
21020 if (opts.isPadded) {
21021 opts.maxLength = Math.max(String(start).length, String(stop).length);
21022 }
21023
21024 // support legacy minimatch/fill-range options
21025 if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize;
21026 if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe;
21027 return expand(start, stop, opts);
21028}
21029
21030function expand(start, stop, options) {
21031 var a = options.isNumber ? toNumber(start) : start.charCodeAt(0);
21032 var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0);
21033
21034 var step = Math.abs(toNumber(options.step)) || 1;
21035 if (options.toRegex && step === 1) {
21036 return toRange(a, b, start, stop, options);
21037 }
21038
21039 var zero = {greater: [], lesser: []};
21040 var asc = a < b;
21041 var arr = new Array(Math.round((asc ? b - a : a - b) / step));
21042 var idx = 0;
21043
21044 while (asc ? a <= b : a >= b) {
21045 var val = options.isNumber ? a : String.fromCharCode(a);
21046 if (options.toRegex && (val >= 0 || !options.isNumber)) {
21047 zero.greater.push(val);
21048 } else {
21049 zero.lesser.push(Math.abs(val));
21050 }
21051
21052 if (options.isPadded) {
21053 val = zeros(val, options);
21054 }
21055
21056 if (options.toString) {
21057 val = String(val);
21058 }
21059
21060 if (typeof options.transform === 'function') {
21061 arr[idx++] = options.transform(val, a, b, step, idx, arr, options);
21062 } else {
21063 arr[idx++] = val;
21064 }
21065
21066 if (asc) {
21067 a += step;
21068 } else {
21069 a -= step;
21070 }
21071 }
21072
21073 if (options.toRegex === true) {
21074 return toSequence(arr, zero, options);
21075 }
21076 return arr;
21077}
21078
21079function toRange(a, b, start, stop, options) {
21080 if (options.isPadded) {
21081 return toRegexRange_1(start, stop, options);
21082 }
21083
21084 if (options.isNumber) {
21085 return toRegexRange_1(Math.min(a, b), Math.max(a, b), options);
21086 }
21087
21088 var start = String.fromCharCode(Math.min(a, b));
21089 var stop = String.fromCharCode(Math.max(a, b));
21090 return '[' + start + '-' + stop + ']';
21091}
21092
21093function toSequence(arr, zeros, options) {
21094 var greater = '', lesser = '';
21095 if (zeros.greater.length) {
21096 greater = zeros.greater.join('|');
21097 }
21098 if (zeros.lesser.length) {
21099 lesser = '-(' + zeros.lesser.join('|') + ')';
21100 }
21101 var res = greater && lesser
21102 ? greater + '|' + lesser
21103 : greater || lesser;
21104
21105 if (options.capture) {
21106 return '(' + res + ')';
21107 }
21108 return res;
21109}
21110
21111function zeros(val, options) {
21112 if (options.isPadded) {
21113 var str = String(val);
21114 var len = str.length;
21115 var dash = '';
21116 if (str.charAt(0) === '-') {
21117 dash = '-';
21118 str = str.slice(1);
21119 }
21120 var diff = options.maxLength - len;
21121 var pad = repeatString('0', diff);
21122 val = (dash + pad + str);
21123 }
21124 if (options.stringify) {
21125 return String(val);
21126 }
21127 return val;
21128}
21129
21130function toNumber(val) {
21131 return Number(val) || 0;
21132}
21133
21134function isPadded(str) {
21135 return /^-?0\d/.test(str);
21136}
21137
21138function isValid(min, max) {
21139 return (isValidNumber(min) || isValidLetter(min))
21140 && (isValidNumber(max) || isValidLetter(max));
21141}
21142
21143function isValidLetter(ch) {
21144 return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch);
21145}
21146
21147function isValidNumber(n) {
21148 return isNumber(n) && !/\./.test(n);
21149}
21150
21151/**
21152 * Expose `fillRange`
21153 * @type {Function}
21154 */
21155
21156var fillRange_1 = fillRange;
21157
21158/*!
21159 * repeat-element <https://github.com/jonschlinkert/repeat-element>
21160 *
21161 * Copyright (c) 2015-present, Jon Schlinkert.
21162 * Licensed under the MIT license.
21163 */
21164
21165var repeatElement = function repeat(ele, num) {
21166 var arr = new Array(num);
21167
21168 for (var i = 0; i < num; i++) {
21169 arr[i] = ele;
21170 }
21171
21172 return arr;
21173};
21174
21175var utils_1 = createCommonjsModule(function (module) {
21176
21177
21178var utils = module.exports;
21179
21180/**
21181 * Module dependencies
21182 */
21183
21184utils.extend = extendShallow$1;
21185utils.flatten = arrFlatten;
21186utils.isObject = isobject;
21187utils.fillRange = fillRange_1;
21188utils.repeat = repeatElement;
21189utils.unique = arrayUnique;
21190
21191utils.define = function(obj, key, val) {
21192 Object.defineProperty(obj, key, {
21193 writable: true,
21194 configurable: true,
21195 enumerable: false,
21196 value: val
21197 });
21198};
21199
21200/**
21201 * Returns true if the given string contains only empty brace sets.
21202 */
21203
21204utils.isEmptySets = function(str) {
21205 return /^(?:\{,\})+$/.test(str);
21206};
21207
21208/**
21209 * Returns true if the given string contains only empty brace sets.
21210 */
21211
21212utils.isQuotedString = function(str) {
21213 var open = str.charAt(0);
21214 if (open === '\'' || open === '"' || open === '`') {
21215 return str.slice(-1) === open;
21216 }
21217 return false;
21218};
21219
21220/**
21221 * Create the key to use for memoization. The unique key is generated
21222 * by iterating over the options and concatenating key-value pairs
21223 * to the pattern string.
21224 */
21225
21226utils.createKey = function(pattern, options) {
21227 var id = pattern;
21228 if (typeof options === 'undefined') {
21229 return id;
21230 }
21231 var keys = Object.keys(options);
21232 for (var i = 0; i < keys.length; i++) {
21233 var key = keys[i];
21234 id += ';' + key + '=' + String(options[key]);
21235 }
21236 return id;
21237};
21238
21239/**
21240 * Normalize options
21241 */
21242
21243utils.createOptions = function(options) {
21244 var opts = utils.extend.apply(null, arguments);
21245 if (typeof opts.expand === 'boolean') {
21246 opts.optimize = !opts.expand;
21247 }
21248 if (typeof opts.optimize === 'boolean') {
21249 opts.expand = !opts.optimize;
21250 }
21251 if (opts.optimize === true) {
21252 opts.makeRe = true;
21253 }
21254 return opts;
21255};
21256
21257/**
21258 * Join patterns in `a` to patterns in `b`
21259 */
21260
21261utils.join = function(a, b, options) {
21262 options = options || {};
21263 a = utils.arrayify(a);
21264 b = utils.arrayify(b);
21265
21266 if (!a.length) return b;
21267 if (!b.length) return a;
21268
21269 var len = a.length;
21270 var idx = -1;
21271 var arr = [];
21272
21273 while (++idx < len) {
21274 var val = a[idx];
21275 if (Array.isArray(val)) {
21276 for (var i = 0; i < val.length; i++) {
21277 val[i] = utils.join(val[i], b, options);
21278 }
21279 arr.push(val);
21280 continue;
21281 }
21282
21283 for (var j = 0; j < b.length; j++) {
21284 var bval = b[j];
21285
21286 if (Array.isArray(bval)) {
21287 arr.push(utils.join(val, bval, options));
21288 } else {
21289 arr.push(val + bval);
21290 }
21291 }
21292 }
21293 return arr;
21294};
21295
21296/**
21297 * Split the given string on `,` if not escaped.
21298 */
21299
21300utils.split = function(str, options) {
21301 var opts = utils.extend({sep: ','}, options);
21302 if (typeof opts.keepQuotes !== 'boolean') {
21303 opts.keepQuotes = true;
21304 }
21305 if (opts.unescape === false) {
21306 opts.keepEscaping = true;
21307 }
21308 return splitString(str, opts, utils.escapeBrackets(opts));
21309};
21310
21311/**
21312 * Expand ranges or sets in the given `pattern`.
21313 *
21314 * @param {String} `str`
21315 * @param {Object} `options`
21316 * @return {Object}
21317 */
21318
21319utils.expand = function(str, options) {
21320 var opts = utils.extend({rangeLimit: 10000}, options);
21321 var segs = utils.split(str, opts);
21322 var tok = { segs: segs };
21323
21324 if (utils.isQuotedString(str)) {
21325 return tok;
21326 }
21327
21328 if (opts.rangeLimit === true) {
21329 opts.rangeLimit = 10000;
21330 }
21331
21332 if (segs.length > 1) {
21333 if (opts.optimize === false) {
21334 tok.val = segs[0];
21335 return tok;
21336 }
21337
21338 tok.segs = utils.stringifyArray(tok.segs);
21339 } else if (segs.length === 1) {
21340 var arr = str.split('..');
21341
21342 if (arr.length === 1) {
21343 tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;
21344 tok.segs = [];
21345 return tok;
21346 }
21347
21348 if (arr.length === 2 && arr[0] === arr[1]) {
21349 tok.escaped = true;
21350 tok.val = arr[0];
21351 tok.segs = [];
21352 return tok;
21353 }
21354
21355 if (arr.length > 1) {
21356 if (opts.optimize !== false) {
21357 opts.optimize = true;
21358 delete opts.expand;
21359 }
21360
21361 if (opts.optimize !== true) {
21362 var min = Math.min(arr[0], arr[1]);
21363 var max = Math.max(arr[0], arr[1]);
21364 var step = arr[2] || 1;
21365
21366 if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {
21367 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
21368 }
21369 }
21370
21371 arr.push(opts);
21372 tok.segs = utils.fillRange.apply(null, arr);
21373
21374 if (!tok.segs.length) {
21375 tok.escaped = true;
21376 tok.val = str;
21377 return tok;
21378 }
21379
21380 if (opts.optimize === true) {
21381 tok.segs = utils.stringifyArray(tok.segs);
21382 }
21383
21384 if (tok.segs === '') {
21385 tok.val = str;
21386 } else {
21387 tok.val = tok.segs[0];
21388 }
21389 return tok;
21390 }
21391 } else {
21392 tok.val = str;
21393 }
21394 return tok;
21395};
21396
21397/**
21398 * Ensure commas inside brackets and parens are not split.
21399 * @param {Object} `tok` Token from the `split-string` module
21400 * @return {undefined}
21401 */
21402
21403utils.escapeBrackets = function(options) {
21404 return function(tok) {
21405 if (tok.escaped && tok.val === 'b') {
21406 tok.val = '\\b';
21407 return;
21408 }
21409
21410 if (tok.val !== '(' && tok.val !== '[') return;
21411 var opts = utils.extend({}, options);
21412 var stack = [];
21413 var val = tok.val;
21414 var str = tok.str;
21415 var i = tok.idx - 1;
21416
21417 while (++i < str.length) {
21418 var ch = str[i];
21419
21420 if (ch === '\\') {
21421 val += (opts.keepEscaping === false ? '' : ch) + str[++i];
21422 continue;
21423 }
21424
21425 if (ch === '(') {
21426 stack.push(ch);
21427 }
21428
21429 if (ch === '[') {
21430 stack.push(ch);
21431 }
21432
21433 if (ch === ')') {
21434 stack.pop();
21435 if (!stack.length) {
21436 val += ch;
21437 break;
21438 }
21439 }
21440
21441 if (ch === ']') {
21442 stack.pop();
21443 if (!stack.length) {
21444 val += ch;
21445 break;
21446 }
21447 }
21448 val += ch;
21449 }
21450
21451 tok.split = false;
21452 tok.val = val.slice(1);
21453 tok.idx = i;
21454 };
21455};
21456
21457/**
21458 * Returns true if the given string looks like a regex quantifier
21459 * @return {Boolean}
21460 */
21461
21462utils.isQuantifier = function(str) {
21463 return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);
21464};
21465
21466/**
21467 * Cast `val` to an array.
21468 * @param {*} `val`
21469 */
21470
21471utils.stringifyArray = function(arr) {
21472 return [utils.arrayify(arr).join('|')];
21473};
21474
21475/**
21476 * Cast `val` to an array.
21477 * @param {*} `val`
21478 */
21479
21480utils.arrayify = function(arr) {
21481 if (typeof arr === 'undefined') {
21482 return [];
21483 }
21484 if (typeof arr === 'string') {
21485 return [arr];
21486 }
21487 return arr;
21488};
21489
21490/**
21491 * Returns true if the given `str` is a non-empty string
21492 * @return {Boolean}
21493 */
21494
21495utils.isString = function(str) {
21496 return str != null && typeof str === 'string';
21497};
21498
21499/**
21500 * Get the last element from `array`
21501 * @param {Array} `array`
21502 * @return {*}
21503 */
21504
21505utils.last = function(arr, n) {
21506 return arr[arr.length - (n || 1)];
21507};
21508
21509utils.escapeRegex = function(str) {
21510 return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1');
21511};
21512});
21513
21514var compilers = function(braces, options) {
21515 braces.compiler
21516
21517 /**
21518 * bos
21519 */
21520
21521 .set('bos', function() {
21522 if (this.output) return;
21523 this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];
21524 this.ast.count = 1;
21525 })
21526
21527 /**
21528 * Square brackets
21529 */
21530
21531 .set('bracket', function(node) {
21532 var close = node.close;
21533 var open = !node.escaped ? '[' : '\\[';
21534 var negated = node.negated;
21535 var inner = node.inner;
21536
21537 inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\');
21538 if (inner === ']-') {
21539 inner = '\\]\\-';
21540 }
21541
21542 if (negated && inner.indexOf('.') === -1) {
21543 inner += '.';
21544 }
21545 if (negated && inner.indexOf('/') === -1) {
21546 inner += '/';
21547 }
21548
21549 var val = open + negated + inner + close;
21550 var queue = node.parent.queue;
21551 var last = utils_1.arrayify(queue.pop());
21552
21553 queue.push(utils_1.join(last, val));
21554 queue.push.apply(queue, []);
21555 })
21556
21557 /**
21558 * Brace
21559 */
21560
21561 .set('brace', function(node) {
21562 node.queue = isEscaped(node) ? [node.val] : [];
21563 node.count = 1;
21564 return this.mapVisit(node.nodes);
21565 })
21566
21567 /**
21568 * Open
21569 */
21570
21571 .set('brace.open', function(node) {
21572 node.parent.open = node.val;
21573 })
21574
21575 /**
21576 * Inner
21577 */
21578
21579 .set('text', function(node) {
21580 var queue = node.parent.queue;
21581 var escaped = node.escaped;
21582 var segs = [node.val];
21583
21584 if (node.optimize === false) {
21585 options = utils_1.extend({}, options, {optimize: false});
21586 }
21587
21588 if (node.multiplier > 1) {
21589 node.parent.count *= node.multiplier;
21590 }
21591
21592 if (options.quantifiers === true && utils_1.isQuantifier(node.val)) {
21593 escaped = true;
21594
21595 } else if (node.val.length > 1) {
21596 if (isType(node.parent, 'brace') && !isEscaped(node)) {
21597 var expanded = utils_1.expand(node.val, options);
21598 segs = expanded.segs;
21599
21600 if (expanded.isOptimized) {
21601 node.parent.isOptimized = true;
21602 }
21603
21604 // if nothing was expanded, we probably have a literal brace
21605 if (!segs.length) {
21606 var val = (expanded.val || node.val);
21607 if (options.unescape !== false) {
21608 // unescape unexpanded brace sequence/set separators
21609 val = val.replace(/\\([,.])/g, '$1');
21610 // strip quotes
21611 val = val.replace(/["'`]/g, '');
21612 }
21613
21614 segs = [val];
21615 escaped = true;
21616 }
21617 }
21618
21619 } else if (node.val === ',') {
21620 if (options.expand) {
21621 node.parent.queue.push(['']);
21622 segs = [''];
21623 } else {
21624 segs = ['|'];
21625 }
21626 } else {
21627 escaped = true;
21628 }
21629
21630 if (escaped && isType(node.parent, 'brace')) {
21631 if (node.parent.nodes.length <= 4 && node.parent.count === 1) {
21632 node.parent.escaped = true;
21633 } else if (node.parent.length <= 3) {
21634 node.parent.escaped = true;
21635 }
21636 }
21637
21638 if (!hasQueue(node.parent)) {
21639 node.parent.queue = segs;
21640 return;
21641 }
21642
21643 var last = utils_1.arrayify(queue.pop());
21644 if (node.parent.count > 1 && options.expand) {
21645 last = multiply(last, node.parent.count);
21646 node.parent.count = 1;
21647 }
21648
21649 queue.push(utils_1.join(utils_1.flatten(last), segs.shift()));
21650 queue.push.apply(queue, segs);
21651 })
21652
21653 /**
21654 * Close
21655 */
21656
21657 .set('brace.close', function(node) {
21658 var queue = node.parent.queue;
21659 var prev = node.parent.parent;
21660 var last = prev.queue.pop();
21661 var open = node.parent.open;
21662 var close = node.val;
21663
21664 if (open && close && isOptimized(node, options)) {
21665 open = '(';
21666 close = ')';
21667 }
21668
21669 // if a close brace exists, and the previous segment is one character
21670 // don't wrap the result in braces or parens
21671 var ele = utils_1.last(queue);
21672 if (node.parent.count > 1 && options.expand) {
21673 ele = multiply(queue.pop(), node.parent.count);
21674 node.parent.count = 1;
21675 queue.push(ele);
21676 }
21677
21678 if (close && typeof ele === 'string' && ele.length === 1) {
21679 open = '';
21680 close = '';
21681 }
21682
21683 if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {
21684 queue.push(utils_1.join(open, queue.pop() || ''));
21685 queue = utils_1.flatten(utils_1.join(queue, close));
21686 }
21687
21688 if (typeof last === 'undefined') {
21689 prev.queue = [queue];
21690 } else {
21691 prev.queue.push(utils_1.flatten(utils_1.join(last, queue)));
21692 }
21693 })
21694
21695 /**
21696 * eos
21697 */
21698
21699 .set('eos', function(node) {
21700 if (this.input) return;
21701
21702 if (options.optimize !== false) {
21703 this.output = utils_1.last(utils_1.flatten(this.ast.queue));
21704 } else if (Array.isArray(utils_1.last(this.ast.queue))) {
21705 this.output = utils_1.flatten(this.ast.queue.pop());
21706 } else {
21707 this.output = utils_1.flatten(this.ast.queue);
21708 }
21709
21710 if (node.parent.count > 1 && options.expand) {
21711 this.output = multiply(this.output, node.parent.count);
21712 }
21713
21714 this.output = utils_1.arrayify(this.output);
21715 this.ast.queue = [];
21716 });
21717
21718};
21719
21720/**
21721 * Multiply the segments in the current brace level
21722 */
21723
21724function multiply(queue, n, options) {
21725 return utils_1.flatten(utils_1.repeat(utils_1.arrayify(queue), n));
21726}
21727
21728/**
21729 * Return true if `node` is escaped
21730 */
21731
21732function isEscaped(node) {
21733 return node.escaped === true;
21734}
21735
21736/**
21737 * Returns true if regex parens should be used for sets. If the parent `type`
21738 * is not `brace`, then we're on a root node, which means we should never
21739 * expand segments and open/close braces should be `{}` (since this indicates
21740 * a brace is missing from the set)
21741 */
21742
21743function isOptimized(node, options) {
21744 if (node.parent.isOptimized) return true;
21745 return isType(node.parent, 'brace')
21746 && !isEscaped(node.parent)
21747 && options.expand !== true;
21748}
21749
21750/**
21751 * Returns true if the value in `node` should be wrapped in a literal brace.
21752 * @return {Boolean}
21753 */
21754
21755function isLiteralBrace(node, options) {
21756 return isEscaped(node.parent) || options.optimize !== false;
21757}
21758
21759/**
21760 * Returns true if the given `node` does not have an inner value.
21761 * @return {Boolean}
21762 */
21763
21764function noInner(node, type) {
21765 if (node.parent.queue.length === 1) {
21766 return true;
21767 }
21768 var nodes = node.parent.nodes;
21769 return nodes.length === 3
21770 && isType(nodes[0], 'brace.open')
21771 && !isType(nodes[1], 'text')
21772 && isType(nodes[2], 'brace.close');
21773}
21774
21775/**
21776 * Returns true if the given `node` is the given `type`
21777 * @return {Boolean}
21778 */
21779
21780function isType(node, type) {
21781 return typeof node !== 'undefined' && node.type === type;
21782}
21783
21784/**
21785 * Returns true if the given `node` has a non-empty queue.
21786 * @return {Boolean}
21787 */
21788
21789function hasQueue(node) {
21790 return Array.isArray(node.queue) && node.queue.length;
21791}
21792
21793// accessor descriptor properties
21794var accessor$1 = {
21795 get: 'function',
21796 set: 'function',
21797 configurable: 'boolean',
21798 enumerable: 'boolean'
21799};
21800
21801function isAccessorDescriptor$1(obj, prop) {
21802 if (typeof prop === 'string') {
21803 var val = Object.getOwnPropertyDescriptor(obj, prop);
21804 return typeof val !== 'undefined';
21805 }
21806
21807 if (kindOf(obj) !== 'object') {
21808 return false;
21809 }
21810
21811 if (has$2(obj, 'value') || has$2(obj, 'writable')) {
21812 return false;
21813 }
21814
21815 if (!has$2(obj, 'get') || typeof obj.get !== 'function') {
21816 return false;
21817 }
21818
21819 // tldr: it's valid to have "set" be undefined
21820 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
21821 // was used to get the value, and only `get` was defined by the user
21822 if (has$2(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
21823 return false;
21824 }
21825
21826 for (var key in obj) {
21827 if (!accessor$1.hasOwnProperty(key)) {
21828 continue;
21829 }
21830
21831 if (kindOf(obj[key]) === accessor$1[key]) {
21832 continue;
21833 }
21834
21835 if (typeof obj[key] !== 'undefined') {
21836 return false;
21837 }
21838 }
21839 return true;
21840}
21841
21842function has$2(obj, key) {
21843 return {}.hasOwnProperty.call(obj, key);
21844}
21845
21846/**
21847 * Expose `isAccessorDescriptor`
21848 */
21849
21850var isAccessorDescriptor_1$1 = isAccessorDescriptor$1;
21851
21852var isDataDescriptor$1 = function isDataDescriptor(obj, prop) {
21853 // data descriptor properties
21854 var data = {
21855 configurable: 'boolean',
21856 enumerable: 'boolean',
21857 writable: 'boolean'
21858 };
21859
21860 if (kindOf(obj) !== 'object') {
21861 return false;
21862 }
21863
21864 if (typeof prop === 'string') {
21865 var val = Object.getOwnPropertyDescriptor(obj, prop);
21866 return typeof val !== 'undefined';
21867 }
21868
21869 if (!('value' in obj) && !('writable' in obj)) {
21870 return false;
21871 }
21872
21873 for (var key in obj) {
21874 if (key === 'value') continue;
21875
21876 if (!data.hasOwnProperty(key)) {
21877 continue;
21878 }
21879
21880 if (kindOf(obj[key]) === data[key]) {
21881 continue;
21882 }
21883
21884 if (typeof obj[key] !== 'undefined') {
21885 return false;
21886 }
21887 }
21888 return true;
21889};
21890
21891var isDescriptor$1 = function isDescriptor(obj, key) {
21892 if (kindOf(obj) !== 'object') {
21893 return false;
21894 }
21895 if ('get' in obj) {
21896 return isAccessorDescriptor_1$1(obj, key);
21897 }
21898 return isDataDescriptor$1(obj, key);
21899};
21900
21901var defineProperty$1 = function defineProperty(obj, prop, val) {
21902 if (typeof obj !== 'object' && typeof obj !== 'function') {
21903 throw new TypeError('expected an object or function.');
21904 }
21905
21906 if (typeof prop !== 'string') {
21907 throw new TypeError('expected `prop` to be a string.');
21908 }
21909
21910 if (isDescriptor$1(val) && ('set' in val || 'get' in val)) {
21911 return Object.defineProperty(obj, prop, val);
21912 }
21913
21914 return Object.defineProperty(obj, prop, {
21915 configurable: true,
21916 enumerable: false,
21917 writable: true,
21918 value: val
21919 });
21920};
21921
21922var toString$3 = Object.prototype.toString;
21923
21924/**
21925 * Get the native `typeof` a value.
21926 *
21927 * @param {*} `val`
21928 * @return {*} Native javascript type
21929 */
21930
21931var kindOf$2 = function kindOf(val) {
21932 // primitivies
21933 if (typeof val === 'undefined') {
21934 return 'undefined';
21935 }
21936 if (val === null) {
21937 return 'null';
21938 }
21939 if (val === true || val === false || val instanceof Boolean) {
21940 return 'boolean';
21941 }
21942 if (typeof val === 'string' || val instanceof String) {
21943 return 'string';
21944 }
21945 if (typeof val === 'number' || val instanceof Number) {
21946 return 'number';
21947 }
21948
21949 // functions
21950 if (typeof val === 'function' || val instanceof Function) {
21951 return 'function';
21952 }
21953
21954 // array
21955 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
21956 return 'array';
21957 }
21958
21959 // check for instances of RegExp and Date before calling `toString`
21960 if (val instanceof RegExp) {
21961 return 'regexp';
21962 }
21963 if (val instanceof Date) {
21964 return 'date';
21965 }
21966
21967 // other objects
21968 var type = toString$3.call(val);
21969
21970 if (type === '[object RegExp]') {
21971 return 'regexp';
21972 }
21973 if (type === '[object Date]') {
21974 return 'date';
21975 }
21976 if (type === '[object Arguments]') {
21977 return 'arguments';
21978 }
21979 if (type === '[object Error]') {
21980 return 'error';
21981 }
21982
21983 // buffer
21984 if (isBuffer_1(val)) {
21985 return 'buffer';
21986 }
21987
21988 // es6: Map, WeakMap, Set, WeakSet
21989 if (type === '[object Set]') {
21990 return 'set';
21991 }
21992 if (type === '[object WeakSet]') {
21993 return 'weakset';
21994 }
21995 if (type === '[object Map]') {
21996 return 'map';
21997 }
21998 if (type === '[object WeakMap]') {
21999 return 'weakmap';
22000 }
22001 if (type === '[object Symbol]') {
22002 return 'symbol';
22003 }
22004
22005 // typed arrays
22006 if (type === '[object Int8Array]') {
22007 return 'int8array';
22008 }
22009 if (type === '[object Uint8Array]') {
22010 return 'uint8array';
22011 }
22012 if (type === '[object Uint8ClampedArray]') {
22013 return 'uint8clampedarray';
22014 }
22015 if (type === '[object Int16Array]') {
22016 return 'int16array';
22017 }
22018 if (type === '[object Uint16Array]') {
22019 return 'uint16array';
22020 }
22021 if (type === '[object Int32Array]') {
22022 return 'int32array';
22023 }
22024 if (type === '[object Uint32Array]') {
22025 return 'uint32array';
22026 }
22027 if (type === '[object Float32Array]') {
22028 return 'float32array';
22029 }
22030 if (type === '[object Float64Array]') {
22031 return 'float64array';
22032 }
22033
22034 // must be a plain object
22035 return 'object';
22036};
22037
22038var snapdragonUtil = createCommonjsModule(function (module) {
22039
22040
22041var utils = module.exports;
22042
22043/**
22044 * Returns true if the given value is a node.
22045 *
22046 * ```js
22047 * var Node = require('snapdragon-node');
22048 * var node = new Node({type: 'foo'});
22049 * console.log(utils.isNode(node)); //=> true
22050 * console.log(utils.isNode({})); //=> false
22051 * ```
22052 * @param {Object} `node` Instance of [snapdragon-node][]
22053 * @returns {Boolean}
22054 * @api public
22055 */
22056
22057utils.isNode = function(node) {
22058 return kindOf$2(node) === 'object' && node.isNode === true;
22059};
22060
22061/**
22062 * Emit an empty string for the given `node`.
22063 *
22064 * ```js
22065 * // do nothing for beginning-of-string
22066 * snapdragon.compiler.set('bos', utils.noop);
22067 * ```
22068 * @param {Object} `node` Instance of [snapdragon-node][]
22069 * @returns {undefined}
22070 * @api public
22071 */
22072
22073utils.noop = function(node) {
22074 append(this, '', node);
22075};
22076
22077/**
22078 * Appdend `node.val` to `compiler.output`, exactly as it was created
22079 * by the parser.
22080 *
22081 * ```js
22082 * snapdragon.compiler.set('text', utils.identity);
22083 * ```
22084 * @param {Object} `node` Instance of [snapdragon-node][]
22085 * @returns {undefined}
22086 * @api public
22087 */
22088
22089utils.identity = function(node) {
22090 append(this, node.val, node);
22091};
22092
22093/**
22094 * Previously named `.emit`, this method appends the given `val`
22095 * to `compiler.output` for the given node. Useful when you know
22096 * what value should be appended advance, regardless of the actual
22097 * value of `node.val`.
22098 *
22099 * ```js
22100 * snapdragon.compiler
22101 * .set('i', function(node) {
22102 * this.mapVisit(node);
22103 * })
22104 * .set('i.open', utils.append('<i>'))
22105 * .set('i.close', utils.append('</i>'))
22106 * ```
22107 * @param {Object} `node` Instance of [snapdragon-node][]
22108 * @returns {Function} Returns a compiler middleware function.
22109 * @api public
22110 */
22111
22112utils.append = function(val) {
22113 return function(node) {
22114 append(this, val, node);
22115 };
22116};
22117
22118/**
22119 * Used in compiler middleware, this onverts an AST node into
22120 * an empty `text` node and deletes `node.nodes` if it exists.
22121 * The advantage of this method is that, as opposed to completely
22122 * removing the node, indices will not need to be re-calculated
22123 * in sibling nodes, and nothing is appended to the output.
22124 *
22125 * ```js
22126 * utils.toNoop(node);
22127 * // convert `node.nodes` to the given value instead of deleting it
22128 * utils.toNoop(node, []);
22129 * ```
22130 * @param {Object} `node` Instance of [snapdragon-node][]
22131 * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array.
22132 * @api public
22133 */
22134
22135utils.toNoop = function(node, nodes) {
22136 if (nodes) {
22137 node.nodes = nodes;
22138 } else {
22139 delete node.nodes;
22140 node.type = 'text';
22141 node.val = '';
22142 }
22143};
22144
22145/**
22146 * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon
22147 * automatically calls registered compilers, this allows you to pass a visitor
22148 * function.
22149 *
22150 * ```js
22151 * snapdragon.compiler.set('i', function(node) {
22152 * utils.visit(node, function(childNode) {
22153 * // do stuff with "childNode"
22154 * return childNode;
22155 * });
22156 * });
22157 * ```
22158 * @param {Object} `node` Instance of [snapdragon-node][]
22159 * @param {Function} `fn`
22160 * @return {Object} returns the node after recursively visiting all child nodes.
22161 * @api public
22162 */
22163
22164utils.visit = function(node, fn) {
22165 assert(utils.isNode(node), 'expected node to be an instance of Node');
22166 assert(isFunction(fn), 'expected a visitor function');
22167 fn(node);
22168 return node.nodes ? utils.mapVisit(node, fn) : node;
22169};
22170
22171/**
22172 * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by
22173 * [visit](#visit), use this method if you do not want `fn` to be called on
22174 * the first node.
22175 *
22176 * ```js
22177 * snapdragon.compiler.set('i', function(node) {
22178 * utils.mapVisit(node, function(childNode) {
22179 * // do stuff with "childNode"
22180 * return childNode;
22181 * });
22182 * });
22183 * ```
22184 * @param {Object} `node` Instance of [snapdragon-node][]
22185 * @param {Object} `options`
22186 * @param {Function} `fn`
22187 * @return {Object} returns the node
22188 * @api public
22189 */
22190
22191utils.mapVisit = function(node, fn) {
22192 assert(utils.isNode(node), 'expected node to be an instance of Node');
22193 assert(isArray(node.nodes), 'expected node.nodes to be an array');
22194 assert(isFunction(fn), 'expected a visitor function');
22195
22196 for (var i = 0; i < node.nodes.length; i++) {
22197 utils.visit(node.nodes[i], fn);
22198 }
22199 return node;
22200};
22201
22202/**
22203 * Unshift an `*.open` node onto `node.nodes`.
22204 *
22205 * ```js
22206 * var Node = require('snapdragon-node');
22207 * snapdragon.parser.set('brace', function(node) {
22208 * var match = this.match(/^{/);
22209 * if (match) {
22210 * var parent = new Node({type: 'brace'});
22211 * utils.addOpen(parent, Node);
22212 * console.log(parent.nodes[0]):
22213 * // { type: 'brace.open', val: '' };
22214 *
22215 * // push the parent "brace" node onto the stack
22216 * this.push(parent);
22217 *
22218 * // return the parent node, so it's also added to the AST
22219 * return brace;
22220 * }
22221 * });
22222 * ```
22223 * @param {Object} `node` Instance of [snapdragon-node][]
22224 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
22225 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
22226 * @return {Object} Returns the created opening node.
22227 * @api public
22228 */
22229
22230utils.addOpen = function(node, Node, val, filter) {
22231 assert(utils.isNode(node), 'expected node to be an instance of Node');
22232 assert(isFunction(Node), 'expected Node to be a constructor function');
22233
22234 if (typeof val === 'function') {
22235 filter = val;
22236 val = '';
22237 }
22238
22239 if (typeof filter === 'function' && !filter(node)) return;
22240 var open = new Node({ type: node.type + '.open', val: val});
22241 var unshift = node.unshift || node.unshiftNode;
22242 if (typeof unshift === 'function') {
22243 unshift.call(node, open);
22244 } else {
22245 utils.unshiftNode(node, open);
22246 }
22247 return open;
22248};
22249
22250/**
22251 * Push a `*.close` node onto `node.nodes`.
22252 *
22253 * ```js
22254 * var Node = require('snapdragon-node');
22255 * snapdragon.parser.set('brace', function(node) {
22256 * var match = this.match(/^}/);
22257 * if (match) {
22258 * var parent = this.parent();
22259 * if (parent.type !== 'brace') {
22260 * throw new Error('missing opening: ' + '}');
22261 * }
22262 *
22263 * utils.addClose(parent, Node);
22264 * console.log(parent.nodes[parent.nodes.length - 1]):
22265 * // { type: 'brace.close', val: '' };
22266 *
22267 * // no need to return a node, since the parent
22268 * // was already added to the AST
22269 * return;
22270 * }
22271 * });
22272 * ```
22273 * @param {Object} `node` Instance of [snapdragon-node][]
22274 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
22275 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
22276 * @return {Object} Returns the created closing node.
22277 * @api public
22278 */
22279
22280utils.addClose = function(node, Node, val, filter) {
22281 assert(utils.isNode(node), 'expected node to be an instance of Node');
22282 assert(isFunction(Node), 'expected Node to be a constructor function');
22283
22284 if (typeof val === 'function') {
22285 filter = val;
22286 val = '';
22287 }
22288
22289 if (typeof filter === 'function' && !filter(node)) return;
22290 var close = new Node({ type: node.type + '.close', val: val});
22291 var push = node.push || node.pushNode;
22292 if (typeof push === 'function') {
22293 push.call(node, close);
22294 } else {
22295 utils.pushNode(node, close);
22296 }
22297 return close;
22298};
22299
22300/**
22301 * Wraps the given `node` with `*.open` and `*.close` nodes.
22302 *
22303 * @param {Object} `node` Instance of [snapdragon-node][]
22304 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
22305 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
22306 * @return {Object} Returns the node
22307 * @api public
22308 */
22309
22310utils.wrapNodes = function(node, Node, filter) {
22311 assert(utils.isNode(node), 'expected node to be an instance of Node');
22312 assert(isFunction(Node), 'expected Node to be a constructor function');
22313
22314 utils.addOpen(node, Node, filter);
22315 utils.addClose(node, Node, filter);
22316 return node;
22317};
22318
22319/**
22320 * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent.
22321 *
22322 * ```js
22323 * var parent = new Node({type: 'foo'});
22324 * var node = new Node({type: 'bar'});
22325 * utils.pushNode(parent, node);
22326 * console.log(parent.nodes[0].type) // 'bar'
22327 * console.log(node.parent.type) // 'foo'
22328 * ```
22329 * @param {Object} `parent`
22330 * @param {Object} `node` Instance of [snapdragon-node][]
22331 * @return {Object} Returns the child node
22332 * @api public
22333 */
22334
22335utils.pushNode = function(parent, node) {
22336 assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
22337 assert(utils.isNode(node), 'expected node to be an instance of Node');
22338
22339 node.define('parent', parent);
22340 parent.nodes = parent.nodes || [];
22341 parent.nodes.push(node);
22342 return node;
22343};
22344
22345/**
22346 * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent.
22347 *
22348 * ```js
22349 * var parent = new Node({type: 'foo'});
22350 * var node = new Node({type: 'bar'});
22351 * utils.unshiftNode(parent, node);
22352 * console.log(parent.nodes[0].type) // 'bar'
22353 * console.log(node.parent.type) // 'foo'
22354 * ```
22355 * @param {Object} `parent`
22356 * @param {Object} `node` Instance of [snapdragon-node][]
22357 * @return {undefined}
22358 * @api public
22359 */
22360
22361utils.unshiftNode = function(parent, node) {
22362 assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
22363 assert(utils.isNode(node), 'expected node to be an instance of Node');
22364
22365 node.define('parent', parent);
22366 parent.nodes = parent.nodes || [];
22367 parent.nodes.unshift(node);
22368};
22369
22370/**
22371 * Pop the last `node` off of `parent.nodes`. The advantage of
22372 * using this method is that it checks for `node.nodes` and works
22373 * with any version of `snapdragon-node`.
22374 *
22375 * ```js
22376 * var parent = new Node({type: 'foo'});
22377 * utils.pushNode(parent, new Node({type: 'foo'}));
22378 * utils.pushNode(parent, new Node({type: 'bar'}));
22379 * utils.pushNode(parent, new Node({type: 'baz'}));
22380 * console.log(parent.nodes.length); //=> 3
22381 * utils.popNode(parent);
22382 * console.log(parent.nodes.length); //=> 2
22383 * ```
22384 * @param {Object} `parent`
22385 * @param {Object} `node` Instance of [snapdragon-node][]
22386 * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
22387 * @api public
22388 */
22389
22390utils.popNode = function(node) {
22391 assert(utils.isNode(node), 'expected node to be an instance of Node');
22392 if (typeof node.pop === 'function') {
22393 return node.pop();
22394 }
22395 return node.nodes && node.nodes.pop();
22396};
22397
22398/**
22399 * Shift the first `node` off of `parent.nodes`. The advantage of
22400 * using this method is that it checks for `node.nodes` and works
22401 * with any version of `snapdragon-node`.
22402 *
22403 * ```js
22404 * var parent = new Node({type: 'foo'});
22405 * utils.pushNode(parent, new Node({type: 'foo'}));
22406 * utils.pushNode(parent, new Node({type: 'bar'}));
22407 * utils.pushNode(parent, new Node({type: 'baz'}));
22408 * console.log(parent.nodes.length); //=> 3
22409 * utils.shiftNode(parent);
22410 * console.log(parent.nodes.length); //=> 2
22411 * ```
22412 * @param {Object} `parent`
22413 * @param {Object} `node` Instance of [snapdragon-node][]
22414 * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
22415 * @api public
22416 */
22417
22418utils.shiftNode = function(node) {
22419 assert(utils.isNode(node), 'expected node to be an instance of Node');
22420 if (typeof node.shift === 'function') {
22421 return node.shift();
22422 }
22423 return node.nodes && node.nodes.shift();
22424};
22425
22426/**
22427 * Remove the specified `node` from `parent.nodes`.
22428 *
22429 * ```js
22430 * var parent = new Node({type: 'abc'});
22431 * var foo = new Node({type: 'foo'});
22432 * utils.pushNode(parent, foo);
22433 * utils.pushNode(parent, new Node({type: 'bar'}));
22434 * utils.pushNode(parent, new Node({type: 'baz'}));
22435 * console.log(parent.nodes.length); //=> 3
22436 * utils.removeNode(parent, foo);
22437 * console.log(parent.nodes.length); //=> 2
22438 * ```
22439 * @param {Object} `parent`
22440 * @param {Object} `node` Instance of [snapdragon-node][]
22441 * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`.
22442 * @api public
22443 */
22444
22445utils.removeNode = function(parent, node) {
22446 assert(utils.isNode(parent), 'expected parent.node to be an instance of Node');
22447 assert(utils.isNode(node), 'expected node to be an instance of Node');
22448
22449 if (!parent.nodes) {
22450 return null;
22451 }
22452
22453 if (typeof parent.remove === 'function') {
22454 return parent.remove(node);
22455 }
22456
22457 var idx = parent.nodes.indexOf(node);
22458 if (idx !== -1) {
22459 return parent.nodes.splice(idx, 1);
22460 }
22461};
22462
22463/**
22464 * Returns true if `node.type` matches the given `type`. Throws a
22465 * `TypeError` if `node` is not an instance of `Node`.
22466 *
22467 * ```js
22468 * var Node = require('snapdragon-node');
22469 * var node = new Node({type: 'foo'});
22470 * console.log(utils.isType(node, 'foo')); // false
22471 * console.log(utils.isType(node, 'bar')); // true
22472 * ```
22473 * @param {Object} `node` Instance of [snapdragon-node][]
22474 * @param {String} `type`
22475 * @return {Boolean}
22476 * @api public
22477 */
22478
22479utils.isType = function(node, type) {
22480 assert(utils.isNode(node), 'expected node to be an instance of Node');
22481 switch (kindOf$2(type)) {
22482 case 'array':
22483 var types = type.slice();
22484 for (var i = 0; i < types.length; i++) {
22485 if (utils.isType(node, types[i])) {
22486 return true;
22487 }
22488 }
22489 return false;
22490 case 'string':
22491 return node.type === type;
22492 case 'regexp':
22493 return type.test(node.type);
22494 default: {
22495 throw new TypeError('expected "type" to be an array, string or regexp');
22496 }
22497 }
22498};
22499
22500/**
22501 * Returns true if the given `node` has the given `type` in `node.nodes`.
22502 * Throws a `TypeError` if `node` is not an instance of `Node`.
22503 *
22504 * ```js
22505 * var Node = require('snapdragon-node');
22506 * var node = new Node({
22507 * type: 'foo',
22508 * nodes: [
22509 * new Node({type: 'bar'}),
22510 * new Node({type: 'baz'})
22511 * ]
22512 * });
22513 * console.log(utils.hasType(node, 'xyz')); // false
22514 * console.log(utils.hasType(node, 'baz')); // true
22515 * ```
22516 * @param {Object} `node` Instance of [snapdragon-node][]
22517 * @param {String} `type`
22518 * @return {Boolean}
22519 * @api public
22520 */
22521
22522utils.hasType = function(node, type) {
22523 assert(utils.isNode(node), 'expected node to be an instance of Node');
22524 if (!Array.isArray(node.nodes)) return false;
22525 for (var i = 0; i < node.nodes.length; i++) {
22526 if (utils.isType(node.nodes[i], type)) {
22527 return true;
22528 }
22529 }
22530 return false;
22531};
22532
22533/**
22534 * Returns the first node from `node.nodes` of the given `type`
22535 *
22536 * ```js
22537 * var node = new Node({
22538 * type: 'foo',
22539 * nodes: [
22540 * new Node({type: 'text', val: 'abc'}),
22541 * new Node({type: 'text', val: 'xyz'})
22542 * ]
22543 * });
22544 *
22545 * var textNode = utils.firstOfType(node.nodes, 'text');
22546 * console.log(textNode.val);
22547 * //=> 'abc'
22548 * ```
22549 * @param {Array} `nodes`
22550 * @param {String} `type`
22551 * @return {Object|undefined} Returns the first matching node or undefined.
22552 * @api public
22553 */
22554
22555utils.firstOfType = function(nodes, type) {
22556 for (var i = 0; i < nodes.length; i++) {
22557 var node = nodes[i];
22558 if (utils.isType(node, type)) {
22559 return node;
22560 }
22561 }
22562};
22563
22564/**
22565 * Returns the node at the specified index, or the first node of the
22566 * given `type` from `node.nodes`.
22567 *
22568 * ```js
22569 * var node = new Node({
22570 * type: 'foo',
22571 * nodes: [
22572 * new Node({type: 'text', val: 'abc'}),
22573 * new Node({type: 'text', val: 'xyz'})
22574 * ]
22575 * });
22576 *
22577 * var nodeOne = utils.findNode(node.nodes, 'text');
22578 * console.log(nodeOne.val);
22579 * //=> 'abc'
22580 *
22581 * var nodeTwo = utils.findNode(node.nodes, 1);
22582 * console.log(nodeTwo.val);
22583 * //=> 'xyz'
22584 * ```
22585 *
22586 * @param {Array} `nodes`
22587 * @param {String|Number} `type` Node type or index.
22588 * @return {Object} Returns a node or undefined.
22589 * @api public
22590 */
22591
22592utils.findNode = function(nodes, type) {
22593 if (!Array.isArray(nodes)) {
22594 return null;
22595 }
22596 if (typeof type === 'number') {
22597 return nodes[type];
22598 }
22599 return utils.firstOfType(nodes, type);
22600};
22601
22602/**
22603 * Returns true if the given node is an "*.open" node.
22604 *
22605 * ```js
22606 * var Node = require('snapdragon-node');
22607 * var brace = new Node({type: 'brace'});
22608 * var open = new Node({type: 'brace.open'});
22609 * var close = new Node({type: 'brace.close'});
22610 *
22611 * console.log(utils.isOpen(brace)); // false
22612 * console.log(utils.isOpen(open)); // true
22613 * console.log(utils.isOpen(close)); // false
22614 * ```
22615 * @param {Object} `node` Instance of [snapdragon-node][]
22616 * @return {Boolean}
22617 * @api public
22618 */
22619
22620utils.isOpen = function(node) {
22621 assert(utils.isNode(node), 'expected node to be an instance of Node');
22622 return node.type.slice(-5) === '.open';
22623};
22624
22625/**
22626 * Returns true if the given node is a "*.close" node.
22627 *
22628 * ```js
22629 * var Node = require('snapdragon-node');
22630 * var brace = new Node({type: 'brace'});
22631 * var open = new Node({type: 'brace.open'});
22632 * var close = new Node({type: 'brace.close'});
22633 *
22634 * console.log(utils.isClose(brace)); // false
22635 * console.log(utils.isClose(open)); // false
22636 * console.log(utils.isClose(close)); // true
22637 * ```
22638 * @param {Object} `node` Instance of [snapdragon-node][]
22639 * @return {Boolean}
22640 * @api public
22641 */
22642
22643utils.isClose = function(node) {
22644 assert(utils.isNode(node), 'expected node to be an instance of Node');
22645 return node.type.slice(-6) === '.close';
22646};
22647
22648/**
22649 * Returns true if `node.nodes` **has** an `.open` node
22650 *
22651 * ```js
22652 * var Node = require('snapdragon-node');
22653 * var brace = new Node({
22654 * type: 'brace',
22655 * nodes: []
22656 * });
22657 *
22658 * var open = new Node({type: 'brace.open'});
22659 * console.log(utils.hasOpen(brace)); // false
22660 *
22661 * brace.pushNode(open);
22662 * console.log(utils.hasOpen(brace)); // true
22663 * ```
22664 * @param {Object} `node` Instance of [snapdragon-node][]
22665 * @return {Boolean}
22666 * @api public
22667 */
22668
22669utils.hasOpen = function(node) {
22670 assert(utils.isNode(node), 'expected node to be an instance of Node');
22671 var first = node.first || node.nodes ? node.nodes[0] : null;
22672 if (utils.isNode(first)) {
22673 return first.type === node.type + '.open';
22674 }
22675 return false;
22676};
22677
22678/**
22679 * Returns true if `node.nodes` **has** a `.close` node
22680 *
22681 * ```js
22682 * var Node = require('snapdragon-node');
22683 * var brace = new Node({
22684 * type: 'brace',
22685 * nodes: []
22686 * });
22687 *
22688 * var close = new Node({type: 'brace.close'});
22689 * console.log(utils.hasClose(brace)); // false
22690 *
22691 * brace.pushNode(close);
22692 * console.log(utils.hasClose(brace)); // true
22693 * ```
22694 * @param {Object} `node` Instance of [snapdragon-node][]
22695 * @return {Boolean}
22696 * @api public
22697 */
22698
22699utils.hasClose = function(node) {
22700 assert(utils.isNode(node), 'expected node to be an instance of Node');
22701 var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null;
22702 if (utils.isNode(last)) {
22703 return last.type === node.type + '.close';
22704 }
22705 return false;
22706};
22707
22708/**
22709 * Returns true if `node.nodes` has both `.open` and `.close` nodes
22710 *
22711 * ```js
22712 * var Node = require('snapdragon-node');
22713 * var brace = new Node({
22714 * type: 'brace',
22715 * nodes: []
22716 * });
22717 *
22718 * var open = new Node({type: 'brace.open'});
22719 * var close = new Node({type: 'brace.close'});
22720 * console.log(utils.hasOpen(brace)); // false
22721 * console.log(utils.hasClose(brace)); // false
22722 *
22723 * brace.pushNode(open);
22724 * brace.pushNode(close);
22725 * console.log(utils.hasOpen(brace)); // true
22726 * console.log(utils.hasClose(brace)); // true
22727 * ```
22728 * @param {Object} `node` Instance of [snapdragon-node][]
22729 * @return {Boolean}
22730 * @api public
22731 */
22732
22733utils.hasOpenAndClose = function(node) {
22734 return utils.hasOpen(node) && utils.hasClose(node);
22735};
22736
22737/**
22738 * Push the given `node` onto the `state.inside` array for the
22739 * given type. This array is used as a specialized "stack" for
22740 * only the given `node.type`.
22741 *
22742 * ```js
22743 * var state = { inside: {}};
22744 * var node = new Node({type: 'brace'});
22745 * utils.addType(state, node);
22746 * console.log(state.inside);
22747 * //=> { brace: [{type: 'brace'}] }
22748 * ```
22749 * @param {Object} `state` The `compiler.state` object or custom state object.
22750 * @param {Object} `node` Instance of [snapdragon-node][]
22751 * @return {Array} Returns the `state.inside` stack for the given type.
22752 * @api public
22753 */
22754
22755utils.addType = function(state, node) {
22756 assert(utils.isNode(node), 'expected node to be an instance of Node');
22757 assert(isObject(state), 'expected state to be an object');
22758
22759 var type = node.parent
22760 ? node.parent.type
22761 : node.type.replace(/\.open$/, '');
22762
22763 if (!state.hasOwnProperty('inside')) {
22764 state.inside = {};
22765 }
22766 if (!state.inside.hasOwnProperty(type)) {
22767 state.inside[type] = [];
22768 }
22769
22770 var arr = state.inside[type];
22771 arr.push(node);
22772 return arr;
22773};
22774
22775/**
22776 * Remove the given `node` from the `state.inside` array for the
22777 * given type. This array is used as a specialized "stack" for
22778 * only the given `node.type`.
22779 *
22780 * ```js
22781 * var state = { inside: {}};
22782 * var node = new Node({type: 'brace'});
22783 * utils.addType(state, node);
22784 * console.log(state.inside);
22785 * //=> { brace: [{type: 'brace'}] }
22786 * utils.removeType(state, node);
22787 * //=> { brace: [] }
22788 * ```
22789 * @param {Object} `state` The `compiler.state` object or custom state object.
22790 * @param {Object} `node` Instance of [snapdragon-node][]
22791 * @return {Array} Returns the `state.inside` stack for the given type.
22792 * @api public
22793 */
22794
22795utils.removeType = function(state, node) {
22796 assert(utils.isNode(node), 'expected node to be an instance of Node');
22797 assert(isObject(state), 'expected state to be an object');
22798
22799 var type = node.parent
22800 ? node.parent.type
22801 : node.type.replace(/\.close$/, '');
22802
22803 if (state.inside.hasOwnProperty(type)) {
22804 return state.inside[type].pop();
22805 }
22806};
22807
22808/**
22809 * Returns true if `node.val` is an empty string, or `node.nodes` does
22810 * not contain any non-empty text nodes.
22811 *
22812 * ```js
22813 * var node = new Node({type: 'text'});
22814 * utils.isEmpty(node); //=> true
22815 * node.val = 'foo';
22816 * utils.isEmpty(node); //=> false
22817 * ```
22818 * @param {Object} `node` Instance of [snapdragon-node][]
22819 * @param {Function} `fn`
22820 * @return {Boolean}
22821 * @api public
22822 */
22823
22824utils.isEmpty = function(node, fn) {
22825 assert(utils.isNode(node), 'expected node to be an instance of Node');
22826
22827 if (!Array.isArray(node.nodes)) {
22828 if (node.type !== 'text') {
22829 return true;
22830 }
22831 if (typeof fn === 'function') {
22832 return fn(node, node.parent);
22833 }
22834 return !utils.trim(node.val);
22835 }
22836
22837 for (var i = 0; i < node.nodes.length; i++) {
22838 var child = node.nodes[i];
22839 if (utils.isOpen(child) || utils.isClose(child)) {
22840 continue;
22841 }
22842 if (!utils.isEmpty(child, fn)) {
22843 return false;
22844 }
22845 }
22846
22847 return true;
22848};
22849
22850/**
22851 * Returns true if the `state.inside` stack for the given type exists
22852 * and has one or more nodes on it.
22853 *
22854 * ```js
22855 * var state = { inside: {}};
22856 * var node = new Node({type: 'brace'});
22857 * console.log(utils.isInsideType(state, 'brace')); //=> false
22858 * utils.addType(state, node);
22859 * console.log(utils.isInsideType(state, 'brace')); //=> true
22860 * utils.removeType(state, node);
22861 * console.log(utils.isInsideType(state, 'brace')); //=> false
22862 * ```
22863 * @param {Object} `state`
22864 * @param {String} `type`
22865 * @return {Boolean}
22866 * @api public
22867 */
22868
22869utils.isInsideType = function(state, type) {
22870 assert(isObject(state), 'expected state to be an object');
22871 assert(isString(type), 'expected type to be a string');
22872
22873 if (!state.hasOwnProperty('inside')) {
22874 return false;
22875 }
22876
22877 if (!state.inside.hasOwnProperty(type)) {
22878 return false;
22879 }
22880
22881 return state.inside[type].length > 0;
22882};
22883
22884/**
22885 * Returns true if `node` is either a child or grand-child of the given `type`,
22886 * or `state.inside[type]` is a non-empty array.
22887 *
22888 * ```js
22889 * var state = { inside: {}};
22890 * var node = new Node({type: 'brace'});
22891 * var open = new Node({type: 'brace.open'});
22892 * console.log(utils.isInside(state, open, 'brace')); //=> false
22893 * utils.pushNode(node, open);
22894 * console.log(utils.isInside(state, open, 'brace')); //=> true
22895 * ```
22896 * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object.
22897 * @param {Object} `node` Instance of [snapdragon-node][]
22898 * @param {String} `type` The `node.type` to check for.
22899 * @return {Boolean}
22900 * @api public
22901 */
22902
22903utils.isInside = function(state, node, type) {
22904 assert(utils.isNode(node), 'expected node to be an instance of Node');
22905 assert(isObject(state), 'expected state to be an object');
22906
22907 if (Array.isArray(type)) {
22908 for (var i = 0; i < type.length; i++) {
22909 if (utils.isInside(state, node, type[i])) {
22910 return true;
22911 }
22912 }
22913 return false;
22914 }
22915
22916 var parent = node.parent;
22917 if (typeof type === 'string') {
22918 return (parent && parent.type === type) || utils.isInsideType(state, type);
22919 }
22920
22921 if (kindOf$2(type) === 'regexp') {
22922 if (parent && parent.type && type.test(parent.type)) {
22923 return true;
22924 }
22925
22926 var keys = Object.keys(state.inside);
22927 var len = keys.length;
22928 var idx = -1;
22929 while (++idx < len) {
22930 var key = keys[idx];
22931 var val = state.inside[key];
22932
22933 if (Array.isArray(val) && val.length !== 0 && type.test(key)) {
22934 return true;
22935 }
22936 }
22937 }
22938 return false;
22939};
22940
22941/**
22942 * Get the last `n` element from the given `array`. Used for getting
22943 * a node from `node.nodes.`
22944 *
22945 * @param {Array} `array`
22946 * @param {Number} `n`
22947 * @return {undefined}
22948 * @api public
22949 */
22950
22951utils.last = function(arr, n) {
22952 return arr[arr.length - (n || 1)];
22953};
22954
22955/**
22956 * Cast the given `val` to an array.
22957 *
22958 * ```js
22959 * console.log(utils.arrayify(''));
22960 * //=> []
22961 * console.log(utils.arrayify('foo'));
22962 * //=> ['foo']
22963 * console.log(utils.arrayify(['foo']));
22964 * //=> ['foo']
22965 * ```
22966 * @param {any} `val`
22967 * @return {Array}
22968 * @api public
22969 */
22970
22971utils.arrayify = function(val) {
22972 if (typeof val === 'string' && val !== '') {
22973 return [val];
22974 }
22975 if (!Array.isArray(val)) {
22976 return [];
22977 }
22978 return val;
22979};
22980
22981/**
22982 * Convert the given `val` to a string by joining with `,`. Useful
22983 * for creating a cheerio/CSS/DOM-style selector from a list of strings.
22984 *
22985 * @param {any} `val`
22986 * @return {Array}
22987 * @api public
22988 */
22989
22990utils.stringify = function(val) {
22991 return utils.arrayify(val).join(',');
22992};
22993
22994/**
22995 * Ensure that the given value is a string and call `.trim()` on it,
22996 * or return an empty string.
22997 *
22998 * @param {String} `str`
22999 * @return {String}
23000 * @api public
23001 */
23002
23003utils.trim = function(str) {
23004 return typeof str === 'string' ? str.trim() : '';
23005};
23006
23007/**
23008 * Return true if val is an object
23009 */
23010
23011function isObject(val) {
23012 return kindOf$2(val) === 'object';
23013}
23014
23015/**
23016 * Return true if val is a string
23017 */
23018
23019function isString(val) {
23020 return typeof val === 'string';
23021}
23022
23023/**
23024 * Return true if val is a function
23025 */
23026
23027function isFunction(val) {
23028 return typeof val === 'function';
23029}
23030
23031/**
23032 * Return true if val is an array
23033 */
23034
23035function isArray(val) {
23036 return Array.isArray(val);
23037}
23038
23039/**
23040 * Shim to ensure the `.append` methods work with any version of snapdragon
23041 */
23042
23043function append(compiler, val, node) {
23044 if (typeof compiler.append !== 'function') {
23045 return compiler.emit(val, node);
23046 }
23047 return compiler.append(val, node);
23048}
23049
23050/**
23051 * Simplified assertion. Throws an error is `val` is falsey.
23052 */
23053
23054function assert(val, message) {
23055 if (!val) throw new Error(message);
23056}
23057});
23058
23059var snapdragonNode = createCommonjsModule(function (module, exports) {
23060
23061
23062
23063
23064var ownNames;
23065
23066/**
23067 * Create a new AST `Node` with the given `val` and `type`.
23068 *
23069 * ```js
23070 * var node = new Node('*', 'Star');
23071 * var node = new Node({type: 'star', val: '*'});
23072 * ```
23073 * @name Node
23074 * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node.
23075 * @param {String} `type` The node type to use when `val` is a string.
23076 * @return {Object} node instance
23077 * @api public
23078 */
23079
23080function Node(val, type, parent) {
23081 if (typeof type !== 'string') {
23082 parent = type;
23083 type = null;
23084 }
23085
23086 defineProperty$1(this, 'parent', parent);
23087 defineProperty$1(this, 'isNode', true);
23088 defineProperty$1(this, 'expect', null);
23089
23090 if (typeof type !== 'string' && isobject(val)) {
23091 lazyKeys();
23092 var keys = Object.keys(val);
23093 for (var i = 0; i < keys.length; i++) {
23094 var key = keys[i];
23095 if (ownNames.indexOf(key) === -1) {
23096 this[key] = val[key];
23097 }
23098 }
23099 } else {
23100 this.type = type;
23101 this.val = val;
23102 }
23103}
23104
23105/**
23106 * Returns true if the given value is a node.
23107 *
23108 * ```js
23109 * var Node = require('snapdragon-node');
23110 * var node = new Node({type: 'foo'});
23111 * console.log(Node.isNode(node)); //=> true
23112 * console.log(Node.isNode({})); //=> false
23113 * ```
23114 * @param {Object} `node`
23115 * @returns {Boolean}
23116 * @api public
23117 */
23118
23119Node.isNode = function(node) {
23120 return snapdragonUtil.isNode(node);
23121};
23122
23123/**
23124 * Define a non-enumberable property on the node instance.
23125 * Useful for adding properties that shouldn't be extended
23126 * or visible during debugging.
23127 *
23128 * ```js
23129 * var node = new Node();
23130 * node.define('foo', 'something non-enumerable');
23131 * ```
23132 * @param {String} `name`
23133 * @param {any} `val`
23134 * @return {Object} returns the node instance
23135 * @api public
23136 */
23137
23138Node.prototype.define = function(name, val) {
23139 defineProperty$1(this, name, val);
23140 return this;
23141};
23142
23143/**
23144 * Returns true if `node.val` is an empty string, or `node.nodes` does
23145 * not contain any non-empty text nodes.
23146 *
23147 * ```js
23148 * var node = new Node({type: 'text'});
23149 * node.isEmpty(); //=> true
23150 * node.val = 'foo';
23151 * node.isEmpty(); //=> false
23152 * ```
23153 * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes.
23154 * @return {Boolean}
23155 * @api public
23156 */
23157
23158Node.prototype.isEmpty = function(fn) {
23159 return snapdragonUtil.isEmpty(this, fn);
23160};
23161
23162/**
23163 * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and
23164 * set `foo` as `bar.parent`.
23165 *
23166 * ```js
23167 * var foo = new Node({type: 'foo'});
23168 * var bar = new Node({type: 'bar'});
23169 * foo.push(bar);
23170 * ```
23171 * @param {Object} `node`
23172 * @return {Number} Returns the length of `node.nodes`
23173 * @api public
23174 */
23175
23176Node.prototype.push = function(node) {
23177 assert(Node.isNode(node), 'expected node to be an instance of Node');
23178 defineProperty$1(node, 'parent', this);
23179
23180 this.nodes = this.nodes || [];
23181 return this.nodes.push(node);
23182};
23183
23184/**
23185 * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and
23186 * set `foo` as `bar.parent`.
23187 *
23188 * ```js
23189 * var foo = new Node({type: 'foo'});
23190 * var bar = new Node({type: 'bar'});
23191 * foo.unshift(bar);
23192 * ```
23193 * @param {Object} `node`
23194 * @return {Number} Returns the length of `node.nodes`
23195 * @api public
23196 */
23197
23198Node.prototype.unshift = function(node) {
23199 assert(Node.isNode(node), 'expected node to be an instance of Node');
23200 defineProperty$1(node, 'parent', this);
23201
23202 this.nodes = this.nodes || [];
23203 return this.nodes.unshift(node);
23204};
23205
23206/**
23207 * Pop a node from `node.nodes`.
23208 *
23209 * ```js
23210 * var node = new Node({type: 'foo'});
23211 * node.push(new Node({type: 'a'}));
23212 * node.push(new Node({type: 'b'}));
23213 * node.push(new Node({type: 'c'}));
23214 * node.push(new Node({type: 'd'}));
23215 * console.log(node.nodes.length);
23216 * //=> 4
23217 * node.pop();
23218 * console.log(node.nodes.length);
23219 * //=> 3
23220 * ```
23221 * @return {Number} Returns the popped `node`
23222 * @api public
23223 */
23224
23225Node.prototype.pop = function() {
23226 return this.nodes && this.nodes.pop();
23227};
23228
23229/**
23230 * Shift a node from `node.nodes`.
23231 *
23232 * ```js
23233 * var node = new Node({type: 'foo'});
23234 * node.push(new Node({type: 'a'}));
23235 * node.push(new Node({type: 'b'}));
23236 * node.push(new Node({type: 'c'}));
23237 * node.push(new Node({type: 'd'}));
23238 * console.log(node.nodes.length);
23239 * //=> 4
23240 * node.shift();
23241 * console.log(node.nodes.length);
23242 * //=> 3
23243 * ```
23244 * @return {Object} Returns the shifted `node`
23245 * @api public
23246 */
23247
23248Node.prototype.shift = function() {
23249 return this.nodes && this.nodes.shift();
23250};
23251
23252/**
23253 * Remove `node` from `node.nodes`.
23254 *
23255 * ```js
23256 * node.remove(childNode);
23257 * ```
23258 * @param {Object} `node`
23259 * @return {Object} Returns the removed node.
23260 * @api public
23261 */
23262
23263Node.prototype.remove = function(node) {
23264 assert(Node.isNode(node), 'expected node to be an instance of Node');
23265 this.nodes = this.nodes || [];
23266 var idx = node.index;
23267 if (idx !== -1) {
23268 node.index = -1;
23269 return this.nodes.splice(idx, 1);
23270 }
23271 return null;
23272};
23273
23274/**
23275 * Get the first child node from `node.nodes` that matches the given `type`.
23276 * If `type` is a number, the child node at that index is returned.
23277 *
23278 * ```js
23279 * var child = node.find(1); //<= index of the node to get
23280 * var child = node.find('foo'); //<= node.type of a child node
23281 * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type
23282 * var child = node.find(['foo', 'bar']); //<= array of node.type(s)
23283 * ```
23284 * @param {String} `type`
23285 * @return {Object} Returns a child node or undefined.
23286 * @api public
23287 */
23288
23289Node.prototype.find = function(type) {
23290 return snapdragonUtil.findNode(this.nodes, type);
23291};
23292
23293/**
23294 * Return true if the node is the given `type`.
23295 *
23296 * ```js
23297 * var node = new Node({type: 'bar'});
23298 * cosole.log(node.isType('foo')); // false
23299 * cosole.log(node.isType(/^(foo|bar)$/)); // true
23300 * cosole.log(node.isType(['foo', 'bar'])); // true
23301 * ```
23302 * @param {String} `type`
23303 * @return {Boolean}
23304 * @api public
23305 */
23306
23307Node.prototype.isType = function(type) {
23308 return snapdragonUtil.isType(this, type);
23309};
23310
23311/**
23312 * Return true if the `node.nodes` has the given `type`.
23313 *
23314 * ```js
23315 * var foo = new Node({type: 'foo'});
23316 * var bar = new Node({type: 'bar'});
23317 * foo.push(bar);
23318 *
23319 * cosole.log(foo.hasType('qux')); // false
23320 * cosole.log(foo.hasType(/^(qux|bar)$/)); // true
23321 * cosole.log(foo.hasType(['qux', 'bar'])); // true
23322 * ```
23323 * @param {String} `type`
23324 * @return {Boolean}
23325 * @api public
23326 */
23327
23328Node.prototype.hasType = function(type) {
23329 return snapdragonUtil.hasType(this, type);
23330};
23331
23332/**
23333 * Get the siblings array, or `null` if it doesn't exist.
23334 *
23335 * ```js
23336 * var foo = new Node({type: 'foo'});
23337 * var bar = new Node({type: 'bar'});
23338 * var baz = new Node({type: 'baz'});
23339 * foo.push(bar);
23340 * foo.push(baz);
23341 *
23342 * console.log(bar.siblings.length) // 2
23343 * console.log(baz.siblings.length) // 2
23344 * ```
23345 * @return {Array}
23346 * @api public
23347 */
23348
23349Object.defineProperty(Node.prototype, 'siblings', {
23350 set: function() {
23351 throw new Error('node.siblings is a getter and cannot be defined');
23352 },
23353 get: function() {
23354 return this.parent ? this.parent.nodes : null;
23355 }
23356});
23357
23358/**
23359 * Get the node's current index from `node.parent.nodes`.
23360 * This should always be correct, even when the parent adds nodes.
23361 *
23362 * ```js
23363 * var foo = new Node({type: 'foo'});
23364 * var bar = new Node({type: 'bar'});
23365 * var baz = new Node({type: 'baz'});
23366 * var qux = new Node({type: 'qux'});
23367 * foo.push(bar);
23368 * foo.push(baz);
23369 * foo.unshift(qux);
23370 *
23371 * console.log(bar.index) // 1
23372 * console.log(baz.index) // 2
23373 * console.log(qux.index) // 0
23374 * ```
23375 * @return {Number}
23376 * @api public
23377 */
23378
23379Object.defineProperty(Node.prototype, 'index', {
23380 set: function(index) {
23381 defineProperty$1(this, 'idx', index);
23382 },
23383 get: function() {
23384 if (!Array.isArray(this.siblings)) {
23385 return -1;
23386 }
23387 var tok = this.idx !== -1 ? this.siblings[this.idx] : null;
23388 if (tok !== this) {
23389 this.idx = this.siblings.indexOf(this);
23390 }
23391 return this.idx;
23392 }
23393});
23394
23395/**
23396 * Get the previous node from the siblings array or `null`.
23397 *
23398 * ```js
23399 * var foo = new Node({type: 'foo'});
23400 * var bar = new Node({type: 'bar'});
23401 * var baz = new Node({type: 'baz'});
23402 * foo.push(bar);
23403 * foo.push(baz);
23404 *
23405 * console.log(baz.prev.type) // 'bar'
23406 * ```
23407 * @return {Object}
23408 * @api public
23409 */
23410
23411Object.defineProperty(Node.prototype, 'prev', {
23412 set: function() {
23413 throw new Error('node.prev is a getter and cannot be defined');
23414 },
23415 get: function() {
23416 if (Array.isArray(this.siblings)) {
23417 return this.siblings[this.index - 1] || this.parent.prev;
23418 }
23419 return null;
23420 }
23421});
23422
23423/**
23424 * Get the siblings array, or `null` if it doesn't exist.
23425 *
23426 * ```js
23427 * var foo = new Node({type: 'foo'});
23428 * var bar = new Node({type: 'bar'});
23429 * var baz = new Node({type: 'baz'});
23430 * foo.push(bar);
23431 * foo.push(baz);
23432 *
23433 * console.log(bar.siblings.length) // 2
23434 * console.log(baz.siblings.length) // 2
23435 * ```
23436 * @return {Object}
23437 * @api public
23438 */
23439
23440Object.defineProperty(Node.prototype, 'next', {
23441 set: function() {
23442 throw new Error('node.next is a getter and cannot be defined');
23443 },
23444 get: function() {
23445 if (Array.isArray(this.siblings)) {
23446 return this.siblings[this.index + 1] || this.parent.next;
23447 }
23448 return null;
23449 }
23450});
23451
23452/**
23453 * Get the first node from `node.nodes`.
23454 *
23455 * ```js
23456 * var foo = new Node({type: 'foo'});
23457 * var bar = new Node({type: 'bar'});
23458 * var baz = new Node({type: 'baz'});
23459 * var qux = new Node({type: 'qux'});
23460 * foo.push(bar);
23461 * foo.push(baz);
23462 * foo.push(qux);
23463 *
23464 * console.log(foo.first.type) // 'bar'
23465 * ```
23466 * @return {Object} The first node, or undefiend
23467 * @api public
23468 */
23469
23470Object.defineProperty(Node.prototype, 'first', {
23471 get: function() {
23472 return this.nodes ? this.nodes[0] : null;
23473 }
23474});
23475
23476/**
23477 * Get the last node from `node.nodes`.
23478 *
23479 * ```js
23480 * var foo = new Node({type: 'foo'});
23481 * var bar = new Node({type: 'bar'});
23482 * var baz = new Node({type: 'baz'});
23483 * var qux = new Node({type: 'qux'});
23484 * foo.push(bar);
23485 * foo.push(baz);
23486 * foo.push(qux);
23487 *
23488 * console.log(foo.last.type) // 'qux'
23489 * ```
23490 * @return {Object} The last node, or undefiend
23491 * @api public
23492 */
23493
23494Object.defineProperty(Node.prototype, 'last', {
23495 get: function() {
23496 return this.nodes ? snapdragonUtil.last(this.nodes) : null;
23497 }
23498});
23499
23500/**
23501 * Get the last node from `node.nodes`.
23502 *
23503 * ```js
23504 * var foo = new Node({type: 'foo'});
23505 * var bar = new Node({type: 'bar'});
23506 * var baz = new Node({type: 'baz'});
23507 * var qux = new Node({type: 'qux'});
23508 * foo.push(bar);
23509 * foo.push(baz);
23510 * foo.push(qux);
23511 *
23512 * console.log(foo.last.type) // 'qux'
23513 * ```
23514 * @return {Object} The last node, or undefiend
23515 * @api public
23516 */
23517
23518Object.defineProperty(Node.prototype, 'scope', {
23519 get: function() {
23520 if (this.isScope !== true) {
23521 return this.parent ? this.parent.scope : this;
23522 }
23523 return this;
23524 }
23525});
23526
23527/**
23528 * Get own property names from Node prototype, but only the
23529 * first time `Node` is instantiated
23530 */
23531
23532function lazyKeys() {
23533 if (!ownNames) {
23534 ownNames = Object.getOwnPropertyNames(Node.prototype);
23535 }
23536}
23537
23538/**
23539 * Simplified assertion. Throws an error is `val` is falsey.
23540 */
23541
23542function assert(val, message) {
23543 if (!val) throw new Error(message);
23544}
23545
23546/**
23547 * Expose `Node`
23548 */
23549
23550exports = module.exports = Node;
23551});
23552
23553/**
23554 * Braces parsers
23555 */
23556
23557var parsers = function(braces, options) {
23558 braces.parser
23559 .set('bos', function() {
23560 if (!this.parsed) {
23561 this.ast = this.nodes[0] = new snapdragonNode(this.ast);
23562 }
23563 })
23564
23565 /**
23566 * Character parsers
23567 */
23568
23569 .set('escape', function() {
23570 var pos = this.position();
23571 var m = this.match(/^(?:\\(.)|\$\{)/);
23572 if (!m) return;
23573
23574 var prev = this.prev();
23575 var last = utils_1.last(prev.nodes);
23576
23577 var node = pos(new snapdragonNode({
23578 type: 'text',
23579 multiplier: 1,
23580 val: m[0]
23581 }));
23582
23583 if (node.val === '\\\\') {
23584 return node;
23585 }
23586
23587 if (node.val === '${') {
23588 var str = this.input;
23589 var idx = -1;
23590 var ch;
23591
23592 while ((ch = str[++idx])) {
23593 this.consume(1);
23594 node.val += ch;
23595 if (ch === '\\') {
23596 node.val += str[++idx];
23597 continue;
23598 }
23599 if (ch === '}') {
23600 break;
23601 }
23602 }
23603 }
23604
23605 if (this.options.unescape !== false) {
23606 node.val = node.val.replace(/\\([{}])/g, '$1');
23607 }
23608
23609 if (last.val === '"' && this.input.charAt(0) === '"') {
23610 last.val = node.val;
23611 this.consume(1);
23612 return;
23613 }
23614
23615 return concatNodes.call(this, pos, node, prev, options);
23616 })
23617
23618 /**
23619 * Brackets: "[...]" (basic, this is overridden by
23620 * other parsers in more advanced implementations)
23621 */
23622
23623 .set('bracket', function() {
23624 var isInside = this.isInside('brace');
23625 var pos = this.position();
23626 var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/);
23627 if (!m) return;
23628
23629 var prev = this.prev();
23630 var val = m[0];
23631 var negated = m[1] ? '^' : '';
23632 var inner = m[2] || '';
23633 var close = m[3] || '';
23634
23635 if (isInside && prev.type === 'brace') {
23636 prev.text = prev.text || '';
23637 prev.text += val;
23638 }
23639
23640 var esc = this.input.slice(0, 2);
23641 if (inner === '' && esc === '\\]') {
23642 inner += esc;
23643 this.consume(2);
23644
23645 var str = this.input;
23646 var idx = -1;
23647 var ch;
23648
23649 while ((ch = str[++idx])) {
23650 this.consume(1);
23651 if (ch === ']') {
23652 close = ch;
23653 break;
23654 }
23655 inner += ch;
23656 }
23657 }
23658
23659 return pos(new snapdragonNode({
23660 type: 'bracket',
23661 val: val,
23662 escaped: close !== ']',
23663 negated: negated,
23664 inner: inner,
23665 close: close
23666 }));
23667 })
23668
23669 /**
23670 * Empty braces (we capture these early to
23671 * speed up processing in the compiler)
23672 */
23673
23674 .set('multiplier', function() {
23675 var isInside = this.isInside('brace');
23676 var pos = this.position();
23677 var m = this.match(/^\{((?:,|\{,+\})+)\}/);
23678 if (!m) return;
23679
23680 this.multiplier = true;
23681 var prev = this.prev();
23682 var val = m[0];
23683
23684 if (isInside && prev.type === 'brace') {
23685 prev.text = prev.text || '';
23686 prev.text += val;
23687 }
23688
23689 var node = pos(new snapdragonNode({
23690 type: 'text',
23691 multiplier: 1,
23692 match: m,
23693 val: val
23694 }));
23695
23696 return concatNodes.call(this, pos, node, prev, options);
23697 })
23698
23699 /**
23700 * Open
23701 */
23702
23703 .set('brace.open', function() {
23704 var pos = this.position();
23705 var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/);
23706 if (!m) return;
23707
23708 var prev = this.prev();
23709 var last = utils_1.last(prev.nodes);
23710
23711 // if the last parsed character was an extglob character
23712 // we need to _not optimize_ the brace pattern because
23713 // it might be mistaken for an extglob by a downstream parser
23714 if (last && last.val && isExtglobChar(last.val.slice(-1))) {
23715 last.optimize = false;
23716 }
23717
23718 var open = pos(new snapdragonNode({
23719 type: 'brace.open',
23720 val: m[0]
23721 }));
23722
23723 var node = pos(new snapdragonNode({
23724 type: 'brace',
23725 nodes: []
23726 }));
23727
23728 node.push(open);
23729 prev.push(node);
23730 this.push('brace', node);
23731 })
23732
23733 /**
23734 * Close
23735 */
23736
23737 .set('brace.close', function() {
23738 var pos = this.position();
23739 var m = this.match(/^\}/);
23740 if (!m || !m[0]) return;
23741
23742 var brace = this.pop('brace');
23743 var node = pos(new snapdragonNode({
23744 type: 'brace.close',
23745 val: m[0]
23746 }));
23747
23748 if (!this.isType(brace, 'brace')) {
23749 if (this.options.strict) {
23750 throw new Error('missing opening "{"');
23751 }
23752 node.type = 'text';
23753 node.multiplier = 0;
23754 node.escaped = true;
23755 return node;
23756 }
23757
23758 var prev = this.prev();
23759 var last = utils_1.last(prev.nodes);
23760 if (last.text) {
23761 var lastNode = utils_1.last(last.nodes);
23762 if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) {
23763 var open = last.nodes[0];
23764 var text = last.nodes[1];
23765 if (open.type === 'brace.open' && text && text.type === 'text') {
23766 text.optimize = false;
23767 }
23768 }
23769 }
23770
23771 if (brace.nodes.length > 2) {
23772 var first = brace.nodes[1];
23773 if (first.type === 'text' && first.val === ',') {
23774 brace.nodes.splice(1, 1);
23775 brace.nodes.push(first);
23776 }
23777 }
23778
23779 brace.push(node);
23780 })
23781
23782 /**
23783 * Capture boundary characters
23784 */
23785
23786 .set('boundary', function() {
23787 var pos = this.position();
23788 var m = this.match(/^[$^](?!\{)/);
23789 if (!m) return;
23790 return pos(new snapdragonNode({
23791 type: 'text',
23792 val: m[0]
23793 }));
23794 })
23795
23796 /**
23797 * One or zero, non-comma characters wrapped in braces
23798 */
23799
23800 .set('nobrace', function() {
23801 var isInside = this.isInside('brace');
23802 var pos = this.position();
23803 var m = this.match(/^\{[^,]?\}/);
23804 if (!m) return;
23805
23806 var prev = this.prev();
23807 var val = m[0];
23808
23809 if (isInside && prev.type === 'brace') {
23810 prev.text = prev.text || '';
23811 prev.text += val;
23812 }
23813
23814 return pos(new snapdragonNode({
23815 type: 'text',
23816 multiplier: 0,
23817 val: val
23818 }));
23819 })
23820
23821 /**
23822 * Text
23823 */
23824
23825 .set('text', function() {
23826 var isInside = this.isInside('brace');
23827 var pos = this.position();
23828 var m = this.match(/^((?!\\)[^${}[\]])+/);
23829 if (!m) return;
23830
23831 var prev = this.prev();
23832 var val = m[0];
23833
23834 if (isInside && prev.type === 'brace') {
23835 prev.text = prev.text || '';
23836 prev.text += val;
23837 }
23838
23839 var node = pos(new snapdragonNode({
23840 type: 'text',
23841 multiplier: 1,
23842 val: val
23843 }));
23844
23845 return concatNodes.call(this, pos, node, prev, options);
23846 });
23847};
23848
23849/**
23850 * Returns true if the character is an extglob character.
23851 */
23852
23853function isExtglobChar(ch) {
23854 return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';
23855}
23856
23857/**
23858 * Combine text nodes, and calculate empty sets (`{,,}`)
23859 * @param {Function} `pos` Function to calculate node position
23860 * @param {Object} `node` AST node
23861 * @return {Object}
23862 */
23863
23864function concatNodes(pos, node, parent, options) {
23865 node.orig = node.val;
23866 var prev = this.prev();
23867 var last = utils_1.last(prev.nodes);
23868 var isEscaped = false;
23869
23870 if (node.val.length > 1) {
23871 var a = node.val.charAt(0);
23872 var b = node.val.slice(-1);
23873
23874 isEscaped = (a === '"' && b === '"')
23875 || (a === "'" && b === "'")
23876 || (a === '`' && b === '`');
23877 }
23878
23879 if (isEscaped && options.unescape !== false) {
23880 node.val = node.val.slice(1, node.val.length - 1);
23881 node.escaped = true;
23882 }
23883
23884 if (node.match) {
23885 var match = node.match[1];
23886 if (!match || match.indexOf('}') === -1) {
23887 match = node.match[0];
23888 }
23889
23890 // replace each set with a single ","
23891 var val = match.replace(/\{/g, ',').replace(/\}/g, '');
23892 node.multiplier *= val.length;
23893 node.val = '';
23894 }
23895
23896 var simpleText = last.type === 'text'
23897 && last.multiplier === 1
23898 && node.multiplier === 1
23899 && node.val;
23900
23901 if (simpleText) {
23902 last.val += node.val;
23903 return;
23904 }
23905
23906 prev.push(node);
23907}
23908
23909// accessor descriptor properties
23910var accessor$2 = {
23911 get: 'function',
23912 set: 'function',
23913 configurable: 'boolean',
23914 enumerable: 'boolean'
23915};
23916
23917function isAccessorDescriptor$2(obj, prop) {
23918 if (typeof prop === 'string') {
23919 var val = Object.getOwnPropertyDescriptor(obj, prop);
23920 return typeof val !== 'undefined';
23921 }
23922
23923 if (kindOf(obj) !== 'object') {
23924 return false;
23925 }
23926
23927 if (has$3(obj, 'value') || has$3(obj, 'writable')) {
23928 return false;
23929 }
23930
23931 if (!has$3(obj, 'get') || typeof obj.get !== 'function') {
23932 return false;
23933 }
23934
23935 // tldr: it's valid to have "set" be undefined
23936 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
23937 // was used to get the value, and only `get` was defined by the user
23938 if (has$3(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
23939 return false;
23940 }
23941
23942 for (var key in obj) {
23943 if (!accessor$2.hasOwnProperty(key)) {
23944 continue;
23945 }
23946
23947 if (kindOf(obj[key]) === accessor$2[key]) {
23948 continue;
23949 }
23950
23951 if (typeof obj[key] !== 'undefined') {
23952 return false;
23953 }
23954 }
23955 return true;
23956}
23957
23958function has$3(obj, key) {
23959 return {}.hasOwnProperty.call(obj, key);
23960}
23961
23962/**
23963 * Expose `isAccessorDescriptor`
23964 */
23965
23966var isAccessorDescriptor_1$2 = isAccessorDescriptor$2;
23967
23968var isDataDescriptor$2 = function isDataDescriptor(obj, prop) {
23969 // data descriptor properties
23970 var data = {
23971 configurable: 'boolean',
23972 enumerable: 'boolean',
23973 writable: 'boolean'
23974 };
23975
23976 if (kindOf(obj) !== 'object') {
23977 return false;
23978 }
23979
23980 if (typeof prop === 'string') {
23981 var val = Object.getOwnPropertyDescriptor(obj, prop);
23982 return typeof val !== 'undefined';
23983 }
23984
23985 if (!('value' in obj) && !('writable' in obj)) {
23986 return false;
23987 }
23988
23989 for (var key in obj) {
23990 if (key === 'value') continue;
23991
23992 if (!data.hasOwnProperty(key)) {
23993 continue;
23994 }
23995
23996 if (kindOf(obj[key]) === data[key]) {
23997 continue;
23998 }
23999
24000 if (typeof obj[key] !== 'undefined') {
24001 return false;
24002 }
24003 }
24004 return true;
24005};
24006
24007var isDescriptor$2 = function isDescriptor(obj, key) {
24008 if (kindOf(obj) !== 'object') {
24009 return false;
24010 }
24011 if ('get' in obj) {
24012 return isAccessorDescriptor_1$2(obj, key);
24013 }
24014 return isDataDescriptor$2(obj, key);
24015};
24016
24017var defineProperty$2 = function defineProperty(obj, prop, val) {
24018 if (typeof obj !== 'object' && typeof obj !== 'function') {
24019 throw new TypeError('expected an object or function.');
24020 }
24021
24022 if (typeof prop !== 'string') {
24023 throw new TypeError('expected `prop` to be a string.');
24024 }
24025
24026 if (isDescriptor$2(val) && ('set' in val || 'get' in val)) {
24027 return Object.defineProperty(obj, prop, val);
24028 }
24029
24030 return Object.defineProperty(obj, prop, {
24031 configurable: true,
24032 enumerable: false,
24033 writable: true,
24034 value: val
24035 });
24036};
24037
24038var componentEmitter = createCommonjsModule(function (module) {
24039/**
24040 * Expose `Emitter`.
24041 */
24042
24043{
24044 module.exports = Emitter;
24045}
24046
24047/**
24048 * Initialize a new `Emitter`.
24049 *
24050 * @api public
24051 */
24052
24053function Emitter(obj) {
24054 if (obj) return mixin(obj);
24055}
24056/**
24057 * Mixin the emitter properties.
24058 *
24059 * @param {Object} obj
24060 * @return {Object}
24061 * @api private
24062 */
24063
24064function mixin(obj) {
24065 for (var key in Emitter.prototype) {
24066 obj[key] = Emitter.prototype[key];
24067 }
24068 return obj;
24069}
24070
24071/**
24072 * Listen on the given `event` with `fn`.
24073 *
24074 * @param {String} event
24075 * @param {Function} fn
24076 * @return {Emitter}
24077 * @api public
24078 */
24079
24080Emitter.prototype.on =
24081Emitter.prototype.addEventListener = function(event, fn){
24082 this._callbacks = this._callbacks || {};
24083 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
24084 .push(fn);
24085 return this;
24086};
24087
24088/**
24089 * Adds an `event` listener that will be invoked a single
24090 * time then automatically removed.
24091 *
24092 * @param {String} event
24093 * @param {Function} fn
24094 * @return {Emitter}
24095 * @api public
24096 */
24097
24098Emitter.prototype.once = function(event, fn){
24099 function on() {
24100 this.off(event, on);
24101 fn.apply(this, arguments);
24102 }
24103
24104 on.fn = fn;
24105 this.on(event, on);
24106 return this;
24107};
24108
24109/**
24110 * Remove the given callback for `event` or all
24111 * registered callbacks.
24112 *
24113 * @param {String} event
24114 * @param {Function} fn
24115 * @return {Emitter}
24116 * @api public
24117 */
24118
24119Emitter.prototype.off =
24120Emitter.prototype.removeListener =
24121Emitter.prototype.removeAllListeners =
24122Emitter.prototype.removeEventListener = function(event, fn){
24123 this._callbacks = this._callbacks || {};
24124
24125 // all
24126 if (0 == arguments.length) {
24127 this._callbacks = {};
24128 return this;
24129 }
24130
24131 // specific event
24132 var callbacks = this._callbacks['$' + event];
24133 if (!callbacks) return this;
24134
24135 // remove all handlers
24136 if (1 == arguments.length) {
24137 delete this._callbacks['$' + event];
24138 return this;
24139 }
24140
24141 // remove specific handler
24142 var cb;
24143 for (var i = 0; i < callbacks.length; i++) {
24144 cb = callbacks[i];
24145 if (cb === fn || cb.fn === fn) {
24146 callbacks.splice(i, 1);
24147 break;
24148 }
24149 }
24150 return this;
24151};
24152
24153/**
24154 * Emit `event` with the given args.
24155 *
24156 * @param {String} event
24157 * @param {Mixed} ...
24158 * @return {Emitter}
24159 */
24160
24161Emitter.prototype.emit = function(event){
24162 this._callbacks = this._callbacks || {};
24163 var args = [].slice.call(arguments, 1)
24164 , callbacks = this._callbacks['$' + event];
24165
24166 if (callbacks) {
24167 callbacks = callbacks.slice(0);
24168 for (var i = 0, len = callbacks.length; i < len; ++i) {
24169 callbacks[i].apply(this, args);
24170 }
24171 }
24172
24173 return this;
24174};
24175
24176/**
24177 * Return array of callbacks for `event`.
24178 *
24179 * @param {String} event
24180 * @return {Array}
24181 * @api public
24182 */
24183
24184Emitter.prototype.listeners = function(event){
24185 this._callbacks = this._callbacks || {};
24186 return this._callbacks['$' + event] || [];
24187};
24188
24189/**
24190 * Check if this emitter has `event` handlers.
24191 *
24192 * @param {String} event
24193 * @return {Boolean}
24194 * @api public
24195 */
24196
24197Emitter.prototype.hasListeners = function(event){
24198 return !! this.listeners(event).length;
24199};
24200});
24201
24202var objectVisit = function visit(thisArg, method, target, val) {
24203 if (!isobject(thisArg) && typeof thisArg !== 'function') {
24204 throw new Error('object-visit expects `thisArg` to be an object.');
24205 }
24206
24207 if (typeof method !== 'string') {
24208 throw new Error('object-visit expects `method` name to be a string');
24209 }
24210
24211 if (typeof thisArg[method] !== 'function') {
24212 return thisArg;
24213 }
24214
24215 var args = [].slice.call(arguments, 3);
24216 target = target || {};
24217
24218 for (var key in target) {
24219 var arr = [key, target[key]].concat(args);
24220 thisArg[method].apply(thisArg, arr);
24221 }
24222 return thisArg;
24223};
24224
24225/**
24226 * Map `visit` over an array of objects.
24227 *
24228 * @param {Object} `collection` The context in which to invoke `method`
24229 * @param {String} `method` Name of the method to call on `collection`
24230 * @param {Object} `arr` Array of objects.
24231 */
24232
24233var mapVisit = function mapVisit(collection, method, val) {
24234 if (isObject$2(val)) {
24235 return objectVisit.apply(null, arguments);
24236 }
24237
24238 if (!Array.isArray(val)) {
24239 throw new TypeError('expected an array: ' + util$2.inspect(val));
24240 }
24241
24242 var args = [].slice.call(arguments, 3);
24243
24244 for (var i = 0; i < val.length; i++) {
24245 var ele = val[i];
24246 if (isObject$2(ele)) {
24247 objectVisit.apply(null, [collection, method, ele].concat(args));
24248 } else {
24249 collection[method].apply(collection, [ele].concat(args));
24250 }
24251 }
24252};
24253
24254function isObject$2(val) {
24255 return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object'));
24256}
24257
24258var collectionVisit = function(collection, method, val) {
24259 var result;
24260
24261 if (typeof val === 'string' && (method in collection)) {
24262 var args = [].slice.call(arguments, 2);
24263 result = collection[method].apply(collection, args);
24264 } else if (Array.isArray(val)) {
24265 result = mapVisit.apply(null, arguments);
24266 } else {
24267 result = objectVisit.apply(null, arguments);
24268 }
24269
24270 if (typeof result !== 'undefined') {
24271 return result;
24272 }
24273
24274 return collection;
24275};
24276
24277var toString$4 = Object.prototype.toString;
24278
24279/**
24280 * Get the native `typeof` a value.
24281 *
24282 * @param {*} `val`
24283 * @return {*} Native javascript type
24284 */
24285
24286var kindOf$3 = function kindOf(val) {
24287 // primitivies
24288 if (typeof val === 'undefined') {
24289 return 'undefined';
24290 }
24291 if (val === null) {
24292 return 'null';
24293 }
24294 if (val === true || val === false || val instanceof Boolean) {
24295 return 'boolean';
24296 }
24297 if (typeof val === 'string' || val instanceof String) {
24298 return 'string';
24299 }
24300 if (typeof val === 'number' || val instanceof Number) {
24301 return 'number';
24302 }
24303
24304 // functions
24305 if (typeof val === 'function' || val instanceof Function) {
24306 return 'function';
24307 }
24308
24309 // array
24310 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
24311 return 'array';
24312 }
24313
24314 // check for instances of RegExp and Date before calling `toString`
24315 if (val instanceof RegExp) {
24316 return 'regexp';
24317 }
24318 if (val instanceof Date) {
24319 return 'date';
24320 }
24321
24322 // other objects
24323 var type = toString$4.call(val);
24324
24325 if (type === '[object RegExp]') {
24326 return 'regexp';
24327 }
24328 if (type === '[object Date]') {
24329 return 'date';
24330 }
24331 if (type === '[object Arguments]') {
24332 return 'arguments';
24333 }
24334 if (type === '[object Error]') {
24335 return 'error';
24336 }
24337
24338 // buffer
24339 if (isBuffer_1(val)) {
24340 return 'buffer';
24341 }
24342
24343 // es6: Map, WeakMap, Set, WeakSet
24344 if (type === '[object Set]') {
24345 return 'set';
24346 }
24347 if (type === '[object WeakSet]') {
24348 return 'weakset';
24349 }
24350 if (type === '[object Map]') {
24351 return 'map';
24352 }
24353 if (type === '[object WeakMap]') {
24354 return 'weakmap';
24355 }
24356 if (type === '[object Symbol]') {
24357 return 'symbol';
24358 }
24359
24360 // typed arrays
24361 if (type === '[object Int8Array]') {
24362 return 'int8array';
24363 }
24364 if (type === '[object Uint8Array]') {
24365 return 'uint8array';
24366 }
24367 if (type === '[object Uint8ClampedArray]') {
24368 return 'uint8clampedarray';
24369 }
24370 if (type === '[object Int16Array]') {
24371 return 'int16array';
24372 }
24373 if (type === '[object Uint16Array]') {
24374 return 'uint16array';
24375 }
24376 if (type === '[object Int32Array]') {
24377 return 'int32array';
24378 }
24379 if (type === '[object Uint32Array]') {
24380 return 'uint32array';
24381 }
24382 if (type === '[object Float32Array]') {
24383 return 'float32array';
24384 }
24385 if (type === '[object Float64Array]') {
24386 return 'float64array';
24387 }
24388
24389 // must be a plain object
24390 return 'object';
24391};
24392
24393var toObjectPath = function toPath(args) {
24394 if (kindOf$3(args) !== 'arguments') {
24395 args = arguments;
24396 }
24397 return filter(args).join('.');
24398};
24399
24400function filter(arr) {
24401 var len = arr.length;
24402 var idx = -1;
24403 var res = [];
24404
24405 while (++idx < len) {
24406 var ele = arr[idx];
24407 if (kindOf$3(ele) === 'arguments' || Array.isArray(ele)) {
24408 res.push.apply(res, filter(ele));
24409 } else if (typeof ele === 'string') {
24410 res.push(ele);
24411 }
24412 }
24413 return res;
24414}
24415
24416var arrUnion = function union(init) {
24417 if (!Array.isArray(init)) {
24418 throw new TypeError('arr-union expects the first argument to be an array.');
24419 }
24420
24421 var len = arguments.length;
24422 var i = 0;
24423
24424 while (++i < len) {
24425 var arg = arguments[i];
24426 if (!arg) continue;
24427
24428 if (!Array.isArray(arg)) {
24429 arg = [arg];
24430 }
24431
24432 for (var j = 0; j < arg.length; j++) {
24433 var ele = arg[j];
24434
24435 if (init.indexOf(ele) >= 0) {
24436 continue;
24437 }
24438 init.push(ele);
24439 }
24440 }
24441 return init;
24442};
24443
24444/*!
24445 * get-value <https://github.com/jonschlinkert/get-value>
24446 *
24447 * Copyright (c) 2014-2015, Jon Schlinkert.
24448 * Licensed under the MIT License.
24449 */
24450
24451var getValue = function(obj, prop, a, b, c) {
24452 if (!isObject$3(obj) || !prop) {
24453 return obj;
24454 }
24455
24456 prop = toString$5(prop);
24457
24458 // allowing for multiple properties to be passed as
24459 // a string or array, but much faster (3-4x) than doing
24460 // `[].slice.call(arguments)`
24461 if (a) prop += '.' + toString$5(a);
24462 if (b) prop += '.' + toString$5(b);
24463 if (c) prop += '.' + toString$5(c);
24464
24465 if (prop in obj) {
24466 return obj[prop];
24467 }
24468
24469 var segs = prop.split('.');
24470 var len = segs.length;
24471 var i = -1;
24472
24473 while (obj && (++i < len)) {
24474 var key = segs[i];
24475 while (key[key.length - 1] === '\\') {
24476 key = key.slice(0, -1) + '.' + segs[++i];
24477 }
24478 obj = obj[key];
24479 }
24480 return obj;
24481};
24482
24483function isObject$3(val) {
24484 return val !== null && (typeof val === 'object' || typeof val === 'function');
24485}
24486
24487function toString$5(val) {
24488 if (!val) return '';
24489 if (Array.isArray(val)) {
24490 return val.join('.');
24491 }
24492 return val;
24493}
24494
24495var extendShallow$3 = function extend(o/*, objects*/) {
24496 if (!isExtendable$1(o)) { o = {}; }
24497
24498 var len = arguments.length;
24499 for (var i = 1; i < len; i++) {
24500 var obj = arguments[i];
24501
24502 if (isExtendable$1(obj)) {
24503 assign$3(o, obj);
24504 }
24505 }
24506 return o;
24507};
24508
24509function assign$3(a, b) {
24510 for (var key in b) {
24511 if (hasOwn$3(b, key)) {
24512 a[key] = b[key];
24513 }
24514 }
24515}
24516
24517/**
24518 * Returns true if the given `key` is an own property of `obj`.
24519 */
24520
24521function hasOwn$3(obj, key) {
24522 return Object.prototype.hasOwnProperty.call(obj, key);
24523}
24524
24525var setValue = function(obj, path, val) {
24526 if (!isExtendable$1(obj)) {
24527 return obj;
24528 }
24529
24530 if (Array.isArray(path)) {
24531 path = toObjectPath(path);
24532 }
24533
24534 if (typeof path !== 'string') {
24535 return obj;
24536 }
24537
24538 var segs = path.split('.');
24539 var len = segs.length, i = -1;
24540 var res = obj;
24541 var last;
24542
24543 while (++i < len) {
24544 var key = segs[i];
24545
24546 while (key[key.length - 1] === '\\') {
24547 key = key.slice(0, -1) + '.' + segs[++i];
24548 }
24549
24550 if (i === len - 1) {
24551 last = key;
24552 break;
24553 }
24554
24555 if (!isExtendable$1(obj[key])) {
24556 obj[key] = {};
24557 }
24558 obj = obj[key];
24559 }
24560
24561 if (obj.hasOwnProperty(last) && isExtendable$1(obj[last])) {
24562 if (isPlainObject(val)) {
24563 extendShallow$3(obj[last], val);
24564 } else {
24565 obj[last] = val;
24566 }
24567
24568 } else {
24569 obj[last] = val;
24570 }
24571 return res;
24572};
24573
24574var unionValue = function unionValue(obj, prop, value) {
24575 if (!isExtendable$1(obj)) {
24576 throw new TypeError('union-value expects the first argument to be an object.');
24577 }
24578
24579 if (typeof prop !== 'string') {
24580 throw new TypeError('union-value expects `prop` to be a string.');
24581 }
24582
24583 var arr = arrayify(getValue(obj, prop));
24584 setValue(obj, prop, arrUnion(arr, arrayify(value)));
24585 return obj;
24586};
24587
24588function arrayify(val) {
24589 if (val === null || typeof val === 'undefined') {
24590 return [];
24591 }
24592 if (Array.isArray(val)) {
24593 return val;
24594 }
24595 return [val];
24596}
24597
24598var toString$6 = {}.toString;
24599
24600var isarray = Array.isArray || function (arr) {
24601 return toString$6.call(arr) == '[object Array]';
24602};
24603
24604var isobject$1 = function isObject(val) {
24605 return val != null && typeof val === 'object' && isarray(val) === false;
24606};
24607
24608/*!
24609 * has-values <https://github.com/jonschlinkert/has-values>
24610 *
24611 * Copyright (c) 2014-2015, Jon Schlinkert.
24612 * Licensed under the MIT License.
24613 */
24614
24615var hasValues = function hasValue(o, noZero) {
24616 if (o === null || o === undefined) {
24617 return false;
24618 }
24619
24620 if (typeof o === 'boolean') {
24621 return true;
24622 }
24623
24624 if (typeof o === 'number') {
24625 if (o === 0 && noZero === true) {
24626 return false;
24627 }
24628 return true;
24629 }
24630
24631 if (o.length !== undefined) {
24632 return o.length !== 0;
24633 }
24634
24635 for (var key in o) {
24636 if (o.hasOwnProperty(key)) {
24637 return true;
24638 }
24639 }
24640 return false;
24641};
24642
24643var hasValue = function(obj, prop, noZero) {
24644 if (isobject$1(obj)) {
24645 return hasValues(getValue(obj, prop), noZero);
24646 }
24647 return hasValues(obj, prop);
24648};
24649
24650var unsetValue = function unset(obj, prop) {
24651 if (!isobject(obj)) {
24652 throw new TypeError('expected an object.');
24653 }
24654 if (obj.hasOwnProperty(prop)) {
24655 delete obj[prop];
24656 return true;
24657 }
24658
24659 if (hasValue(obj, prop)) {
24660 var segs = prop.split('.');
24661 var last = segs.pop();
24662 while (segs.length && segs[segs.length - 1].slice(-1) === '\\') {
24663 last = segs.pop().slice(0, -1) + '.' + last;
24664 }
24665 while (segs.length) obj = obj[prop = segs.shift()];
24666 return (delete obj[last]);
24667 }
24668 return true;
24669};
24670
24671var extendShallow$4 = function extend(o/*, objects*/) {
24672 if (!isExtendable$1(o)) { o = {}; }
24673
24674 var len = arguments.length;
24675 for (var i = 1; i < len; i++) {
24676 var obj = arguments[i];
24677
24678 if (isExtendable$1(obj)) {
24679 assign$4(o, obj);
24680 }
24681 }
24682 return o;
24683};
24684
24685function assign$4(a, b) {
24686 for (var key in b) {
24687 if (hasOwn$4(b, key)) {
24688 a[key] = b[key];
24689 }
24690 }
24691}
24692
24693/**
24694 * Returns true if the given `key` is an own property of `obj`.
24695 */
24696
24697function hasOwn$4(obj, key) {
24698 return Object.prototype.hasOwnProperty.call(obj, key);
24699}
24700
24701var setValue$1 = function(obj, prop, val) {
24702 if (!isExtendable$1(obj)) {
24703 return obj;
24704 }
24705
24706 if (Array.isArray(prop)) {
24707 prop = [].concat.apply([], prop).join('.');
24708 }
24709
24710 if (typeof prop !== 'string') {
24711 return obj;
24712 }
24713
24714 var keys = splitString(prop, {sep: '.', brackets: true});
24715 var len = keys.length;
24716 var idx = -1;
24717 var current = obj;
24718
24719 while (++idx < len) {
24720 var key = keys[idx];
24721 if (idx !== len - 1) {
24722 if (!isExtendable$1(current[key])) {
24723 current[key] = {};
24724 }
24725 current = current[key];
24726 continue;
24727 }
24728
24729 if (isPlainObject(current[key]) && isPlainObject(val)) {
24730 current[key] = extendShallow$4({}, current[key], val);
24731 } else {
24732 current[key] = val;
24733 }
24734 }
24735
24736 return obj;
24737};
24738
24739/**
24740 * Create a `Cache` constructor that when instantiated will
24741 * store values on the given `prop`.
24742 *
24743 * ```js
24744 * var Cache = require('cache-base').namespace('data');
24745 * var cache = new Cache();
24746 *
24747 * cache.set('foo', 'bar');
24748 * //=> {data: {foo: 'bar'}}
24749 * ```
24750 * @param {String} `prop` The property name to use for storing values.
24751 * @return {Function} Returns a custom `Cache` constructor
24752 * @api public
24753 */
24754
24755function namespace(prop) {
24756
24757 /**
24758 * Create a new `Cache`. Internally the `Cache` constructor is created using
24759 * the `namespace` function, with `cache` defined as the storage object.
24760 *
24761 * ```js
24762 * var app = new Cache();
24763 * ```
24764 * @param {Object} `cache` Optionally pass an object to initialize with.
24765 * @constructor
24766 * @api public
24767 */
24768
24769 function Cache(cache) {
24770 if (prop) {
24771 this[prop] = {};
24772 }
24773 if (cache) {
24774 this.set(cache);
24775 }
24776 }
24777
24778 /**
24779 * Inherit Emitter
24780 */
24781
24782 componentEmitter(Cache.prototype);
24783
24784 /**
24785 * Assign `value` to `key`. Also emits `set` with
24786 * the key and value.
24787 *
24788 * ```js
24789 * app.on('set', function(key, val) {
24790 * // do something when `set` is emitted
24791 * });
24792 *
24793 * app.set(key, value);
24794 *
24795 * // also takes an object or array
24796 * app.set({name: 'Halle'});
24797 * app.set([{foo: 'bar'}, {baz: 'quux'}]);
24798 * console.log(app);
24799 * //=> {name: 'Halle', foo: 'bar', baz: 'quux'}
24800 * ```
24801 *
24802 * @name .set
24803 * @emits `set` with `key` and `value` as arguments.
24804 * @param {String} `key`
24805 * @param {any} `value`
24806 * @return {Object} Returns the instance for chaining.
24807 * @api public
24808 */
24809
24810 Cache.prototype.set = function(key, val) {
24811 if (Array.isArray(key) && arguments.length === 2) {
24812 key = toObjectPath(key);
24813 }
24814 if (isobject(key) || Array.isArray(key)) {
24815 this.visit('set', key);
24816 } else {
24817 setValue$1(prop ? this[prop] : this, key, val);
24818 this.emit('set', key, val);
24819 }
24820 return this;
24821 };
24822
24823 /**
24824 * Union `array` to `key`. Also emits `set` with
24825 * the key and value.
24826 *
24827 * ```js
24828 * app.union('a.b', ['foo']);
24829 * app.union('a.b', ['bar']);
24830 * console.log(app.get('a'));
24831 * //=> {b: ['foo', 'bar']}
24832 * ```
24833 * @name .union
24834 * @param {String} `key`
24835 * @param {any} `value`
24836 * @return {Object} Returns the instance for chaining.
24837 * @api public
24838 */
24839
24840 Cache.prototype.union = function(key, val) {
24841 if (Array.isArray(key) && arguments.length === 2) {
24842 key = toObjectPath(key);
24843 }
24844 var ctx = prop ? this[prop] : this;
24845 unionValue(ctx, key, arrayify$1(val));
24846 this.emit('union', val);
24847 return this;
24848 };
24849
24850 /**
24851 * Return the value of `key`. Dot notation may be used
24852 * to get [nested property values][get-value].
24853 *
24854 * ```js
24855 * app.set('a.b.c', 'd');
24856 * app.get('a.b');
24857 * //=> {c: 'd'}
24858 *
24859 * app.get(['a', 'b']);
24860 * //=> {c: 'd'}
24861 * ```
24862 *
24863 * @name .get
24864 * @emits `get` with `key` and `value` as arguments.
24865 * @param {String} `key` The name of the property to get. Dot-notation may be used.
24866 * @return {any} Returns the value of `key`
24867 * @api public
24868 */
24869
24870 Cache.prototype.get = function(key) {
24871 key = toObjectPath(arguments);
24872
24873 var ctx = prop ? this[prop] : this;
24874 var val = getValue(ctx, key);
24875
24876 this.emit('get', key, val);
24877 return val;
24878 };
24879
24880 /**
24881 * Return true if app has a stored value for `key`,
24882 * false only if value is `undefined`.
24883 *
24884 * ```js
24885 * app.set('foo', 'bar');
24886 * app.has('foo');
24887 * //=> true
24888 * ```
24889 *
24890 * @name .has
24891 * @emits `has` with `key` and true or false as arguments.
24892 * @param {String} `key`
24893 * @return {Boolean}
24894 * @api public
24895 */
24896
24897 Cache.prototype.has = function(key) {
24898 key = toObjectPath(arguments);
24899
24900 var ctx = prop ? this[prop] : this;
24901 var val = getValue(ctx, key);
24902
24903 var has = typeof val !== 'undefined';
24904 this.emit('has', key, has);
24905 return has;
24906 };
24907
24908 /**
24909 * Delete one or more properties from the instance.
24910 *
24911 * ```js
24912 * app.del(); // delete all
24913 * // or
24914 * app.del('foo');
24915 * // or
24916 * app.del(['foo', 'bar']);
24917 * ```
24918 * @name .del
24919 * @emits `del` with the `key` as the only argument.
24920 * @param {String|Array} `key` Property name or array of property names.
24921 * @return {Object} Returns the instance for chaining.
24922 * @api public
24923 */
24924
24925 Cache.prototype.del = function(key) {
24926 if (Array.isArray(key)) {
24927 this.visit('del', key);
24928 } else {
24929 unsetValue(prop ? this[prop] : this, key);
24930 this.emit('del', key);
24931 }
24932 return this;
24933 };
24934
24935 /**
24936 * Reset the entire cache to an empty object.
24937 *
24938 * ```js
24939 * app.clear();
24940 * ```
24941 * @api public
24942 */
24943
24944 Cache.prototype.clear = function() {
24945 if (prop) {
24946 this[prop] = {};
24947 }
24948 };
24949
24950 /**
24951 * Visit `method` over the properties in the given object, or map
24952 * visit over the object-elements in an array.
24953 *
24954 * @name .visit
24955 * @param {String} `method` The name of the `base` method to call.
24956 * @param {Object|Array} `val` The object or array to iterate over.
24957 * @return {Object} Returns the instance for chaining.
24958 * @api public
24959 */
24960
24961 Cache.prototype.visit = function(method, val) {
24962 collectionVisit(this, method, val);
24963 return this;
24964 };
24965
24966 return Cache;
24967}
24968
24969/**
24970 * Cast val to an array
24971 */
24972
24973function arrayify$1(val) {
24974 return val ? (Array.isArray(val) ? val : [val]) : [];
24975}
24976
24977/**
24978 * Expose `Cache`
24979 */
24980
24981var cacheBase = namespace();
24982
24983/**
24984 * Expose `Cache.namespace`
24985 */
24986
24987var namespace_1 = namespace;
24988cacheBase.namespace = namespace_1;
24989
24990var isExtendable$2 = function isExtendable(val) {
24991 return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);
24992};
24993
24994/*!
24995 * for-in <https://github.com/jonschlinkert/for-in>
24996 *
24997 * Copyright (c) 2014-2017, Jon Schlinkert.
24998 * Released under the MIT License.
24999 */
25000
25001var forIn = function forIn(obj, fn, thisArg) {
25002 for (var key in obj) {
25003 if (fn.call(thisArg, obj[key], key, obj) === false) {
25004 break;
25005 }
25006 }
25007};
25008
25009function mixinDeep(target, objects) {
25010 var len = arguments.length, i = 0;
25011 while (++i < len) {
25012 var obj = arguments[i];
25013 if (isObject$4(obj)) {
25014 forIn(obj, copy, target);
25015 }
25016 }
25017 return target;
25018}
25019
25020/**
25021 * Copy properties from the source object to the
25022 * target object.
25023 *
25024 * @param {*} `val`
25025 * @param {String} `key`
25026 */
25027
25028function copy(val, key) {
25029 if (key === '__proto__') {
25030 return;
25031 }
25032
25033 var obj = this[key];
25034 if (isObject$4(val) && isObject$4(obj)) {
25035 mixinDeep(obj, val);
25036 } else {
25037 this[key] = val;
25038 }
25039}
25040
25041/**
25042 * Returns true if `val` is an object or function.
25043 *
25044 * @param {any} val
25045 * @return {Boolean}
25046 */
25047
25048function isObject$4(val) {
25049 return isExtendable$2(val) && !Array.isArray(val);
25050}
25051
25052/**
25053 * Expose `mixinDeep`
25054 */
25055
25056var mixinDeep_1 = mixinDeep;
25057
25058/*!
25059 * pascalcase <https://github.com/jonschlinkert/pascalcase>
25060 *
25061 * Copyright (c) 2015, Jon Schlinkert.
25062 * Licensed under the MIT License.
25063 */
25064
25065function pascalcase(str) {
25066 if (typeof str !== 'string') {
25067 throw new TypeError('expected a string.');
25068 }
25069 str = str.replace(/([A-Z])/g, ' $1');
25070 if (str.length === 1) { return str.toUpperCase(); }
25071 str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
25072 str = str.charAt(0).toUpperCase() + str.slice(1);
25073 return str.replace(/[\W_]+(\w|$)/g, function (_, ch) {
25074 return ch.toUpperCase();
25075 });
25076}
25077
25078var pascalcase_1 = pascalcase;
25079
25080var toString$7 = Object.prototype.toString;
25081
25082/**
25083 * Get the native `typeof` a value.
25084 *
25085 * @param {*} `val`
25086 * @return {*} Native javascript type
25087 */
25088
25089var kindOf$4 = function kindOf(val) {
25090 var type = typeof val;
25091
25092 // primitivies
25093 if (type === 'undefined') {
25094 return 'undefined';
25095 }
25096 if (val === null) {
25097 return 'null';
25098 }
25099 if (val === true || val === false || val instanceof Boolean) {
25100 return 'boolean';
25101 }
25102 if (type === 'string' || val instanceof String) {
25103 return 'string';
25104 }
25105 if (type === 'number' || val instanceof Number) {
25106 return 'number';
25107 }
25108
25109 // functions
25110 if (type === 'function' || val instanceof Function) {
25111 if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') {
25112 return 'generatorfunction';
25113 }
25114 return 'function';
25115 }
25116
25117 // array
25118 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25119 return 'array';
25120 }
25121
25122 // check for instances of RegExp and Date before calling `toString`
25123 if (val instanceof RegExp) {
25124 return 'regexp';
25125 }
25126 if (val instanceof Date) {
25127 return 'date';
25128 }
25129
25130 // other objects
25131 type = toString$7.call(val);
25132
25133 if (type === '[object RegExp]') {
25134 return 'regexp';
25135 }
25136 if (type === '[object Date]') {
25137 return 'date';
25138 }
25139 if (type === '[object Arguments]') {
25140 return 'arguments';
25141 }
25142 if (type === '[object Error]') {
25143 return 'error';
25144 }
25145 if (type === '[object Promise]') {
25146 return 'promise';
25147 }
25148
25149 // buffer
25150 if (isBuffer$2(val)) {
25151 return 'buffer';
25152 }
25153
25154 // es6: Map, WeakMap, Set, WeakSet
25155 if (type === '[object Set]') {
25156 return 'set';
25157 }
25158 if (type === '[object WeakSet]') {
25159 return 'weakset';
25160 }
25161 if (type === '[object Map]') {
25162 return 'map';
25163 }
25164 if (type === '[object WeakMap]') {
25165 return 'weakmap';
25166 }
25167 if (type === '[object Symbol]') {
25168 return 'symbol';
25169 }
25170
25171 if (type === '[object Map Iterator]') {
25172 return 'mapiterator';
25173 }
25174 if (type === '[object Set Iterator]') {
25175 return 'setiterator';
25176 }
25177 if (type === '[object String Iterator]') {
25178 return 'stringiterator';
25179 }
25180 if (type === '[object Array Iterator]') {
25181 return 'arrayiterator';
25182 }
25183
25184 // typed arrays
25185 if (type === '[object Int8Array]') {
25186 return 'int8array';
25187 }
25188 if (type === '[object Uint8Array]') {
25189 return 'uint8array';
25190 }
25191 if (type === '[object Uint8ClampedArray]') {
25192 return 'uint8clampedarray';
25193 }
25194 if (type === '[object Int16Array]') {
25195 return 'int16array';
25196 }
25197 if (type === '[object Uint16Array]') {
25198 return 'uint16array';
25199 }
25200 if (type === '[object Int32Array]') {
25201 return 'int32array';
25202 }
25203 if (type === '[object Uint32Array]') {
25204 return 'uint32array';
25205 }
25206 if (type === '[object Float32Array]') {
25207 return 'float32array';
25208 }
25209 if (type === '[object Float64Array]') {
25210 return 'float64array';
25211 }
25212
25213 // must be a plain object
25214 return 'object';
25215};
25216
25217/**
25218 * If you need to support Safari 5-7 (8-10 yr-old browser),
25219 * take a look at https://github.com/feross/is-buffer
25220 */
25221
25222function isBuffer$2(val) {
25223 return val.constructor
25224 && typeof val.constructor.isBuffer === 'function'
25225 && val.constructor.isBuffer(val);
25226}
25227
25228var toString$8 = Object.prototype.toString;
25229
25230/**
25231 * Get the native `typeof` a value.
25232 *
25233 * @param {*} `val`
25234 * @return {*} Native javascript type
25235 */
25236
25237var kindOf$5 = function kindOf(val) {
25238 // primitivies
25239 if (typeof val === 'undefined') {
25240 return 'undefined';
25241 }
25242 if (val === null) {
25243 return 'null';
25244 }
25245 if (val === true || val === false || val instanceof Boolean) {
25246 return 'boolean';
25247 }
25248 if (typeof val === 'string' || val instanceof String) {
25249 return 'string';
25250 }
25251 if (typeof val === 'number' || val instanceof Number) {
25252 return 'number';
25253 }
25254
25255 // functions
25256 if (typeof val === 'function' || val instanceof Function) {
25257 return 'function';
25258 }
25259
25260 // array
25261 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25262 return 'array';
25263 }
25264
25265 // check for instances of RegExp and Date before calling `toString`
25266 if (val instanceof RegExp) {
25267 return 'regexp';
25268 }
25269 if (val instanceof Date) {
25270 return 'date';
25271 }
25272
25273 // other objects
25274 var type = toString$8.call(val);
25275
25276 if (type === '[object RegExp]') {
25277 return 'regexp';
25278 }
25279 if (type === '[object Date]') {
25280 return 'date';
25281 }
25282 if (type === '[object Arguments]') {
25283 return 'arguments';
25284 }
25285 if (type === '[object Error]') {
25286 return 'error';
25287 }
25288
25289 // buffer
25290 if (isBuffer_1(val)) {
25291 return 'buffer';
25292 }
25293
25294 // es6: Map, WeakMap, Set, WeakSet
25295 if (type === '[object Set]') {
25296 return 'set';
25297 }
25298 if (type === '[object WeakSet]') {
25299 return 'weakset';
25300 }
25301 if (type === '[object Map]') {
25302 return 'map';
25303 }
25304 if (type === '[object WeakMap]') {
25305 return 'weakmap';
25306 }
25307 if (type === '[object Symbol]') {
25308 return 'symbol';
25309 }
25310
25311 // typed arrays
25312 if (type === '[object Int8Array]') {
25313 return 'int8array';
25314 }
25315 if (type === '[object Uint8Array]') {
25316 return 'uint8array';
25317 }
25318 if (type === '[object Uint8ClampedArray]') {
25319 return 'uint8clampedarray';
25320 }
25321 if (type === '[object Int16Array]') {
25322 return 'int16array';
25323 }
25324 if (type === '[object Uint16Array]') {
25325 return 'uint16array';
25326 }
25327 if (type === '[object Int32Array]') {
25328 return 'int32array';
25329 }
25330 if (type === '[object Uint32Array]') {
25331 return 'uint32array';
25332 }
25333 if (type === '[object Float32Array]') {
25334 return 'float32array';
25335 }
25336 if (type === '[object Float64Array]') {
25337 return 'float64array';
25338 }
25339
25340 // must be a plain object
25341 return 'object';
25342};
25343
25344// accessor descriptor properties
25345var accessor$3 = {
25346 get: 'function',
25347 set: 'function',
25348 configurable: 'boolean',
25349 enumerable: 'boolean'
25350};
25351
25352function isAccessorDescriptor$3(obj, prop) {
25353 if (typeof prop === 'string') {
25354 var val = Object.getOwnPropertyDescriptor(obj, prop);
25355 return typeof val !== 'undefined';
25356 }
25357
25358 if (kindOf$5(obj) !== 'object') {
25359 return false;
25360 }
25361
25362 if (has$4(obj, 'value') || has$4(obj, 'writable')) {
25363 return false;
25364 }
25365
25366 if (!has$4(obj, 'get') || typeof obj.get !== 'function') {
25367 return false;
25368 }
25369
25370 // tldr: it's valid to have "set" be undefined
25371 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
25372 // was used to get the value, and only `get` was defined by the user
25373 if (has$4(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
25374 return false;
25375 }
25376
25377 for (var key in obj) {
25378 if (!accessor$3.hasOwnProperty(key)) {
25379 continue;
25380 }
25381
25382 if (kindOf$5(obj[key]) === accessor$3[key]) {
25383 continue;
25384 }
25385
25386 if (typeof obj[key] !== 'undefined') {
25387 return false;
25388 }
25389 }
25390 return true;
25391}
25392
25393function has$4(obj, key) {
25394 return {}.hasOwnProperty.call(obj, key);
25395}
25396
25397/**
25398 * Expose `isAccessorDescriptor`
25399 */
25400
25401var isAccessorDescriptor_1$3 = isAccessorDescriptor$3;
25402
25403var toString$9 = Object.prototype.toString;
25404
25405/**
25406 * Get the native `typeof` a value.
25407 *
25408 * @param {*} `val`
25409 * @return {*} Native javascript type
25410 */
25411
25412var kindOf$6 = function kindOf(val) {
25413 // primitivies
25414 if (typeof val === 'undefined') {
25415 return 'undefined';
25416 }
25417 if (val === null) {
25418 return 'null';
25419 }
25420 if (val === true || val === false || val instanceof Boolean) {
25421 return 'boolean';
25422 }
25423 if (typeof val === 'string' || val instanceof String) {
25424 return 'string';
25425 }
25426 if (typeof val === 'number' || val instanceof Number) {
25427 return 'number';
25428 }
25429
25430 // functions
25431 if (typeof val === 'function' || val instanceof Function) {
25432 return 'function';
25433 }
25434
25435 // array
25436 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25437 return 'array';
25438 }
25439
25440 // check for instances of RegExp and Date before calling `toString`
25441 if (val instanceof RegExp) {
25442 return 'regexp';
25443 }
25444 if (val instanceof Date) {
25445 return 'date';
25446 }
25447
25448 // other objects
25449 var type = toString$9.call(val);
25450
25451 if (type === '[object RegExp]') {
25452 return 'regexp';
25453 }
25454 if (type === '[object Date]') {
25455 return 'date';
25456 }
25457 if (type === '[object Arguments]') {
25458 return 'arguments';
25459 }
25460 if (type === '[object Error]') {
25461 return 'error';
25462 }
25463
25464 // buffer
25465 if (isBuffer_1(val)) {
25466 return 'buffer';
25467 }
25468
25469 // es6: Map, WeakMap, Set, WeakSet
25470 if (type === '[object Set]') {
25471 return 'set';
25472 }
25473 if (type === '[object WeakSet]') {
25474 return 'weakset';
25475 }
25476 if (type === '[object Map]') {
25477 return 'map';
25478 }
25479 if (type === '[object WeakMap]') {
25480 return 'weakmap';
25481 }
25482 if (type === '[object Symbol]') {
25483 return 'symbol';
25484 }
25485
25486 // typed arrays
25487 if (type === '[object Int8Array]') {
25488 return 'int8array';
25489 }
25490 if (type === '[object Uint8Array]') {
25491 return 'uint8array';
25492 }
25493 if (type === '[object Uint8ClampedArray]') {
25494 return 'uint8clampedarray';
25495 }
25496 if (type === '[object Int16Array]') {
25497 return 'int16array';
25498 }
25499 if (type === '[object Uint16Array]') {
25500 return 'uint16array';
25501 }
25502 if (type === '[object Int32Array]') {
25503 return 'int32array';
25504 }
25505 if (type === '[object Uint32Array]') {
25506 return 'uint32array';
25507 }
25508 if (type === '[object Float32Array]') {
25509 return 'float32array';
25510 }
25511 if (type === '[object Float64Array]') {
25512 return 'float64array';
25513 }
25514
25515 // must be a plain object
25516 return 'object';
25517};
25518
25519// data descriptor properties
25520var data = {
25521 configurable: 'boolean',
25522 enumerable: 'boolean',
25523 writable: 'boolean'
25524};
25525
25526function isDataDescriptor$3(obj, prop) {
25527 if (kindOf$6(obj) !== 'object') {
25528 return false;
25529 }
25530
25531 if (typeof prop === 'string') {
25532 var val = Object.getOwnPropertyDescriptor(obj, prop);
25533 return typeof val !== 'undefined';
25534 }
25535
25536 if (!('value' in obj) && !('writable' in obj)) {
25537 return false;
25538 }
25539
25540 for (var key in obj) {
25541 if (key === 'value') continue;
25542
25543 if (!data.hasOwnProperty(key)) {
25544 continue;
25545 }
25546
25547 if (kindOf$6(obj[key]) === data[key]) {
25548 continue;
25549 }
25550
25551 if (typeof obj[key] !== 'undefined') {
25552 return false;
25553 }
25554 }
25555 return true;
25556}
25557
25558/**
25559 * Expose `isDataDescriptor`
25560 */
25561
25562var isDataDescriptor_1 = isDataDescriptor$3;
25563
25564var isDescriptor$3 = function isDescriptor(obj, key) {
25565 if (kindOf$4(obj) !== 'object') {
25566 return false;
25567 }
25568 if ('get' in obj) {
25569 return isAccessorDescriptor_1$3(obj, key);
25570 }
25571 return isDataDescriptor_1(obj, key);
25572};
25573
25574var defineProperty$3 = function defineProperty(obj, prop, val) {
25575 if (typeof obj !== 'object' && typeof obj !== 'function') {
25576 throw new TypeError('expected an object or function.');
25577 }
25578
25579 if (typeof prop !== 'string') {
25580 throw new TypeError('expected `prop` to be a string.');
25581 }
25582
25583 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
25584 return Object.defineProperty(obj, prop, val);
25585 }
25586
25587 return Object.defineProperty(obj, prop, {
25588 configurable: true,
25589 enumerable: false,
25590 writable: true,
25591 value: val
25592 });
25593};
25594
25595var toString$a = Object.prototype.toString;
25596
25597/**
25598 * Get the native `typeof` a value.
25599 *
25600 * @param {*} `val`
25601 * @return {*} Native javascript type
25602 */
25603
25604var kindOf$7 = function kindOf(val) {
25605 // primitivies
25606 if (typeof val === 'undefined') {
25607 return 'undefined';
25608 }
25609 if (val === null) {
25610 return 'null';
25611 }
25612 if (val === true || val === false || val instanceof Boolean) {
25613 return 'boolean';
25614 }
25615 if (typeof val === 'string' || val instanceof String) {
25616 return 'string';
25617 }
25618 if (typeof val === 'number' || val instanceof Number) {
25619 return 'number';
25620 }
25621
25622 // functions
25623 if (typeof val === 'function' || val instanceof Function) {
25624 return 'function';
25625 }
25626
25627 // array
25628 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25629 return 'array';
25630 }
25631
25632 // check for instances of RegExp and Date before calling `toString`
25633 if (val instanceof RegExp) {
25634 return 'regexp';
25635 }
25636 if (val instanceof Date) {
25637 return 'date';
25638 }
25639
25640 // other objects
25641 var type = toString$a.call(val);
25642
25643 if (type === '[object RegExp]') {
25644 return 'regexp';
25645 }
25646 if (type === '[object Date]') {
25647 return 'date';
25648 }
25649 if (type === '[object Arguments]') {
25650 return 'arguments';
25651 }
25652 if (type === '[object Error]') {
25653 return 'error';
25654 }
25655
25656 // buffer
25657 if (isBuffer_1(val)) {
25658 return 'buffer';
25659 }
25660
25661 // es6: Map, WeakMap, Set, WeakSet
25662 if (type === '[object Set]') {
25663 return 'set';
25664 }
25665 if (type === '[object WeakSet]') {
25666 return 'weakset';
25667 }
25668 if (type === '[object Map]') {
25669 return 'map';
25670 }
25671 if (type === '[object WeakMap]') {
25672 return 'weakmap';
25673 }
25674 if (type === '[object Symbol]') {
25675 return 'symbol';
25676 }
25677
25678 // typed arrays
25679 if (type === '[object Int8Array]') {
25680 return 'int8array';
25681 }
25682 if (type === '[object Uint8Array]') {
25683 return 'uint8array';
25684 }
25685 if (type === '[object Uint8ClampedArray]') {
25686 return 'uint8clampedarray';
25687 }
25688 if (type === '[object Int16Array]') {
25689 return 'int16array';
25690 }
25691 if (type === '[object Uint16Array]') {
25692 return 'uint16array';
25693 }
25694 if (type === '[object Int32Array]') {
25695 return 'int32array';
25696 }
25697 if (type === '[object Uint32Array]') {
25698 return 'uint32array';
25699 }
25700 if (type === '[object Float32Array]') {
25701 return 'float32array';
25702 }
25703 if (type === '[object Float64Array]') {
25704 return 'float64array';
25705 }
25706
25707 // must be a plain object
25708 return 'object';
25709};
25710
25711/*!
25712 * copy-descriptor <https://github.com/jonschlinkert/copy-descriptor>
25713 *
25714 * Copyright (c) 2015, Jon Schlinkert.
25715 * Licensed under the MIT License.
25716 */
25717
25718/**
25719 * Copy a descriptor from one object to another.
25720 *
25721 * ```js
25722 * function App() {
25723 * this.cache = {};
25724 * }
25725 * App.prototype.set = function(key, val) {
25726 * this.cache[key] = val;
25727 * return this;
25728 * };
25729 * Object.defineProperty(App.prototype, 'count', {
25730 * get: function() {
25731 * return Object.keys(this.cache).length;
25732 * }
25733 * });
25734 *
25735 * copy(App.prototype, 'count', 'len');
25736 *
25737 * // create an instance
25738 * var app = new App();
25739 *
25740 * app.set('a', true);
25741 * app.set('b', true);
25742 * app.set('c', true);
25743 *
25744 * console.log(app.count);
25745 * //=> 3
25746 * console.log(app.len);
25747 * //=> 3
25748 * ```
25749 * @name copy
25750 * @param {Object} `receiver` The target object
25751 * @param {Object} `provider` The provider object
25752 * @param {String} `from` The key to copy on provider.
25753 * @param {String} `to` Optionally specify a new key name to use.
25754 * @return {Object}
25755 * @api public
25756 */
25757
25758var copyDescriptor = function copyDescriptor(receiver, provider, from, to) {
25759 if (!isObject$5(provider) && typeof provider !== 'function') {
25760 to = from;
25761 from = provider;
25762 provider = receiver;
25763 }
25764 if (!isObject$5(receiver) && typeof receiver !== 'function') {
25765 throw new TypeError('expected the first argument to be an object');
25766 }
25767 if (!isObject$5(provider) && typeof provider !== 'function') {
25768 throw new TypeError('expected provider to be an object');
25769 }
25770
25771 if (typeof to !== 'string') {
25772 to = from;
25773 }
25774 if (typeof from !== 'string') {
25775 throw new TypeError('expected key to be a string');
25776 }
25777
25778 if (!(from in provider)) {
25779 throw new Error('property "' + from + '" does not exist');
25780 }
25781
25782 var val = Object.getOwnPropertyDescriptor(provider, from);
25783 if (val) Object.defineProperty(receiver, to, val);
25784};
25785
25786function isObject$5(val) {
25787 return {}.toString.call(val) === '[object Object]';
25788}
25789
25790var defineProperty$4 = function defineProperty(obj, prop, val) {
25791 if (typeof obj !== 'object' && typeof obj !== 'function') {
25792 throw new TypeError('expected an object or function.');
25793 }
25794
25795 if (typeof prop !== 'string') {
25796 throw new TypeError('expected `prop` to be a string.');
25797 }
25798
25799 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
25800 return Object.defineProperty(obj, prop, val);
25801 }
25802
25803 return Object.defineProperty(obj, prop, {
25804 configurable: true,
25805 enumerable: false,
25806 writable: true,
25807 value: val
25808 });
25809};
25810
25811/**
25812 * Copy static properties, prototype properties, and descriptors from one object to another.
25813 *
25814 * ```js
25815 * function App() {}
25816 * var proto = App.prototype;
25817 * App.prototype.set = function() {};
25818 * App.prototype.get = function() {};
25819 *
25820 * var obj = {};
25821 * copy(obj, proto);
25822 * ```
25823 * @param {Object} `receiver`
25824 * @param {Object} `provider`
25825 * @param {String|Array} `omit` One or more properties to omit
25826 * @return {Object}
25827 * @api public
25828 */
25829
25830function copy$1(receiver, provider, omit) {
25831 if (!isObject$6(receiver)) {
25832 throw new TypeError('expected receiving object to be an object.');
25833 }
25834 if (!isObject$6(provider)) {
25835 throw new TypeError('expected providing object to be an object.');
25836 }
25837
25838 var props = nativeKeys(provider);
25839 var keys = Object.keys(provider);
25840 var len = props.length;
25841 omit = arrayify$2(omit);
25842
25843 while (len--) {
25844 var key = props[len];
25845
25846 if (has$5(keys, key)) {
25847 defineProperty$4(receiver, key, provider[key]);
25848 } else if (!(key in receiver) && !has$5(omit, key)) {
25849 copyDescriptor(receiver, provider, key);
25850 }
25851 }
25852}
25853/**
25854 * Return true if the given value is an object or function
25855 */
25856
25857function isObject$6(val) {
25858 return kindOf$7(val) === 'object' || typeof val === 'function';
25859}
25860
25861/**
25862 * Returns true if an array has any of the given elements, or an
25863 * object has any of the give keys.
25864 *
25865 * ```js
25866 * has(['a', 'b', 'c'], 'c');
25867 * //=> true
25868 *
25869 * has(['a', 'b', 'c'], ['c', 'z']);
25870 * //=> true
25871 *
25872 * has({a: 'b', c: 'd'}, ['c', 'z']);
25873 * //=> true
25874 * ```
25875 * @param {Object} `obj`
25876 * @param {String|Array} `val`
25877 * @return {Boolean}
25878 */
25879
25880function has$5(obj, val) {
25881 val = arrayify$2(val);
25882 var len = val.length;
25883
25884 if (isObject$6(obj)) {
25885 for (var key in obj) {
25886 if (val.indexOf(key) > -1) {
25887 return true;
25888 }
25889 }
25890
25891 var keys = nativeKeys(obj);
25892 return has$5(keys, val);
25893 }
25894
25895 if (Array.isArray(obj)) {
25896 var arr = obj;
25897 while (len--) {
25898 if (arr.indexOf(val[len]) > -1) {
25899 return true;
25900 }
25901 }
25902 return false;
25903 }
25904
25905 throw new TypeError('expected an array or object.');
25906}
25907
25908/**
25909 * Cast the given value to an array.
25910 *
25911 * ```js
25912 * arrayify('foo');
25913 * //=> ['foo']
25914 *
25915 * arrayify(['foo']);
25916 * //=> ['foo']
25917 * ```
25918 *
25919 * @param {String|Array} `val`
25920 * @return {Array}
25921 */
25922
25923function arrayify$2(val) {
25924 return val ? (Array.isArray(val) ? val : [val]) : [];
25925}
25926
25927/**
25928 * Returns true if a value has a `contructor`
25929 *
25930 * ```js
25931 * hasConstructor({});
25932 * //=> true
25933 *
25934 * hasConstructor(Object.create(null));
25935 * //=> false
25936 * ```
25937 * @param {Object} `value`
25938 * @return {Boolean}
25939 */
25940
25941function hasConstructor(val) {
25942 return isObject$6(val) && typeof val.constructor !== 'undefined';
25943}
25944
25945/**
25946 * Get the native `ownPropertyNames` from the constructor of the
25947 * given `object`. An empty array is returned if the object does
25948 * not have a constructor.
25949 *
25950 * ```js
25951 * nativeKeys({a: 'b', b: 'c', c: 'd'})
25952 * //=> ['a', 'b', 'c']
25953 *
25954 * nativeKeys(function(){})
25955 * //=> ['length', 'caller']
25956 * ```
25957 *
25958 * @param {Object} `obj` Object that has a `constructor`.
25959 * @return {Array} Array of keys.
25960 */
25961
25962function nativeKeys(val) {
25963 if (!hasConstructor(val)) return [];
25964 return Object.getOwnPropertyNames(val);
25965}
25966
25967/**
25968 * Expose `copy`
25969 */
25970
25971var objectCopy = copy$1;
25972
25973/**
25974 * Expose `copy.has` for tests
25975 */
25976
25977var has_1 = has$5;
25978objectCopy.has = has_1;
25979
25980var defineProperty$5 = function defineProperty(obj, prop, val) {
25981 if (typeof obj !== 'object' && typeof obj !== 'function') {
25982 throw new TypeError('expected an object or function.');
25983 }
25984
25985 if (typeof prop !== 'string') {
25986 throw new TypeError('expected `prop` to be a string.');
25987 }
25988
25989 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
25990 return Object.defineProperty(obj, prop, val);
25991 }
25992
25993 return Object.defineProperty(obj, prop, {
25994 configurable: true,
25995 enumerable: false,
25996 writable: true,
25997 value: val
25998 });
25999};
26000
26001/**
26002 * Returns a function for extending the static properties,
26003 * prototype properties, and descriptors from the `Parent`
26004 * constructor onto `Child` constructors.
26005 *
26006 * ```js
26007 * var extend = require('static-extend');
26008 * Parent.extend = extend(Parent);
26009 *
26010 * // optionally pass a custom merge function as the second arg
26011 * Parent.extend = extend(Parent, function(Child) {
26012 * Child.prototype.mixin = function(key, val) {
26013 * Child.prototype[key] = val;
26014 * };
26015 * });
26016 *
26017 * // extend "child" constructors
26018 * Parent.extend(Child);
26019 *
26020 * // optionally define prototype methods as the second arg
26021 * Parent.extend(Child, {
26022 * foo: function() {},
26023 * bar: function() {}
26024 * });
26025 * ```
26026 * @param {Function} `Parent` Parent ctor
26027 * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype.
26028 * @param {Function} `Child` Child ctor
26029 * @param {Object} `proto` Optionally pass additional prototype properties to inherit.
26030 * @return {Object}
26031 * @api public
26032 */
26033
26034function extend(Parent, extendFn) {
26035 if (typeof Parent !== 'function') {
26036 throw new TypeError('expected Parent to be a function.');
26037 }
26038
26039 return function(Ctor, proto) {
26040 if (typeof Ctor !== 'function') {
26041 throw new TypeError('expected Ctor to be a function.');
26042 }
26043
26044 util$2.inherits(Ctor, Parent);
26045 objectCopy(Ctor, Parent);
26046
26047 // proto can be null or a plain object
26048 if (typeof proto === 'object') {
26049 var obj = Object.create(proto);
26050
26051 for (var k in obj) {
26052 Ctor.prototype[k] = obj[k];
26053 }
26054 }
26055
26056 // keep a reference to the parent prototype
26057 defineProperty$5(Ctor.prototype, '_parent_', {
26058 configurable: true,
26059 set: function() {},
26060 get: function() {
26061 return Parent.prototype;
26062 }
26063 });
26064
26065 if (typeof extendFn === 'function') {
26066 extendFn(Ctor, Parent);
26067 }
26068
26069 Ctor.extend = extend(Ctor, extendFn);
26070 };
26071}
26072/**
26073 * Expose `extend`
26074 */
26075
26076var staticExtend = extend;
26077
26078var classUtils = createCommonjsModule(function (module) {
26079
26080
26081
26082
26083
26084
26085
26086/**
26087 * Expose class utils
26088 */
26089
26090var cu = module.exports;
26091
26092/**
26093 * Expose class utils: `cu`
26094 */
26095
26096cu.isObject = function isObject(val) {
26097 return isobject(val) || typeof val === 'function';
26098};
26099
26100/**
26101 * Returns true if an array has any of the given elements, or an
26102 * object has any of the give keys.
26103 *
26104 * ```js
26105 * cu.has(['a', 'b', 'c'], 'c');
26106 * //=> true
26107 *
26108 * cu.has(['a', 'b', 'c'], ['c', 'z']);
26109 * //=> true
26110 *
26111 * cu.has({a: 'b', c: 'd'}, ['c', 'z']);
26112 * //=> true
26113 * ```
26114 * @param {Object} `obj`
26115 * @param {String|Array} `val`
26116 * @return {Boolean}
26117 * @api public
26118 */
26119
26120cu.has = function has(obj, val) {
26121 val = cu.arrayify(val);
26122 var len = val.length;
26123
26124 if (cu.isObject(obj)) {
26125 for (var key in obj) {
26126 if (val.indexOf(key) > -1) {
26127 return true;
26128 }
26129 }
26130
26131 var keys = cu.nativeKeys(obj);
26132 return cu.has(keys, val);
26133 }
26134
26135 if (Array.isArray(obj)) {
26136 var arr = obj;
26137 while (len--) {
26138 if (arr.indexOf(val[len]) > -1) {
26139 return true;
26140 }
26141 }
26142 return false;
26143 }
26144
26145 throw new TypeError('expected an array or object.');
26146};
26147
26148/**
26149 * Returns true if an array or object has all of the given values.
26150 *
26151 * ```js
26152 * cu.hasAll(['a', 'b', 'c'], 'c');
26153 * //=> true
26154 *
26155 * cu.hasAll(['a', 'b', 'c'], ['c', 'z']);
26156 * //=> false
26157 *
26158 * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']);
26159 * //=> false
26160 * ```
26161 * @param {Object|Array} `val`
26162 * @param {String|Array} `values`
26163 * @return {Boolean}
26164 * @api public
26165 */
26166
26167cu.hasAll = function hasAll(val, values) {
26168 values = cu.arrayify(values);
26169 var len = values.length;
26170 while (len--) {
26171 if (!cu.has(val, values[len])) {
26172 return false;
26173 }
26174 }
26175 return true;
26176};
26177
26178/**
26179 * Cast the given value to an array.
26180 *
26181 * ```js
26182 * cu.arrayify('foo');
26183 * //=> ['foo']
26184 *
26185 * cu.arrayify(['foo']);
26186 * //=> ['foo']
26187 * ```
26188 *
26189 * @param {String|Array} `val`
26190 * @return {Array}
26191 * @api public
26192 */
26193
26194cu.arrayify = function arrayify(val) {
26195 return val ? (Array.isArray(val) ? val : [val]) : [];
26196};
26197
26198/**
26199 * Noop
26200 */
26201
26202cu.noop = function noop() {
26203 return;
26204};
26205
26206/**
26207 * Returns the first argument passed to the function.
26208 */
26209
26210cu.identity = function identity(val) {
26211 return val;
26212};
26213
26214/**
26215 * Returns true if a value has a `contructor`
26216 *
26217 * ```js
26218 * cu.hasConstructor({});
26219 * //=> true
26220 *
26221 * cu.hasConstructor(Object.create(null));
26222 * //=> false
26223 * ```
26224 * @param {Object} `value`
26225 * @return {Boolean}
26226 * @api public
26227 */
26228
26229cu.hasConstructor = function hasConstructor(val) {
26230 return cu.isObject(val) && typeof val.constructor !== 'undefined';
26231};
26232
26233/**
26234 * Get the native `ownPropertyNames` from the constructor of the
26235 * given `object`. An empty array is returned if the object does
26236 * not have a constructor.
26237 *
26238 * ```js
26239 * cu.nativeKeys({a: 'b', b: 'c', c: 'd'})
26240 * //=> ['a', 'b', 'c']
26241 *
26242 * cu.nativeKeys(function(){})
26243 * //=> ['length', 'caller']
26244 * ```
26245 *
26246 * @param {Object} `obj` Object that has a `constructor`.
26247 * @return {Array} Array of keys.
26248 * @api public
26249 */
26250
26251cu.nativeKeys = function nativeKeys(val) {
26252 if (!cu.hasConstructor(val)) return [];
26253 var keys = Object.getOwnPropertyNames(val);
26254 if ('caller' in val) keys.push('caller');
26255 return keys;
26256};
26257
26258/**
26259 * Returns property descriptor `key` if it's an "own" property
26260 * of the given object.
26261 *
26262 * ```js
26263 * function App() {}
26264 * Object.defineProperty(App.prototype, 'count', {
26265 * get: function() {
26266 * return Object.keys(this).length;
26267 * }
26268 * });
26269 * cu.getDescriptor(App.prototype, 'count');
26270 * // returns:
26271 * // {
26272 * // get: [Function],
26273 * // set: undefined,
26274 * // enumerable: false,
26275 * // configurable: false
26276 * // }
26277 * ```
26278 *
26279 * @param {Object} `obj`
26280 * @param {String} `key`
26281 * @return {Object} Returns descriptor `key`
26282 * @api public
26283 */
26284
26285cu.getDescriptor = function getDescriptor(obj, key) {
26286 if (!cu.isObject(obj)) {
26287 throw new TypeError('expected an object.');
26288 }
26289 if (typeof key !== 'string') {
26290 throw new TypeError('expected key to be a string.');
26291 }
26292 return Object.getOwnPropertyDescriptor(obj, key);
26293};
26294
26295/**
26296 * Copy a descriptor from one object to another.
26297 *
26298 * ```js
26299 * function App() {}
26300 * Object.defineProperty(App.prototype, 'count', {
26301 * get: function() {
26302 * return Object.keys(this).length;
26303 * }
26304 * });
26305 * var obj = {};
26306 * cu.copyDescriptor(obj, App.prototype, 'count');
26307 * ```
26308 * @param {Object} `receiver`
26309 * @param {Object} `provider`
26310 * @param {String} `name`
26311 * @return {Object}
26312 * @api public
26313 */
26314
26315cu.copyDescriptor = function copyDescriptor(receiver, provider, name) {
26316 if (!cu.isObject(receiver)) {
26317 throw new TypeError('expected receiving object to be an object.');
26318 }
26319 if (!cu.isObject(provider)) {
26320 throw new TypeError('expected providing object to be an object.');
26321 }
26322 if (typeof name !== 'string') {
26323 throw new TypeError('expected name to be a string.');
26324 }
26325
26326 var val = cu.getDescriptor(provider, name);
26327 if (val) Object.defineProperty(receiver, name, val);
26328};
26329
26330/**
26331 * Copy static properties, prototype properties, and descriptors
26332 * from one object to another.
26333 *
26334 * @param {Object} `receiver`
26335 * @param {Object} `provider`
26336 * @param {String|Array} `omit` One or more properties to omit
26337 * @return {Object}
26338 * @api public
26339 */
26340
26341cu.copy = function copy(receiver, provider, omit) {
26342 if (!cu.isObject(receiver)) {
26343 throw new TypeError('expected receiving object to be an object.');
26344 }
26345 if (!cu.isObject(provider)) {
26346 throw new TypeError('expected providing object to be an object.');
26347 }
26348 var props = Object.getOwnPropertyNames(provider);
26349 var keys = Object.keys(provider);
26350 var len = props.length,
26351 key;
26352 omit = cu.arrayify(omit);
26353
26354 while (len--) {
26355 key = props[len];
26356
26357 if (cu.has(keys, key)) {
26358 defineProperty$3(receiver, key, provider[key]);
26359 } else if (!(key in receiver) && !cu.has(omit, key)) {
26360 cu.copyDescriptor(receiver, provider, key);
26361 }
26362 }
26363};
26364
26365/**
26366 * Inherit the static properties, prototype properties, and descriptors
26367 * from of an object.
26368 *
26369 * @param {Object} `receiver`
26370 * @param {Object} `provider`
26371 * @param {String|Array} `omit` One or more properties to omit
26372 * @return {Object}
26373 * @api public
26374 */
26375
26376cu.inherit = function inherit(receiver, provider, omit) {
26377 if (!cu.isObject(receiver)) {
26378 throw new TypeError('expected receiving object to be an object.');
26379 }
26380 if (!cu.isObject(provider)) {
26381 throw new TypeError('expected providing object to be an object.');
26382 }
26383
26384 var keys = [];
26385 for (var key in provider) {
26386 keys.push(key);
26387 receiver[key] = provider[key];
26388 }
26389
26390 keys = keys.concat(cu.arrayify(omit));
26391
26392 var a = provider.prototype || provider;
26393 var b = receiver.prototype || receiver;
26394 cu.copy(b, a, keys);
26395};
26396
26397/**
26398 * Returns a function for extending the static properties,
26399 * prototype properties, and descriptors from the `Parent`
26400 * constructor onto `Child` constructors.
26401 *
26402 * ```js
26403 * var extend = cu.extend(Parent);
26404 * Parent.extend(Child);
26405 *
26406 * // optional methods
26407 * Parent.extend(Child, {
26408 * foo: function() {},
26409 * bar: function() {}
26410 * });
26411 * ```
26412 * @param {Function} `Parent` Parent ctor
26413 * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype.
26414 * @param {Function} `Child` Child ctor
26415 * @param {Object} `proto` Optionally pass additional prototype properties to inherit.
26416 * @return {Object}
26417 * @api public
26418 */
26419
26420cu.extend = function() {
26421 // keep it lazy, instead of assigning to `cu.extend`
26422 return staticExtend.apply(null, arguments);
26423};
26424
26425/**
26426 * Bubble up events emitted from static methods on the Parent ctor.
26427 *
26428 * @param {Object} `Parent`
26429 * @param {Array} `events` Event names to bubble up
26430 * @api public
26431 */
26432
26433cu.bubble = function(Parent, events) {
26434 events = events || [];
26435 Parent.bubble = function(Child, arr) {
26436 if (Array.isArray(arr)) {
26437 events = arrUnion([], events, arr);
26438 }
26439 var len = events.length;
26440 var idx = -1;
26441 while (++idx < len) {
26442 var name = events[idx];
26443 Parent.on(name, Child.emit.bind(Child, name));
26444 }
26445 cu.bubble(Child, events);
26446 };
26447};
26448});
26449
26450/**
26451 * Optionally define a custom `cache` namespace to use.
26452 */
26453
26454function namespace$1(name) {
26455 var Cache = name ? cacheBase.namespace(name) : cacheBase;
26456 var fns = [];
26457
26458 /**
26459 * Create an instance of `Base` with the given `config` and `options`.
26460 *
26461 * ```js
26462 * // initialize with `config` and `options`
26463 * var app = new Base({isApp: true}, {abc: true});
26464 * app.set('foo', 'bar');
26465 *
26466 * // values defined with the given `config` object will be on the root of the instance
26467 * console.log(app.baz); //=> undefined
26468 * console.log(app.foo); //=> 'bar'
26469 * // or use `.get`
26470 * console.log(app.get('isApp')); //=> true
26471 * console.log(app.get('foo')); //=> 'bar'
26472 *
26473 * // values defined with the given `options` object will be on `app.options
26474 * console.log(app.options.abc); //=> true
26475 * ```
26476 *
26477 * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation.
26478 * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object.
26479 * @api public
26480 */
26481
26482 function Base(config, options) {
26483 if (!(this instanceof Base)) {
26484 return new Base(config, options);
26485 }
26486 Cache.call(this, config);
26487 this.is('base');
26488 this.initBase(config, options);
26489 }
26490
26491 /**
26492 * Inherit cache-base
26493 */
26494
26495 util$2.inherits(Base, Cache);
26496
26497 /**
26498 * Add static emitter methods
26499 */
26500
26501 componentEmitter(Base);
26502
26503 /**
26504 * Initialize `Base` defaults with the given `config` object
26505 */
26506
26507 Base.prototype.initBase = function(config, options) {
26508 this.options = mixinDeep_1({}, this.options, options);
26509 this.cache = this.cache || {};
26510 this.define('registered', {});
26511 if (name) this[name] = {};
26512
26513 // make `app._callbacks` non-enumerable
26514 this.define('_callbacks', this._callbacks);
26515 if (isobject(config)) {
26516 this.visit('set', config);
26517 }
26518 Base.run(this, 'use', fns);
26519 };
26520
26521 /**
26522 * Set the given `name` on `app._name` and `app.is*` properties. Used for doing
26523 * lookups in plugins.
26524 *
26525 * ```js
26526 * app.is('foo');
26527 * console.log(app._name);
26528 * //=> 'foo'
26529 * console.log(app.isFoo);
26530 * //=> true
26531 * app.is('bar');
26532 * console.log(app.isFoo);
26533 * //=> true
26534 * console.log(app.isBar);
26535 * //=> true
26536 * console.log(app._name);
26537 * //=> 'bar'
26538 * ```
26539 * @name .is
26540 * @param {String} `name`
26541 * @return {Boolean}
26542 * @api public
26543 */
26544
26545 Base.prototype.is = function(name) {
26546 if (typeof name !== 'string') {
26547 throw new TypeError('expected name to be a string');
26548 }
26549 this.define('is' + pascalcase_1(name), true);
26550 this.define('_name', name);
26551 this.define('_appname', name);
26552 return this;
26553 };
26554
26555 /**
26556 * Returns true if a plugin has already been registered on an instance.
26557 *
26558 * Plugin implementors are encouraged to use this first thing in a plugin
26559 * to prevent the plugin from being called more than once on the same
26560 * instance.
26561 *
26562 * ```js
26563 * var base = new Base();
26564 * base.use(function(app) {
26565 * if (app.isRegistered('myPlugin')) return;
26566 * // do stuff to `app`
26567 * });
26568 *
26569 * // to also record the plugin as being registered
26570 * base.use(function(app) {
26571 * if (app.isRegistered('myPlugin', true)) return;
26572 * // do stuff to `app`
26573 * });
26574 * ```
26575 * @name .isRegistered
26576 * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once.
26577 * @param {String} `name` The plugin name.
26578 * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument.
26579 * @return {Boolean} Returns true if a plugin is already registered.
26580 * @api public
26581 */
26582
26583 Base.prototype.isRegistered = function(name, register) {
26584 if (this.registered.hasOwnProperty(name)) {
26585 return true;
26586 }
26587 if (register !== false) {
26588 this.registered[name] = true;
26589 this.emit('plugin', name);
26590 }
26591 return false;
26592 };
26593
26594 /**
26595 * Define a plugin function to be called immediately upon init. Plugins are chainable
26596 * and expose the following arguments to the plugin function:
26597 *
26598 * - `app`: the current instance of `Base`
26599 * - `base`: the [first ancestor instance](#base) of `Base`
26600 *
26601 * ```js
26602 * var app = new Base()
26603 * .use(foo)
26604 * .use(bar)
26605 * .use(baz)
26606 * ```
26607 * @name .use
26608 * @param {Function} `fn` plugin function to call
26609 * @return {Object} Returns the item instance for chaining.
26610 * @api public
26611 */
26612
26613 Base.prototype.use = function(fn) {
26614 fn.call(this, this);
26615 return this;
26616 };
26617
26618 /**
26619 * The `.define` method is used for adding non-enumerable property on the instance.
26620 * Dot-notation is **not supported** with `define`.
26621 *
26622 * ```js
26623 * // arbitrary `render` function using lodash `template`
26624 * app.define('render', function(str, locals) {
26625 * return _.template(str)(locals);
26626 * });
26627 * ```
26628 * @name .define
26629 * @param {String} `key` The name of the property to define.
26630 * @param {any} `value`
26631 * @return {Object} Returns the instance for chaining.
26632 * @api public
26633 */
26634
26635 Base.prototype.define = function(key, val) {
26636 if (isobject(key)) {
26637 return this.visit('define', key);
26638 }
26639 defineProperty$2(this, key, val);
26640 return this;
26641 };
26642
26643 /**
26644 * Mix property `key` onto the Base prototype. If base is inherited using
26645 * `Base.extend` this method will be overridden by a new `mixin` method that will
26646 * only add properties to the prototype of the inheriting application.
26647 *
26648 * ```js
26649 * app.mixin('foo', function() {
26650 * // do stuff
26651 * });
26652 * ```
26653 * @name .mixin
26654 * @param {String} `key`
26655 * @param {Object|Array} `val`
26656 * @return {Object} Returns the `base` instance for chaining.
26657 * @api public
26658 */
26659
26660 Base.prototype.mixin = function(key, val) {
26661 Base.prototype[key] = val;
26662 return this;
26663 };
26664
26665 /**
26666 * Non-enumberable mixin array, used by the static [Base.mixin]() method.
26667 */
26668
26669 Base.prototype.mixins = Base.prototype.mixins || [];
26670
26671 /**
26672 * Getter/setter used when creating nested instances of `Base`, for storing a reference
26673 * to the first ancestor instance. This works by setting an instance of `Base` on the `parent`
26674 * property of a "child" instance. The `base` property defaults to the current instance if
26675 * no `parent` property is defined.
26676 *
26677 * ```js
26678 * // create an instance of `Base`, this is our first ("base") instance
26679 * var first = new Base();
26680 * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later
26681 *
26682 * // create another instance
26683 * var second = new Base();
26684 * // create a reference to the first instance (`first`)
26685 * second.parent = first;
26686 *
26687 * // create another instance
26688 * var third = new Base();
26689 * // create a reference to the previous instance (`second`)
26690 * // repeat this pattern every time a "child" instance is created
26691 * third.parent = second;
26692 *
26693 * // we can always access the first instance using the `base` property
26694 * console.log(first.base.foo);
26695 * //=> 'bar'
26696 * console.log(second.base.foo);
26697 * //=> 'bar'
26698 * console.log(third.base.foo);
26699 * //=> 'bar'
26700 * // and now you know how to get to third base ;)
26701 * ```
26702 * @name .base
26703 * @api public
26704 */
26705
26706 Object.defineProperty(Base.prototype, 'base', {
26707 configurable: true,
26708 get: function() {
26709 return this.parent ? this.parent.base : this;
26710 }
26711 });
26712
26713 /**
26714 * Static method for adding global plugin functions that will
26715 * be added to an instance when created.
26716 *
26717 * ```js
26718 * Base.use(function(app) {
26719 * app.foo = 'bar';
26720 * });
26721 * var app = new Base();
26722 * console.log(app.foo);
26723 * //=> 'bar'
26724 * ```
26725 * @name #use
26726 * @param {Function} `fn` Plugin function to use on each instance.
26727 * @return {Object} Returns the `Base` constructor for chaining
26728 * @api public
26729 */
26730
26731 defineProperty$2(Base, 'use', function(fn) {
26732 fns.push(fn);
26733 return Base;
26734 });
26735
26736 /**
26737 * Run an array of functions by passing each function
26738 * to a method on the given object specified by the given property.
26739 *
26740 * @param {Object} `obj` Object containing method to use.
26741 * @param {String} `prop` Name of the method on the object to use.
26742 * @param {Array} `arr` Array of functions to pass to the method.
26743 */
26744
26745 defineProperty$2(Base, 'run', function(obj, prop, arr) {
26746 var len = arr.length, i = 0;
26747 while (len--) {
26748 obj[prop](arr[i++]);
26749 }
26750 return Base;
26751 });
26752
26753 /**
26754 * Static method for inheriting the prototype and static methods of the `Base` class.
26755 * This method greatly simplifies the process of creating inheritance-based applications.
26756 * See [static-extend][] for more details.
26757 *
26758 * ```js
26759 * var extend = cu.extend(Parent);
26760 * Parent.extend(Child);
26761 *
26762 * // optional methods
26763 * Parent.extend(Child, {
26764 * foo: function() {},
26765 * bar: function() {}
26766 * });
26767 * ```
26768 * @name #extend
26769 * @param {Function} `Ctor` constructor to extend
26770 * @param {Object} `methods` Optional prototype properties to mix in.
26771 * @return {Object} Returns the `Base` constructor for chaining
26772 * @api public
26773 */
26774
26775 defineProperty$2(Base, 'extend', classUtils.extend(Base, function(Ctor, Parent) {
26776 Ctor.prototype.mixins = Ctor.prototype.mixins || [];
26777
26778 defineProperty$2(Ctor, 'mixin', function(fn) {
26779 var mixin = fn(Ctor.prototype, Ctor);
26780 if (typeof mixin === 'function') {
26781 Ctor.prototype.mixins.push(mixin);
26782 }
26783 return Ctor;
26784 });
26785
26786 defineProperty$2(Ctor, 'mixins', function(Child) {
26787 Base.run(Child, 'mixin', Ctor.prototype.mixins);
26788 return Ctor;
26789 });
26790
26791 Ctor.prototype.mixin = function(key, value) {
26792 Ctor.prototype[key] = value;
26793 return this;
26794 };
26795 return Base;
26796 }));
26797
26798 /**
26799 * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances.
26800 * When a mixin function returns a function, the returned function is pushed onto the `.mixins`
26801 * array, making it available to be used on inheriting classes whenever `Base.mixins()` is
26802 * called (e.g. `Base.mixins(Child)`).
26803 *
26804 * ```js
26805 * Base.mixin(function(proto) {
26806 * proto.foo = function(msg) {
26807 * return 'foo ' + msg;
26808 * };
26809 * });
26810 * ```
26811 * @name #mixin
26812 * @param {Function} `fn` Function to call
26813 * @return {Object} Returns the `Base` constructor for chaining
26814 * @api public
26815 */
26816
26817 defineProperty$2(Base, 'mixin', function(fn) {
26818 var mixin = fn(Base.prototype, Base);
26819 if (typeof mixin === 'function') {
26820 Base.prototype.mixins.push(mixin);
26821 }
26822 return Base;
26823 });
26824
26825 /**
26826 * Static method for running global mixin functions against a child constructor.
26827 * Mixins must be registered before calling this method.
26828 *
26829 * ```js
26830 * Base.extend(Child);
26831 * Base.mixins(Child);
26832 * ```
26833 * @name #mixins
26834 * @param {Function} `Child` Constructor function of a child class
26835 * @return {Object} Returns the `Base` constructor for chaining
26836 * @api public
26837 */
26838
26839 defineProperty$2(Base, 'mixins', function(Child) {
26840 Base.run(Child, 'mixin', Base.prototype.mixins);
26841 return Base;
26842 });
26843
26844 /**
26845 * Similar to `util.inherit`, but copies all static properties, prototype properties, and
26846 * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details.
26847 *
26848 * ```js
26849 * Base.inherit(Foo, Bar);
26850 * ```
26851 * @name #inherit
26852 * @param {Function} `Receiver` Receiving (child) constructor
26853 * @param {Function} `Provider` Providing (parent) constructor
26854 * @return {Object} Returns the `Base` constructor for chaining
26855 * @api public
26856 */
26857
26858 defineProperty$2(Base, 'inherit', classUtils.inherit);
26859 defineProperty$2(Base, 'bubble', classUtils.bubble);
26860 return Base;
26861}
26862
26863/**
26864 * Expose `Base` with default settings
26865 */
26866
26867var base$2 = namespace$1();
26868
26869/**
26870 * Allow users to define a namespace
26871 */
26872
26873var namespace_1$1 = namespace$1;
26874base$2.namespace = namespace_1$1;
26875
26876var defineProperty$6 = function defineProperty(obj, prop, val) {
26877 if (typeof obj !== 'object' && typeof obj !== 'function') {
26878 throw new TypeError('expected an object or function.');
26879 }
26880
26881 if (typeof prop !== 'string') {
26882 throw new TypeError('expected `prop` to be a string.');
26883 }
26884
26885 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
26886 return Object.defineProperty(obj, prop, val);
26887 }
26888
26889 return Object.defineProperty(obj, prop, {
26890 configurable: true,
26891 enumerable: false,
26892 writable: true,
26893 value: val
26894 });
26895};
26896
26897/*!
26898 * use <https://github.com/jonschlinkert/use>
26899 *
26900 * Copyright (c) 2015-2017, Jon Schlinkert.
26901 * Released under the MIT License.
26902 */
26903
26904var use = function base(app, options) {
26905 if (!isObject$7(app) && typeof app !== 'function') {
26906 throw new TypeError('expected an object or function');
26907 }
26908
26909 var opts = isObject$7(options) ? options : {};
26910 var prop = typeof opts.prop === 'string' ? opts.prop : 'fns';
26911 if (!Array.isArray(app[prop])) {
26912 define$1(app, prop, []);
26913 }
26914
26915 /**
26916 * Define a plugin function to be passed to use. The only
26917 * parameter exposed to the plugin is `app`, the object or function.
26918 * passed to `use(app)`. `app` is also exposed as `this` in plugins.
26919 *
26920 * Additionally, **if a plugin returns a function, the function will
26921 * be pushed onto the `fns` array**, allowing the plugin to be
26922 * called at a later point by the `run` method.
26923 *
26924 * ```js
26925 * var use = require('use');
26926 *
26927 * // define a plugin
26928 * function foo(app) {
26929 * // do stuff
26930 * }
26931 *
26932 * var app = function(){};
26933 * use(app);
26934 *
26935 * // register plugins
26936 * app.use(foo);
26937 * app.use(bar);
26938 * app.use(baz);
26939 * ```
26940 * @name .use
26941 * @param {Function} `fn` plugin function to call
26942 * @api public
26943 */
26944
26945 define$1(app, 'use', use);
26946
26947 /**
26948 * Run all plugins on `fns`. Any plugin that returns a function
26949 * when called by `use` is pushed onto the `fns` array.
26950 *
26951 * ```js
26952 * var config = {};
26953 * app.run(config);
26954 * ```
26955 * @name .run
26956 * @param {Object} `value` Object to be modified by plugins.
26957 * @return {Object} Returns the object passed to `run`
26958 * @api public
26959 */
26960
26961 define$1(app, 'run', function(val) {
26962 if (!isObject$7(val)) return;
26963
26964 if (!val.use || !val.run) {
26965 define$1(val, prop, val[prop] || []);
26966 define$1(val, 'use', use);
26967 }
26968
26969 if (!val[prop] || val[prop].indexOf(base) === -1) {
26970 val.use(base);
26971 }
26972
26973 var self = this || app;
26974 var fns = self[prop];
26975 var len = fns.length;
26976 var idx = -1;
26977
26978 while (++idx < len) {
26979 val.use(fns[idx]);
26980 }
26981 return val;
26982 });
26983
26984 /**
26985 * Call plugin `fn`. If a function is returned push it into the
26986 * `fns` array to be called by the `run` method.
26987 */
26988
26989 function use(type, fn, options) {
26990 var offset = 1;
26991
26992 if (typeof type === 'string' || Array.isArray(type)) {
26993 fn = wrap(type, fn);
26994 offset++;
26995 } else {
26996 options = fn;
26997 fn = type;
26998 }
26999
27000 if (typeof fn !== 'function') {
27001 throw new TypeError('expected a function');
27002 }
27003
27004 var self = this || app;
27005 var fns = self[prop];
27006
27007 var args = [].slice.call(arguments, offset);
27008 args.unshift(self);
27009
27010 if (typeof opts.hook === 'function') {
27011 opts.hook.apply(self, args);
27012 }
27013
27014 var val = fn.apply(self, args);
27015 if (typeof val === 'function' && fns.indexOf(val) === -1) {
27016 fns.push(val);
27017 }
27018 return self;
27019 }
27020
27021 /**
27022 * Wrap a named plugin function so that it's only called on objects of the
27023 * given `type`
27024 *
27025 * @param {String} `type`
27026 * @param {Function} `fn` Plugin function
27027 * @return {Function}
27028 */
27029
27030 function wrap(type, fn) {
27031 return function plugin() {
27032 return this.type === type ? fn.apply(this, arguments) : plugin;
27033 };
27034 }
27035
27036 return app;
27037};
27038
27039function isObject$7(val) {
27040 return val && typeof val === 'object' && !Array.isArray(val);
27041}
27042
27043function define$1(obj, key, val) {
27044 Object.defineProperty(obj, key, {
27045 configurable: true,
27046 writable: true,
27047 value: val
27048 });
27049}
27050
27051/**
27052 * Helpers.
27053 */
27054
27055var s = 1000;
27056var m = s * 60;
27057var h = m * 60;
27058var d = h * 24;
27059var y = d * 365.25;
27060
27061/**
27062 * Parse or format the given `val`.
27063 *
27064 * Options:
27065 *
27066 * - `long` verbose formatting [false]
27067 *
27068 * @param {String|Number} val
27069 * @param {Object} [options]
27070 * @throws {Error} throw an error if val is not a non-empty string or a number
27071 * @return {String|Number}
27072 * @api public
27073 */
27074
27075var ms = function(val, options) {
27076 options = options || {};
27077 var type = typeof val;
27078 if (type === 'string' && val.length > 0) {
27079 return parse(val);
27080 } else if (type === 'number' && isNaN(val) === false) {
27081 return options.long ? fmtLong(val) : fmtShort(val);
27082 }
27083 throw new Error(
27084 'val is not a non-empty string or a valid number. val=' +
27085 JSON.stringify(val)
27086 );
27087};
27088
27089/**
27090 * Parse the given `str` and return milliseconds.
27091 *
27092 * @param {String} str
27093 * @return {Number}
27094 * @api private
27095 */
27096
27097function parse(str) {
27098 str = String(str);
27099 if (str.length > 100) {
27100 return;
27101 }
27102 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
27103 str
27104 );
27105 if (!match) {
27106 return;
27107 }
27108 var n = parseFloat(match[1]);
27109 var type = (match[2] || 'ms').toLowerCase();
27110 switch (type) {
27111 case 'years':
27112 case 'year':
27113 case 'yrs':
27114 case 'yr':
27115 case 'y':
27116 return n * y;
27117 case 'days':
27118 case 'day':
27119 case 'd':
27120 return n * d;
27121 case 'hours':
27122 case 'hour':
27123 case 'hrs':
27124 case 'hr':
27125 case 'h':
27126 return n * h;
27127 case 'minutes':
27128 case 'minute':
27129 case 'mins':
27130 case 'min':
27131 case 'm':
27132 return n * m;
27133 case 'seconds':
27134 case 'second':
27135 case 'secs':
27136 case 'sec':
27137 case 's':
27138 return n * s;
27139 case 'milliseconds':
27140 case 'millisecond':
27141 case 'msecs':
27142 case 'msec':
27143 case 'ms':
27144 return n;
27145 default:
27146 return undefined;
27147 }
27148}
27149
27150/**
27151 * Short format for `ms`.
27152 *
27153 * @param {Number} ms
27154 * @return {String}
27155 * @api private
27156 */
27157
27158function fmtShort(ms) {
27159 if (ms >= d) {
27160 return Math.round(ms / d) + 'd';
27161 }
27162 if (ms >= h) {
27163 return Math.round(ms / h) + 'h';
27164 }
27165 if (ms >= m) {
27166 return Math.round(ms / m) + 'm';
27167 }
27168 if (ms >= s) {
27169 return Math.round(ms / s) + 's';
27170 }
27171 return ms + 'ms';
27172}
27173
27174/**
27175 * Long format for `ms`.
27176 *
27177 * @param {Number} ms
27178 * @return {String}
27179 * @api private
27180 */
27181
27182function fmtLong(ms) {
27183 return plural(ms, d, 'day') ||
27184 plural(ms, h, 'hour') ||
27185 plural(ms, m, 'minute') ||
27186 plural(ms, s, 'second') ||
27187 ms + ' ms';
27188}
27189
27190/**
27191 * Pluralization helper.
27192 */
27193
27194function plural(ms, n, name) {
27195 if (ms < n) {
27196 return;
27197 }
27198 if (ms < n * 1.5) {
27199 return Math.floor(ms / n) + ' ' + name;
27200 }
27201 return Math.ceil(ms / n) + ' ' + name + 's';
27202}
27203
27204var debug = createCommonjsModule(function (module, exports) {
27205/**
27206 * This is the common logic for both the Node.js and web browser
27207 * implementations of `debug()`.
27208 *
27209 * Expose `debug()` as the module.
27210 */
27211
27212exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
27213exports.coerce = coerce;
27214exports.disable = disable;
27215exports.enable = enable;
27216exports.enabled = enabled;
27217exports.humanize = ms;
27218
27219/**
27220 * The currently active debug mode names, and names to skip.
27221 */
27222
27223exports.names = [];
27224exports.skips = [];
27225
27226/**
27227 * Map of special "%n" handling functions, for the debug "format" argument.
27228 *
27229 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
27230 */
27231
27232exports.formatters = {};
27233
27234/**
27235 * Previous log timestamp.
27236 */
27237
27238var prevTime;
27239
27240/**
27241 * Select a color.
27242 * @param {String} namespace
27243 * @return {Number}
27244 * @api private
27245 */
27246
27247function selectColor(namespace) {
27248 var hash = 0, i;
27249
27250 for (i in namespace) {
27251 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
27252 hash |= 0; // Convert to 32bit integer
27253 }
27254
27255 return exports.colors[Math.abs(hash) % exports.colors.length];
27256}
27257
27258/**
27259 * Create a debugger with the given `namespace`.
27260 *
27261 * @param {String} namespace
27262 * @return {Function}
27263 * @api public
27264 */
27265
27266function createDebug(namespace) {
27267
27268 function debug() {
27269 // disabled?
27270 if (!debug.enabled) return;
27271
27272 var self = debug;
27273
27274 // set `diff` timestamp
27275 var curr = +new Date();
27276 var ms = curr - (prevTime || curr);
27277 self.diff = ms;
27278 self.prev = prevTime;
27279 self.curr = curr;
27280 prevTime = curr;
27281
27282 // turn the `arguments` into a proper Array
27283 var args = new Array(arguments.length);
27284 for (var i = 0; i < args.length; i++) {
27285 args[i] = arguments[i];
27286 }
27287
27288 args[0] = exports.coerce(args[0]);
27289
27290 if ('string' !== typeof args[0]) {
27291 // anything else let's inspect with %O
27292 args.unshift('%O');
27293 }
27294
27295 // apply any `formatters` transformations
27296 var index = 0;
27297 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
27298 // if we encounter an escaped % then don't increase the array index
27299 if (match === '%%') return match;
27300 index++;
27301 var formatter = exports.formatters[format];
27302 if ('function' === typeof formatter) {
27303 var val = args[index];
27304 match = formatter.call(self, val);
27305
27306 // now we need to remove `args[index]` since it's inlined in the `format`
27307 args.splice(index, 1);
27308 index--;
27309 }
27310 return match;
27311 });
27312
27313 // apply env-specific formatting (colors, etc.)
27314 exports.formatArgs.call(self, args);
27315
27316 var logFn = debug.log || exports.log || console.log.bind(console);
27317 logFn.apply(self, args);
27318 }
27319
27320 debug.namespace = namespace;
27321 debug.enabled = exports.enabled(namespace);
27322 debug.useColors = exports.useColors();
27323 debug.color = selectColor(namespace);
27324
27325 // env-specific initialization logic for debug instances
27326 if ('function' === typeof exports.init) {
27327 exports.init(debug);
27328 }
27329
27330 return debug;
27331}
27332
27333/**
27334 * Enables a debug mode by namespaces. This can include modes
27335 * separated by a colon and wildcards.
27336 *
27337 * @param {String} namespaces
27338 * @api public
27339 */
27340
27341function enable(namespaces) {
27342 exports.save(namespaces);
27343
27344 exports.names = [];
27345 exports.skips = [];
27346
27347 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
27348 var len = split.length;
27349
27350 for (var i = 0; i < len; i++) {
27351 if (!split[i]) continue; // ignore empty strings
27352 namespaces = split[i].replace(/\*/g, '.*?');
27353 if (namespaces[0] === '-') {
27354 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
27355 } else {
27356 exports.names.push(new RegExp('^' + namespaces + '$'));
27357 }
27358 }
27359}
27360
27361/**
27362 * Disable debug output.
27363 *
27364 * @api public
27365 */
27366
27367function disable() {
27368 exports.enable('');
27369}
27370
27371/**
27372 * Returns true if the given mode name is enabled, false otherwise.
27373 *
27374 * @param {String} name
27375 * @return {Boolean}
27376 * @api public
27377 */
27378
27379function enabled(name) {
27380 var i, len;
27381 for (i = 0, len = exports.skips.length; i < len; i++) {
27382 if (exports.skips[i].test(name)) {
27383 return false;
27384 }
27385 }
27386 for (i = 0, len = exports.names.length; i < len; i++) {
27387 if (exports.names[i].test(name)) {
27388 return true;
27389 }
27390 }
27391 return false;
27392}
27393
27394/**
27395 * Coerce `val`.
27396 *
27397 * @param {Mixed} val
27398 * @return {Mixed}
27399 * @api private
27400 */
27401
27402function coerce(val) {
27403 if (val instanceof Error) return val.stack || val.message;
27404 return val;
27405}
27406});
27407
27408var browser = createCommonjsModule(function (module, exports) {
27409/**
27410 * This is the web browser implementation of `debug()`.
27411 *
27412 * Expose `debug()` as the module.
27413 */
27414
27415exports = module.exports = debug;
27416exports.log = log;
27417exports.formatArgs = formatArgs;
27418exports.save = save;
27419exports.load = load;
27420exports.useColors = useColors;
27421exports.storage = 'undefined' != typeof chrome
27422 && 'undefined' != typeof chrome.storage
27423 ? chrome.storage.local
27424 : localstorage();
27425
27426/**
27427 * Colors.
27428 */
27429
27430exports.colors = [
27431 'lightseagreen',
27432 'forestgreen',
27433 'goldenrod',
27434 'dodgerblue',
27435 'darkorchid',
27436 'crimson'
27437];
27438
27439/**
27440 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
27441 * and the Firebug extension (any Firefox version) are known
27442 * to support "%c" CSS customizations.
27443 *
27444 * TODO: add a `localStorage` variable to explicitly enable/disable colors
27445 */
27446
27447function useColors() {
27448 // NB: In an Electron preload script, document will be defined but not fully
27449 // initialized. Since we know we're in Chrome, we'll just detect this case
27450 // explicitly
27451 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
27452 return true;
27453 }
27454
27455 // is webkit? http://stackoverflow.com/a/16459606/376773
27456 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
27457 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
27458 // is firebug? http://stackoverflow.com/a/398120/376773
27459 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
27460 // is firefox >= v31?
27461 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
27462 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
27463 // double check webkit in userAgent just in case we are in a worker
27464 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
27465}
27466
27467/**
27468 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
27469 */
27470
27471exports.formatters.j = function(v) {
27472 try {
27473 return JSON.stringify(v);
27474 } catch (err) {
27475 return '[UnexpectedJSONParseError]: ' + err.message;
27476 }
27477};
27478
27479
27480/**
27481 * Colorize log arguments if enabled.
27482 *
27483 * @api public
27484 */
27485
27486function formatArgs(args) {
27487 var useColors = this.useColors;
27488
27489 args[0] = (useColors ? '%c' : '')
27490 + this.namespace
27491 + (useColors ? ' %c' : ' ')
27492 + args[0]
27493 + (useColors ? '%c ' : ' ')
27494 + '+' + exports.humanize(this.diff);
27495
27496 if (!useColors) return;
27497
27498 var c = 'color: ' + this.color;
27499 args.splice(1, 0, c, 'color: inherit');
27500
27501 // the final "%c" is somewhat tricky, because there could be other
27502 // arguments passed either before or after the %c, so we need to
27503 // figure out the correct index to insert the CSS into
27504 var index = 0;
27505 var lastC = 0;
27506 args[0].replace(/%[a-zA-Z%]/g, function(match) {
27507 if ('%%' === match) return;
27508 index++;
27509 if ('%c' === match) {
27510 // we only are interested in the *last* %c
27511 // (the user may have provided their own)
27512 lastC = index;
27513 }
27514 });
27515
27516 args.splice(lastC, 0, c);
27517}
27518
27519/**
27520 * Invokes `console.log()` when available.
27521 * No-op when `console.log` is not a "function".
27522 *
27523 * @api public
27524 */
27525
27526function log() {
27527 // this hackery is required for IE8/9, where
27528 // the `console.log` function doesn't have 'apply'
27529 return 'object' === typeof console
27530 && console.log
27531 && Function.prototype.apply.call(console.log, console, arguments);
27532}
27533
27534/**
27535 * Save `namespaces`.
27536 *
27537 * @param {String} namespaces
27538 * @api private
27539 */
27540
27541function save(namespaces) {
27542 try {
27543 if (null == namespaces) {
27544 exports.storage.removeItem('debug');
27545 } else {
27546 exports.storage.debug = namespaces;
27547 }
27548 } catch(e) {}
27549}
27550
27551/**
27552 * Load `namespaces`.
27553 *
27554 * @return {String} returns the previously persisted debug modes
27555 * @api private
27556 */
27557
27558function load() {
27559 var r;
27560 try {
27561 r = exports.storage.debug;
27562 } catch(e) {}
27563
27564 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
27565 if (!r && typeof process !== 'undefined' && 'env' in process) {
27566 r = process.env.DEBUG;
27567 }
27568
27569 return r;
27570}
27571
27572/**
27573 * Enable namespaces listed in `localStorage.debug` initially.
27574 */
27575
27576exports.enable(load());
27577
27578/**
27579 * Localstorage attempts to return the localstorage.
27580 *
27581 * This is necessary because safari throws
27582 * when a user disables cookies/localstorage
27583 * and you attempt to access it.
27584 *
27585 * @return {LocalStorage}
27586 * @api private
27587 */
27588
27589function localstorage() {
27590 try {
27591 return window.localStorage;
27592 } catch (e) {}
27593}
27594});
27595
27596var node = createCommonjsModule(function (module, exports) {
27597/**
27598 * Module dependencies.
27599 */
27600
27601
27602
27603
27604/**
27605 * This is the Node.js implementation of `debug()`.
27606 *
27607 * Expose `debug()` as the module.
27608 */
27609
27610exports = module.exports = debug;
27611exports.init = init;
27612exports.log = log;
27613exports.formatArgs = formatArgs;
27614exports.save = save;
27615exports.load = load;
27616exports.useColors = useColors;
27617
27618/**
27619 * Colors.
27620 */
27621
27622exports.colors = [6, 2, 3, 4, 5, 1];
27623
27624/**
27625 * Build up the default `inspectOpts` object from the environment variables.
27626 *
27627 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
27628 */
27629
27630exports.inspectOpts = Object.keys(process.env).filter(function (key) {
27631 return /^debug_/i.test(key);
27632}).reduce(function (obj, key) {
27633 // camel-case
27634 var prop = key
27635 .substring(6)
27636 .toLowerCase()
27637 .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
27638
27639 // coerce string value into JS value
27640 var val = process.env[key];
27641 if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
27642 else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
27643 else if (val === 'null') val = null;
27644 else val = Number(val);
27645
27646 obj[prop] = val;
27647 return obj;
27648}, {});
27649
27650/**
27651 * The file descriptor to write the `debug()` calls to.
27652 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
27653 *
27654 * $ DEBUG_FD=3 node script.js 3>debug.log
27655 */
27656
27657var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
27658
27659if (1 !== fd && 2 !== fd) {
27660 util$2.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
27661}
27662
27663var stream = 1 === fd ? process.stdout :
27664 2 === fd ? process.stderr :
27665 createWritableStdioStream(fd);
27666
27667/**
27668 * Is stdout a TTY? Colored output is enabled when `true`.
27669 */
27670
27671function useColors() {
27672 return 'colors' in exports.inspectOpts
27673 ? Boolean(exports.inspectOpts.colors)
27674 : tty.isatty(fd);
27675}
27676
27677/**
27678 * Map %o to `util.inspect()`, all on a single line.
27679 */
27680
27681exports.formatters.o = function(v) {
27682 this.inspectOpts.colors = this.useColors;
27683 return util$2.inspect(v, this.inspectOpts)
27684 .split('\n').map(function(str) {
27685 return str.trim()
27686 }).join(' ');
27687};
27688
27689/**
27690 * Map %o to `util.inspect()`, allowing multiple lines if needed.
27691 */
27692
27693exports.formatters.O = function(v) {
27694 this.inspectOpts.colors = this.useColors;
27695 return util$2.inspect(v, this.inspectOpts);
27696};
27697
27698/**
27699 * Adds ANSI color escape codes if enabled.
27700 *
27701 * @api public
27702 */
27703
27704function formatArgs(args) {
27705 var name = this.namespace;
27706 var useColors = this.useColors;
27707
27708 if (useColors) {
27709 var c = this.color;
27710 var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
27711
27712 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
27713 args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
27714 } else {
27715 args[0] = new Date().toUTCString()
27716 + ' ' + name + ' ' + args[0];
27717 }
27718}
27719
27720/**
27721 * Invokes `util.format()` with the specified arguments and writes to `stream`.
27722 */
27723
27724function log() {
27725 return stream.write(util$2.format.apply(util$2, arguments) + '\n');
27726}
27727
27728/**
27729 * Save `namespaces`.
27730 *
27731 * @param {String} namespaces
27732 * @api private
27733 */
27734
27735function save(namespaces) {
27736 if (null == namespaces) {
27737 // If you set a process.env field to null or undefined, it gets cast to the
27738 // string 'null' or 'undefined'. Just delete instead.
27739 delete process.env.DEBUG;
27740 } else {
27741 process.env.DEBUG = namespaces;
27742 }
27743}
27744
27745/**
27746 * Load `namespaces`.
27747 *
27748 * @return {String} returns the previously persisted debug modes
27749 * @api private
27750 */
27751
27752function load() {
27753 return process.env.DEBUG;
27754}
27755
27756/**
27757 * Copied from `node/src/node.js`.
27758 *
27759 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
27760 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
27761 */
27762
27763function createWritableStdioStream (fd) {
27764 var stream;
27765 var tty_wrap = process.binding('tty_wrap');
27766
27767 // Note stream._type is used for test-module-load-list.js
27768
27769 switch (tty_wrap.guessHandleType(fd)) {
27770 case 'TTY':
27771 stream = new tty.WriteStream(fd);
27772 stream._type = 'tty';
27773
27774 // Hack to have stream not keep the event loop alive.
27775 // See https://github.com/joyent/node/issues/1726
27776 if (stream._handle && stream._handle.unref) {
27777 stream._handle.unref();
27778 }
27779 break;
27780
27781 case 'FILE':
27782 var fs = fs__default;
27783 stream = new fs.SyncWriteStream(fd, { autoClose: false });
27784 stream._type = 'fs';
27785 break;
27786
27787 case 'PIPE':
27788 case 'TCP':
27789 var net$1 = net;
27790 stream = new net$1.Socket({
27791 fd: fd,
27792 readable: false,
27793 writable: true
27794 });
27795
27796 // FIXME Should probably have an option in net.Socket to create a
27797 // stream from an existing fd which is writable only. But for now
27798 // we'll just add this hack and set the `readable` member to false.
27799 // Test: ./node test/fixtures/echo.js < /etc/passwd
27800 stream.readable = false;
27801 stream.read = null;
27802 stream._type = 'pipe';
27803
27804 // FIXME Hack to have stream not keep the event loop alive.
27805 // See https://github.com/joyent/node/issues/1726
27806 if (stream._handle && stream._handle.unref) {
27807 stream._handle.unref();
27808 }
27809 break;
27810
27811 default:
27812 // Probably an error on in uv_guess_handle()
27813 throw new Error('Implement me. Unknown stream file type!');
27814 }
27815
27816 // For supporting legacy API we put the FD here.
27817 stream.fd = fd;
27818
27819 stream._isStdio = true;
27820
27821 return stream;
27822}
27823
27824/**
27825 * Init logic for `debug` instances.
27826 *
27827 * Create a new `inspectOpts` object in case `useColors` is set
27828 * differently for a particular `debug` instance.
27829 */
27830
27831function init (debug) {
27832 debug.inspectOpts = {};
27833
27834 var keys = Object.keys(exports.inspectOpts);
27835 for (var i = 0; i < keys.length; i++) {
27836 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
27837 }
27838}
27839
27840/**
27841 * Enable namespaces listed in `process.env.DEBUG` initially.
27842 */
27843
27844exports.enable(load());
27845});
27846
27847var src = createCommonjsModule(function (module) {
27848/**
27849 * Detect Electron renderer process, which is node, but we should
27850 * treat as a browser.
27851 */
27852
27853if (typeof process !== 'undefined' && process.type === 'renderer') {
27854 module.exports = browser;
27855} else {
27856 module.exports = node;
27857}
27858});
27859
27860var extendShallow$5 = function extend(o/*, objects*/) {
27861 if (!isExtendable$1(o)) { o = {}; }
27862
27863 var len = arguments.length;
27864 for (var i = 1; i < len; i++) {
27865 var obj = arguments[i];
27866
27867 if (isExtendable$1(obj)) {
27868 assign$5(o, obj);
27869 }
27870 }
27871 return o;
27872};
27873
27874function assign$5(a, b) {
27875 for (var key in b) {
27876 if (hasOwn$5(b, key)) {
27877 a[key] = b[key];
27878 }
27879 }
27880}
27881
27882/**
27883 * Returns true if the given `key` is an own property of `obj`.
27884 */
27885
27886function hasOwn$5(obj, key) {
27887 return Object.prototype.hasOwnProperty.call(obj, key);
27888}
27889
27890/* -*- Mode: js; js-indent-level: 2; -*- */
27891/*
27892 * Copyright 2011 Mozilla Foundation and contributors
27893 * Licensed under the New BSD license. See LICENSE or:
27894 * http://opensource.org/licenses/BSD-3-Clause
27895 */
27896
27897var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
27898
27899/**
27900 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
27901 */
27902var encode$1 = function (number) {
27903 if (0 <= number && number < intToCharMap.length) {
27904 return intToCharMap[number];
27905 }
27906 throw new TypeError("Must be between 0 and 63: " + number);
27907};
27908
27909/**
27910 * Decode a single base 64 character code digit to an integer. Returns -1 on
27911 * failure.
27912 */
27913var decode$1 = function (charCode) {
27914 var bigA = 65; // 'A'
27915 var bigZ = 90; // 'Z'
27916
27917 var littleA = 97; // 'a'
27918 var littleZ = 122; // 'z'
27919
27920 var zero = 48; // '0'
27921 var nine = 57; // '9'
27922
27923 var plus = 43; // '+'
27924 var slash = 47; // '/'
27925
27926 var littleOffset = 26;
27927 var numberOffset = 52;
27928
27929 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
27930 if (bigA <= charCode && charCode <= bigZ) {
27931 return (charCode - bigA);
27932 }
27933
27934 // 26 - 51: abcdefghijklmnopqrstuvwxyz
27935 if (littleA <= charCode && charCode <= littleZ) {
27936 return (charCode - littleA + littleOffset);
27937 }
27938
27939 // 52 - 61: 0123456789
27940 if (zero <= charCode && charCode <= nine) {
27941 return (charCode - zero + numberOffset);
27942 }
27943
27944 // 62: +
27945 if (charCode == plus) {
27946 return 62;
27947 }
27948
27949 // 63: /
27950 if (charCode == slash) {
27951 return 63;
27952 }
27953
27954 // Invalid base64 digit.
27955 return -1;
27956};
27957
27958var base64 = {
27959 encode: encode$1,
27960 decode: decode$1
27961};
27962
27963/* -*- Mode: js; js-indent-level: 2; -*- */
27964/*
27965 * Copyright 2011 Mozilla Foundation and contributors
27966 * Licensed under the New BSD license. See LICENSE or:
27967 * http://opensource.org/licenses/BSD-3-Clause
27968 *
27969 * Based on the Base 64 VLQ implementation in Closure Compiler:
27970 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
27971 *
27972 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
27973 * Redistribution and use in source and binary forms, with or without
27974 * modification, are permitted provided that the following conditions are
27975 * met:
27976 *
27977 * * Redistributions of source code must retain the above copyright
27978 * notice, this list of conditions and the following disclaimer.
27979 * * Redistributions in binary form must reproduce the above
27980 * copyright notice, this list of conditions and the following
27981 * disclaimer in the documentation and/or other materials provided
27982 * with the distribution.
27983 * * Neither the name of Google Inc. nor the names of its
27984 * contributors may be used to endorse or promote products derived
27985 * from this software without specific prior written permission.
27986 *
27987 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27988 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27989 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27990 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27991 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27992 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27993 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27994 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27995 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27996 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27997 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27998 */
27999
28000
28001
28002// A single base 64 digit can contain 6 bits of data. For the base 64 variable
28003// length quantities we use in the source map spec, the first bit is the sign,
28004// the next four bits are the actual value, and the 6th bit is the
28005// continuation bit. The continuation bit tells us whether there are more
28006// digits in this value following this digit.
28007//
28008// Continuation
28009// | Sign
28010// | |
28011// V V
28012// 101011
28013
28014var VLQ_BASE_SHIFT = 5;
28015
28016// binary: 100000
28017var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
28018
28019// binary: 011111
28020var VLQ_BASE_MASK = VLQ_BASE - 1;
28021
28022// binary: 100000
28023var VLQ_CONTINUATION_BIT = VLQ_BASE;
28024
28025/**
28026 * Converts from a two-complement value to a value where the sign bit is
28027 * placed in the least significant bit. For example, as decimals:
28028 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
28029 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
28030 */
28031function toVLQSigned(aValue) {
28032 return aValue < 0
28033 ? ((-aValue) << 1) + 1
28034 : (aValue << 1) + 0;
28035}
28036
28037/**
28038 * Converts to a two-complement value from a value where the sign bit is
28039 * placed in the least significant bit. For example, as decimals:
28040 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
28041 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
28042 */
28043function fromVLQSigned(aValue) {
28044 var isNegative = (aValue & 1) === 1;
28045 var shifted = aValue >> 1;
28046 return isNegative
28047 ? -shifted
28048 : shifted;
28049}
28050
28051/**
28052 * Returns the base 64 VLQ encoded value.
28053 */
28054var encode$2 = function base64VLQ_encode(aValue) {
28055 var encoded = "";
28056 var digit;
28057
28058 var vlq = toVLQSigned(aValue);
28059
28060 do {
28061 digit = vlq & VLQ_BASE_MASK;
28062 vlq >>>= VLQ_BASE_SHIFT;
28063 if (vlq > 0) {
28064 // There are still more digits in this value, so we must make sure the
28065 // continuation bit is marked.
28066 digit |= VLQ_CONTINUATION_BIT;
28067 }
28068 encoded += base64.encode(digit);
28069 } while (vlq > 0);
28070
28071 return encoded;
28072};
28073
28074/**
28075 * Decodes the next base 64 VLQ value from the given string and returns the
28076 * value and the rest of the string via the out parameter.
28077 */
28078var decode$2 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
28079 var strLen = aStr.length;
28080 var result = 0;
28081 var shift = 0;
28082 var continuation, digit;
28083
28084 do {
28085 if (aIndex >= strLen) {
28086 throw new Error("Expected more digits in base 64 VLQ value.");
28087 }
28088
28089 digit = base64.decode(aStr.charCodeAt(aIndex++));
28090 if (digit === -1) {
28091 throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
28092 }
28093
28094 continuation = !!(digit & VLQ_CONTINUATION_BIT);
28095 digit &= VLQ_BASE_MASK;
28096 result = result + (digit << shift);
28097 shift += VLQ_BASE_SHIFT;
28098 } while (continuation);
28099
28100 aOutParam.value = fromVLQSigned(result);
28101 aOutParam.rest = aIndex;
28102};
28103
28104var base64Vlq = {
28105 encode: encode$2,
28106 decode: decode$2
28107};
28108
28109var util$1 = createCommonjsModule(function (module, exports) {
28110/* -*- Mode: js; js-indent-level: 2; -*- */
28111/*
28112 * Copyright 2011 Mozilla Foundation and contributors
28113 * Licensed under the New BSD license. See LICENSE or:
28114 * http://opensource.org/licenses/BSD-3-Clause
28115 */
28116
28117/**
28118 * This is a helper function for getting values from parameter/options
28119 * objects.
28120 *
28121 * @param args The object we are extracting values from
28122 * @param name The name of the property we are getting.
28123 * @param defaultValue An optional value to return if the property is missing
28124 * from the object. If this is not specified and the property is missing, an
28125 * error will be thrown.
28126 */
28127function getArg(aArgs, aName, aDefaultValue) {
28128 if (aName in aArgs) {
28129 return aArgs[aName];
28130 } else if (arguments.length === 3) {
28131 return aDefaultValue;
28132 } else {
28133 throw new Error('"' + aName + '" is a required argument.');
28134 }
28135}
28136exports.getArg = getArg;
28137
28138var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
28139var dataUrlRegexp = /^data:.+\,.+$/;
28140
28141function urlParse(aUrl) {
28142 var match = aUrl.match(urlRegexp);
28143 if (!match) {
28144 return null;
28145 }
28146 return {
28147 scheme: match[1],
28148 auth: match[2],
28149 host: match[3],
28150 port: match[4],
28151 path: match[5]
28152 };
28153}
28154exports.urlParse = urlParse;
28155
28156function urlGenerate(aParsedUrl) {
28157 var url = '';
28158 if (aParsedUrl.scheme) {
28159 url += aParsedUrl.scheme + ':';
28160 }
28161 url += '//';
28162 if (aParsedUrl.auth) {
28163 url += aParsedUrl.auth + '@';
28164 }
28165 if (aParsedUrl.host) {
28166 url += aParsedUrl.host;
28167 }
28168 if (aParsedUrl.port) {
28169 url += ":" + aParsedUrl.port;
28170 }
28171 if (aParsedUrl.path) {
28172 url += aParsedUrl.path;
28173 }
28174 return url;
28175}
28176exports.urlGenerate = urlGenerate;
28177
28178/**
28179 * Normalizes a path, or the path portion of a URL:
28180 *
28181 * - Replaces consecutive slashes with one slash.
28182 * - Removes unnecessary '.' parts.
28183 * - Removes unnecessary '<dir>/..' parts.
28184 *
28185 * Based on code in the Node.js 'path' core module.
28186 *
28187 * @param aPath The path or url to normalize.
28188 */
28189function normalize(aPath) {
28190 var path = aPath;
28191 var url = urlParse(aPath);
28192 if (url) {
28193 if (!url.path) {
28194 return aPath;
28195 }
28196 path = url.path;
28197 }
28198 var isAbsolute = exports.isAbsolute(path);
28199
28200 var parts = path.split(/\/+/);
28201 for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
28202 part = parts[i];
28203 if (part === '.') {
28204 parts.splice(i, 1);
28205 } else if (part === '..') {
28206 up++;
28207 } else if (up > 0) {
28208 if (part === '') {
28209 // The first part is blank if the path is absolute. Trying to go
28210 // above the root is a no-op. Therefore we can remove all '..' parts
28211 // directly after the root.
28212 parts.splice(i + 1, up);
28213 up = 0;
28214 } else {
28215 parts.splice(i, 2);
28216 up--;
28217 }
28218 }
28219 }
28220 path = parts.join('/');
28221
28222 if (path === '') {
28223 path = isAbsolute ? '/' : '.';
28224 }
28225
28226 if (url) {
28227 url.path = path;
28228 return urlGenerate(url);
28229 }
28230 return path;
28231}
28232exports.normalize = normalize;
28233
28234/**
28235 * Joins two paths/URLs.
28236 *
28237 * @param aRoot The root path or URL.
28238 * @param aPath The path or URL to be joined with the root.
28239 *
28240 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
28241 * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
28242 * first.
28243 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
28244 * is updated with the result and aRoot is returned. Otherwise the result
28245 * is returned.
28246 * - If aPath is absolute, the result is aPath.
28247 * - Otherwise the two paths are joined with a slash.
28248 * - Joining for example 'http://' and 'www.example.com' is also supported.
28249 */
28250function join(aRoot, aPath) {
28251 if (aRoot === "") {
28252 aRoot = ".";
28253 }
28254 if (aPath === "") {
28255 aPath = ".";
28256 }
28257 var aPathUrl = urlParse(aPath);
28258 var aRootUrl = urlParse(aRoot);
28259 if (aRootUrl) {
28260 aRoot = aRootUrl.path || '/';
28261 }
28262
28263 // `join(foo, '//www.example.org')`
28264 if (aPathUrl && !aPathUrl.scheme) {
28265 if (aRootUrl) {
28266 aPathUrl.scheme = aRootUrl.scheme;
28267 }
28268 return urlGenerate(aPathUrl);
28269 }
28270
28271 if (aPathUrl || aPath.match(dataUrlRegexp)) {
28272 return aPath;
28273 }
28274
28275 // `join('http://', 'www.example.com')`
28276 if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
28277 aRootUrl.host = aPath;
28278 return urlGenerate(aRootUrl);
28279 }
28280
28281 var joined = aPath.charAt(0) === '/'
28282 ? aPath
28283 : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
28284
28285 if (aRootUrl) {
28286 aRootUrl.path = joined;
28287 return urlGenerate(aRootUrl);
28288 }
28289 return joined;
28290}
28291exports.join = join;
28292
28293exports.isAbsolute = function (aPath) {
28294 return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
28295};
28296
28297/**
28298 * Make a path relative to a URL or another path.
28299 *
28300 * @param aRoot The root path or URL.
28301 * @param aPath The path or URL to be made relative to aRoot.
28302 */
28303function relative(aRoot, aPath) {
28304 if (aRoot === "") {
28305 aRoot = ".";
28306 }
28307
28308 aRoot = aRoot.replace(/\/$/, '');
28309
28310 // It is possible for the path to be above the root. In this case, simply
28311 // checking whether the root is a prefix of the path won't work. Instead, we
28312 // need to remove components from the root one by one, until either we find
28313 // a prefix that fits, or we run out of components to remove.
28314 var level = 0;
28315 while (aPath.indexOf(aRoot + '/') !== 0) {
28316 var index = aRoot.lastIndexOf("/");
28317 if (index < 0) {
28318 return aPath;
28319 }
28320
28321 // If the only part of the root that is left is the scheme (i.e. http://,
28322 // file:///, etc.), one or more slashes (/), or simply nothing at all, we
28323 // have exhausted all components, so the path is not relative to the root.
28324 aRoot = aRoot.slice(0, index);
28325 if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
28326 return aPath;
28327 }
28328
28329 ++level;
28330 }
28331
28332 // Make sure we add a "../" for each component we removed from the root.
28333 return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
28334}
28335exports.relative = relative;
28336
28337var supportsNullProto = (function () {
28338 var obj = Object.create(null);
28339 return !('__proto__' in obj);
28340}());
28341
28342function identity (s) {
28343 return s;
28344}
28345
28346/**
28347 * Because behavior goes wacky when you set `__proto__` on objects, we
28348 * have to prefix all the strings in our set with an arbitrary character.
28349 *
28350 * See https://github.com/mozilla/source-map/pull/31 and
28351 * https://github.com/mozilla/source-map/issues/30
28352 *
28353 * @param String aStr
28354 */
28355function toSetString(aStr) {
28356 if (isProtoString(aStr)) {
28357 return '$' + aStr;
28358 }
28359
28360 return aStr;
28361}
28362exports.toSetString = supportsNullProto ? identity : toSetString;
28363
28364function fromSetString(aStr) {
28365 if (isProtoString(aStr)) {
28366 return aStr.slice(1);
28367 }
28368
28369 return aStr;
28370}
28371exports.fromSetString = supportsNullProto ? identity : fromSetString;
28372
28373function isProtoString(s) {
28374 if (!s) {
28375 return false;
28376 }
28377
28378 var length = s.length;
28379
28380 if (length < 9 /* "__proto__".length */) {
28381 return false;
28382 }
28383
28384 if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
28385 s.charCodeAt(length - 2) !== 95 /* '_' */ ||
28386 s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
28387 s.charCodeAt(length - 4) !== 116 /* 't' */ ||
28388 s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
28389 s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
28390 s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
28391 s.charCodeAt(length - 8) !== 95 /* '_' */ ||
28392 s.charCodeAt(length - 9) !== 95 /* '_' */) {
28393 return false;
28394 }
28395
28396 for (var i = length - 10; i >= 0; i--) {
28397 if (s.charCodeAt(i) !== 36 /* '$' */) {
28398 return false;
28399 }
28400 }
28401
28402 return true;
28403}
28404
28405/**
28406 * Comparator between two mappings where the original positions are compared.
28407 *
28408 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
28409 * mappings with the same original source/line/column, but different generated
28410 * line and column the same. Useful when searching for a mapping with a
28411 * stubbed out mapping.
28412 */
28413function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
28414 var cmp = mappingA.source - mappingB.source;
28415 if (cmp !== 0) {
28416 return cmp;
28417 }
28418
28419 cmp = mappingA.originalLine - mappingB.originalLine;
28420 if (cmp !== 0) {
28421 return cmp;
28422 }
28423
28424 cmp = mappingA.originalColumn - mappingB.originalColumn;
28425 if (cmp !== 0 || onlyCompareOriginal) {
28426 return cmp;
28427 }
28428
28429 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
28430 if (cmp !== 0) {
28431 return cmp;
28432 }
28433
28434 cmp = mappingA.generatedLine - mappingB.generatedLine;
28435 if (cmp !== 0) {
28436 return cmp;
28437 }
28438
28439 return mappingA.name - mappingB.name;
28440}
28441exports.compareByOriginalPositions = compareByOriginalPositions;
28442
28443/**
28444 * Comparator between two mappings with deflated source and name indices where
28445 * the generated positions are compared.
28446 *
28447 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
28448 * mappings with the same generated line and column, but different
28449 * source/name/original line and column the same. Useful when searching for a
28450 * mapping with a stubbed out mapping.
28451 */
28452function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
28453 var cmp = mappingA.generatedLine - mappingB.generatedLine;
28454 if (cmp !== 0) {
28455 return cmp;
28456 }
28457
28458 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
28459 if (cmp !== 0 || onlyCompareGenerated) {
28460 return cmp;
28461 }
28462
28463 cmp = mappingA.source - mappingB.source;
28464 if (cmp !== 0) {
28465 return cmp;
28466 }
28467
28468 cmp = mappingA.originalLine - mappingB.originalLine;
28469 if (cmp !== 0) {
28470 return cmp;
28471 }
28472
28473 cmp = mappingA.originalColumn - mappingB.originalColumn;
28474 if (cmp !== 0) {
28475 return cmp;
28476 }
28477
28478 return mappingA.name - mappingB.name;
28479}
28480exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
28481
28482function strcmp(aStr1, aStr2) {
28483 if (aStr1 === aStr2) {
28484 return 0;
28485 }
28486
28487 if (aStr1 > aStr2) {
28488 return 1;
28489 }
28490
28491 return -1;
28492}
28493
28494/**
28495 * Comparator between two mappings with inflated source and name strings where
28496 * the generated positions are compared.
28497 */
28498function compareByGeneratedPositionsInflated(mappingA, mappingB) {
28499 var cmp = mappingA.generatedLine - mappingB.generatedLine;
28500 if (cmp !== 0) {
28501 return cmp;
28502 }
28503
28504 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
28505 if (cmp !== 0) {
28506 return cmp;
28507 }
28508
28509 cmp = strcmp(mappingA.source, mappingB.source);
28510 if (cmp !== 0) {
28511 return cmp;
28512 }
28513
28514 cmp = mappingA.originalLine - mappingB.originalLine;
28515 if (cmp !== 0) {
28516 return cmp;
28517 }
28518
28519 cmp = mappingA.originalColumn - mappingB.originalColumn;
28520 if (cmp !== 0) {
28521 return cmp;
28522 }
28523
28524 return strcmp(mappingA.name, mappingB.name);
28525}
28526exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
28527});
28528
28529/* -*- Mode: js; js-indent-level: 2; -*- */
28530/*
28531 * Copyright 2011 Mozilla Foundation and contributors
28532 * Licensed under the New BSD license. See LICENSE or:
28533 * http://opensource.org/licenses/BSD-3-Clause
28534 */
28535
28536
28537var has$6 = Object.prototype.hasOwnProperty;
28538var hasNativeMap = typeof Map !== "undefined";
28539
28540/**
28541 * A data structure which is a combination of an array and a set. Adding a new
28542 * member is O(1), testing for membership is O(1), and finding the index of an
28543 * element is O(1). Removing elements from the set is not supported. Only
28544 * strings are supported for membership.
28545 */
28546function ArraySet() {
28547 this._array = [];
28548 this._set = hasNativeMap ? new Map() : Object.create(null);
28549}
28550
28551/**
28552 * Static method for creating ArraySet instances from an existing array.
28553 */
28554ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
28555 var set = new ArraySet();
28556 for (var i = 0, len = aArray.length; i < len; i++) {
28557 set.add(aArray[i], aAllowDuplicates);
28558 }
28559 return set;
28560};
28561
28562/**
28563 * Return how many unique items are in this ArraySet. If duplicates have been
28564 * added, than those do not count towards the size.
28565 *
28566 * @returns Number
28567 */
28568ArraySet.prototype.size = function ArraySet_size() {
28569 return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
28570};
28571
28572/**
28573 * Add the given string to this set.
28574 *
28575 * @param String aStr
28576 */
28577ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
28578 var sStr = hasNativeMap ? aStr : util$1.toSetString(aStr);
28579 var isDuplicate = hasNativeMap ? this.has(aStr) : has$6.call(this._set, sStr);
28580 var idx = this._array.length;
28581 if (!isDuplicate || aAllowDuplicates) {
28582 this._array.push(aStr);
28583 }
28584 if (!isDuplicate) {
28585 if (hasNativeMap) {
28586 this._set.set(aStr, idx);
28587 } else {
28588 this._set[sStr] = idx;
28589 }
28590 }
28591};
28592
28593/**
28594 * Is the given string a member of this set?
28595 *
28596 * @param String aStr
28597 */
28598ArraySet.prototype.has = function ArraySet_has(aStr) {
28599 if (hasNativeMap) {
28600 return this._set.has(aStr);
28601 } else {
28602 var sStr = util$1.toSetString(aStr);
28603 return has$6.call(this._set, sStr);
28604 }
28605};
28606
28607/**
28608 * What is the index of the given string in the array?
28609 *
28610 * @param String aStr
28611 */
28612ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
28613 if (hasNativeMap) {
28614 var idx = this._set.get(aStr);
28615 if (idx >= 0) {
28616 return idx;
28617 }
28618 } else {
28619 var sStr = util$1.toSetString(aStr);
28620 if (has$6.call(this._set, sStr)) {
28621 return this._set[sStr];
28622 }
28623 }
28624
28625 throw new Error('"' + aStr + '" is not in the set.');
28626};
28627
28628/**
28629 * What is the element at the given index?
28630 *
28631 * @param Number aIdx
28632 */
28633ArraySet.prototype.at = function ArraySet_at(aIdx) {
28634 if (aIdx >= 0 && aIdx < this._array.length) {
28635 return this._array[aIdx];
28636 }
28637 throw new Error('No element indexed by ' + aIdx);
28638};
28639
28640/**
28641 * Returns the array representation of this set (which has the proper indices
28642 * indicated by indexOf). Note that this is a copy of the internal array used
28643 * for storing the members so that no one can mess with internal state.
28644 */
28645ArraySet.prototype.toArray = function ArraySet_toArray() {
28646 return this._array.slice();
28647};
28648
28649var ArraySet_1 = ArraySet;
28650
28651var arraySet = {
28652 ArraySet: ArraySet_1
28653};
28654
28655/* -*- Mode: js; js-indent-level: 2; -*- */
28656/*
28657 * Copyright 2014 Mozilla Foundation and contributors
28658 * Licensed under the New BSD license. See LICENSE or:
28659 * http://opensource.org/licenses/BSD-3-Clause
28660 */
28661
28662
28663
28664/**
28665 * Determine whether mappingB is after mappingA with respect to generated
28666 * position.
28667 */
28668function generatedPositionAfter(mappingA, mappingB) {
28669 // Optimized for most common case
28670 var lineA = mappingA.generatedLine;
28671 var lineB = mappingB.generatedLine;
28672 var columnA = mappingA.generatedColumn;
28673 var columnB = mappingB.generatedColumn;
28674 return lineB > lineA || lineB == lineA && columnB >= columnA ||
28675 util$1.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
28676}
28677
28678/**
28679 * A data structure to provide a sorted view of accumulated mappings in a
28680 * performance conscious manner. It trades a neglibable overhead in general
28681 * case for a large speedup in case of mappings being added in order.
28682 */
28683function MappingList() {
28684 this._array = [];
28685 this._sorted = true;
28686 // Serves as infimum
28687 this._last = {generatedLine: -1, generatedColumn: 0};
28688}
28689
28690/**
28691 * Iterate through internal items. This method takes the same arguments that
28692 * `Array.prototype.forEach` takes.
28693 *
28694 * NOTE: The order of the mappings is NOT guaranteed.
28695 */
28696MappingList.prototype.unsortedForEach =
28697 function MappingList_forEach(aCallback, aThisArg) {
28698 this._array.forEach(aCallback, aThisArg);
28699 };
28700
28701/**
28702 * Add the given source mapping.
28703 *
28704 * @param Object aMapping
28705 */
28706MappingList.prototype.add = function MappingList_add(aMapping) {
28707 if (generatedPositionAfter(this._last, aMapping)) {
28708 this._last = aMapping;
28709 this._array.push(aMapping);
28710 } else {
28711 this._sorted = false;
28712 this._array.push(aMapping);
28713 }
28714};
28715
28716/**
28717 * Returns the flat, sorted array of mappings. The mappings are sorted by
28718 * generated position.
28719 *
28720 * WARNING: This method returns internal data without copying, for
28721 * performance. The return value must NOT be mutated, and should be treated as
28722 * an immutable borrow. If you want to take ownership, you must make your own
28723 * copy.
28724 */
28725MappingList.prototype.toArray = function MappingList_toArray() {
28726 if (!this._sorted) {
28727 this._array.sort(util$1.compareByGeneratedPositionsInflated);
28728 this._sorted = true;
28729 }
28730 return this._array;
28731};
28732
28733var MappingList_1 = MappingList;
28734
28735var mappingList = {
28736 MappingList: MappingList_1
28737};
28738
28739/* -*- Mode: js; js-indent-level: 2; -*- */
28740/*
28741 * Copyright 2011 Mozilla Foundation and contributors
28742 * Licensed under the New BSD license. See LICENSE or:
28743 * http://opensource.org/licenses/BSD-3-Clause
28744 */
28745
28746
28747
28748var ArraySet$1 = arraySet.ArraySet;
28749var MappingList$1 = mappingList.MappingList;
28750
28751/**
28752 * An instance of the SourceMapGenerator represents a source map which is
28753 * being built incrementally. You may pass an object with the following
28754 * properties:
28755 *
28756 * - file: The filename of the generated source.
28757 * - sourceRoot: A root for all relative URLs in this source map.
28758 */
28759function SourceMapGenerator(aArgs) {
28760 if (!aArgs) {
28761 aArgs = {};
28762 }
28763 this._file = util$1.getArg(aArgs, 'file', null);
28764 this._sourceRoot = util$1.getArg(aArgs, 'sourceRoot', null);
28765 this._skipValidation = util$1.getArg(aArgs, 'skipValidation', false);
28766 this._sources = new ArraySet$1();
28767 this._names = new ArraySet$1();
28768 this._mappings = new MappingList$1();
28769 this._sourcesContents = null;
28770}
28771
28772SourceMapGenerator.prototype._version = 3;
28773
28774/**
28775 * Creates a new SourceMapGenerator based on a SourceMapConsumer
28776 *
28777 * @param aSourceMapConsumer The SourceMap.
28778 */
28779SourceMapGenerator.fromSourceMap =
28780 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
28781 var sourceRoot = aSourceMapConsumer.sourceRoot;
28782 var generator = new SourceMapGenerator({
28783 file: aSourceMapConsumer.file,
28784 sourceRoot: sourceRoot
28785 });
28786 aSourceMapConsumer.eachMapping(function (mapping) {
28787 var newMapping = {
28788 generated: {
28789 line: mapping.generatedLine,
28790 column: mapping.generatedColumn
28791 }
28792 };
28793
28794 if (mapping.source != null) {
28795 newMapping.source = mapping.source;
28796 if (sourceRoot != null) {
28797 newMapping.source = util$1.relative(sourceRoot, newMapping.source);
28798 }
28799
28800 newMapping.original = {
28801 line: mapping.originalLine,
28802 column: mapping.originalColumn
28803 };
28804
28805 if (mapping.name != null) {
28806 newMapping.name = mapping.name;
28807 }
28808 }
28809
28810 generator.addMapping(newMapping);
28811 });
28812 aSourceMapConsumer.sources.forEach(function (sourceFile) {
28813 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
28814 if (content != null) {
28815 generator.setSourceContent(sourceFile, content);
28816 }
28817 });
28818 return generator;
28819 };
28820
28821/**
28822 * Add a single mapping from original source line and column to the generated
28823 * source's line and column for this source map being created. The mapping
28824 * object should have the following properties:
28825 *
28826 * - generated: An object with the generated line and column positions.
28827 * - original: An object with the original line and column positions.
28828 * - source: The original source file (relative to the sourceRoot).
28829 * - name: An optional original token name for this mapping.
28830 */
28831SourceMapGenerator.prototype.addMapping =
28832 function SourceMapGenerator_addMapping(aArgs) {
28833 var generated = util$1.getArg(aArgs, 'generated');
28834 var original = util$1.getArg(aArgs, 'original', null);
28835 var source = util$1.getArg(aArgs, 'source', null);
28836 var name = util$1.getArg(aArgs, 'name', null);
28837
28838 if (!this._skipValidation) {
28839 this._validateMapping(generated, original, source, name);
28840 }
28841
28842 if (source != null) {
28843 source = String(source);
28844 if (!this._sources.has(source)) {
28845 this._sources.add(source);
28846 }
28847 }
28848
28849 if (name != null) {
28850 name = String(name);
28851 if (!this._names.has(name)) {
28852 this._names.add(name);
28853 }
28854 }
28855
28856 this._mappings.add({
28857 generatedLine: generated.line,
28858 generatedColumn: generated.column,
28859 originalLine: original != null && original.line,
28860 originalColumn: original != null && original.column,
28861 source: source,
28862 name: name
28863 });
28864 };
28865
28866/**
28867 * Set the source content for a source file.
28868 */
28869SourceMapGenerator.prototype.setSourceContent =
28870 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
28871 var source = aSourceFile;
28872 if (this._sourceRoot != null) {
28873 source = util$1.relative(this._sourceRoot, source);
28874 }
28875
28876 if (aSourceContent != null) {
28877 // Add the source content to the _sourcesContents map.
28878 // Create a new _sourcesContents map if the property is null.
28879 if (!this._sourcesContents) {
28880 this._sourcesContents = Object.create(null);
28881 }
28882 this._sourcesContents[util$1.toSetString(source)] = aSourceContent;
28883 } else if (this._sourcesContents) {
28884 // Remove the source file from the _sourcesContents map.
28885 // If the _sourcesContents map is empty, set the property to null.
28886 delete this._sourcesContents[util$1.toSetString(source)];
28887 if (Object.keys(this._sourcesContents).length === 0) {
28888 this._sourcesContents = null;
28889 }
28890 }
28891 };
28892
28893/**
28894 * Applies the mappings of a sub-source-map for a specific source file to the
28895 * source map being generated. Each mapping to the supplied source file is
28896 * rewritten using the supplied source map. Note: The resolution for the
28897 * resulting mappings is the minimium of this map and the supplied map.
28898 *
28899 * @param aSourceMapConsumer The source map to be applied.
28900 * @param aSourceFile Optional. The filename of the source file.
28901 * If omitted, SourceMapConsumer's file property will be used.
28902 * @param aSourceMapPath Optional. The dirname of the path to the source map
28903 * to be applied. If relative, it is relative to the SourceMapConsumer.
28904 * This parameter is needed when the two source maps aren't in the same
28905 * directory, and the source map to be applied contains relative source
28906 * paths. If so, those relative source paths need to be rewritten
28907 * relative to the SourceMapGenerator.
28908 */
28909SourceMapGenerator.prototype.applySourceMap =
28910 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
28911 var sourceFile = aSourceFile;
28912 // If aSourceFile is omitted, we will use the file property of the SourceMap
28913 if (aSourceFile == null) {
28914 if (aSourceMapConsumer.file == null) {
28915 throw new Error(
28916 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
28917 'or the source map\'s "file" property. Both were omitted.'
28918 );
28919 }
28920 sourceFile = aSourceMapConsumer.file;
28921 }
28922 var sourceRoot = this._sourceRoot;
28923 // Make "sourceFile" relative if an absolute Url is passed.
28924 if (sourceRoot != null) {
28925 sourceFile = util$1.relative(sourceRoot, sourceFile);
28926 }
28927 // Applying the SourceMap can add and remove items from the sources and
28928 // the names array.
28929 var newSources = new ArraySet$1();
28930 var newNames = new ArraySet$1();
28931
28932 // Find mappings for the "sourceFile"
28933 this._mappings.unsortedForEach(function (mapping) {
28934 if (mapping.source === sourceFile && mapping.originalLine != null) {
28935 // Check if it can be mapped by the source map, then update the mapping.
28936 var original = aSourceMapConsumer.originalPositionFor({
28937 line: mapping.originalLine,
28938 column: mapping.originalColumn
28939 });
28940 if (original.source != null) {
28941 // Copy mapping
28942 mapping.source = original.source;
28943 if (aSourceMapPath != null) {
28944 mapping.source = util$1.join(aSourceMapPath, mapping.source);
28945 }
28946 if (sourceRoot != null) {
28947 mapping.source = util$1.relative(sourceRoot, mapping.source);
28948 }
28949 mapping.originalLine = original.line;
28950 mapping.originalColumn = original.column;
28951 if (original.name != null) {
28952 mapping.name = original.name;
28953 }
28954 }
28955 }
28956
28957 var source = mapping.source;
28958 if (source != null && !newSources.has(source)) {
28959 newSources.add(source);
28960 }
28961
28962 var name = mapping.name;
28963 if (name != null && !newNames.has(name)) {
28964 newNames.add(name);
28965 }
28966
28967 }, this);
28968 this._sources = newSources;
28969 this._names = newNames;
28970
28971 // Copy sourcesContents of applied map.
28972 aSourceMapConsumer.sources.forEach(function (sourceFile) {
28973 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
28974 if (content != null) {
28975 if (aSourceMapPath != null) {
28976 sourceFile = util$1.join(aSourceMapPath, sourceFile);
28977 }
28978 if (sourceRoot != null) {
28979 sourceFile = util$1.relative(sourceRoot, sourceFile);
28980 }
28981 this.setSourceContent(sourceFile, content);
28982 }
28983 }, this);
28984 };
28985
28986/**
28987 * A mapping can have one of the three levels of data:
28988 *
28989 * 1. Just the generated position.
28990 * 2. The Generated position, original position, and original source.
28991 * 3. Generated and original position, original source, as well as a name
28992 * token.
28993 *
28994 * To maintain consistency, we validate that any new mapping being added falls
28995 * in to one of these categories.
28996 */
28997SourceMapGenerator.prototype._validateMapping =
28998 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
28999 aName) {
29000 // When aOriginal is truthy but has empty values for .line and .column,
29001 // it is most likely a programmer error. In this case we throw a very
29002 // specific error message to try to guide them the right way.
29003 // For example: https://github.com/Polymer/polymer-bundler/pull/519
29004 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
29005 throw new Error(
29006 'original.line and original.column are not numbers -- you probably meant to omit ' +
29007 'the original mapping entirely and only map the generated position. If so, pass ' +
29008 'null for the original mapping instead of an object with empty or null values.'
29009 );
29010 }
29011
29012 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
29013 && aGenerated.line > 0 && aGenerated.column >= 0
29014 && !aOriginal && !aSource && !aName) {
29015 // Case 1.
29016 return;
29017 }
29018 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
29019 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
29020 && aGenerated.line > 0 && aGenerated.column >= 0
29021 && aOriginal.line > 0 && aOriginal.column >= 0
29022 && aSource) {
29023 // Cases 2 and 3.
29024 return;
29025 }
29026 else {
29027 throw new Error('Invalid mapping: ' + JSON.stringify({
29028 generated: aGenerated,
29029 source: aSource,
29030 original: aOriginal,
29031 name: aName
29032 }));
29033 }
29034 };
29035
29036/**
29037 * Serialize the accumulated mappings in to the stream of base 64 VLQs
29038 * specified by the source map format.
29039 */
29040SourceMapGenerator.prototype._serializeMappings =
29041 function SourceMapGenerator_serializeMappings() {
29042 var previousGeneratedColumn = 0;
29043 var previousGeneratedLine = 1;
29044 var previousOriginalColumn = 0;
29045 var previousOriginalLine = 0;
29046 var previousName = 0;
29047 var previousSource = 0;
29048 var result = '';
29049 var next;
29050 var mapping;
29051 var nameIdx;
29052 var sourceIdx;
29053
29054 var mappings = this._mappings.toArray();
29055 for (var i = 0, len = mappings.length; i < len; i++) {
29056 mapping = mappings[i];
29057 next = '';
29058
29059 if (mapping.generatedLine !== previousGeneratedLine) {
29060 previousGeneratedColumn = 0;
29061 while (mapping.generatedLine !== previousGeneratedLine) {
29062 next += ';';
29063 previousGeneratedLine++;
29064 }
29065 }
29066 else {
29067 if (i > 0) {
29068 if (!util$1.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
29069 continue;
29070 }
29071 next += ',';
29072 }
29073 }
29074
29075 next += base64Vlq.encode(mapping.generatedColumn
29076 - previousGeneratedColumn);
29077 previousGeneratedColumn = mapping.generatedColumn;
29078
29079 if (mapping.source != null) {
29080 sourceIdx = this._sources.indexOf(mapping.source);
29081 next += base64Vlq.encode(sourceIdx - previousSource);
29082 previousSource = sourceIdx;
29083
29084 // lines are stored 0-based in SourceMap spec version 3
29085 next += base64Vlq.encode(mapping.originalLine - 1
29086 - previousOriginalLine);
29087 previousOriginalLine = mapping.originalLine - 1;
29088
29089 next += base64Vlq.encode(mapping.originalColumn
29090 - previousOriginalColumn);
29091 previousOriginalColumn = mapping.originalColumn;
29092
29093 if (mapping.name != null) {
29094 nameIdx = this._names.indexOf(mapping.name);
29095 next += base64Vlq.encode(nameIdx - previousName);
29096 previousName = nameIdx;
29097 }
29098 }
29099
29100 result += next;
29101 }
29102
29103 return result;
29104 };
29105
29106SourceMapGenerator.prototype._generateSourcesContent =
29107 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
29108 return aSources.map(function (source) {
29109 if (!this._sourcesContents) {
29110 return null;
29111 }
29112 if (aSourceRoot != null) {
29113 source = util$1.relative(aSourceRoot, source);
29114 }
29115 var key = util$1.toSetString(source);
29116 return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
29117 ? this._sourcesContents[key]
29118 : null;
29119 }, this);
29120 };
29121
29122/**
29123 * Externalize the source map.
29124 */
29125SourceMapGenerator.prototype.toJSON =
29126 function SourceMapGenerator_toJSON() {
29127 var map = {
29128 version: this._version,
29129 sources: this._sources.toArray(),
29130 names: this._names.toArray(),
29131 mappings: this._serializeMappings()
29132 };
29133 if (this._file != null) {
29134 map.file = this._file;
29135 }
29136 if (this._sourceRoot != null) {
29137 map.sourceRoot = this._sourceRoot;
29138 }
29139 if (this._sourcesContents) {
29140 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
29141 }
29142
29143 return map;
29144 };
29145
29146/**
29147 * Render the source map being generated to a string.
29148 */
29149SourceMapGenerator.prototype.toString =
29150 function SourceMapGenerator_toString() {
29151 return JSON.stringify(this.toJSON());
29152 };
29153
29154var SourceMapGenerator_1 = SourceMapGenerator;
29155
29156var sourceMapGenerator = {
29157 SourceMapGenerator: SourceMapGenerator_1
29158};
29159
29160var binarySearch = createCommonjsModule(function (module, exports) {
29161/* -*- Mode: js; js-indent-level: 2; -*- */
29162/*
29163 * Copyright 2011 Mozilla Foundation and contributors
29164 * Licensed under the New BSD license. See LICENSE or:
29165 * http://opensource.org/licenses/BSD-3-Clause
29166 */
29167
29168exports.GREATEST_LOWER_BOUND = 1;
29169exports.LEAST_UPPER_BOUND = 2;
29170
29171/**
29172 * Recursive implementation of binary search.
29173 *
29174 * @param aLow Indices here and lower do not contain the needle.
29175 * @param aHigh Indices here and higher do not contain the needle.
29176 * @param aNeedle The element being searched for.
29177 * @param aHaystack The non-empty array being searched.
29178 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
29179 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
29180 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
29181 * closest element that is smaller than or greater than the one we are
29182 * searching for, respectively, if the exact element cannot be found.
29183 */
29184function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
29185 // This function terminates when one of the following is true:
29186 //
29187 // 1. We find the exact element we are looking for.
29188 //
29189 // 2. We did not find the exact element, but we can return the index of
29190 // the next-closest element.
29191 //
29192 // 3. We did not find the exact element, and there is no next-closest
29193 // element than the one we are searching for, so we return -1.
29194 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
29195 var cmp = aCompare(aNeedle, aHaystack[mid], true);
29196 if (cmp === 0) {
29197 // Found the element we are looking for.
29198 return mid;
29199 }
29200 else if (cmp > 0) {
29201 // Our needle is greater than aHaystack[mid].
29202 if (aHigh - mid > 1) {
29203 // The element is in the upper half.
29204 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
29205 }
29206
29207 // The exact needle element was not found in this haystack. Determine if
29208 // we are in termination case (3) or (2) and return the appropriate thing.
29209 if (aBias == exports.LEAST_UPPER_BOUND) {
29210 return aHigh < aHaystack.length ? aHigh : -1;
29211 } else {
29212 return mid;
29213 }
29214 }
29215 else {
29216 // Our needle is less than aHaystack[mid].
29217 if (mid - aLow > 1) {
29218 // The element is in the lower half.
29219 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
29220 }
29221
29222 // we are in termination case (3) or (2) and return the appropriate thing.
29223 if (aBias == exports.LEAST_UPPER_BOUND) {
29224 return mid;
29225 } else {
29226 return aLow < 0 ? -1 : aLow;
29227 }
29228 }
29229}
29230
29231/**
29232 * This is an implementation of binary search which will always try and return
29233 * the index of the closest element if there is no exact hit. This is because
29234 * mappings between original and generated line/col pairs are single points,
29235 * and there is an implicit region between each of them, so a miss just means
29236 * that you aren't on the very start of a region.
29237 *
29238 * @param aNeedle The element you are looking for.
29239 * @param aHaystack The array that is being searched.
29240 * @param aCompare A function which takes the needle and an element in the
29241 * array and returns -1, 0, or 1 depending on whether the needle is less
29242 * than, equal to, or greater than the element, respectively.
29243 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
29244 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
29245 * closest element that is smaller than or greater than the one we are
29246 * searching for, respectively, if the exact element cannot be found.
29247 * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
29248 */
29249exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
29250 if (aHaystack.length === 0) {
29251 return -1;
29252 }
29253
29254 var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
29255 aCompare, aBias || exports.GREATEST_LOWER_BOUND);
29256 if (index < 0) {
29257 return -1;
29258 }
29259
29260 // We have found either the exact element, or the next-closest element than
29261 // the one we are searching for. However, there may be more than one such
29262 // element. Make sure we always return the smallest of these.
29263 while (index - 1 >= 0) {
29264 if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
29265 break;
29266 }
29267 --index;
29268 }
29269
29270 return index;
29271};
29272});
29273
29274/* -*- Mode: js; js-indent-level: 2; -*- */
29275/*
29276 * Copyright 2011 Mozilla Foundation and contributors
29277 * Licensed under the New BSD license. See LICENSE or:
29278 * http://opensource.org/licenses/BSD-3-Clause
29279 */
29280
29281// It turns out that some (most?) JavaScript engines don't self-host
29282// `Array.prototype.sort`. This makes sense because C++ will likely remain
29283// faster than JS when doing raw CPU-intensive sorting. However, when using a
29284// custom comparator function, calling back and forth between the VM's C++ and
29285// JIT'd JS is rather slow *and* loses JIT type information, resulting in
29286// worse generated code for the comparator function than would be optimal. In
29287// fact, when sorting with a comparator, these costs outweigh the benefits of
29288// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
29289// a ~3500ms mean speed-up in `bench/bench.html`.
29290
29291/**
29292 * Swap the elements indexed by `x` and `y` in the array `ary`.
29293 *
29294 * @param {Array} ary
29295 * The array.
29296 * @param {Number} x
29297 * The index of the first item.
29298 * @param {Number} y
29299 * The index of the second item.
29300 */
29301function swap(ary, x, y) {
29302 var temp = ary[x];
29303 ary[x] = ary[y];
29304 ary[y] = temp;
29305}
29306
29307/**
29308 * Returns a random integer within the range `low .. high` inclusive.
29309 *
29310 * @param {Number} low
29311 * The lower bound on the range.
29312 * @param {Number} high
29313 * The upper bound on the range.
29314 */
29315function randomIntInRange(low, high) {
29316 return Math.round(low + (Math.random() * (high - low)));
29317}
29318
29319/**
29320 * The Quick Sort algorithm.
29321 *
29322 * @param {Array} ary
29323 * An array to sort.
29324 * @param {function} comparator
29325 * Function to use to compare two items.
29326 * @param {Number} p
29327 * Start index of the array
29328 * @param {Number} r
29329 * End index of the array
29330 */
29331function doQuickSort(ary, comparator, p, r) {
29332 // If our lower bound is less than our upper bound, we (1) partition the
29333 // array into two pieces and (2) recurse on each half. If it is not, this is
29334 // the empty array and our base case.
29335
29336 if (p < r) {
29337 // (1) Partitioning.
29338 //
29339 // The partitioning chooses a pivot between `p` and `r` and moves all
29340 // elements that are less than or equal to the pivot to the before it, and
29341 // all the elements that are greater than it after it. The effect is that
29342 // once partition is done, the pivot is in the exact place it will be when
29343 // the array is put in sorted order, and it will not need to be moved
29344 // again. This runs in O(n) time.
29345
29346 // Always choose a random pivot so that an input array which is reverse
29347 // sorted does not cause O(n^2) running time.
29348 var pivotIndex = randomIntInRange(p, r);
29349 var i = p - 1;
29350
29351 swap(ary, pivotIndex, r);
29352 var pivot = ary[r];
29353
29354 // Immediately after `j` is incremented in this loop, the following hold
29355 // true:
29356 //
29357 // * Every element in `ary[p .. i]` is less than or equal to the pivot.
29358 //
29359 // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
29360 for (var j = p; j < r; j++) {
29361 if (comparator(ary[j], pivot) <= 0) {
29362 i += 1;
29363 swap(ary, i, j);
29364 }
29365 }
29366
29367 swap(ary, i + 1, j);
29368 var q = i + 1;
29369
29370 // (2) Recurse on each half.
29371
29372 doQuickSort(ary, comparator, p, q - 1);
29373 doQuickSort(ary, comparator, q + 1, r);
29374 }
29375}
29376
29377/**
29378 * Sort the given array in-place with the given comparator function.
29379 *
29380 * @param {Array} ary
29381 * An array to sort.
29382 * @param {function} comparator
29383 * Function to use to compare two items.
29384 */
29385var quickSort_1 = function (ary, comparator) {
29386 doQuickSort(ary, comparator, 0, ary.length - 1);
29387};
29388
29389var quickSort = {
29390 quickSort: quickSort_1
29391};
29392
29393/* -*- Mode: js; js-indent-level: 2; -*- */
29394/*
29395 * Copyright 2011 Mozilla Foundation and contributors
29396 * Licensed under the New BSD license. See LICENSE or:
29397 * http://opensource.org/licenses/BSD-3-Clause
29398 */
29399
29400
29401
29402var ArraySet$2 = arraySet.ArraySet;
29403
29404var quickSort$1 = quickSort.quickSort;
29405
29406function SourceMapConsumer(aSourceMap) {
29407 var sourceMap = aSourceMap;
29408 if (typeof aSourceMap === 'string') {
29409 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
29410 }
29411
29412 return sourceMap.sections != null
29413 ? new IndexedSourceMapConsumer(sourceMap)
29414 : new BasicSourceMapConsumer(sourceMap);
29415}
29416
29417SourceMapConsumer.fromSourceMap = function(aSourceMap) {
29418 return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
29419};
29420
29421/**
29422 * The version of the source mapping spec that we are consuming.
29423 */
29424SourceMapConsumer.prototype._version = 3;
29425
29426// `__generatedMappings` and `__originalMappings` are arrays that hold the
29427// parsed mapping coordinates from the source map's "mappings" attribute. They
29428// are lazily instantiated, accessed via the `_generatedMappings` and
29429// `_originalMappings` getters respectively, and we only parse the mappings
29430// and create these arrays once queried for a source location. We jump through
29431// these hoops because there can be many thousands of mappings, and parsing
29432// them is expensive, so we only want to do it if we must.
29433//
29434// Each object in the arrays is of the form:
29435//
29436// {
29437// generatedLine: The line number in the generated code,
29438// generatedColumn: The column number in the generated code,
29439// source: The path to the original source file that generated this
29440// chunk of code,
29441// originalLine: The line number in the original source that
29442// corresponds to this chunk of generated code,
29443// originalColumn: The column number in the original source that
29444// corresponds to this chunk of generated code,
29445// name: The name of the original symbol which generated this chunk of
29446// code.
29447// }
29448//
29449// All properties except for `generatedLine` and `generatedColumn` can be
29450// `null`.
29451//
29452// `_generatedMappings` is ordered by the generated positions.
29453//
29454// `_originalMappings` is ordered by the original positions.
29455
29456SourceMapConsumer.prototype.__generatedMappings = null;
29457Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
29458 get: function () {
29459 if (!this.__generatedMappings) {
29460 this._parseMappings(this._mappings, this.sourceRoot);
29461 }
29462
29463 return this.__generatedMappings;
29464 }
29465});
29466
29467SourceMapConsumer.prototype.__originalMappings = null;
29468Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
29469 get: function () {
29470 if (!this.__originalMappings) {
29471 this._parseMappings(this._mappings, this.sourceRoot);
29472 }
29473
29474 return this.__originalMappings;
29475 }
29476});
29477
29478SourceMapConsumer.prototype._charIsMappingSeparator =
29479 function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
29480 var c = aStr.charAt(index);
29481 return c === ";" || c === ",";
29482 };
29483
29484/**
29485 * Parse the mappings in a string in to a data structure which we can easily
29486 * query (the ordered arrays in the `this.__generatedMappings` and
29487 * `this.__originalMappings` properties).
29488 */
29489SourceMapConsumer.prototype._parseMappings =
29490 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
29491 throw new Error("Subclasses must implement _parseMappings");
29492 };
29493
29494SourceMapConsumer.GENERATED_ORDER = 1;
29495SourceMapConsumer.ORIGINAL_ORDER = 2;
29496
29497SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
29498SourceMapConsumer.LEAST_UPPER_BOUND = 2;
29499
29500/**
29501 * Iterate over each mapping between an original source/line/column and a
29502 * generated line/column in this source map.
29503 *
29504 * @param Function aCallback
29505 * The function that is called with each mapping.
29506 * @param Object aContext
29507 * Optional. If specified, this object will be the value of `this` every
29508 * time that `aCallback` is called.
29509 * @param aOrder
29510 * Either `SourceMapConsumer.GENERATED_ORDER` or
29511 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
29512 * iterate over the mappings sorted by the generated file's line/column
29513 * order or the original's source/line/column order, respectively. Defaults to
29514 * `SourceMapConsumer.GENERATED_ORDER`.
29515 */
29516SourceMapConsumer.prototype.eachMapping =
29517 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
29518 var context = aContext || null;
29519 var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
29520
29521 var mappings;
29522 switch (order) {
29523 case SourceMapConsumer.GENERATED_ORDER:
29524 mappings = this._generatedMappings;
29525 break;
29526 case SourceMapConsumer.ORIGINAL_ORDER:
29527 mappings = this._originalMappings;
29528 break;
29529 default:
29530 throw new Error("Unknown order of iteration.");
29531 }
29532
29533 var sourceRoot = this.sourceRoot;
29534 mappings.map(function (mapping) {
29535 var source = mapping.source === null ? null : this._sources.at(mapping.source);
29536 if (source != null && sourceRoot != null) {
29537 source = util$1.join(sourceRoot, source);
29538 }
29539 return {
29540 source: source,
29541 generatedLine: mapping.generatedLine,
29542 generatedColumn: mapping.generatedColumn,
29543 originalLine: mapping.originalLine,
29544 originalColumn: mapping.originalColumn,
29545 name: mapping.name === null ? null : this._names.at(mapping.name)
29546 };
29547 }, this).forEach(aCallback, context);
29548 };
29549
29550/**
29551 * Returns all generated line and column information for the original source,
29552 * line, and column provided. If no column is provided, returns all mappings
29553 * corresponding to a either the line we are searching for or the next
29554 * closest line that has any mappings. Otherwise, returns all mappings
29555 * corresponding to the given line and either the column we are searching for
29556 * or the next closest column that has any offsets.
29557 *
29558 * The only argument is an object with the following properties:
29559 *
29560 * - source: The filename of the original source.
29561 * - line: The line number in the original source.
29562 * - column: Optional. the column number in the original source.
29563 *
29564 * and an array of objects is returned, each with the following properties:
29565 *
29566 * - line: The line number in the generated source, or null.
29567 * - column: The column number in the generated source, or null.
29568 */
29569SourceMapConsumer.prototype.allGeneratedPositionsFor =
29570 function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
29571 var line = util$1.getArg(aArgs, 'line');
29572
29573 // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
29574 // returns the index of the closest mapping less than the needle. By
29575 // setting needle.originalColumn to 0, we thus find the last mapping for
29576 // the given line, provided such a mapping exists.
29577 var needle = {
29578 source: util$1.getArg(aArgs, 'source'),
29579 originalLine: line,
29580 originalColumn: util$1.getArg(aArgs, 'column', 0)
29581 };
29582
29583 if (this.sourceRoot != null) {
29584 needle.source = util$1.relative(this.sourceRoot, needle.source);
29585 }
29586 if (!this._sources.has(needle.source)) {
29587 return [];
29588 }
29589 needle.source = this._sources.indexOf(needle.source);
29590
29591 var mappings = [];
29592
29593 var index = this._findMapping(needle,
29594 this._originalMappings,
29595 "originalLine",
29596 "originalColumn",
29597 util$1.compareByOriginalPositions,
29598 binarySearch.LEAST_UPPER_BOUND);
29599 if (index >= 0) {
29600 var mapping = this._originalMappings[index];
29601
29602 if (aArgs.column === undefined) {
29603 var originalLine = mapping.originalLine;
29604
29605 // Iterate until either we run out of mappings, or we run into
29606 // a mapping for a different line than the one we found. Since
29607 // mappings are sorted, this is guaranteed to find all mappings for
29608 // the line we found.
29609 while (mapping && mapping.originalLine === originalLine) {
29610 mappings.push({
29611 line: util$1.getArg(mapping, 'generatedLine', null),
29612 column: util$1.getArg(mapping, 'generatedColumn', null),
29613 lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
29614 });
29615
29616 mapping = this._originalMappings[++index];
29617 }
29618 } else {
29619 var originalColumn = mapping.originalColumn;
29620
29621 // Iterate until either we run out of mappings, or we run into
29622 // a mapping for a different line than the one we were searching for.
29623 // Since mappings are sorted, this is guaranteed to find all mappings for
29624 // the line we are searching for.
29625 while (mapping &&
29626 mapping.originalLine === line &&
29627 mapping.originalColumn == originalColumn) {
29628 mappings.push({
29629 line: util$1.getArg(mapping, 'generatedLine', null),
29630 column: util$1.getArg(mapping, 'generatedColumn', null),
29631 lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
29632 });
29633
29634 mapping = this._originalMappings[++index];
29635 }
29636 }
29637 }
29638
29639 return mappings;
29640 };
29641
29642var SourceMapConsumer_1 = SourceMapConsumer;
29643
29644/**
29645 * A BasicSourceMapConsumer instance represents a parsed source map which we can
29646 * query for information about the original file positions by giving it a file
29647 * position in the generated source.
29648 *
29649 * The only parameter is the raw source map (either as a JSON string, or
29650 * already parsed to an object). According to the spec, source maps have the
29651 * following attributes:
29652 *
29653 * - version: Which version of the source map spec this map is following.
29654 * - sources: An array of URLs to the original source files.
29655 * - names: An array of identifiers which can be referrenced by individual mappings.
29656 * - sourceRoot: Optional. The URL root from which all sources are relative.
29657 * - sourcesContent: Optional. An array of contents of the original source files.
29658 * - mappings: A string of base64 VLQs which contain the actual mappings.
29659 * - file: Optional. The generated file this source map is associated with.
29660 *
29661 * Here is an example source map, taken from the source map spec[0]:
29662 *
29663 * {
29664 * version : 3,
29665 * file: "out.js",
29666 * sourceRoot : "",
29667 * sources: ["foo.js", "bar.js"],
29668 * names: ["src", "maps", "are", "fun"],
29669 * mappings: "AA,AB;;ABCDE;"
29670 * }
29671 *
29672 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
29673 */
29674function BasicSourceMapConsumer(aSourceMap) {
29675 var sourceMap = aSourceMap;
29676 if (typeof aSourceMap === 'string') {
29677 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
29678 }
29679
29680 var version = util$1.getArg(sourceMap, 'version');
29681 var sources = util$1.getArg(sourceMap, 'sources');
29682 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
29683 // requires the array) to play nice here.
29684 var names = util$1.getArg(sourceMap, 'names', []);
29685 var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
29686 var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
29687 var mappings = util$1.getArg(sourceMap, 'mappings');
29688 var file = util$1.getArg(sourceMap, 'file', null);
29689
29690 // Once again, Sass deviates from the spec and supplies the version as a
29691 // string rather than a number, so we use loose equality checking here.
29692 if (version != this._version) {
29693 throw new Error('Unsupported version: ' + version);
29694 }
29695
29696 sources = sources
29697 .map(String)
29698 // Some source maps produce relative source paths like "./foo.js" instead of
29699 // "foo.js". Normalize these first so that future comparisons will succeed.
29700 // See bugzil.la/1090768.
29701 .map(util$1.normalize)
29702 // Always ensure that absolute sources are internally stored relative to
29703 // the source root, if the source root is absolute. Not doing this would
29704 // be particularly problematic when the source root is a prefix of the
29705 // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
29706 .map(function (source) {
29707 return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
29708 ? util$1.relative(sourceRoot, source)
29709 : source;
29710 });
29711
29712 // Pass `true` below to allow duplicate names and sources. While source maps
29713 // are intended to be compressed and deduplicated, the TypeScript compiler
29714 // sometimes generates source maps with duplicates in them. See Github issue
29715 // #72 and bugzil.la/889492.
29716 this._names = ArraySet$2.fromArray(names.map(String), true);
29717 this._sources = ArraySet$2.fromArray(sources, true);
29718
29719 this.sourceRoot = sourceRoot;
29720 this.sourcesContent = sourcesContent;
29721 this._mappings = mappings;
29722 this.file = file;
29723}
29724
29725BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
29726BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
29727
29728/**
29729 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
29730 *
29731 * @param SourceMapGenerator aSourceMap
29732 * The source map that will be consumed.
29733 * @returns BasicSourceMapConsumer
29734 */
29735BasicSourceMapConsumer.fromSourceMap =
29736 function SourceMapConsumer_fromSourceMap(aSourceMap) {
29737 var smc = Object.create(BasicSourceMapConsumer.prototype);
29738
29739 var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
29740 var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
29741 smc.sourceRoot = aSourceMap._sourceRoot;
29742 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
29743 smc.sourceRoot);
29744 smc.file = aSourceMap._file;
29745
29746 // Because we are modifying the entries (by converting string sources and
29747 // names to indices into the sources and names ArraySets), we have to make
29748 // a copy of the entry or else bad things happen. Shared mutable state
29749 // strikes again! See github issue #191.
29750
29751 var generatedMappings = aSourceMap._mappings.toArray().slice();
29752 var destGeneratedMappings = smc.__generatedMappings = [];
29753 var destOriginalMappings = smc.__originalMappings = [];
29754
29755 for (var i = 0, length = generatedMappings.length; i < length; i++) {
29756 var srcMapping = generatedMappings[i];
29757 var destMapping = new Mapping;
29758 destMapping.generatedLine = srcMapping.generatedLine;
29759 destMapping.generatedColumn = srcMapping.generatedColumn;
29760
29761 if (srcMapping.source) {
29762 destMapping.source = sources.indexOf(srcMapping.source);
29763 destMapping.originalLine = srcMapping.originalLine;
29764 destMapping.originalColumn = srcMapping.originalColumn;
29765
29766 if (srcMapping.name) {
29767 destMapping.name = names.indexOf(srcMapping.name);
29768 }
29769
29770 destOriginalMappings.push(destMapping);
29771 }
29772
29773 destGeneratedMappings.push(destMapping);
29774 }
29775
29776 quickSort$1(smc.__originalMappings, util$1.compareByOriginalPositions);
29777
29778 return smc;
29779 };
29780
29781/**
29782 * The version of the source mapping spec that we are consuming.
29783 */
29784BasicSourceMapConsumer.prototype._version = 3;
29785
29786/**
29787 * The list of original sources.
29788 */
29789Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
29790 get: function () {
29791 return this._sources.toArray().map(function (s) {
29792 return this.sourceRoot != null ? util$1.join(this.sourceRoot, s) : s;
29793 }, this);
29794 }
29795});
29796
29797/**
29798 * Provide the JIT with a nice shape / hidden class.
29799 */
29800function Mapping() {
29801 this.generatedLine = 0;
29802 this.generatedColumn = 0;
29803 this.source = null;
29804 this.originalLine = null;
29805 this.originalColumn = null;
29806 this.name = null;
29807}
29808
29809/**
29810 * Parse the mappings in a string in to a data structure which we can easily
29811 * query (the ordered arrays in the `this.__generatedMappings` and
29812 * `this.__originalMappings` properties).
29813 */
29814BasicSourceMapConsumer.prototype._parseMappings =
29815 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
29816 var generatedLine = 1;
29817 var previousGeneratedColumn = 0;
29818 var previousOriginalLine = 0;
29819 var previousOriginalColumn = 0;
29820 var previousSource = 0;
29821 var previousName = 0;
29822 var length = aStr.length;
29823 var index = 0;
29824 var cachedSegments = {};
29825 var temp = {};
29826 var originalMappings = [];
29827 var generatedMappings = [];
29828 var mapping, str, segment, end, value;
29829
29830 while (index < length) {
29831 if (aStr.charAt(index) === ';') {
29832 generatedLine++;
29833 index++;
29834 previousGeneratedColumn = 0;
29835 }
29836 else if (aStr.charAt(index) === ',') {
29837 index++;
29838 }
29839 else {
29840 mapping = new Mapping();
29841 mapping.generatedLine = generatedLine;
29842
29843 // Because each offset is encoded relative to the previous one,
29844 // many segments often have the same encoding. We can exploit this
29845 // fact by caching the parsed variable length fields of each segment,
29846 // allowing us to avoid a second parse if we encounter the same
29847 // segment again.
29848 for (end = index; end < length; end++) {
29849 if (this._charIsMappingSeparator(aStr, end)) {
29850 break;
29851 }
29852 }
29853 str = aStr.slice(index, end);
29854
29855 segment = cachedSegments[str];
29856 if (segment) {
29857 index += str.length;
29858 } else {
29859 segment = [];
29860 while (index < end) {
29861 base64Vlq.decode(aStr, index, temp);
29862 value = temp.value;
29863 index = temp.rest;
29864 segment.push(value);
29865 }
29866
29867 if (segment.length === 2) {
29868 throw new Error('Found a source, but no line and column');
29869 }
29870
29871 if (segment.length === 3) {
29872 throw new Error('Found a source and line, but no column');
29873 }
29874
29875 cachedSegments[str] = segment;
29876 }
29877
29878 // Generated column.
29879 mapping.generatedColumn = previousGeneratedColumn + segment[0];
29880 previousGeneratedColumn = mapping.generatedColumn;
29881
29882 if (segment.length > 1) {
29883 // Original source.
29884 mapping.source = previousSource + segment[1];
29885 previousSource += segment[1];
29886
29887 // Original line.
29888 mapping.originalLine = previousOriginalLine + segment[2];
29889 previousOriginalLine = mapping.originalLine;
29890 // Lines are stored 0-based
29891 mapping.originalLine += 1;
29892
29893 // Original column.
29894 mapping.originalColumn = previousOriginalColumn + segment[3];
29895 previousOriginalColumn = mapping.originalColumn;
29896
29897 if (segment.length > 4) {
29898 // Original name.
29899 mapping.name = previousName + segment[4];
29900 previousName += segment[4];
29901 }
29902 }
29903
29904 generatedMappings.push(mapping);
29905 if (typeof mapping.originalLine === 'number') {
29906 originalMappings.push(mapping);
29907 }
29908 }
29909 }
29910
29911 quickSort$1(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
29912 this.__generatedMappings = generatedMappings;
29913
29914 quickSort$1(originalMappings, util$1.compareByOriginalPositions);
29915 this.__originalMappings = originalMappings;
29916 };
29917
29918/**
29919 * Find the mapping that best matches the hypothetical "needle" mapping that
29920 * we are searching for in the given "haystack" of mappings.
29921 */
29922BasicSourceMapConsumer.prototype._findMapping =
29923 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
29924 aColumnName, aComparator, aBias) {
29925 // To return the position we are searching for, we must first find the
29926 // mapping for the given position and then return the opposite position it
29927 // points to. Because the mappings are sorted, we can use binary search to
29928 // find the best mapping.
29929
29930 if (aNeedle[aLineName] <= 0) {
29931 throw new TypeError('Line must be greater than or equal to 1, got '
29932 + aNeedle[aLineName]);
29933 }
29934 if (aNeedle[aColumnName] < 0) {
29935 throw new TypeError('Column must be greater than or equal to 0, got '
29936 + aNeedle[aColumnName]);
29937 }
29938
29939 return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
29940 };
29941
29942/**
29943 * Compute the last column for each generated mapping. The last column is
29944 * inclusive.
29945 */
29946BasicSourceMapConsumer.prototype.computeColumnSpans =
29947 function SourceMapConsumer_computeColumnSpans() {
29948 for (var index = 0; index < this._generatedMappings.length; ++index) {
29949 var mapping = this._generatedMappings[index];
29950
29951 // Mappings do not contain a field for the last generated columnt. We
29952 // can come up with an optimistic estimate, however, by assuming that
29953 // mappings are contiguous (i.e. given two consecutive mappings, the
29954 // first mapping ends where the second one starts).
29955 if (index + 1 < this._generatedMappings.length) {
29956 var nextMapping = this._generatedMappings[index + 1];
29957
29958 if (mapping.generatedLine === nextMapping.generatedLine) {
29959 mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
29960 continue;
29961 }
29962 }
29963
29964 // The last mapping for each line spans the entire line.
29965 mapping.lastGeneratedColumn = Infinity;
29966 }
29967 };
29968
29969/**
29970 * Returns the original source, line, and column information for the generated
29971 * source's line and column positions provided. The only argument is an object
29972 * with the following properties:
29973 *
29974 * - line: The line number in the generated source.
29975 * - column: The column number in the generated source.
29976 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
29977 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
29978 * closest element that is smaller than or greater than the one we are
29979 * searching for, respectively, if the exact element cannot be found.
29980 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
29981 *
29982 * and an object is returned with the following properties:
29983 *
29984 * - source: The original source file, or null.
29985 * - line: The line number in the original source, or null.
29986 * - column: The column number in the original source, or null.
29987 * - name: The original identifier, or null.
29988 */
29989BasicSourceMapConsumer.prototype.originalPositionFor =
29990 function SourceMapConsumer_originalPositionFor(aArgs) {
29991 var needle = {
29992 generatedLine: util$1.getArg(aArgs, 'line'),
29993 generatedColumn: util$1.getArg(aArgs, 'column')
29994 };
29995
29996 var index = this._findMapping(
29997 needle,
29998 this._generatedMappings,
29999 "generatedLine",
30000 "generatedColumn",
30001 util$1.compareByGeneratedPositionsDeflated,
30002 util$1.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
30003 );
30004
30005 if (index >= 0) {
30006 var mapping = this._generatedMappings[index];
30007
30008 if (mapping.generatedLine === needle.generatedLine) {
30009 var source = util$1.getArg(mapping, 'source', null);
30010 if (source !== null) {
30011 source = this._sources.at(source);
30012 if (this.sourceRoot != null) {
30013 source = util$1.join(this.sourceRoot, source);
30014 }
30015 }
30016 var name = util$1.getArg(mapping, 'name', null);
30017 if (name !== null) {
30018 name = this._names.at(name);
30019 }
30020 return {
30021 source: source,
30022 line: util$1.getArg(mapping, 'originalLine', null),
30023 column: util$1.getArg(mapping, 'originalColumn', null),
30024 name: name
30025 };
30026 }
30027 }
30028
30029 return {
30030 source: null,
30031 line: null,
30032 column: null,
30033 name: null
30034 };
30035 };
30036
30037/**
30038 * Return true if we have the source content for every source in the source
30039 * map, false otherwise.
30040 */
30041BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
30042 function BasicSourceMapConsumer_hasContentsOfAllSources() {
30043 if (!this.sourcesContent) {
30044 return false;
30045 }
30046 return this.sourcesContent.length >= this._sources.size() &&
30047 !this.sourcesContent.some(function (sc) { return sc == null; });
30048 };
30049
30050/**
30051 * Returns the original source content. The only argument is the url of the
30052 * original source file. Returns null if no original source content is
30053 * available.
30054 */
30055BasicSourceMapConsumer.prototype.sourceContentFor =
30056 function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
30057 if (!this.sourcesContent) {
30058 return null;
30059 }
30060
30061 if (this.sourceRoot != null) {
30062 aSource = util$1.relative(this.sourceRoot, aSource);
30063 }
30064
30065 if (this._sources.has(aSource)) {
30066 return this.sourcesContent[this._sources.indexOf(aSource)];
30067 }
30068
30069 var url;
30070 if (this.sourceRoot != null
30071 && (url = util$1.urlParse(this.sourceRoot))) {
30072 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
30073 // many users. We can help them out when they expect file:// URIs to
30074 // behave like it would if they were running a local HTTP server. See
30075 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
30076 var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
30077 if (url.scheme == "file"
30078 && this._sources.has(fileUriAbsPath)) {
30079 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
30080 }
30081
30082 if ((!url.path || url.path == "/")
30083 && this._sources.has("/" + aSource)) {
30084 return this.sourcesContent[this._sources.indexOf("/" + aSource)];
30085 }
30086 }
30087
30088 // This function is used recursively from
30089 // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
30090 // don't want to throw if we can't find the source - we just want to
30091 // return null, so we provide a flag to exit gracefully.
30092 if (nullOnMissing) {
30093 return null;
30094 }
30095 else {
30096 throw new Error('"' + aSource + '" is not in the SourceMap.');
30097 }
30098 };
30099
30100/**
30101 * Returns the generated line and column information for the original source,
30102 * line, and column positions provided. The only argument is an object with
30103 * the following properties:
30104 *
30105 * - source: The filename of the original source.
30106 * - line: The line number in the original source.
30107 * - column: The column number in the original source.
30108 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
30109 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
30110 * closest element that is smaller than or greater than the one we are
30111 * searching for, respectively, if the exact element cannot be found.
30112 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
30113 *
30114 * and an object is returned with the following properties:
30115 *
30116 * - line: The line number in the generated source, or null.
30117 * - column: The column number in the generated source, or null.
30118 */
30119BasicSourceMapConsumer.prototype.generatedPositionFor =
30120 function SourceMapConsumer_generatedPositionFor(aArgs) {
30121 var source = util$1.getArg(aArgs, 'source');
30122 if (this.sourceRoot != null) {
30123 source = util$1.relative(this.sourceRoot, source);
30124 }
30125 if (!this._sources.has(source)) {
30126 return {
30127 line: null,
30128 column: null,
30129 lastColumn: null
30130 };
30131 }
30132 source = this._sources.indexOf(source);
30133
30134 var needle = {
30135 source: source,
30136 originalLine: util$1.getArg(aArgs, 'line'),
30137 originalColumn: util$1.getArg(aArgs, 'column')
30138 };
30139
30140 var index = this._findMapping(
30141 needle,
30142 this._originalMappings,
30143 "originalLine",
30144 "originalColumn",
30145 util$1.compareByOriginalPositions,
30146 util$1.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
30147 );
30148
30149 if (index >= 0) {
30150 var mapping = this._originalMappings[index];
30151
30152 if (mapping.source === needle.source) {
30153 return {
30154 line: util$1.getArg(mapping, 'generatedLine', null),
30155 column: util$1.getArg(mapping, 'generatedColumn', null),
30156 lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
30157 };
30158 }
30159 }
30160
30161 return {
30162 line: null,
30163 column: null,
30164 lastColumn: null
30165 };
30166 };
30167
30168var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
30169
30170/**
30171 * An IndexedSourceMapConsumer instance represents a parsed source map which
30172 * we can query for information. It differs from BasicSourceMapConsumer in
30173 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
30174 * input.
30175 *
30176 * The only parameter is a raw source map (either as a JSON string, or already
30177 * parsed to an object). According to the spec for indexed source maps, they
30178 * have the following attributes:
30179 *
30180 * - version: Which version of the source map spec this map is following.
30181 * - file: Optional. The generated file this source map is associated with.
30182 * - sections: A list of section definitions.
30183 *
30184 * Each value under the "sections" field has two fields:
30185 * - offset: The offset into the original specified at which this section
30186 * begins to apply, defined as an object with a "line" and "column"
30187 * field.
30188 * - map: A source map definition. This source map could also be indexed,
30189 * but doesn't have to be.
30190 *
30191 * Instead of the "map" field, it's also possible to have a "url" field
30192 * specifying a URL to retrieve a source map from, but that's currently
30193 * unsupported.
30194 *
30195 * Here's an example source map, taken from the source map spec[0], but
30196 * modified to omit a section which uses the "url" field.
30197 *
30198 * {
30199 * version : 3,
30200 * file: "app.js",
30201 * sections: [{
30202 * offset: {line:100, column:10},
30203 * map: {
30204 * version : 3,
30205 * file: "section.js",
30206 * sources: ["foo.js", "bar.js"],
30207 * names: ["src", "maps", "are", "fun"],
30208 * mappings: "AAAA,E;;ABCDE;"
30209 * }
30210 * }],
30211 * }
30212 *
30213 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
30214 */
30215function IndexedSourceMapConsumer(aSourceMap) {
30216 var sourceMap = aSourceMap;
30217 if (typeof aSourceMap === 'string') {
30218 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
30219 }
30220
30221 var version = util$1.getArg(sourceMap, 'version');
30222 var sections = util$1.getArg(sourceMap, 'sections');
30223
30224 if (version != this._version) {
30225 throw new Error('Unsupported version: ' + version);
30226 }
30227
30228 this._sources = new ArraySet$2();
30229 this._names = new ArraySet$2();
30230
30231 var lastOffset = {
30232 line: -1,
30233 column: 0
30234 };
30235 this._sections = sections.map(function (s) {
30236 if (s.url) {
30237 // The url field will require support for asynchronicity.
30238 // See https://github.com/mozilla/source-map/issues/16
30239 throw new Error('Support for url field in sections not implemented.');
30240 }
30241 var offset = util$1.getArg(s, 'offset');
30242 var offsetLine = util$1.getArg(offset, 'line');
30243 var offsetColumn = util$1.getArg(offset, 'column');
30244
30245 if (offsetLine < lastOffset.line ||
30246 (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
30247 throw new Error('Section offsets must be ordered and non-overlapping.');
30248 }
30249 lastOffset = offset;
30250
30251 return {
30252 generatedOffset: {
30253 // The offset fields are 0-based, but we use 1-based indices when
30254 // encoding/decoding from VLQ.
30255 generatedLine: offsetLine + 1,
30256 generatedColumn: offsetColumn + 1
30257 },
30258 consumer: new SourceMapConsumer(util$1.getArg(s, 'map'))
30259 }
30260 });
30261}
30262
30263IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
30264IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
30265
30266/**
30267 * The version of the source mapping spec that we are consuming.
30268 */
30269IndexedSourceMapConsumer.prototype._version = 3;
30270
30271/**
30272 * The list of original sources.
30273 */
30274Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
30275 get: function () {
30276 var sources = [];
30277 for (var i = 0; i < this._sections.length; i++) {
30278 for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
30279 sources.push(this._sections[i].consumer.sources[j]);
30280 }
30281 }
30282 return sources;
30283 }
30284});
30285
30286/**
30287 * Returns the original source, line, and column information for the generated
30288 * source's line and column positions provided. The only argument is an object
30289 * with the following properties:
30290 *
30291 * - line: The line number in the generated source.
30292 * - column: The column number in the generated source.
30293 *
30294 * and an object is returned with the following properties:
30295 *
30296 * - source: The original source file, or null.
30297 * - line: The line number in the original source, or null.
30298 * - column: The column number in the original source, or null.
30299 * - name: The original identifier, or null.
30300 */
30301IndexedSourceMapConsumer.prototype.originalPositionFor =
30302 function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
30303 var needle = {
30304 generatedLine: util$1.getArg(aArgs, 'line'),
30305 generatedColumn: util$1.getArg(aArgs, 'column')
30306 };
30307
30308 // Find the section containing the generated position we're trying to map
30309 // to an original position.
30310 var sectionIndex = binarySearch.search(needle, this._sections,
30311 function(needle, section) {
30312 var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
30313 if (cmp) {
30314 return cmp;
30315 }
30316
30317 return (needle.generatedColumn -
30318 section.generatedOffset.generatedColumn);
30319 });
30320 var section = this._sections[sectionIndex];
30321
30322 if (!section) {
30323 return {
30324 source: null,
30325 line: null,
30326 column: null,
30327 name: null
30328 };
30329 }
30330
30331 return section.consumer.originalPositionFor({
30332 line: needle.generatedLine -
30333 (section.generatedOffset.generatedLine - 1),
30334 column: needle.generatedColumn -
30335 (section.generatedOffset.generatedLine === needle.generatedLine
30336 ? section.generatedOffset.generatedColumn - 1
30337 : 0),
30338 bias: aArgs.bias
30339 });
30340 };
30341
30342/**
30343 * Return true if we have the source content for every source in the source
30344 * map, false otherwise.
30345 */
30346IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
30347 function IndexedSourceMapConsumer_hasContentsOfAllSources() {
30348 return this._sections.every(function (s) {
30349 return s.consumer.hasContentsOfAllSources();
30350 });
30351 };
30352
30353/**
30354 * Returns the original source content. The only argument is the url of the
30355 * original source file. Returns null if no original source content is
30356 * available.
30357 */
30358IndexedSourceMapConsumer.prototype.sourceContentFor =
30359 function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
30360 for (var i = 0; i < this._sections.length; i++) {
30361 var section = this._sections[i];
30362
30363 var content = section.consumer.sourceContentFor(aSource, true);
30364 if (content) {
30365 return content;
30366 }
30367 }
30368 if (nullOnMissing) {
30369 return null;
30370 }
30371 else {
30372 throw new Error('"' + aSource + '" is not in the SourceMap.');
30373 }
30374 };
30375
30376/**
30377 * Returns the generated line and column information for the original source,
30378 * line, and column positions provided. The only argument is an object with
30379 * the following properties:
30380 *
30381 * - source: The filename of the original source.
30382 * - line: The line number in the original source.
30383 * - column: The column number in the original source.
30384 *
30385 * and an object is returned with the following properties:
30386 *
30387 * - line: The line number in the generated source, or null.
30388 * - column: The column number in the generated source, or null.
30389 */
30390IndexedSourceMapConsumer.prototype.generatedPositionFor =
30391 function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
30392 for (var i = 0; i < this._sections.length; i++) {
30393 var section = this._sections[i];
30394
30395 // Only consider this section if the requested source is in the list of
30396 // sources of the consumer.
30397 if (section.consumer.sources.indexOf(util$1.getArg(aArgs, 'source')) === -1) {
30398 continue;
30399 }
30400 var generatedPosition = section.consumer.generatedPositionFor(aArgs);
30401 if (generatedPosition) {
30402 var ret = {
30403 line: generatedPosition.line +
30404 (section.generatedOffset.generatedLine - 1),
30405 column: generatedPosition.column +
30406 (section.generatedOffset.generatedLine === generatedPosition.line
30407 ? section.generatedOffset.generatedColumn - 1
30408 : 0)
30409 };
30410 return ret;
30411 }
30412 }
30413
30414 return {
30415 line: null,
30416 column: null
30417 };
30418 };
30419
30420/**
30421 * Parse the mappings in a string in to a data structure which we can easily
30422 * query (the ordered arrays in the `this.__generatedMappings` and
30423 * `this.__originalMappings` properties).
30424 */
30425IndexedSourceMapConsumer.prototype._parseMappings =
30426 function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
30427 this.__generatedMappings = [];
30428 this.__originalMappings = [];
30429 for (var i = 0; i < this._sections.length; i++) {
30430 var section = this._sections[i];
30431 var sectionMappings = section.consumer._generatedMappings;
30432 for (var j = 0; j < sectionMappings.length; j++) {
30433 var mapping = sectionMappings[j];
30434
30435 var source = section.consumer._sources.at(mapping.source);
30436 if (section.consumer.sourceRoot !== null) {
30437 source = util$1.join(section.consumer.sourceRoot, source);
30438 }
30439 this._sources.add(source);
30440 source = this._sources.indexOf(source);
30441
30442 var name = section.consumer._names.at(mapping.name);
30443 this._names.add(name);
30444 name = this._names.indexOf(name);
30445
30446 // The mappings coming from the consumer for the section have
30447 // generated positions relative to the start of the section, so we
30448 // need to offset them to be relative to the start of the concatenated
30449 // generated file.
30450 var adjustedMapping = {
30451 source: source,
30452 generatedLine: mapping.generatedLine +
30453 (section.generatedOffset.generatedLine - 1),
30454 generatedColumn: mapping.generatedColumn +
30455 (section.generatedOffset.generatedLine === mapping.generatedLine
30456 ? section.generatedOffset.generatedColumn - 1
30457 : 0),
30458 originalLine: mapping.originalLine,
30459 originalColumn: mapping.originalColumn,
30460 name: name
30461 };
30462
30463 this.__generatedMappings.push(adjustedMapping);
30464 if (typeof adjustedMapping.originalLine === 'number') {
30465 this.__originalMappings.push(adjustedMapping);
30466 }
30467 }
30468 }
30469
30470 quickSort$1(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
30471 quickSort$1(this.__originalMappings, util$1.compareByOriginalPositions);
30472 };
30473
30474var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
30475
30476var sourceMapConsumer = {
30477 SourceMapConsumer: SourceMapConsumer_1,
30478 BasicSourceMapConsumer: BasicSourceMapConsumer_1,
30479 IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
30480};
30481
30482/* -*- Mode: js; js-indent-level: 2; -*- */
30483/*
30484 * Copyright 2011 Mozilla Foundation and contributors
30485 * Licensed under the New BSD license. See LICENSE or:
30486 * http://opensource.org/licenses/BSD-3-Clause
30487 */
30488
30489var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
30490
30491
30492// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
30493// operating systems these days (capturing the result).
30494var REGEX_NEWLINE = /(\r?\n)/;
30495
30496// Newline character code for charCodeAt() comparisons
30497var NEWLINE_CODE = 10;
30498
30499// Private symbol for identifying `SourceNode`s when multiple versions of
30500// the source-map library are loaded. This MUST NOT CHANGE across
30501// versions!
30502var isSourceNode = "$$$isSourceNode$$$";
30503
30504/**
30505 * SourceNodes provide a way to abstract over interpolating/concatenating
30506 * snippets of generated JavaScript source code while maintaining the line and
30507 * column information associated with the original source code.
30508 *
30509 * @param aLine The original line number.
30510 * @param aColumn The original column number.
30511 * @param aSource The original source's filename.
30512 * @param aChunks Optional. An array of strings which are snippets of
30513 * generated JS, or other SourceNodes.
30514 * @param aName The original identifier.
30515 */
30516function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
30517 this.children = [];
30518 this.sourceContents = {};
30519 this.line = aLine == null ? null : aLine;
30520 this.column = aColumn == null ? null : aColumn;
30521 this.source = aSource == null ? null : aSource;
30522 this.name = aName == null ? null : aName;
30523 this[isSourceNode] = true;
30524 if (aChunks != null) this.add(aChunks);
30525}
30526
30527/**
30528 * Creates a SourceNode from generated code and a SourceMapConsumer.
30529 *
30530 * @param aGeneratedCode The generated code
30531 * @param aSourceMapConsumer The SourceMap for the generated code
30532 * @param aRelativePath Optional. The path that relative sources in the
30533 * SourceMapConsumer should be relative to.
30534 */
30535SourceNode.fromStringWithSourceMap =
30536 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
30537 // The SourceNode we want to fill with the generated code
30538 // and the SourceMap
30539 var node = new SourceNode();
30540
30541 // All even indices of this array are one line of the generated code,
30542 // while all odd indices are the newlines between two adjacent lines
30543 // (since `REGEX_NEWLINE` captures its match).
30544 // Processed fragments are accessed by calling `shiftNextLine`.
30545 var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
30546 var remainingLinesIndex = 0;
30547 var shiftNextLine = function() {
30548 var lineContents = getNextLine();
30549 // The last line of a file might not have a newline.
30550 var newLine = getNextLine() || "";
30551 return lineContents + newLine;
30552
30553 function getNextLine() {
30554 return remainingLinesIndex < remainingLines.length ?
30555 remainingLines[remainingLinesIndex++] : undefined;
30556 }
30557 };
30558
30559 // We need to remember the position of "remainingLines"
30560 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
30561
30562 // The generate SourceNodes we need a code range.
30563 // To extract it current and last mapping is used.
30564 // Here we store the last mapping.
30565 var lastMapping = null;
30566
30567 aSourceMapConsumer.eachMapping(function (mapping) {
30568 if (lastMapping !== null) {
30569 // We add the code from "lastMapping" to "mapping":
30570 // First check if there is a new line in between.
30571 if (lastGeneratedLine < mapping.generatedLine) {
30572 // Associate first line with "lastMapping"
30573 addMappingWithCode(lastMapping, shiftNextLine());
30574 lastGeneratedLine++;
30575 lastGeneratedColumn = 0;
30576 // The remaining code is added without mapping
30577 } else {
30578 // There is no new line in between.
30579 // Associate the code between "lastGeneratedColumn" and
30580 // "mapping.generatedColumn" with "lastMapping"
30581 var nextLine = remainingLines[remainingLinesIndex];
30582 var code = nextLine.substr(0, mapping.generatedColumn -
30583 lastGeneratedColumn);
30584 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
30585 lastGeneratedColumn);
30586 lastGeneratedColumn = mapping.generatedColumn;
30587 addMappingWithCode(lastMapping, code);
30588 // No more remaining code, continue
30589 lastMapping = mapping;
30590 return;
30591 }
30592 }
30593 // We add the generated code until the first mapping
30594 // to the SourceNode without any mapping.
30595 // Each line is added as separate string.
30596 while (lastGeneratedLine < mapping.generatedLine) {
30597 node.add(shiftNextLine());
30598 lastGeneratedLine++;
30599 }
30600 if (lastGeneratedColumn < mapping.generatedColumn) {
30601 var nextLine = remainingLines[remainingLinesIndex];
30602 node.add(nextLine.substr(0, mapping.generatedColumn));
30603 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
30604 lastGeneratedColumn = mapping.generatedColumn;
30605 }
30606 lastMapping = mapping;
30607 }, this);
30608 // We have processed all mappings.
30609 if (remainingLinesIndex < remainingLines.length) {
30610 if (lastMapping) {
30611 // Associate the remaining code in the current line with "lastMapping"
30612 addMappingWithCode(lastMapping, shiftNextLine());
30613 }
30614 // and add the remaining lines without any mapping
30615 node.add(remainingLines.splice(remainingLinesIndex).join(""));
30616 }
30617
30618 // Copy sourcesContent into SourceNode
30619 aSourceMapConsumer.sources.forEach(function (sourceFile) {
30620 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
30621 if (content != null) {
30622 if (aRelativePath != null) {
30623 sourceFile = util$1.join(aRelativePath, sourceFile);
30624 }
30625 node.setSourceContent(sourceFile, content);
30626 }
30627 });
30628
30629 return node;
30630
30631 function addMappingWithCode(mapping, code) {
30632 if (mapping === null || mapping.source === undefined) {
30633 node.add(code);
30634 } else {
30635 var source = aRelativePath
30636 ? util$1.join(aRelativePath, mapping.source)
30637 : mapping.source;
30638 node.add(new SourceNode(mapping.originalLine,
30639 mapping.originalColumn,
30640 source,
30641 code,
30642 mapping.name));
30643 }
30644 }
30645 };
30646
30647/**
30648 * Add a chunk of generated JS to this source node.
30649 *
30650 * @param aChunk A string snippet of generated JS code, another instance of
30651 * SourceNode, or an array where each member is one of those things.
30652 */
30653SourceNode.prototype.add = function SourceNode_add(aChunk) {
30654 if (Array.isArray(aChunk)) {
30655 aChunk.forEach(function (chunk) {
30656 this.add(chunk);
30657 }, this);
30658 }
30659 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
30660 if (aChunk) {
30661 this.children.push(aChunk);
30662 }
30663 }
30664 else {
30665 throw new TypeError(
30666 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
30667 );
30668 }
30669 return this;
30670};
30671
30672/**
30673 * Add a chunk of generated JS to the beginning of this source node.
30674 *
30675 * @param aChunk A string snippet of generated JS code, another instance of
30676 * SourceNode, or an array where each member is one of those things.
30677 */
30678SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
30679 if (Array.isArray(aChunk)) {
30680 for (var i = aChunk.length-1; i >= 0; i--) {
30681 this.prepend(aChunk[i]);
30682 }
30683 }
30684 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
30685 this.children.unshift(aChunk);
30686 }
30687 else {
30688 throw new TypeError(
30689 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
30690 );
30691 }
30692 return this;
30693};
30694
30695/**
30696 * Walk over the tree of JS snippets in this node and its children. The
30697 * walking function is called once for each snippet of JS and is passed that
30698 * snippet and the its original associated source's line/column location.
30699 *
30700 * @param aFn The traversal function.
30701 */
30702SourceNode.prototype.walk = function SourceNode_walk(aFn) {
30703 var chunk;
30704 for (var i = 0, len = this.children.length; i < len; i++) {
30705 chunk = this.children[i];
30706 if (chunk[isSourceNode]) {
30707 chunk.walk(aFn);
30708 }
30709 else {
30710 if (chunk !== '') {
30711 aFn(chunk, { source: this.source,
30712 line: this.line,
30713 column: this.column,
30714 name: this.name });
30715 }
30716 }
30717 }
30718};
30719
30720/**
30721 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
30722 * each of `this.children`.
30723 *
30724 * @param aSep The separator.
30725 */
30726SourceNode.prototype.join = function SourceNode_join(aSep) {
30727 var newChildren;
30728 var i;
30729 var len = this.children.length;
30730 if (len > 0) {
30731 newChildren = [];
30732 for (i = 0; i < len-1; i++) {
30733 newChildren.push(this.children[i]);
30734 newChildren.push(aSep);
30735 }
30736 newChildren.push(this.children[i]);
30737 this.children = newChildren;
30738 }
30739 return this;
30740};
30741
30742/**
30743 * Call String.prototype.replace on the very right-most source snippet. Useful
30744 * for trimming whitespace from the end of a source node, etc.
30745 *
30746 * @param aPattern The pattern to replace.
30747 * @param aReplacement The thing to replace the pattern with.
30748 */
30749SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
30750 var lastChild = this.children[this.children.length - 1];
30751 if (lastChild[isSourceNode]) {
30752 lastChild.replaceRight(aPattern, aReplacement);
30753 }
30754 else if (typeof lastChild === 'string') {
30755 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
30756 }
30757 else {
30758 this.children.push(''.replace(aPattern, aReplacement));
30759 }
30760 return this;
30761};
30762
30763/**
30764 * Set the source content for a source file. This will be added to the SourceMapGenerator
30765 * in the sourcesContent field.
30766 *
30767 * @param aSourceFile The filename of the source file
30768 * @param aSourceContent The content of the source file
30769 */
30770SourceNode.prototype.setSourceContent =
30771 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
30772 this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
30773 };
30774
30775/**
30776 * Walk over the tree of SourceNodes. The walking function is called for each
30777 * source file content and is passed the filename and source content.
30778 *
30779 * @param aFn The traversal function.
30780 */
30781SourceNode.prototype.walkSourceContents =
30782 function SourceNode_walkSourceContents(aFn) {
30783 for (var i = 0, len = this.children.length; i < len; i++) {
30784 if (this.children[i][isSourceNode]) {
30785 this.children[i].walkSourceContents(aFn);
30786 }
30787 }
30788
30789 var sources = Object.keys(this.sourceContents);
30790 for (var i = 0, len = sources.length; i < len; i++) {
30791 aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
30792 }
30793 };
30794
30795/**
30796 * Return the string representation of this source node. Walks over the tree
30797 * and concatenates all the various snippets together to one string.
30798 */
30799SourceNode.prototype.toString = function SourceNode_toString() {
30800 var str = "";
30801 this.walk(function (chunk) {
30802 str += chunk;
30803 });
30804 return str;
30805};
30806
30807/**
30808 * Returns the string representation of this source node along with a source
30809 * map.
30810 */
30811SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
30812 var generated = {
30813 code: "",
30814 line: 1,
30815 column: 0
30816 };
30817 var map = new SourceMapGenerator$1(aArgs);
30818 var sourceMappingActive = false;
30819 var lastOriginalSource = null;
30820 var lastOriginalLine = null;
30821 var lastOriginalColumn = null;
30822 var lastOriginalName = null;
30823 this.walk(function (chunk, original) {
30824 generated.code += chunk;
30825 if (original.source !== null
30826 && original.line !== null
30827 && original.column !== null) {
30828 if(lastOriginalSource !== original.source
30829 || lastOriginalLine !== original.line
30830 || lastOriginalColumn !== original.column
30831 || lastOriginalName !== original.name) {
30832 map.addMapping({
30833 source: original.source,
30834 original: {
30835 line: original.line,
30836 column: original.column
30837 },
30838 generated: {
30839 line: generated.line,
30840 column: generated.column
30841 },
30842 name: original.name
30843 });
30844 }
30845 lastOriginalSource = original.source;
30846 lastOriginalLine = original.line;
30847 lastOriginalColumn = original.column;
30848 lastOriginalName = original.name;
30849 sourceMappingActive = true;
30850 } else if (sourceMappingActive) {
30851 map.addMapping({
30852 generated: {
30853 line: generated.line,
30854 column: generated.column
30855 }
30856 });
30857 lastOriginalSource = null;
30858 sourceMappingActive = false;
30859 }
30860 for (var idx = 0, length = chunk.length; idx < length; idx++) {
30861 if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
30862 generated.line++;
30863 generated.column = 0;
30864 // Mappings end at eol
30865 if (idx + 1 === length) {
30866 lastOriginalSource = null;
30867 sourceMappingActive = false;
30868 } else if (sourceMappingActive) {
30869 map.addMapping({
30870 source: original.source,
30871 original: {
30872 line: original.line,
30873 column: original.column
30874 },
30875 generated: {
30876 line: generated.line,
30877 column: generated.column
30878 },
30879 name: original.name
30880 });
30881 }
30882 } else {
30883 generated.column++;
30884 }
30885 }
30886 });
30887 this.walkSourceContents(function (sourceFile, sourceContent) {
30888 map.setSourceContent(sourceFile, sourceContent);
30889 });
30890
30891 return { code: generated.code, map: map };
30892};
30893
30894var SourceNode_1 = SourceNode;
30895
30896var sourceNode = {
30897 SourceNode: SourceNode_1
30898};
30899
30900/*
30901 * Copyright 2009-2011 Mozilla Foundation and contributors
30902 * Licensed under the New BSD license. See LICENSE.txt or:
30903 * http://opensource.org/licenses/BSD-3-Clause
30904 */
30905var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
30906var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
30907var SourceNode$1 = sourceNode.SourceNode;
30908
30909var sourceMap = {
30910 SourceMapGenerator: SourceMapGenerator$2,
30911 SourceMapConsumer: SourceMapConsumer$1,
30912 SourceNode: SourceNode$1
30913};
30914
30915var sourceMapUrl = createCommonjsModule(function (module, exports) {
30916// Copyright 2014 Simon Lydell
30917// X11 (“MIT”) Licensed. (See LICENSE.)
30918
30919void (function(root, factory) {
30920 {
30921 module.exports = factory();
30922 }
30923}(commonjsGlobal, function() {
30924
30925 var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/;
30926
30927 var regex = RegExp(
30928 "(?:" +
30929 "/\\*" +
30930 "(?:\\s*\r?\n(?://)?)?" +
30931 "(?:" + innerRegex.source + ")" +
30932 "\\s*" +
30933 "\\*/" +
30934 "|" +
30935 "//(?:" + innerRegex.source + ")" +
30936 ")" +
30937 "\\s*"
30938 );
30939
30940 return {
30941
30942 regex: regex,
30943 _innerRegex: innerRegex,
30944
30945 getFrom: function(code) {
30946 var match = code.match(regex);
30947 return (match ? match[1] || match[2] || "" : null)
30948 },
30949
30950 existsIn: function(code) {
30951 return regex.test(code)
30952 },
30953
30954 removeFrom: function(code) {
30955 return code.replace(regex, "")
30956 },
30957
30958 insertBefore: function(code, string) {
30959 var match = code.match(regex);
30960 if (match) {
30961 return code.slice(0, match.index) + string + code.slice(match.index)
30962 } else {
30963 return code + string
30964 }
30965 }
30966 }
30967
30968}));
30969});
30970
30971// Copyright 2014 Simon Lydell
30972// X11 (“MIT”) Licensed. (See LICENSE.)
30973
30974
30975
30976function resolveUrl(/* ...urls */) {
30977 return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) {
30978 return url.resolve(resolved, nextUrl)
30979 })
30980}
30981
30982var resolveUrl_1 = resolveUrl;
30983
30984var token = '%[a-f0-9]{2}';
30985var singleMatcher = new RegExp(token, 'gi');
30986var multiMatcher = new RegExp('(' + token + ')+', 'gi');
30987
30988function decodeComponents(components, split) {
30989 try {
30990 // Try to decode the entire string first
30991 return decodeURIComponent(components.join(''));
30992 } catch (err) {
30993 // Do nothing
30994 }
30995
30996 if (components.length === 1) {
30997 return components;
30998 }
30999
31000 split = split || 1;
31001
31002 // Split the array in 2 parts
31003 var left = components.slice(0, split);
31004 var right = components.slice(split);
31005
31006 return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
31007}
31008
31009function decode$3(input) {
31010 try {
31011 return decodeURIComponent(input);
31012 } catch (err) {
31013 var tokens = input.match(singleMatcher);
31014
31015 for (var i = 1; i < tokens.length; i++) {
31016 input = decodeComponents(tokens, i).join('');
31017
31018 tokens = input.match(singleMatcher);
31019 }
31020
31021 return input;
31022 }
31023}
31024
31025function customDecodeURIComponent(input) {
31026 // Keep track of all the replacements and prefill the map with the `BOM`
31027 var replaceMap = {
31028 '%FE%FF': '\uFFFD\uFFFD',
31029 '%FF%FE': '\uFFFD\uFFFD'
31030 };
31031
31032 var match = multiMatcher.exec(input);
31033 while (match) {
31034 try {
31035 // Decode as big chunks as possible
31036 replaceMap[match[0]] = decodeURIComponent(match[0]);
31037 } catch (err) {
31038 var result = decode$3(match[0]);
31039
31040 if (result !== match[0]) {
31041 replaceMap[match[0]] = result;
31042 }
31043 }
31044
31045 match = multiMatcher.exec(input);
31046 }
31047
31048 // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
31049 replaceMap['%C2'] = '\uFFFD';
31050
31051 var entries = Object.keys(replaceMap);
31052
31053 for (var i = 0; i < entries.length; i++) {
31054 // Replace all decoded components
31055 var key = entries[i];
31056 input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
31057 }
31058
31059 return input;
31060}
31061
31062var decodeUriComponent = function (encodedURI) {
31063 if (typeof encodedURI !== 'string') {
31064 throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
31065 }
31066
31067 try {
31068 encodedURI = encodedURI.replace(/\+/g, ' ');
31069
31070 // Try the built in decoder first
31071 return decodeURIComponent(encodedURI);
31072 } catch (err) {
31073 // Fallback to a more advanced decoder
31074 return customDecodeURIComponent(encodedURI);
31075 }
31076};
31077
31078// Copyright 2017 Simon Lydell
31079// X11 (“MIT”) Licensed. (See LICENSE.)
31080
31081
31082
31083function customDecodeUriComponent(string) {
31084 // `decodeUriComponent` turns `+` into ` `, but that's not wanted.
31085 return decodeUriComponent(string.replace(/\+/g, "%2B"))
31086}
31087
31088var decodeUriComponent_1 = customDecodeUriComponent;
31089
31090function urix(aPath) {
31091 if (path.sep === "\\") {
31092 return aPath
31093 .replace(/\\/g, "/")
31094 .replace(/^[a-z]:\/?/i, "/")
31095 }
31096 return aPath
31097}
31098
31099var urix_1 = urix;
31100
31101function atob(str) {
31102 return Buffer.from(str, 'base64').toString('binary');
31103}
31104
31105var nodeAtob = atob.atob = atob;
31106
31107// Copyright 2014, 2015, 2016, 2017 Simon Lydell
31108// X11 (“MIT”) Licensed. (See LICENSE.)
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118function callbackAsync(callback, error, result) {
31119 setImmediate(function() { callback(error, result); });
31120}
31121
31122function parseMapToJSON(string, data) {
31123 try {
31124 return JSON.parse(string.replace(/^\)\]\}'/, ""))
31125 } catch (error) {
31126 error.sourceMapData = data;
31127 throw error
31128 }
31129}
31130
31131function readSync(read, url, data) {
31132 var readUrl = decodeUriComponent_1(url);
31133 try {
31134 return String(read(readUrl))
31135 } catch (error) {
31136 error.sourceMapData = data;
31137 throw error
31138 }
31139}
31140
31141
31142
31143function resolveSourceMap(code, codeUrl, read, callback) {
31144 var mapData;
31145 try {
31146 mapData = resolveSourceMapHelper(code, codeUrl);
31147 } catch (error) {
31148 return callbackAsync(callback, error)
31149 }
31150 if (!mapData || mapData.map) {
31151 return callbackAsync(callback, null, mapData)
31152 }
31153 var readUrl = decodeUriComponent_1(mapData.url);
31154 read(readUrl, function(error, result) {
31155 if (error) {
31156 error.sourceMapData = mapData;
31157 return callback(error)
31158 }
31159 mapData.map = String(result);
31160 try {
31161 mapData.map = parseMapToJSON(mapData.map, mapData);
31162 } catch (error) {
31163 return callback(error)
31164 }
31165 callback(null, mapData);
31166 });
31167}
31168
31169function resolveSourceMapSync(code, codeUrl, read) {
31170 var mapData = resolveSourceMapHelper(code, codeUrl);
31171 if (!mapData || mapData.map) {
31172 return mapData
31173 }
31174 mapData.map = readSync(read, mapData.url, mapData);
31175 mapData.map = parseMapToJSON(mapData.map, mapData);
31176 return mapData
31177}
31178
31179var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/;
31180var jsonMimeTypeRegex = /^(?:application|text)\/json$/;
31181
31182function resolveSourceMapHelper(code, codeUrl) {
31183 codeUrl = urix_1(codeUrl);
31184
31185 var url = sourceMapUrl.getFrom(code);
31186 if (!url) {
31187 return null
31188 }
31189
31190 var dataUri = url.match(dataUriRegex);
31191 if (dataUri) {
31192 var mimeType = dataUri[1];
31193 var lastParameter = dataUri[2] || "";
31194 var encoded = dataUri[3] || "";
31195 var data = {
31196 sourceMappingURL: url,
31197 url: null,
31198 sourcesRelativeTo: codeUrl,
31199 map: encoded
31200 };
31201 if (!jsonMimeTypeRegex.test(mimeType)) {
31202 var error = new Error("Unuseful data uri mime type: " + (mimeType || "text/plain"));
31203 error.sourceMapData = data;
31204 throw error
31205 }
31206 data.map = parseMapToJSON(
31207 lastParameter === ";base64" ? nodeAtob(encoded) : decodeURIComponent(encoded),
31208 data
31209 );
31210 return data
31211 }
31212
31213 var mapUrl = resolveUrl_1(codeUrl, url);
31214 return {
31215 sourceMappingURL: url,
31216 url: mapUrl,
31217 sourcesRelativeTo: mapUrl,
31218 map: null
31219 }
31220}
31221
31222
31223
31224function resolveSources(map, mapUrl, read, options, callback) {
31225 if (typeof options === "function") {
31226 callback = options;
31227 options = {};
31228 }
31229 var pending = map.sources ? map.sources.length : 0;
31230 var result = {
31231 sourcesResolved: [],
31232 sourcesContent: []
31233 };
31234
31235 if (pending === 0) {
31236 callbackAsync(callback, null, result);
31237 return
31238 }
31239
31240 var done = function() {
31241 pending--;
31242 if (pending === 0) {
31243 callback(null, result);
31244 }
31245 };
31246
31247 resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {
31248 result.sourcesResolved[index] = fullUrl;
31249 if (typeof sourceContent === "string") {
31250 result.sourcesContent[index] = sourceContent;
31251 callbackAsync(done, null);
31252 } else {
31253 var readUrl = decodeUriComponent_1(fullUrl);
31254 read(readUrl, function(error, source) {
31255 result.sourcesContent[index] = error ? error : String(source);
31256 done();
31257 });
31258 }
31259 });
31260}
31261
31262function resolveSourcesSync(map, mapUrl, read, options) {
31263 var result = {
31264 sourcesResolved: [],
31265 sourcesContent: []
31266 };
31267
31268 if (!map.sources || map.sources.length === 0) {
31269 return result
31270 }
31271
31272 resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {
31273 result.sourcesResolved[index] = fullUrl;
31274 if (read !== null) {
31275 if (typeof sourceContent === "string") {
31276 result.sourcesContent[index] = sourceContent;
31277 } else {
31278 var readUrl = decodeUriComponent_1(fullUrl);
31279 try {
31280 result.sourcesContent[index] = String(read(readUrl));
31281 } catch (error) {
31282 result.sourcesContent[index] = error;
31283 }
31284 }
31285 }
31286 });
31287
31288 return result
31289}
31290
31291var endingSlash = /\/?$/;
31292
31293function resolveSourcesHelper(map, mapUrl, options, fn) {
31294 options = options || {};
31295 mapUrl = urix_1(mapUrl);
31296 var fullUrl;
31297 var sourceContent;
31298 var sourceRoot;
31299 for (var index = 0, len = map.sources.length; index < len; index++) {
31300 sourceRoot = null;
31301 if (typeof options.sourceRoot === "string") {
31302 sourceRoot = options.sourceRoot;
31303 } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) {
31304 sourceRoot = map.sourceRoot;
31305 }
31306 // If the sourceRoot is the empty string, it is equivalent to not setting
31307 // the property at all.
31308 if (sourceRoot === null || sourceRoot === '') {
31309 fullUrl = resolveUrl_1(mapUrl, map.sources[index]);
31310 } else {
31311 // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes
31312 // `/scripts/subdir/<source>`, not `/scripts/<source>`. Pointing to a file as source root
31313 // does not make sense.
31314 fullUrl = resolveUrl_1(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]);
31315 }
31316 sourceContent = (map.sourcesContent || [])[index];
31317 fn(fullUrl, sourceContent, index);
31318 }
31319}
31320
31321
31322
31323function resolve(code, codeUrl, read, options, callback) {
31324 if (typeof options === "function") {
31325 callback = options;
31326 options = {};
31327 }
31328 if (code === null) {
31329 var mapUrl = codeUrl;
31330 var data = {
31331 sourceMappingURL: null,
31332 url: mapUrl,
31333 sourcesRelativeTo: mapUrl,
31334 map: null
31335 };
31336 var readUrl = decodeUriComponent_1(mapUrl);
31337 read(readUrl, function(error, result) {
31338 if (error) {
31339 error.sourceMapData = data;
31340 return callback(error)
31341 }
31342 data.map = String(result);
31343 try {
31344 data.map = parseMapToJSON(data.map, data);
31345 } catch (error) {
31346 return callback(error)
31347 }
31348 _resolveSources(data);
31349 });
31350 } else {
31351 resolveSourceMap(code, codeUrl, read, function(error, mapData) {
31352 if (error) {
31353 return callback(error)
31354 }
31355 if (!mapData) {
31356 return callback(null, null)
31357 }
31358 _resolveSources(mapData);
31359 });
31360 }
31361
31362 function _resolveSources(mapData) {
31363 resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) {
31364 if (error) {
31365 return callback(error)
31366 }
31367 mapData.sourcesResolved = result.sourcesResolved;
31368 mapData.sourcesContent = result.sourcesContent;
31369 callback(null, mapData);
31370 });
31371 }
31372}
31373
31374function resolveSync(code, codeUrl, read, options) {
31375 var mapData;
31376 if (code === null) {
31377 var mapUrl = codeUrl;
31378 mapData = {
31379 sourceMappingURL: null,
31380 url: mapUrl,
31381 sourcesRelativeTo: mapUrl,
31382 map: null
31383 };
31384 mapData.map = readSync(read, mapUrl, mapData);
31385 mapData.map = parseMapToJSON(mapData.map, mapData);
31386 } else {
31387 mapData = resolveSourceMapSync(code, codeUrl, read);
31388 if (!mapData) {
31389 return null
31390 }
31391 }
31392 var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options);
31393 mapData.sourcesResolved = result.sourcesResolved;
31394 mapData.sourcesContent = result.sourcesContent;
31395 return mapData
31396}
31397
31398
31399
31400var sourceMapResolveNode = {
31401 resolveSourceMap: resolveSourceMap,
31402 resolveSourceMapSync: resolveSourceMapSync,
31403 resolveSources: resolveSources,
31404 resolveSourcesSync: resolveSourcesSync,
31405 resolve: resolve,
31406 resolveSync: resolveSync,
31407 parseMapToJSON: parseMapToJSON
31408};
31409
31410/**
31411 * Module dependencies
31412 */
31413
31414var extend$1 = extendShallow$5;
31415var SourceMap$1 = sourceMap;
31416var sourceMapResolve = sourceMapResolveNode;
31417
31418/**
31419 * Convert backslash in the given string to forward slashes
31420 */
31421
31422var unixify = function(fp) {
31423 return fp.split(/\\+/).join('/');
31424};
31425
31426/**
31427 * Return true if `val` is a non-empty string
31428 *
31429 * @param {String} `str`
31430 * @return {Boolean}
31431 */
31432
31433var isString$1 = function(str) {
31434 return str && typeof str === 'string';
31435};
31436
31437/**
31438 * Cast `val` to an array
31439 * @return {Array}
31440 */
31441
31442var arrayify$3 = function(val) {
31443 if (typeof val === 'string') return [val];
31444 return val ? (Array.isArray(val) ? val : [val]) : [];
31445};
31446
31447/**
31448 * Get the last `n` element from the given `array`
31449 * @param {Array} `array`
31450 * @return {*}
31451 */
31452
31453var last = function(arr, n) {
31454 return arr[arr.length - (n || 1)];
31455};
31456
31457var utils$1 = {
31458 extend: extend$1,
31459 SourceMap: SourceMap$1,
31460 sourceMapResolve: sourceMapResolve,
31461 unixify: unixify,
31462 isString: isString$1,
31463 arrayify: arrayify$3,
31464 last: last
31465};
31466
31467var sourceMaps = createCommonjsModule(function (module, exports) {
31468
31469
31470
31471
31472
31473
31474/**
31475 * Expose `mixin()`.
31476 * This code is based on `source-maps-support.js` in reworkcss/css
31477 * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js
31478 * Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>
31479 */
31480
31481module.exports = mixin;
31482
31483/**
31484 * Mixin source map support into `compiler`.
31485 *
31486 * @param {Object} `compiler`
31487 * @api public
31488 */
31489
31490function mixin(compiler) {
31491 defineProperty$6(compiler, '_comment', compiler.comment);
31492 compiler.map = new utils$1.SourceMap.SourceMapGenerator();
31493 compiler.position = { line: 1, column: 1 };
31494 compiler.content = {};
31495 compiler.files = {};
31496
31497 for (var key in exports) {
31498 defineProperty$6(compiler, key, exports[key]);
31499 }
31500}
31501
31502/**
31503 * Update position.
31504 *
31505 * @param {String} str
31506 */
31507
31508exports.updatePosition = function(str) {
31509 var lines = str.match(/\n/g);
31510 if (lines) this.position.line += lines.length;
31511 var i = str.lastIndexOf('\n');
31512 this.position.column = ~i ? str.length - i : this.position.column + str.length;
31513};
31514
31515/**
31516 * Emit `str` with `position`.
31517 *
31518 * @param {String} str
31519 * @param {Object} [pos]
31520 * @return {String}
31521 */
31522
31523exports.emit = function(str, node) {
31524 var position = node.position || {};
31525 var source = position.source;
31526 if (source) {
31527 if (position.filepath) {
31528 source = utils$1.unixify(position.filepath);
31529 }
31530
31531 this.map.addMapping({
31532 source: source,
31533 generated: {
31534 line: this.position.line,
31535 column: Math.max(this.position.column - 1, 0)
31536 },
31537 original: {
31538 line: position.start.line,
31539 column: position.start.column - 1
31540 }
31541 });
31542
31543 if (position.content) {
31544 this.addContent(source, position);
31545 }
31546 if (position.filepath) {
31547 this.addFile(source, position);
31548 }
31549
31550 this.updatePosition(str);
31551 this.output += str;
31552 }
31553 return str;
31554};
31555
31556/**
31557 * Adds a file to the source map output if it has not already been added
31558 * @param {String} `file`
31559 * @param {Object} `pos`
31560 */
31561
31562exports.addFile = function(file, position) {
31563 if (typeof position.content !== 'string') return;
31564 if (Object.prototype.hasOwnProperty.call(this.files, file)) return;
31565 this.files[file] = position.content;
31566};
31567
31568/**
31569 * Adds a content source to the source map output if it has not already been added
31570 * @param {String} `source`
31571 * @param {Object} `position`
31572 */
31573
31574exports.addContent = function(source, position) {
31575 if (typeof position.content !== 'string') return;
31576 if (Object.prototype.hasOwnProperty.call(this.content, source)) return;
31577 this.map.setSourceContent(source, position.content);
31578};
31579
31580/**
31581 * Applies any original source maps to the output and embeds the source file
31582 * contents in the source map.
31583 */
31584
31585exports.applySourceMaps = function() {
31586 Object.keys(this.files).forEach(function(file) {
31587 var content = this.files[file];
31588 this.map.setSourceContent(file, content);
31589
31590 if (this.options.inputSourcemaps === true) {
31591 var originalMap = utils$1.sourceMapResolve.resolveSync(content, file, fs__default.readFileSync);
31592 if (originalMap) {
31593 var map = new utils$1.SourceMap.SourceMapConsumer(originalMap.map);
31594 var relativeTo = originalMap.sourcesRelativeTo;
31595 this.map.applySourceMap(map, file, utils$1.unixify(path.dirname(relativeTo)));
31596 }
31597 }
31598 }, this);
31599};
31600
31601/**
31602 * Process comments, drops sourceMap comments.
31603 * @param {Object} node
31604 */
31605
31606exports.comment = function(node) {
31607 if (/^# sourceMappingURL=/.test(node.comment)) {
31608 return this.emit('', node.position);
31609 }
31610 return this._comment(node);
31611};
31612});
31613
31614var debug$1 = src('snapdragon:compiler');
31615
31616
31617/**
31618 * Create a new `Compiler` with the given `options`.
31619 * @param {Object} `options`
31620 */
31621
31622function Compiler(options, state) {
31623 debug$1('initializing', __filename);
31624 this.options = utils$1.extend({source: 'string'}, options);
31625 this.state = state || {};
31626 this.compilers = {};
31627 this.output = '';
31628 this.set('eos', function(node) {
31629 return this.emit(node.val, node);
31630 });
31631 this.set('noop', function(node) {
31632 return this.emit(node.val, node);
31633 });
31634 this.set('bos', function(node) {
31635 return this.emit(node.val, node);
31636 });
31637 use(this);
31638}
31639
31640/**
31641 * Prototype methods
31642 */
31643
31644Compiler.prototype = {
31645
31646 /**
31647 * Throw an error message with details including the cursor position.
31648 * @param {String} `msg` Message to use in the Error.
31649 */
31650
31651 error: function(msg, node) {
31652 var pos = node.position || {start: {column: 0}};
31653 var message = this.options.source + ' column:' + pos.start.column + ': ' + msg;
31654
31655 var err = new Error(message);
31656 err.reason = msg;
31657 err.column = pos.start.column;
31658 err.source = this.pattern;
31659
31660 if (this.options.silent) {
31661 this.errors.push(err);
31662 } else {
31663 throw err;
31664 }
31665 },
31666
31667 /**
31668 * Define a non-enumberable property on the `Compiler` instance.
31669 *
31670 * ```js
31671 * compiler.define('foo', 'bar');
31672 * ```
31673 * @name .define
31674 * @param {String} `key` propery name
31675 * @param {any} `val` property value
31676 * @return {Object} Returns the Compiler instance for chaining.
31677 * @api public
31678 */
31679
31680 define: function(key, val) {
31681 defineProperty$6(this, key, val);
31682 return this;
31683 },
31684
31685 /**
31686 * Emit `node.val`
31687 */
31688
31689 emit: function(str, node) {
31690 this.output += str;
31691 return str;
31692 },
31693
31694 /**
31695 * Add a compiler `fn` with the given `name`
31696 */
31697
31698 set: function(name, fn) {
31699 this.compilers[name] = fn;
31700 return this;
31701 },
31702
31703 /**
31704 * Get compiler `name`.
31705 */
31706
31707 get: function(name) {
31708 return this.compilers[name];
31709 },
31710
31711 /**
31712 * Get the previous AST node.
31713 */
31714
31715 prev: function(n) {
31716 return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' };
31717 },
31718
31719 /**
31720 * Get the next AST node.
31721 */
31722
31723 next: function(n) {
31724 return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' };
31725 },
31726
31727 /**
31728 * Visit `node`.
31729 */
31730
31731 visit: function(node, nodes, i) {
31732 var fn = this.compilers[node.type];
31733 this.idx = i;
31734
31735 if (typeof fn !== 'function') {
31736 throw this.error('compiler "' + node.type + '" is not registered', node);
31737 }
31738 return fn.call(this, node, nodes, i);
31739 },
31740
31741 /**
31742 * Map visit over array of `nodes`.
31743 */
31744
31745 mapVisit: function(nodes) {
31746 if (!Array.isArray(nodes)) {
31747 throw new TypeError('expected an array');
31748 }
31749 var len = nodes.length;
31750 var idx = -1;
31751 while (++idx < len) {
31752 this.visit(nodes[idx], nodes, idx);
31753 }
31754 return this;
31755 },
31756
31757 /**
31758 * Compile `ast`.
31759 */
31760
31761 compile: function(ast, options) {
31762 var opts = utils$1.extend({}, this.options, options);
31763 this.ast = ast;
31764 this.parsingErrors = this.ast.errors;
31765 this.output = '';
31766
31767 // source map support
31768 if (opts.sourcemap) {
31769 var sourcemaps = sourceMaps;
31770 sourcemaps(this);
31771 this.mapVisit(this.ast.nodes);
31772 this.applySourceMaps();
31773 this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON();
31774 return this;
31775 }
31776
31777 this.mapVisit(this.ast.nodes);
31778 return this;
31779 }
31780};
31781
31782/**
31783 * Expose `Compiler`
31784 */
31785
31786var compiler = Compiler;
31787
31788/*!
31789 * map-cache <https://github.com/jonschlinkert/map-cache>
31790 *
31791 * Copyright (c) 2015, Jon Schlinkert.
31792 * Licensed under the MIT License.
31793 */
31794
31795var hasOwn$6 = Object.prototype.hasOwnProperty;
31796
31797/**
31798 * Expose `MapCache`
31799 */
31800
31801var mapCache = MapCache;
31802
31803/**
31804 * Creates a cache object to store key/value pairs.
31805 *
31806 * ```js
31807 * var cache = new MapCache();
31808 * ```
31809 *
31810 * @api public
31811 */
31812
31813function MapCache(data) {
31814 this.__data__ = data || {};
31815}
31816
31817/**
31818 * Adds `value` to `key` on the cache.
31819 *
31820 * ```js
31821 * cache.set('foo', 'bar');
31822 * ```
31823 *
31824 * @param {String} `key` The key of the value to cache.
31825 * @param {*} `value` The value to cache.
31826 * @returns {Object} Returns the `Cache` object for chaining.
31827 * @api public
31828 */
31829
31830MapCache.prototype.set = function mapSet(key, value) {
31831 if (key !== '__proto__') {
31832 this.__data__[key] = value;
31833 }
31834 return this;
31835};
31836
31837/**
31838 * Gets the cached value for `key`.
31839 *
31840 * ```js
31841 * cache.get('foo');
31842 * //=> 'bar'
31843 * ```
31844 *
31845 * @param {String} `key` The key of the value to get.
31846 * @returns {*} Returns the cached value.
31847 * @api public
31848 */
31849
31850MapCache.prototype.get = function mapGet(key) {
31851 return key === '__proto__' ? undefined : this.__data__[key];
31852};
31853
31854/**
31855 * Checks if a cached value for `key` exists.
31856 *
31857 * ```js
31858 * cache.has('foo');
31859 * //=> true
31860 * ```
31861 *
31862 * @param {String} `key` The key of the entry to check.
31863 * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`.
31864 * @api public
31865 */
31866
31867MapCache.prototype.has = function mapHas(key) {
31868 return key !== '__proto__' && hasOwn$6.call(this.__data__, key);
31869};
31870
31871/**
31872 * Removes `key` and its value from the cache.
31873 *
31874 * ```js
31875 * cache.del('foo');
31876 * ```
31877 * @title .del
31878 * @param {String} `key` The key of the value to remove.
31879 * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`.
31880 * @api public
31881 */
31882
31883MapCache.prototype.del = function mapDelete(key) {
31884 return this.has(key) && delete this.__data__[key];
31885};
31886
31887/**
31888 * Store position for a node
31889 */
31890
31891var position = function Position(start, parser) {
31892 this.start = start;
31893 this.end = { line: parser.line, column: parser.column };
31894 defineProperty$6(this, 'content', parser.orig);
31895 defineProperty$6(this, 'source', parser.options.source);
31896};
31897
31898var debug$2 = src('snapdragon:parser');
31899
31900
31901
31902/**
31903 * Create a new `Parser` with the given `input` and `options`.
31904 * @param {String} `input`
31905 * @param {Object} `options`
31906 * @api public
31907 */
31908
31909function Parser(options) {
31910 debug$2('initializing', __filename);
31911 this.options = utils$1.extend({source: 'string'}, options);
31912 this.init(this.options);
31913 use(this);
31914}
31915
31916/**
31917 * Prototype methods
31918 */
31919
31920Parser.prototype = {
31921 constructor: Parser,
31922
31923 init: function(options) {
31924 this.orig = '';
31925 this.input = '';
31926 this.parsed = '';
31927
31928 this.column = 1;
31929 this.line = 1;
31930
31931 this.regex = new mapCache();
31932 this.errors = this.errors || [];
31933 this.parsers = this.parsers || {};
31934 this.types = this.types || [];
31935 this.sets = this.sets || {};
31936 this.fns = this.fns || [];
31937 this.currentType = 'root';
31938
31939 var pos = this.position();
31940 this.bos = pos({type: 'bos', val: ''});
31941
31942 this.ast = {
31943 type: 'root',
31944 errors: this.errors,
31945 nodes: [this.bos]
31946 };
31947
31948 defineProperty$6(this.bos, 'parent', this.ast);
31949 this.nodes = [this.ast];
31950
31951 this.count = 0;
31952 this.setCount = 0;
31953 this.stack = [];
31954 },
31955
31956 /**
31957 * Throw a formatted error with the cursor column and `msg`.
31958 * @param {String} `msg` Message to use in the Error.
31959 */
31960
31961 error: function(msg, node) {
31962 var pos = node.position || {start: {column: 0, line: 0}};
31963 var line = pos.start.line;
31964 var column = pos.start.column;
31965 var source = this.options.source;
31966
31967 var message = source + ' <line:' + line + ' column:' + column + '>: ' + msg;
31968 var err = new Error(message);
31969 err.source = source;
31970 err.reason = msg;
31971 err.pos = pos;
31972
31973 if (this.options.silent) {
31974 this.errors.push(err);
31975 } else {
31976 throw err;
31977 }
31978 },
31979
31980 /**
31981 * Define a non-enumberable property on the `Parser` instance.
31982 *
31983 * ```js
31984 * parser.define('foo', 'bar');
31985 * ```
31986 * @name .define
31987 * @param {String} `key` propery name
31988 * @param {any} `val` property value
31989 * @return {Object} Returns the Parser instance for chaining.
31990 * @api public
31991 */
31992
31993 define: function(key, val) {
31994 defineProperty$6(this, key, val);
31995 return this;
31996 },
31997
31998 /**
31999 * Mark position and patch `node.position`.
32000 */
32001
32002 position: function() {
32003 var start = { line: this.line, column: this.column };
32004 var self = this;
32005
32006 return function(node) {
32007 defineProperty$6(node, 'position', new position(start, self));
32008 return node;
32009 };
32010 },
32011
32012 /**
32013 * Set parser `name` with the given `fn`
32014 * @param {String} `name`
32015 * @param {Function} `fn`
32016 * @api public
32017 */
32018
32019 set: function(type, fn) {
32020 if (this.types.indexOf(type) === -1) {
32021 this.types.push(type);
32022 }
32023 this.parsers[type] = fn.bind(this);
32024 return this;
32025 },
32026
32027 /**
32028 * Get parser `name`
32029 * @param {String} `name`
32030 * @api public
32031 */
32032
32033 get: function(name) {
32034 return this.parsers[name];
32035 },
32036
32037 /**
32038 * Push a `token` onto the `type` stack.
32039 *
32040 * @param {String} `type`
32041 * @return {Object} `token`
32042 * @api public
32043 */
32044
32045 push: function(type, token) {
32046 this.sets[type] = this.sets[type] || [];
32047 this.count++;
32048 this.stack.push(token);
32049 return this.sets[type].push(token);
32050 },
32051
32052 /**
32053 * Pop a token off of the `type` stack
32054 * @param {String} `type`
32055 * @returns {Object} Returns a token
32056 * @api public
32057 */
32058
32059 pop: function(type) {
32060 this.sets[type] = this.sets[type] || [];
32061 this.count--;
32062 this.stack.pop();
32063 return this.sets[type].pop();
32064 },
32065
32066 /**
32067 * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`.
32068 *
32069 * @param {String} `type`
32070 * @return {Boolean}
32071 * @api public
32072 */
32073
32074 isInside: function(type) {
32075 this.sets[type] = this.sets[type] || [];
32076 return this.sets[type].length > 0;
32077 },
32078
32079 /**
32080 * Return true if `node` is the given `type`.
32081 *
32082 * ```js
32083 * parser.isType(node, 'brace');
32084 * ```
32085 * @param {Object} `node`
32086 * @param {String} `type`
32087 * @return {Boolean}
32088 * @api public
32089 */
32090
32091 isType: function(node, type) {
32092 return node && node.type === type;
32093 },
32094
32095 /**
32096 * Get the previous AST node
32097 * @return {Object}
32098 */
32099
32100 prev: function(n) {
32101 return this.stack.length > 0
32102 ? utils$1.last(this.stack, n)
32103 : utils$1.last(this.nodes, n);
32104 },
32105
32106 /**
32107 * Update line and column based on `str`.
32108 */
32109
32110 consume: function(len) {
32111 this.input = this.input.substr(len);
32112 },
32113
32114 /**
32115 * Update column based on `str`.
32116 */
32117
32118 updatePosition: function(str, len) {
32119 var lines = str.match(/\n/g);
32120 if (lines) this.line += lines.length;
32121 var i = str.lastIndexOf('\n');
32122 this.column = ~i ? len - i : this.column + len;
32123 this.parsed += str;
32124 this.consume(len);
32125 },
32126
32127 /**
32128 * Match `regex`, return captures, and update the cursor position by `match[0]` length.
32129 * @param {RegExp} `regex`
32130 * @return {Object}
32131 */
32132
32133 match: function(regex) {
32134 var m = regex.exec(this.input);
32135 if (m) {
32136 this.updatePosition(m[0], m[0].length);
32137 return m;
32138 }
32139 },
32140
32141 /**
32142 * Capture `type` with the given regex.
32143 * @param {String} `type`
32144 * @param {RegExp} `regex`
32145 * @return {Function}
32146 */
32147
32148 capture: function(type, regex) {
32149 if (typeof regex === 'function') {
32150 return this.set.apply(this, arguments);
32151 }
32152
32153 this.regex.set(type, regex);
32154 this.set(type, function() {
32155 var parsed = this.parsed;
32156 var pos = this.position();
32157 var m = this.match(regex);
32158 if (!m || !m[0]) return;
32159
32160 var prev = this.prev();
32161 var node = pos({
32162 type: type,
32163 val: m[0],
32164 parsed: parsed,
32165 rest: this.input
32166 });
32167
32168 if (m[1]) {
32169 node.inner = m[1];
32170 }
32171
32172 defineProperty$6(node, 'inside', this.stack.length > 0);
32173 defineProperty$6(node, 'parent', prev);
32174 prev.nodes.push(node);
32175 }.bind(this));
32176 return this;
32177 },
32178
32179 /**
32180 * Create a parser with open and close for parens,
32181 * brackets or braces
32182 */
32183
32184 capturePair: function(type, openRegex, closeRegex, fn) {
32185 this.sets[type] = this.sets[type] || [];
32186
32187 /**
32188 * Open
32189 */
32190
32191 this.set(type + '.open', function() {
32192 var parsed = this.parsed;
32193 var pos = this.position();
32194 var m = this.match(openRegex);
32195 if (!m || !m[0]) return;
32196
32197 var val = m[0];
32198 this.setCount++;
32199 this.specialChars = true;
32200 var open = pos({
32201 type: type + '.open',
32202 val: val,
32203 rest: this.input
32204 });
32205
32206 if (typeof m[1] !== 'undefined') {
32207 open.inner = m[1];
32208 }
32209
32210 var prev = this.prev();
32211 var node = pos({
32212 type: type,
32213 nodes: [open]
32214 });
32215
32216 defineProperty$6(node, 'rest', this.input);
32217 defineProperty$6(node, 'parsed', parsed);
32218 defineProperty$6(node, 'prefix', m[1]);
32219 defineProperty$6(node, 'parent', prev);
32220 defineProperty$6(open, 'parent', node);
32221
32222 if (typeof fn === 'function') {
32223 fn.call(this, open, node);
32224 }
32225
32226 this.push(type, node);
32227 prev.nodes.push(node);
32228 });
32229
32230 /**
32231 * Close
32232 */
32233
32234 this.set(type + '.close', function() {
32235 var pos = this.position();
32236 var m = this.match(closeRegex);
32237 if (!m || !m[0]) return;
32238
32239 var parent = this.pop(type);
32240 var node = pos({
32241 type: type + '.close',
32242 rest: this.input,
32243 suffix: m[1],
32244 val: m[0]
32245 });
32246
32247 if (!this.isType(parent, type)) {
32248 if (this.options.strict) {
32249 throw new Error('missing opening "' + type + '"');
32250 }
32251
32252 this.setCount--;
32253 node.escaped = true;
32254 return node;
32255 }
32256
32257 if (node.suffix === '\\') {
32258 parent.escaped = true;
32259 node.escaped = true;
32260 }
32261
32262 parent.nodes.push(node);
32263 defineProperty$6(node, 'parent', parent);
32264 });
32265
32266 return this;
32267 },
32268
32269 /**
32270 * Capture end-of-string
32271 */
32272
32273 eos: function() {
32274 var pos = this.position();
32275 if (this.input) return;
32276 var prev = this.prev();
32277
32278 while (prev.type !== 'root' && !prev.visited) {
32279 if (this.options.strict === true) {
32280 throw new SyntaxError('invalid syntax:' + util$2.inspect(prev, null, 2));
32281 }
32282
32283 if (!hasDelims(prev)) {
32284 prev.parent.escaped = true;
32285 prev.escaped = true;
32286 }
32287
32288 visit(prev, function(node) {
32289 if (!hasDelims(node.parent)) {
32290 node.parent.escaped = true;
32291 node.escaped = true;
32292 }
32293 });
32294
32295 prev = prev.parent;
32296 }
32297
32298 var tok = pos({
32299 type: 'eos',
32300 val: this.append || ''
32301 });
32302
32303 defineProperty$6(tok, 'parent', this.ast);
32304 return tok;
32305 },
32306
32307 /**
32308 * Run parsers to advance the cursor position
32309 */
32310
32311 next: function() {
32312 var parsed = this.parsed;
32313 var len = this.types.length;
32314 var idx = -1;
32315 var tok;
32316
32317 while (++idx < len) {
32318 if ((tok = this.parsers[this.types[idx]].call(this))) {
32319 defineProperty$6(tok, 'rest', this.input);
32320 defineProperty$6(tok, 'parsed', parsed);
32321 this.last = tok;
32322 return tok;
32323 }
32324 }
32325 },
32326
32327 /**
32328 * Parse the given string.
32329 * @return {Array}
32330 */
32331
32332 parse: function(input) {
32333 if (typeof input !== 'string') {
32334 throw new TypeError('expected a string');
32335 }
32336
32337 this.init(this.options);
32338 this.orig = input;
32339 this.input = input;
32340 var self = this;
32341
32342 function parse() {
32343 // check input before calling `.next()`
32344 input = self.input;
32345
32346 // get the next AST ndoe
32347 var node = self.next();
32348 if (node) {
32349 var prev = self.prev();
32350 if (prev) {
32351 defineProperty$6(node, 'parent', prev);
32352 if (prev.nodes) {
32353 prev.nodes.push(node);
32354 }
32355 }
32356
32357 if (self.sets.hasOwnProperty(prev.type)) {
32358 self.currentType = prev.type;
32359 }
32360 }
32361
32362 // if we got here but input is not changed, throw an error
32363 if (self.input && input === self.input) {
32364 throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"');
32365 }
32366 }
32367
32368 while (this.input) parse();
32369 if (this.stack.length && this.options.strict) {
32370 var node = this.stack.pop();
32371 throw this.error('missing opening ' + node.type + ': "' + this.orig + '"');
32372 }
32373
32374 var eos = this.eos();
32375 var tok = this.prev();
32376 if (tok.type !== 'eos') {
32377 this.ast.nodes.push(eos);
32378 }
32379
32380 return this.ast;
32381 }
32382};
32383
32384/**
32385 * Visit `node` with the given `fn`
32386 */
32387
32388function visit(node, fn) {
32389 if (!node.visited) {
32390 defineProperty$6(node, 'visited', true);
32391 return node.nodes ? mapVisit$1(node.nodes, fn) : fn(node);
32392 }
32393 return node;
32394}
32395
32396/**
32397 * Map visit over array of `nodes`.
32398 */
32399
32400function mapVisit$1(nodes, fn) {
32401 var len = nodes.length;
32402 var idx = -1;
32403 while (++idx < len) {
32404 visit(nodes[idx], fn);
32405 }
32406}
32407
32408function hasOpen(node) {
32409 return node.nodes && node.nodes[0].type === (node.type + '.open');
32410}
32411
32412function hasClose(node) {
32413 return node.nodes && utils$1.last(node.nodes).type === (node.type + '.close');
32414}
32415
32416function hasDelims(node) {
32417 return hasOpen(node) && hasClose(node);
32418}
32419
32420/**
32421 * Expose `Parser`
32422 */
32423
32424var parser = Parser;
32425
32426/**
32427 * Create a new instance of `Snapdragon` with the given `options`.
32428 *
32429 * ```js
32430 * var snapdragon = new Snapdragon();
32431 * ```
32432 *
32433 * @param {Object} `options`
32434 * @api public
32435 */
32436
32437function Snapdragon(options) {
32438 base$2.call(this, null, options);
32439 this.options = utils$1.extend({source: 'string'}, this.options);
32440 this.compiler = new compiler(this.options);
32441 this.parser = new parser(this.options);
32442
32443 Object.defineProperty(this, 'compilers', {
32444 get: function() {
32445 return this.compiler.compilers;
32446 }
32447 });
32448
32449 Object.defineProperty(this, 'parsers', {
32450 get: function() {
32451 return this.parser.parsers;
32452 }
32453 });
32454
32455 Object.defineProperty(this, 'regex', {
32456 get: function() {
32457 return this.parser.regex;
32458 }
32459 });
32460}
32461
32462/**
32463 * Inherit Base
32464 */
32465
32466base$2.extend(Snapdragon);
32467
32468/**
32469 * Add a parser to `snapdragon.parsers` for capturing the given `type` using
32470 * the specified regex or parser function. A function is useful if you need
32471 * to customize how the token is created and/or have access to the parser
32472 * instance to check options, etc.
32473 *
32474 * ```js
32475 * snapdragon
32476 * .capture('slash', /^\//)
32477 * .capture('dot', function() {
32478 * var pos = this.position();
32479 * var m = this.match(/^\./);
32480 * if (!m) return;
32481 * return pos({
32482 * type: 'dot',
32483 * val: m[0]
32484 * });
32485 * });
32486 * ```
32487 * @param {String} `type`
32488 * @param {RegExp|Function} `regex`
32489 * @return {Object} Returns the parser instance for chaining
32490 * @api public
32491 */
32492
32493Snapdragon.prototype.capture = function() {
32494 return this.parser.capture.apply(this.parser, arguments);
32495};
32496
32497/**
32498 * Register a plugin `fn`.
32499 *
32500 * ```js
32501 * var snapdragon = new Snapdgragon([options]);
32502 * snapdragon.use(function() {
32503 * console.log(this); //<= snapdragon instance
32504 * console.log(this.parser); //<= parser instance
32505 * console.log(this.compiler); //<= compiler instance
32506 * });
32507 * ```
32508 * @param {Object} `fn`
32509 * @api public
32510 */
32511
32512Snapdragon.prototype.use = function(fn) {
32513 fn.call(this, this);
32514 return this;
32515};
32516
32517/**
32518 * Parse the given `str`.
32519 *
32520 * ```js
32521 * var snapdragon = new Snapdgragon([options]);
32522 * // register parsers
32523 * snapdragon.parser.use(function() {});
32524 *
32525 * // parse
32526 * var ast = snapdragon.parse('foo/bar');
32527 * console.log(ast);
32528 * ```
32529 * @param {String} `str`
32530 * @param {Object} `options` Set `options.sourcemap` to true to enable source maps.
32531 * @return {Object} Returns an AST.
32532 * @api public
32533 */
32534
32535Snapdragon.prototype.parse = function(str, options) {
32536 this.options = utils$1.extend({}, this.options, options);
32537 var parsed = this.parser.parse(str, this.options);
32538
32539 // add non-enumerable parser reference
32540 defineProperty$6(parsed, 'parser', this.parser);
32541 return parsed;
32542};
32543
32544/**
32545 * Compile the given `AST`.
32546 *
32547 * ```js
32548 * var snapdragon = new Snapdgragon([options]);
32549 * // register plugins
32550 * snapdragon.use(function() {});
32551 * // register parser plugins
32552 * snapdragon.parser.use(function() {});
32553 * // register compiler plugins
32554 * snapdragon.compiler.use(function() {});
32555 *
32556 * // parse
32557 * var ast = snapdragon.parse('foo/bar');
32558 *
32559 * // compile
32560 * var res = snapdragon.compile(ast);
32561 * console.log(res.output);
32562 * ```
32563 * @param {Object} `ast`
32564 * @param {Object} `options`
32565 * @return {Object} Returns an object with an `output` property with the rendered string.
32566 * @api public
32567 */
32568
32569Snapdragon.prototype.compile = function(ast, options) {
32570 this.options = utils$1.extend({}, this.options, options);
32571 var compiled = this.compiler.compile(ast, this.options);
32572
32573 // add non-enumerable compiler reference
32574 defineProperty$6(compiled, 'compiler', this.compiler);
32575 return compiled;
32576};
32577
32578/**
32579 * Expose `Snapdragon`
32580 */
32581
32582var snapdragon = Snapdragon;
32583
32584/**
32585 * Expose `Parser` and `Compiler`
32586 */
32587
32588var Compiler_1 = compiler;
32589var Parser_1 = parser;
32590snapdragon.Compiler = Compiler_1;
32591snapdragon.Parser = Parser_1;
32592
32593/**
32594 * Customize Snapdragon parser and renderer
32595 */
32596
32597function Braces(options) {
32598 this.options = extendShallow$1({}, options);
32599}
32600
32601/**
32602 * Initialize braces
32603 */
32604
32605Braces.prototype.init = function(options) {
32606 if (this.isInitialized) return;
32607 this.isInitialized = true;
32608 var opts = utils_1.createOptions({}, this.options, options);
32609 this.snapdragon = this.options.snapdragon || new snapdragon(opts);
32610 this.compiler = this.snapdragon.compiler;
32611 this.parser = this.snapdragon.parser;
32612
32613 compilers(this.snapdragon, opts);
32614 parsers(this.snapdragon, opts);
32615
32616 /**
32617 * Call Snapdragon `.parse` method. When AST is returned, we check to
32618 * see if any unclosed braces are left on the stack and, if so, we iterate
32619 * over the stack and correct the AST so that compilers are called in the correct
32620 * order and unbalance braces are properly escaped.
32621 */
32622
32623 utils_1.define(this.snapdragon, 'parse', function(pattern, options) {
32624 var parsed = snapdragon.prototype.parse.apply(this, arguments);
32625 this.parser.ast.input = pattern;
32626
32627 var stack = this.parser.stack;
32628 while (stack.length) {
32629 addParent({type: 'brace.close', val: ''}, stack.pop());
32630 }
32631
32632 function addParent(node, parent) {
32633 utils_1.define(node, 'parent', parent);
32634 parent.nodes.push(node);
32635 }
32636
32637 // add non-enumerable parser reference
32638 utils_1.define(parsed, 'parser', this.parser);
32639 return parsed;
32640 });
32641};
32642
32643/**
32644 * Decorate `.parse` method
32645 */
32646
32647Braces.prototype.parse = function(ast, options) {
32648 if (ast && typeof ast === 'object' && ast.nodes) return ast;
32649 this.init(options);
32650 return this.snapdragon.parse(ast, options);
32651};
32652
32653/**
32654 * Decorate `.compile` method
32655 */
32656
32657Braces.prototype.compile = function(ast, options) {
32658 if (typeof ast === 'string') {
32659 ast = this.parse(ast, options);
32660 } else {
32661 this.init(options);
32662 }
32663 return this.snapdragon.compile(ast, options);
32664};
32665
32666/**
32667 * Expand
32668 */
32669
32670Braces.prototype.expand = function(pattern) {
32671 var ast = this.parse(pattern, {expand: true});
32672 return this.compile(ast, {expand: true});
32673};
32674
32675/**
32676 * Optimize
32677 */
32678
32679Braces.prototype.optimize = function(pattern) {
32680 var ast = this.parse(pattern, {optimize: true});
32681 return this.compile(ast, {optimize: true});
32682};
32683
32684/**
32685 * Expose `Braces`
32686 */
32687
32688var braces = Braces;
32689
32690/**
32691 * Module dependencies
32692 */
32693
32694
32695
32696
32697
32698/**
32699 * Local dependencies
32700 */
32701
32702
32703
32704
32705
32706var MAX_LENGTH$1 = 1024 * 64;
32707var cache$3 = {};
32708
32709/**
32710 * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)).
32711 *
32712 * ```js
32713 * var braces = require('braces');
32714 * console.log(braces('{a,b,c}'));
32715 * //=> ['(a|b|c)']
32716 *
32717 * console.log(braces('{a,b,c}', {expand: true}));
32718 * //=> ['a', 'b', 'c']
32719 * ```
32720 * @param {String} `str`
32721 * @param {Object} `options`
32722 * @return {String}
32723 * @api public
32724 */
32725
32726function braces$1(pattern, options) {
32727 var key = utils_1.createKey(String(pattern), options);
32728 var arr = [];
32729
32730 var disabled = options && options.cache === false;
32731 if (!disabled && cache$3.hasOwnProperty(key)) {
32732 return cache$3[key];
32733 }
32734
32735 if (Array.isArray(pattern)) {
32736 for (var i = 0; i < pattern.length; i++) {
32737 arr.push.apply(arr, braces$1.create(pattern[i], options));
32738 }
32739 } else {
32740 arr = braces$1.create(pattern, options);
32741 }
32742
32743 if (options && options.nodupes === true) {
32744 arr = arrayUnique(arr);
32745 }
32746
32747 if (!disabled) {
32748 cache$3[key] = arr;
32749 }
32750 return arr;
32751}
32752
32753/**
32754 * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead.
32755 *
32756 * ```js
32757 * var braces = require('braces');
32758 * console.log(braces.expand('a/{b,c}/d'));
32759 * //=> ['a/b/d', 'a/c/d'];
32760 * ```
32761 * @param {String} `pattern` Brace pattern
32762 * @param {Object} `options`
32763 * @return {Array} Returns an array of expanded values.
32764 * @api public
32765 */
32766
32767braces$1.expand = function(pattern, options) {
32768 return braces$1.create(pattern, extendShallow$1({}, options, {expand: true}));
32769};
32770
32771/**
32772 * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
32773 *
32774 * ```js
32775 * var braces = require('braces');
32776 * console.log(braces.expand('a/{b,c}/d'));
32777 * //=> ['a/(b|c)/d']
32778 * ```
32779 * @param {String} `pattern` Brace pattern
32780 * @param {Object} `options`
32781 * @return {Array} Returns an array of expanded values.
32782 * @api public
32783 */
32784
32785braces$1.optimize = function(pattern, options) {
32786 return braces$1.create(pattern, options);
32787};
32788
32789/**
32790 * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function.
32791 *
32792 * ```js
32793 * var braces = require('braces');
32794 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
32795 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
32796 * ```
32797 * @param {String} `pattern` Brace pattern
32798 * @param {Object} `options`
32799 * @return {Array} Returns an array of expanded values.
32800 * @api public
32801 */
32802
32803braces$1.create = function(pattern, options) {
32804 if (typeof pattern !== 'string') {
32805 throw new TypeError('expected a string');
32806 }
32807
32808 var maxLength = (options && options.maxLength) || MAX_LENGTH$1;
32809 if (pattern.length >= maxLength) {
32810 throw new Error('expected pattern to be less than ' + maxLength + ' characters');
32811 }
32812
32813 function create() {
32814 if (pattern === '' || pattern.length < 3) {
32815 return [pattern];
32816 }
32817
32818 if (utils_1.isEmptySets(pattern)) {
32819 return [];
32820 }
32821
32822 if (utils_1.isQuotedString(pattern)) {
32823 return [pattern.slice(1, -1)];
32824 }
32825
32826 var proto = new braces(options);
32827 var result = !options || options.expand !== true
32828 ? proto.optimize(pattern, options)
32829 : proto.expand(pattern, options);
32830
32831 // get the generated pattern(s)
32832 var arr = result.output;
32833
32834 // filter out empty strings if specified
32835 if (options && options.noempty === true) {
32836 arr = arr.filter(Boolean);
32837 }
32838
32839 // filter out duplicates if specified
32840 if (options && options.nodupes === true) {
32841 arr = arrayUnique(arr);
32842 }
32843
32844 Object.defineProperty(arr, 'result', {
32845 enumerable: false,
32846 value: result
32847 });
32848
32849 return arr;
32850 }
32851
32852 return memoize$1('create', pattern, options, create);
32853};
32854
32855/**
32856 * Create a regular expression from the given string `pattern`.
32857 *
32858 * ```js
32859 * var braces = require('braces');
32860 *
32861 * console.log(braces.makeRe('id-{200..300}'));
32862 * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
32863 * ```
32864 * @param {String} `pattern` The pattern to convert to regex.
32865 * @param {Object} `options`
32866 * @return {RegExp}
32867 * @api public
32868 */
32869
32870braces$1.makeRe = function(pattern, options) {
32871 if (typeof pattern !== 'string') {
32872 throw new TypeError('expected a string');
32873 }
32874
32875 var maxLength = (options && options.maxLength) || MAX_LENGTH$1;
32876 if (pattern.length >= maxLength) {
32877 throw new Error('expected pattern to be less than ' + maxLength + ' characters');
32878 }
32879
32880 function makeRe() {
32881 var arr = braces$1(pattern, options);
32882 var opts = extendShallow$1({strictErrors: false}, options);
32883 return toRegex$1(arr, opts);
32884 }
32885
32886 return memoize$1('makeRe', pattern, options, makeRe);
32887};
32888
32889/**
32890 * Parse the given `str` with the given `options`.
32891 *
32892 * ```js
32893 * var braces = require('braces');
32894 * var ast = braces.parse('a/{b,c}/d');
32895 * console.log(ast);
32896 * // { type: 'root',
32897 * // errors: [],
32898 * // input: 'a/{b,c}/d',
32899 * // nodes:
32900 * // [ { type: 'bos', val: '' },
32901 * // { type: 'text', val: 'a/' },
32902 * // { type: 'brace',
32903 * // nodes:
32904 * // [ { type: 'brace.open', val: '{' },
32905 * // { type: 'text', val: 'b,c' },
32906 * // { type: 'brace.close', val: '}' } ] },
32907 * // { type: 'text', val: '/d' },
32908 * // { type: 'eos', val: '' } ] }
32909 * ```
32910 * @param {String} `pattern` Brace pattern to parse
32911 * @param {Object} `options`
32912 * @return {Object} Returns an AST
32913 * @api public
32914 */
32915
32916braces$1.parse = function(pattern, options) {
32917 var proto = new braces(options);
32918 return proto.parse(pattern, options);
32919};
32920
32921/**
32922 * Compile the given `ast` or string with the given `options`.
32923 *
32924 * ```js
32925 * var braces = require('braces');
32926 * var ast = braces.parse('a/{b,c}/d');
32927 * console.log(braces.compile(ast));
32928 * // { options: { source: 'string' },
32929 * // state: {},
32930 * // compilers:
32931 * // { eos: [Function],
32932 * // noop: [Function],
32933 * // bos: [Function],
32934 * // brace: [Function],
32935 * // 'brace.open': [Function],
32936 * // text: [Function],
32937 * // 'brace.close': [Function] },
32938 * // output: [ 'a/(b|c)/d' ],
32939 * // ast:
32940 * // { ... },
32941 * // parsingErrors: [] }
32942 * ```
32943 * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
32944 * @param {Object} `options`
32945 * @return {Object} Returns an object that has an `output` property with the compiled string.
32946 * @api public
32947 */
32948
32949braces$1.compile = function(ast, options) {
32950 var proto = new braces(options);
32951 return proto.compile(ast, options);
32952};
32953
32954/**
32955 * Clear the regex cache.
32956 *
32957 * ```js
32958 * braces.clearCache();
32959 * ```
32960 * @api public
32961 */
32962
32963braces$1.clearCache = function() {
32964 cache$3 = braces$1.cache = {};
32965};
32966
32967/**
32968 * Memoize a generated regex or function. A unique key is generated
32969 * from the method name, pattern, and user-defined options. Set
32970 * options.memoize to false to disable.
32971 */
32972
32973function memoize$1(type, pattern, options, fn) {
32974 var key = utils_1.createKey(type + ':' + pattern, options);
32975 var disabled = options && options.cache === false;
32976 if (disabled) {
32977 braces$1.clearCache();
32978 return fn(pattern, options);
32979 }
32980
32981 if (cache$3.hasOwnProperty(key)) {
32982 return cache$3[key];
32983 }
32984
32985 var res = fn(pattern, options);
32986 cache$3[key] = res;
32987 return res;
32988}
32989
32990/**
32991 * Expose `Braces` constructor and methods
32992 * @type {Function}
32993 */
32994
32995braces$1.Braces = braces;
32996braces$1.compilers = compilers;
32997braces$1.parsers = parsers;
32998braces$1.cache = cache$3;
32999
33000/**
33001 * Expose `braces`
33002 * @type {Function}
33003 */
33004
33005var braces_1 = braces$1;
33006
33007/**
33008* Nanomatch compilers
33009*/
33010
33011var compilers$1 = function(nanomatch, options) {
33012 function slash() {
33013 if (options && typeof options.slash === 'string') {
33014 return options.slash;
33015 }
33016 if (options && typeof options.slash === 'function') {
33017 return options.slash.call(nanomatch);
33018 }
33019 return '\\\\/';
33020 }
33021
33022 function star() {
33023 if (options && typeof options.star === 'string') {
33024 return options.star;
33025 }
33026 if (options && typeof options.star === 'function') {
33027 return options.star.call(nanomatch);
33028 }
33029 return '[^' + slash() + ']*?';
33030 }
33031
33032 var ast = nanomatch.ast = nanomatch.parser.ast;
33033 ast.state = nanomatch.parser.state;
33034 nanomatch.compiler.state = ast.state;
33035 nanomatch.compiler
33036
33037 /**
33038 * Negation / escaping
33039 */
33040
33041 .set('not', function(node) {
33042 var prev = this.prev();
33043 if (this.options.nonegate === true || prev.type !== 'bos') {
33044 return this.emit('\\' + node.val, node);
33045 }
33046 return this.emit(node.val, node);
33047 })
33048 .set('escape', function(node) {
33049 if (this.options.unescape && /^[-\w_.]/.test(node.val)) {
33050 return this.emit(node.val, node);
33051 }
33052 return this.emit('\\' + node.val, node);
33053 })
33054 .set('quoted', function(node) {
33055 return this.emit(node.val, node);
33056 })
33057
33058 /**
33059 * Regex
33060 */
33061
33062 .set('dollar', function(node) {
33063 if (node.parent.type === 'bracket') {
33064 return this.emit(node.val, node);
33065 }
33066 return this.emit('\\' + node.val, node);
33067 })
33068
33069 /**
33070 * Dot: "."
33071 */
33072
33073 .set('dot', function(node) {
33074 if (node.dotfiles === true) this.dotfiles = true;
33075 return this.emit('\\' + node.val, node);
33076 })
33077
33078 /**
33079 * Slashes: "/" and "\"
33080 */
33081
33082 .set('backslash', function(node) {
33083 return this.emit(node.val, node);
33084 })
33085 .set('slash', function(node, nodes, i) {
33086 var val = '[' + slash() + ']';
33087 var parent = node.parent;
33088 var prev = this.prev();
33089
33090 // set "node.hasSlash" to true on all ancestor parens nodes
33091 while (parent.type === 'paren' && !parent.hasSlash) {
33092 parent.hasSlash = true;
33093 parent = parent.parent;
33094 }
33095
33096 if (prev.addQmark) {
33097 val += '?';
33098 }
33099
33100 // word boundary
33101 if (node.rest.slice(0, 2) === '\\b') {
33102 return this.emit(val, node);
33103 }
33104
33105 // globstars
33106 if (node.parsed === '**' || node.parsed === './**') {
33107 this.output = '(?:' + this.output;
33108 return this.emit(val + ')?', node);
33109 }
33110
33111 // negation
33112 if (node.parsed === '!**' && this.options.nonegate !== true) {
33113 return this.emit(val + '?\\b', node);
33114 }
33115 return this.emit(val, node);
33116 })
33117
33118 /**
33119 * Square brackets
33120 */
33121
33122 .set('bracket', function(node) {
33123 var close = node.close;
33124 var open = !node.escaped ? '[' : '\\[';
33125 var negated = node.negated;
33126 var inner = node.inner;
33127 var val = node.val;
33128
33129 if (node.escaped === true) {
33130 inner = inner.replace(/\\?(\W)/g, '\\$1');
33131 negated = '';
33132 }
33133
33134 if (inner === ']-') {
33135 inner = '\\]\\-';
33136 }
33137
33138 if (negated && inner.indexOf('.') === -1) {
33139 inner += '.';
33140 }
33141 if (negated && inner.indexOf('/') === -1) {
33142 inner += '/';
33143 }
33144
33145 val = open + negated + inner + close;
33146 return this.emit(val, node);
33147 })
33148
33149 /**
33150 * Square: "[.]" (only matches a single character in brackets)
33151 */
33152
33153 .set('square', function(node) {
33154 var val = (/^\W/.test(node.val) ? '\\' : '') + node.val;
33155 return this.emit(val, node);
33156 })
33157
33158 /**
33159 * Question mark: "?"
33160 */
33161
33162 .set('qmark', function(node) {
33163 var prev = this.prev();
33164 // don't use "slash" variable so that we always avoid
33165 // matching backslashes and slashes with a qmark
33166 var val = '[^.\\\\/]';
33167 if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) {
33168 val = '[^\\\\/]';
33169 }
33170
33171 if (node.parsed.slice(-1) === '(') {
33172 var ch = node.rest.charAt(0);
33173 if (ch === '!' || ch === '=' || ch === ':') {
33174 return this.emit(node.val, node);
33175 }
33176 }
33177
33178 if (node.val.length > 1) {
33179 val += '{' + node.val.length + '}';
33180 }
33181 return this.emit(val, node);
33182 })
33183
33184 /**
33185 * Plus
33186 */
33187
33188 .set('plus', function(node) {
33189 var prev = node.parsed.slice(-1);
33190 if (prev === ']' || prev === ')') {
33191 return this.emit(node.val, node);
33192 }
33193 if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {
33194 return this.emit('\\+', node);
33195 }
33196 var ch = this.output.slice(-1);
33197 if (/\w/.test(ch) && !node.inside) {
33198 return this.emit('+\\+?', node);
33199 }
33200 return this.emit('+', node);
33201 })
33202
33203 /**
33204 * globstar: '**'
33205 */
33206
33207 .set('globstar', function(node, nodes, i) {
33208 if (!this.output) {
33209 this.state.leadingGlobstar = true;
33210 }
33211
33212 var prev = this.prev();
33213 var before = this.prev(2);
33214 var next = this.next();
33215 var after = this.next(2);
33216 var type = prev.type;
33217 var val = node.val;
33218
33219 if (prev.type === 'slash' && next.type === 'slash') {
33220 if (before.type === 'text') {
33221 this.output += '?';
33222
33223 if (after.type !== 'text') {
33224 this.output += '\\b';
33225 }
33226 }
33227 }
33228
33229 var parsed = node.parsed;
33230 if (parsed.charAt(0) === '!') {
33231 parsed = parsed.slice(1);
33232 }
33233
33234 var isInside = node.isInside.paren || node.isInside.brace;
33235 if (parsed && type !== 'slash' && type !== 'bos' && !isInside) {
33236 val = star();
33237 } else {
33238 val = this.options.dot !== true
33239 ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?'
33240 : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?';
33241 }
33242
33243 if ((type === 'slash' || type === 'bos') && this.options.dot !== true) {
33244 val = '(?!\\.)' + val;
33245 }
33246
33247 if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') {
33248 if (after.type === 'text' || after.type === 'star') {
33249 node.addQmark = true;
33250 }
33251 }
33252
33253 if (this.options.capture) {
33254 val = '(' + val + ')';
33255 }
33256
33257 return this.emit(val, node);
33258 })
33259
33260 /**
33261 * Star: "*"
33262 */
33263
33264 .set('star', function(node, nodes, i) {
33265 var prior = nodes[i - 2] || {};
33266 var prev = this.prev();
33267 var next = this.next();
33268 var type = prev.type;
33269
33270 function isStart(n) {
33271 return n.type === 'bos' || n.type === 'slash';
33272 }
33273
33274 if (this.output === '' && this.options.contains !== true) {
33275 this.output = '(?![' + slash() + '])';
33276 }
33277
33278 if (type === 'bracket' && this.options.bash === false) {
33279 var str = next && next.type === 'bracket' ? star() : '*?';
33280 if (!prev.nodes || prev.nodes[1].type !== 'posix') {
33281 return this.emit(str, node);
33282 }
33283 }
33284
33285 var prefix = !this.dotfiles && type !== 'text' && type !== 'escape'
33286 ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)')
33287 : '';
33288
33289 if (isStart(prev) || (isStart(prior) && type === 'not')) {
33290 if (prefix !== '(?!\\.)') {
33291 prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)';
33292 } else {
33293 prefix += '(?=.)';
33294 }
33295 } else if (prefix === '(?!\\.)') {
33296 prefix = '';
33297 }
33298
33299 if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) {
33300 this.output = '(?!\\.)' + this.output;
33301 }
33302
33303 var output = prefix + star();
33304 if (this.options.capture) {
33305 output = '(' + output + ')';
33306 }
33307
33308 return this.emit(output, node);
33309 })
33310
33311 /**
33312 * Text
33313 */
33314
33315 .set('text', function(node) {
33316 return this.emit(node.val, node);
33317 })
33318
33319 /**
33320 * End-of-string
33321 */
33322
33323 .set('eos', function(node) {
33324 var prev = this.prev();
33325 var val = node.val;
33326
33327 this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output;
33328 if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') {
33329 val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)');
33330 }
33331
33332 return this.emit(val, node);
33333 });
33334
33335 /**
33336 * Allow custom compilers to be passed on options
33337 */
33338
33339 if (options && typeof options.compilers === 'function') {
33340 options.compilers(nanomatch.compiler);
33341 }
33342};
33343
33344/**
33345 * Characters to use in negation regex (we want to "not" match
33346 * characters that are matched by other parsers)
33347 */
33348
33349var cached;
33350var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+';
33351var not$1 = createTextRegex(NOT_REGEX);
33352
33353/**
33354 * Nanomatch parsers
33355 */
33356
33357var parsers$1 = function(nanomatch, options) {
33358 var parser = nanomatch.parser;
33359 var opts = parser.options;
33360
33361 parser.state = {
33362 slashes: 0,
33363 paths: []
33364 };
33365
33366 parser.ast.state = parser.state;
33367 parser
33368
33369 /**
33370 * Beginning-of-string
33371 */
33372
33373 .capture('prefix', function() {
33374 if (this.parsed) return;
33375 var m = this.match(/^\.[\\/]/);
33376 if (!m) return;
33377 this.state.strictOpen = !!this.options.strictOpen;
33378 this.state.addPrefix = true;
33379 })
33380
33381 /**
33382 * Escape: "\\."
33383 */
33384
33385 .capture('escape', function() {
33386 if (this.isInside('bracket')) return;
33387 var pos = this.position();
33388 var m = this.match(/^(?:\\(.)|([$^]))/);
33389 if (!m) return;
33390
33391 return pos({
33392 type: 'escape',
33393 val: m[2] || m[1]
33394 });
33395 })
33396
33397 /**
33398 * Quoted strings
33399 */
33400
33401 .capture('quoted', function() {
33402 var pos = this.position();
33403 var m = this.match(/^["']/);
33404 if (!m) return;
33405
33406 var quote = m[0];
33407 if (this.input.indexOf(quote) === -1) {
33408 return pos({
33409 type: 'escape',
33410 val: quote
33411 });
33412 }
33413
33414 var tok = advanceTo(this.input, quote);
33415 this.consume(tok.len);
33416
33417 return pos({
33418 type: 'quoted',
33419 val: tok.esc
33420 });
33421 })
33422
33423 /**
33424 * Negations: "!"
33425 */
33426
33427 .capture('not', function() {
33428 var parsed = this.parsed;
33429 var pos = this.position();
33430 var m = this.match(this.notRegex || /^!+/);
33431 if (!m) return;
33432 var val = m[0];
33433
33434 var isNegated = (val.length % 2) === 1;
33435 if (parsed === '' && !isNegated) {
33436 val = '';
33437 }
33438
33439 // if nothing has been parsed, we know `!` is at the start,
33440 // so we need to wrap the result in a negation regex
33441 if (parsed === '' && isNegated && this.options.nonegate !== true) {
33442 this.bos.val = '(?!^(?:';
33443 this.append = ')$).*';
33444 val = '';
33445 }
33446 return pos({
33447 type: 'not',
33448 val: val
33449 });
33450 })
33451
33452 /**
33453 * Dot: "."
33454 */
33455
33456 .capture('dot', function() {
33457 var parsed = this.parsed;
33458 var pos = this.position();
33459 var m = this.match(/^\.+/);
33460 if (!m) return;
33461
33462 var val = m[0];
33463 this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/');
33464
33465 return pos({
33466 type: 'dot',
33467 dotfiles: this.state.dot,
33468 val: val
33469 });
33470 })
33471
33472 /**
33473 * Plus: "+"
33474 */
33475
33476 .capture('plus', /^\+(?!\()/)
33477
33478 /**
33479 * Question mark: "?"
33480 */
33481
33482 .capture('qmark', function() {
33483 var parsed = this.parsed;
33484 var pos = this.position();
33485 var m = this.match(/^\?+(?!\()/);
33486 if (!m) return;
33487
33488 this.state.metachar = true;
33489 this.state.qmark = true;
33490
33491 return pos({
33492 type: 'qmark',
33493 parsed: parsed,
33494 val: m[0]
33495 });
33496 })
33497
33498 /**
33499 * Globstar: "**"
33500 */
33501
33502 .capture('globstar', function() {
33503 var parsed = this.parsed;
33504 var pos = this.position();
33505 var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/);
33506 if (!m) return;
33507
33508 var type = opts.noglobstar !== true ? 'globstar' : 'star';
33509 var node = pos({type: type, parsed: parsed});
33510 this.state.metachar = true;
33511
33512 while (this.input.slice(0, 4) === '/**/') {
33513 this.input = this.input.slice(3);
33514 }
33515
33516 node.isInside = {
33517 brace: this.isInside('brace'),
33518 paren: this.isInside('paren')
33519 };
33520
33521 if (type === 'globstar') {
33522 this.state.globstar = true;
33523 node.val = '**';
33524
33525 } else {
33526 this.state.star = true;
33527 node.val = '*';
33528 }
33529
33530 return node;
33531 })
33532
33533 /**
33534 * Star: "*"
33535 */
33536
33537 .capture('star', function() {
33538 var pos = this.position();
33539 var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/;
33540 var m = this.match(starRe);
33541 if (!m) return;
33542
33543 this.state.metachar = true;
33544 this.state.star = true;
33545 return pos({
33546 type: 'star',
33547 val: m[0]
33548 });
33549 })
33550
33551 /**
33552 * Slash: "/"
33553 */
33554
33555 .capture('slash', function() {
33556 var pos = this.position();
33557 var m = this.match(/^\//);
33558 if (!m) return;
33559
33560 this.state.slashes++;
33561 return pos({
33562 type: 'slash',
33563 val: m[0]
33564 });
33565 })
33566
33567 /**
33568 * Backslash: "\\"
33569 */
33570
33571 .capture('backslash', function() {
33572 var pos = this.position();
33573 var m = this.match(/^\\(?![*+?(){}[\]'"])/);
33574 if (!m) return;
33575
33576 var val = m[0];
33577
33578 if (this.isInside('bracket')) {
33579 val = '\\';
33580 } else if (val.length > 1) {
33581 val = '\\\\';
33582 }
33583
33584 return pos({
33585 type: 'backslash',
33586 val: val
33587 });
33588 })
33589
33590 /**
33591 * Square: "[.]"
33592 */
33593
33594 .capture('square', function() {
33595 if (this.isInside('bracket')) return;
33596 var pos = this.position();
33597 var m = this.match(/^\[([^!^\\])\]/);
33598 if (!m) return;
33599
33600 return pos({
33601 type: 'square',
33602 val: m[1]
33603 });
33604 })
33605
33606 /**
33607 * Brackets: "[...]" (basic, this can be overridden by other parsers)
33608 */
33609
33610 .capture('bracket', function() {
33611 var pos = this.position();
33612 var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/);
33613 if (!m) return;
33614
33615 var val = m[0];
33616 var negated = m[1] ? '^' : '';
33617 var inner = (m[2] || '').replace(/\\\\+/, '\\\\');
33618 var close = m[3] || '';
33619
33620 if (m[2] && inner.length < m[2].length) {
33621 val = val.replace(/\\\\+/, '\\\\');
33622 }
33623
33624 var esc = this.input.slice(0, 2);
33625 if (inner === '' && esc === '\\]') {
33626 inner += esc;
33627 this.consume(2);
33628
33629 var str = this.input;
33630 var idx = -1;
33631 var ch;
33632
33633 while ((ch = str[++idx])) {
33634 this.consume(1);
33635 if (ch === ']') {
33636 close = ch;
33637 break;
33638 }
33639 inner += ch;
33640 }
33641 }
33642
33643 return pos({
33644 type: 'bracket',
33645 val: val,
33646 escaped: close !== ']',
33647 negated: negated,
33648 inner: inner,
33649 close: close
33650 });
33651 })
33652
33653 /**
33654 * Text
33655 */
33656
33657 .capture('text', function() {
33658 if (this.isInside('bracket')) return;
33659 var pos = this.position();
33660 var m = this.match(not$1);
33661 if (!m || !m[0]) return;
33662
33663 return pos({
33664 type: 'text',
33665 val: m[0]
33666 });
33667 });
33668
33669 /**
33670 * Allow custom parsers to be passed on options
33671 */
33672
33673 if (options && typeof options.parsers === 'function') {
33674 options.parsers(nanomatch.parser);
33675 }
33676};
33677
33678/**
33679 * Advance to the next non-escaped character
33680 */
33681
33682function advanceTo(input, endChar) {
33683 var ch = input.charAt(0);
33684 var tok = { len: 1, val: '', esc: '' };
33685 var idx = 0;
33686
33687 function advance() {
33688 if (ch !== '\\') {
33689 tok.esc += '\\' + ch;
33690 tok.val += ch;
33691 }
33692
33693 ch = input.charAt(++idx);
33694 tok.len++;
33695
33696 if (ch === '\\') {
33697 advance();
33698 advance();
33699 }
33700 }
33701
33702 while (ch && ch !== endChar) {
33703 advance();
33704 }
33705 return tok;
33706}
33707
33708/**
33709 * Create text regex
33710 */
33711
33712function createTextRegex(pattern) {
33713 if (cached) return cached;
33714 var opts = {contains: true, strictClose: false};
33715 var not = regexNot.create(pattern, opts);
33716 var re = toRegex$1('^(?:[*]\\((?=.)|' + not + ')', opts);
33717 return (cached = re);
33718}
33719
33720/**
33721 * Expose negation string
33722 */
33723
33724var not_1 = NOT_REGEX;
33725parsers$1.not = not_1;
33726
33727var fragmentCache = createCommonjsModule(function (module, exports) {
33728
33729
33730
33731/**
33732 * Create a new `FragmentCache` with an optional object to use for `caches`.
33733 *
33734 * ```js
33735 * var fragment = new FragmentCache();
33736 * ```
33737 * @name FragmentCache
33738 * @param {String} `cacheName`
33739 * @return {Object} Returns the [map-cache][] instance.
33740 * @api public
33741 */
33742
33743function FragmentCache(caches) {
33744 this.caches = caches || {};
33745}
33746
33747/**
33748 * Prototype
33749 */
33750
33751FragmentCache.prototype = {
33752
33753 /**
33754 * Get cache `name` from the `fragment.caches` object. Creates a new
33755 * `MapCache` if it doesn't already exist.
33756 *
33757 * ```js
33758 * var cache = fragment.cache('files');
33759 * console.log(fragment.caches.hasOwnProperty('files'));
33760 * //=> true
33761 * ```
33762 * @name .cache
33763 * @param {String} `cacheName`
33764 * @return {Object} Returns the [map-cache][] instance.
33765 * @api public
33766 */
33767
33768 cache: function(cacheName) {
33769 return this.caches[cacheName] || (this.caches[cacheName] = new mapCache());
33770 },
33771
33772 /**
33773 * Set a value for property `key` on cache `name`
33774 *
33775 * ```js
33776 * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'}));
33777 * ```
33778 * @name .set
33779 * @param {String} `name`
33780 * @param {String} `key` Property name to set
33781 * @param {any} `val` The value of `key`
33782 * @return {Object} The cache instance for chaining
33783 * @api public
33784 */
33785
33786 set: function(cacheName, key, val) {
33787 var cache = this.cache(cacheName);
33788 cache.set(key, val);
33789 return cache;
33790 },
33791
33792 /**
33793 * Returns true if a non-undefined value is set for `key` on fragment cache `name`.
33794 *
33795 * ```js
33796 * var cache = fragment.cache('files');
33797 * cache.set('somefile.js');
33798 *
33799 * console.log(cache.has('somefile.js'));
33800 * //=> true
33801 *
33802 * console.log(cache.has('some-other-file.js'));
33803 * //=> false
33804 * ```
33805 * @name .has
33806 * @param {String} `name` Cache name
33807 * @param {String} `key` Optionally specify a property to check for on cache `name`
33808 * @return {Boolean}
33809 * @api public
33810 */
33811
33812 has: function(cacheName, key) {
33813 return typeof this.get(cacheName, key) !== 'undefined';
33814 },
33815
33816 /**
33817 * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method,
33818 * so that cache `name` will be created it doesn't already exist. If `key` is not passed,
33819 * the entire cache (`name`) is returned.
33820 *
33821 * ```js
33822 * var Vinyl = require('vinyl');
33823 * var cache = fragment.cache('files');
33824 * cache.set('somefile.js', new Vinyl({path: 'somefile.js'}));
33825 * console.log(cache.get('somefile.js'));
33826 * //=> <File "somefile.js">
33827 * ```
33828 * @name .get
33829 * @param {String} `name`
33830 * @return {Object} Returns cache `name`, or the value of `key` if specified
33831 * @api public
33832 */
33833
33834 get: function(name, key) {
33835 var cache = this.cache(name);
33836 if (typeof key === 'string') {
33837 return cache.get(key);
33838 }
33839 return cache;
33840 }
33841};
33842
33843/**
33844 * Expose `FragmentCache`
33845 */
33846
33847exports = module.exports = FragmentCache;
33848});
33849
33850var cache$4 = new (fragmentCache)();
33851
33852var isWindows = createCommonjsModule(function (module, exports) {
33853/*!
33854 * is-windows <https://github.com/jonschlinkert/is-windows>
33855 *
33856 * Copyright © 2015-2018, Jon Schlinkert.
33857 * Released under the MIT License.
33858 */
33859
33860(function(factory) {
33861 if (exports && 'object' === 'object' && 'object' !== 'undefined') {
33862 module.exports = factory();
33863 } else if (typeof window !== 'undefined') {
33864 window.isWindows = factory();
33865 } else if (typeof commonjsGlobal !== 'undefined') {
33866 commonjsGlobal.isWindows = factory();
33867 } else if (typeof self !== 'undefined') {
33868 self.isWindows = factory();
33869 } else {
33870 this.isWindows = factory();
33871 }
33872})(function() {
33873 return function isWindows() {
33874 return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE));
33875 };
33876});
33877});
33878
33879/*!
33880 * arr-diff <https://github.com/jonschlinkert/arr-diff>
33881 *
33882 * Copyright (c) 2014-2017, Jon Schlinkert.
33883 * Released under the MIT License.
33884 */
33885
33886var arrDiff = function diff(arr/*, arrays*/) {
33887 var len = arguments.length;
33888 var idx = 0;
33889 while (++idx < len) {
33890 arr = diffArray(arr, arguments[idx]);
33891 }
33892 return arr;
33893};
33894
33895function diffArray(one, two) {
33896 if (!Array.isArray(two)) {
33897 return one.slice();
33898 }
33899
33900 var tlen = two.length;
33901 var olen = one.length;
33902 var idx = -1;
33903 var arr = [];
33904
33905 while (++idx < olen) {
33906 var ele = one[idx];
33907
33908 var hasEle = false;
33909 for (var i = 0; i < tlen; i++) {
33910 var val = two[i];
33911
33912 if (ele === val) {
33913 hasEle = true;
33914 break;
33915 }
33916 }
33917
33918 if (hasEle === false) {
33919 arr.push(ele);
33920 }
33921 }
33922 return arr;
33923}
33924
33925var object_pick = function pick(obj, keys) {
33926 if (!isobject(obj) && typeof obj !== 'function') {
33927 return {};
33928 }
33929
33930 var res = {};
33931 if (typeof keys === 'string') {
33932 if (keys in obj) {
33933 res[keys] = obj[keys];
33934 }
33935 return res;
33936 }
33937
33938 var len = keys.length;
33939 var idx = -1;
33940
33941 while (++idx < len) {
33942 var key = keys[idx];
33943 if (key in obj) {
33944 res[key] = obj[key];
33945 }
33946 }
33947 return res;
33948};
33949
33950var utils_1$1 = createCommonjsModule(function (module) {
33951
33952var utils = module.exports;
33953
33954
33955/**
33956 * Module dependencies
33957 */
33958
33959var isWindows$1 = isWindows();
33960
33961utils.define = defineProperty;
33962utils.diff = arrDiff;
33963utils.extend = extendShallow;
33964utils.pick = object_pick;
33965utils.typeOf = kindOf;
33966utils.unique = arrayUnique;
33967
33968/**
33969 * Returns true if the given value is effectively an empty string
33970 */
33971
33972utils.isEmptyString = function(val) {
33973 return String(val) === '' || String(val) === './';
33974};
33975
33976/**
33977 * Returns true if the platform is windows, or `path.sep` is `\\`.
33978 * This is defined as a function to allow `path.sep` to be set in unit tests,
33979 * or by the user, if there is a reason to do so.
33980 * @return {Boolean}
33981 */
33982
33983utils.isWindows = function() {
33984 return path.sep === '\\' || isWindows$1 === true;
33985};
33986
33987/**
33988 * Return the last element from an array
33989 */
33990
33991utils.last = function(arr, n) {
33992 return arr[arr.length - (n || 1)];
33993};
33994
33995/**
33996 * Get the `Snapdragon` instance to use
33997 */
33998
33999utils.instantiate = function(ast, options) {
34000 var snapdragon$1;
34001 // if an instance was created by `.parse`, use that instance
34002 if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
34003 snapdragon$1 = ast.snapdragon;
34004 // if the user supplies an instance on options, use that instance
34005 } else if (utils.typeOf(options) === 'object' && options.snapdragon) {
34006 snapdragon$1 = options.snapdragon;
34007 // create a new instance
34008 } else {
34009 snapdragon$1 = new snapdragon(options);
34010 }
34011
34012 utils.define(snapdragon$1, 'parse', function(str, options) {
34013 var parsed = snapdragon.prototype.parse.call(this, str, options);
34014 parsed.input = str;
34015
34016 // escape unmatched brace/bracket/parens
34017 var last = this.parser.stack.pop();
34018 if (last && this.options.strictErrors !== true) {
34019 var open = last.nodes[0];
34020 var inner = last.nodes[1];
34021 if (last.type === 'bracket') {
34022 if (inner.val.charAt(0) === '[') {
34023 inner.val = '\\' + inner.val;
34024 }
34025
34026 } else {
34027 open.val = '\\' + open.val;
34028 var sibling = open.parent.nodes[1];
34029 if (sibling.type === 'star') {
34030 sibling.loose = true;
34031 }
34032 }
34033 }
34034
34035 // add non-enumerable parser reference
34036 utils.define(parsed, 'parser', this.parser);
34037 return parsed;
34038 });
34039
34040 return snapdragon$1;
34041};
34042
34043/**
34044 * Create the key to use for memoization. The key is generated
34045 * by iterating over the options and concatenating key-value pairs
34046 * to the pattern string.
34047 */
34048
34049utils.createKey = function(pattern, options) {
34050 if (typeof options === 'undefined') {
34051 return pattern;
34052 }
34053 var key = pattern;
34054 for (var prop in options) {
34055 if (options.hasOwnProperty(prop)) {
34056 key += ';' + prop + '=' + String(options[prop]);
34057 }
34058 }
34059 return key;
34060};
34061
34062/**
34063 * Cast `val` to an array
34064 * @return {Array}
34065 */
34066
34067utils.arrayify = function(val) {
34068 if (typeof val === 'string') return [val];
34069 return val ? (Array.isArray(val) ? val : [val]) : [];
34070};
34071
34072/**
34073 * Return true if `val` is a non-empty string
34074 */
34075
34076utils.isString = function(val) {
34077 return typeof val === 'string';
34078};
34079
34080/**
34081 * Return true if `val` is a non-empty string
34082 */
34083
34084utils.isRegex = function(val) {
34085 return utils.typeOf(val) === 'regexp';
34086};
34087
34088/**
34089 * Return true if `val` is a non-empty string
34090 */
34091
34092utils.isObject = function(val) {
34093 return utils.typeOf(val) === 'object';
34094};
34095
34096/**
34097 * Escape regex characters in the given string
34098 */
34099
34100utils.escapeRegex = function(str) {
34101 return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&');
34102};
34103
34104/**
34105 * Combines duplicate characters in the provided `input` string.
34106 * @param {String} `input`
34107 * @returns {String}
34108 */
34109
34110utils.combineDupes = function(input, patterns) {
34111 patterns = utils.arrayify(patterns).join('|').split('|');
34112 patterns = patterns.map(function(s) {
34113 return s.replace(/\\?([+*\\/])/g, '\\$1');
34114 });
34115 var substr = patterns.join('|');
34116 var regex = new RegExp('(' + substr + ')(?=\\1)', 'g');
34117 return input.replace(regex, '');
34118};
34119
34120/**
34121 * Returns true if the given `str` has special characters
34122 */
34123
34124utils.hasSpecialChars = function(str) {
34125 return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str);
34126};
34127
34128/**
34129 * Normalize slashes in the given filepath.
34130 *
34131 * @param {String} `filepath`
34132 * @return {String}
34133 */
34134
34135utils.toPosixPath = function(str) {
34136 return str.replace(/\\+/g, '/');
34137};
34138
34139/**
34140 * Strip backslashes before special characters in a string.
34141 *
34142 * @param {String} `str`
34143 * @return {String}
34144 */
34145
34146utils.unescape = function(str) {
34147 return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
34148};
34149
34150/**
34151 * Strip the drive letter from a windows filepath
34152 * @param {String} `fp`
34153 * @return {String}
34154 */
34155
34156utils.stripDrive = function(fp) {
34157 return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp;
34158};
34159
34160/**
34161 * Strip the prefix from a filepath
34162 * @param {String} `fp`
34163 * @return {String}
34164 */
34165
34166utils.stripPrefix = function(str) {
34167 if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) {
34168 return str.slice(2);
34169 }
34170 return str;
34171};
34172
34173/**
34174 * Returns true if `str` is a common character that doesn't need
34175 * to be processed to be used for matching.
34176 * @param {String} `str`
34177 * @return {Boolean}
34178 */
34179
34180utils.isSimpleChar = function(str) {
34181 return str.trim() === '' || str === '.';
34182};
34183
34184/**
34185 * Returns true if the given str is an escaped or
34186 * unescaped path character
34187 */
34188
34189utils.isSlash = function(str) {
34190 return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
34191};
34192
34193/**
34194 * Returns a function that returns true if the given
34195 * pattern matches or contains a `filepath`
34196 *
34197 * @param {String} `pattern`
34198 * @return {Function}
34199 */
34200
34201utils.matchPath = function(pattern, options) {
34202 return (options && options.contains)
34203 ? utils.containsPattern(pattern, options)
34204 : utils.equalsPattern(pattern, options);
34205};
34206
34207/**
34208 * Returns true if the given (original) filepath or unixified path are equal
34209 * to the given pattern.
34210 */
34211
34212utils._equals = function(filepath, unixPath, pattern) {
34213 return pattern === filepath || pattern === unixPath;
34214};
34215
34216/**
34217 * Returns true if the given (original) filepath or unixified path contain
34218 * the given pattern.
34219 */
34220
34221utils._contains = function(filepath, unixPath, pattern) {
34222 return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
34223};
34224
34225/**
34226 * Returns a function that returns true if the given
34227 * pattern is the same as a given `filepath`
34228 *
34229 * @param {String} `pattern`
34230 * @return {Function}
34231 */
34232
34233utils.equalsPattern = function(pattern, options) {
34234 var unixify = utils.unixify(options);
34235 options = options || {};
34236
34237 return function fn(filepath) {
34238 var equal = utils._equals(filepath, unixify(filepath), pattern);
34239 if (equal === true || options.nocase !== true) {
34240 return equal;
34241 }
34242 var lower = filepath.toLowerCase();
34243 return utils._equals(lower, unixify(lower), pattern);
34244 };
34245};
34246
34247/**
34248 * Returns a function that returns true if the given
34249 * pattern contains a `filepath`
34250 *
34251 * @param {String} `pattern`
34252 * @return {Function}
34253 */
34254
34255utils.containsPattern = function(pattern, options) {
34256 var unixify = utils.unixify(options);
34257 options = options || {};
34258
34259 return function(filepath) {
34260 var contains = utils._contains(filepath, unixify(filepath), pattern);
34261 if (contains === true || options.nocase !== true) {
34262 return contains;
34263 }
34264 var lower = filepath.toLowerCase();
34265 return utils._contains(lower, unixify(lower), pattern);
34266 };
34267};
34268
34269/**
34270 * Returns a function that returns true if the given
34271 * regex matches the `filename` of a file path.
34272 *
34273 * @param {RegExp} `re` Matching regex
34274 * @return {Function}
34275 */
34276
34277utils.matchBasename = function(re) {
34278 return function(filepath) {
34279 return re.test(filepath) || re.test(path.basename(filepath));
34280 };
34281};
34282
34283/**
34284 * Returns the given value unchanced.
34285 * @return {any}
34286 */
34287
34288utils.identity = function(val) {
34289 return val;
34290};
34291
34292/**
34293 * Determines the filepath to return based on the provided options.
34294 * @return {any}
34295 */
34296
34297utils.value = function(str, unixify, options) {
34298 if (options && options.unixify === false) {
34299 return str;
34300 }
34301 if (options && typeof options.unixify === 'function') {
34302 return options.unixify(str);
34303 }
34304 return unixify(str);
34305};
34306
34307/**
34308 * Returns a function that normalizes slashes in a string to forward
34309 * slashes, strips `./` from beginning of paths, and optionally unescapes
34310 * special characters.
34311 * @return {Function}
34312 */
34313
34314utils.unixify = function(options) {
34315 var opts = options || {};
34316 return function(filepath) {
34317 if (opts.stripPrefix !== false) {
34318 filepath = utils.stripPrefix(filepath);
34319 }
34320 if (opts.unescape === true) {
34321 filepath = utils.unescape(filepath);
34322 }
34323 if (opts.unixify === true || utils.isWindows()) {
34324 filepath = utils.toPosixPath(filepath);
34325 }
34326 return filepath;
34327 };
34328};
34329});
34330
34331/**
34332 * Module dependencies
34333 */
34334
34335
34336
34337
34338
34339/**
34340 * Local dependencies
34341 */
34342
34343
34344
34345
34346
34347var MAX_LENGTH$2 = 1024 * 64;
34348
34349/**
34350 * The main function takes a list of strings and one or more
34351 * glob patterns to use for matching.
34352 *
34353 * ```js
34354 * var nm = require('nanomatch');
34355 * nm(list, patterns[, options]);
34356 *
34357 * console.log(nm(['a.js', 'a.txt'], ['*.js']));
34358 * //=> [ 'a.js' ]
34359 * ```
34360 * @param {Array} `list` A list of strings to match
34361 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34362 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34363 * @return {Array} Returns an array of matches
34364 * @summary false
34365 * @api public
34366 */
34367
34368function nanomatch(list, patterns, options) {
34369 patterns = utils_1$1.arrayify(patterns);
34370 list = utils_1$1.arrayify(list);
34371
34372 var len = patterns.length;
34373 if (list.length === 0 || len === 0) {
34374 return [];
34375 }
34376
34377 if (len === 1) {
34378 return nanomatch.match(list, patterns[0], options);
34379 }
34380
34381 var negated = false;
34382 var omit = [];
34383 var keep = [];
34384 var idx = -1;
34385
34386 while (++idx < len) {
34387 var pattern = patterns[idx];
34388
34389 if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
34390 omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options));
34391 negated = true;
34392 } else {
34393 keep.push.apply(keep, nanomatch.match(list, pattern, options));
34394 }
34395 }
34396
34397 // minimatch.match parity
34398 if (negated && keep.length === 0) {
34399 if (options && options.unixify === false) {
34400 keep = list.slice();
34401 } else {
34402 var unixify = utils_1$1.unixify(options);
34403 for (var i = 0; i < list.length; i++) {
34404 keep.push(unixify(list[i]));
34405 }
34406 }
34407 }
34408
34409 var matches = utils_1$1.diff(keep, omit);
34410 if (!options || options.nodupes !== false) {
34411 return utils_1$1.unique(matches);
34412 }
34413
34414 return matches;
34415}
34416
34417/**
34418 * Similar to the main function, but `pattern` must be a string.
34419 *
34420 * ```js
34421 * var nm = require('nanomatch');
34422 * nm.match(list, pattern[, options]);
34423 *
34424 * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
34425 * //=> ['a.a', 'a.aa']
34426 * ```
34427 * @param {Array} `list` Array of strings to match
34428 * @param {String} `pattern` Glob pattern to use for matching.
34429 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34430 * @return {Array} Returns an array of matches
34431 * @api public
34432 */
34433
34434nanomatch.match = function(list, pattern, options) {
34435 if (Array.isArray(pattern)) {
34436 throw new TypeError('expected pattern to be a string');
34437 }
34438
34439 var unixify = utils_1$1.unixify(options);
34440 var isMatch = memoize$2('match', pattern, options, nanomatch.matcher);
34441 var matches = [];
34442
34443 list = utils_1$1.arrayify(list);
34444 var len = list.length;
34445 var idx = -1;
34446
34447 while (++idx < len) {
34448 var ele = list[idx];
34449 if (ele === pattern || isMatch(ele)) {
34450 matches.push(utils_1$1.value(ele, unixify, options));
34451 }
34452 }
34453
34454 // if no options were passed, uniquify results and return
34455 if (typeof options === 'undefined') {
34456 return utils_1$1.unique(matches);
34457 }
34458
34459 if (matches.length === 0) {
34460 if (options.failglob === true) {
34461 throw new Error('no matches found for "' + pattern + '"');
34462 }
34463 if (options.nonull === true || options.nullglob === true) {
34464 return [options.unescape ? utils_1$1.unescape(pattern) : pattern];
34465 }
34466 }
34467
34468 // if `opts.ignore` was defined, diff ignored list
34469 if (options.ignore) {
34470 matches = nanomatch.not(matches, options.ignore, options);
34471 }
34472
34473 return options.nodupes !== false ? utils_1$1.unique(matches) : matches;
34474};
34475
34476/**
34477 * Returns true if the specified `string` matches the given glob `pattern`.
34478 *
34479 * ```js
34480 * var nm = require('nanomatch');
34481 * nm.isMatch(string, pattern[, options]);
34482 *
34483 * console.log(nm.isMatch('a.a', '*.a'));
34484 * //=> true
34485 * console.log(nm.isMatch('a.b', '*.a'));
34486 * //=> false
34487 * ```
34488 * @param {String} `string` String to match
34489 * @param {String} `pattern` Glob pattern to use for matching.
34490 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34491 * @return {Boolean} Returns true if the string matches the glob pattern.
34492 * @api public
34493 */
34494
34495nanomatch.isMatch = function(str, pattern, options) {
34496 if (typeof str !== 'string') {
34497 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34498 }
34499
34500 if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(pattern)) {
34501 return false;
34502 }
34503
34504 var equals = utils_1$1.equalsPattern(options);
34505 if (equals(str)) {
34506 return true;
34507 }
34508
34509 var isMatch = memoize$2('isMatch', pattern, options, nanomatch.matcher);
34510 return isMatch(str);
34511};
34512
34513/**
34514 * Returns true if some of the elements in the given `list` match any of the
34515 * given glob `patterns`.
34516 *
34517 * ```js
34518 * var nm = require('nanomatch');
34519 * nm.some(list, patterns[, options]);
34520 *
34521 * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
34522 * // true
34523 * console.log(nm.some(['foo.js'], ['*.js', '!foo.js']));
34524 * // false
34525 * ```
34526 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
34527 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34528 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34529 * @return {Boolean} Returns true if any patterns match `str`
34530 * @api public
34531 */
34532
34533nanomatch.some = function(list, patterns, options) {
34534 if (typeof list === 'string') {
34535 list = [list];
34536 }
34537
34538 for (var i = 0; i < list.length; i++) {
34539 if (nanomatch(list[i], patterns, options).length === 1) {
34540 return true;
34541 }
34542 }
34543
34544 return false;
34545};
34546
34547/**
34548 * Returns true if every element in the given `list` matches
34549 * at least one of the given glob `patterns`.
34550 *
34551 * ```js
34552 * var nm = require('nanomatch');
34553 * nm.every(list, patterns[, options]);
34554 *
34555 * console.log(nm.every('foo.js', ['foo.js']));
34556 * // true
34557 * console.log(nm.every(['foo.js', 'bar.js'], ['*.js']));
34558 * // true
34559 * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
34560 * // false
34561 * console.log(nm.every(['foo.js'], ['*.js', '!foo.js']));
34562 * // false
34563 * ```
34564 * @param {String|Array} `list` The string or array of strings to test.
34565 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34566 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34567 * @return {Boolean} Returns true if any patterns match `str`
34568 * @api public
34569 */
34570
34571nanomatch.every = function(list, patterns, options) {
34572 if (typeof list === 'string') {
34573 list = [list];
34574 }
34575
34576 for (var i = 0; i < list.length; i++) {
34577 if (nanomatch(list[i], patterns, options).length !== 1) {
34578 return false;
34579 }
34580 }
34581
34582 return true;
34583};
34584
34585/**
34586 * Returns true if **any** of the given glob `patterns`
34587 * match the specified `string`.
34588 *
34589 * ```js
34590 * var nm = require('nanomatch');
34591 * nm.any(string, patterns[, options]);
34592 *
34593 * console.log(nm.any('a.a', ['b.*', '*.a']));
34594 * //=> true
34595 * console.log(nm.any('a.a', 'b.*'));
34596 * //=> false
34597 * ```
34598 * @param {String|Array} `str` The string to test.
34599 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34600 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34601 * @return {Boolean} Returns true if any patterns match `str`
34602 * @api public
34603 */
34604
34605nanomatch.any = function(str, patterns, options) {
34606 if (typeof str !== 'string') {
34607 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34608 }
34609
34610 if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(patterns)) {
34611 return false;
34612 }
34613
34614 if (typeof patterns === 'string') {
34615 patterns = [patterns];
34616 }
34617
34618 for (var i = 0; i < patterns.length; i++) {
34619 if (nanomatch.isMatch(str, patterns[i], options)) {
34620 return true;
34621 }
34622 }
34623 return false;
34624};
34625
34626/**
34627 * Returns true if **all** of the given `patterns`
34628 * match the specified string.
34629 *
34630 * ```js
34631 * var nm = require('nanomatch');
34632 * nm.all(string, patterns[, options]);
34633 *
34634 * console.log(nm.all('foo.js', ['foo.js']));
34635 * // true
34636 *
34637 * console.log(nm.all('foo.js', ['*.js', '!foo.js']));
34638 * // false
34639 *
34640 * console.log(nm.all('foo.js', ['*.js', 'foo.js']));
34641 * // true
34642 *
34643 * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
34644 * // true
34645 * ```
34646 * @param {String|Array} `str` The string to test.
34647 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34648 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34649 * @return {Boolean} Returns true if any patterns match `str`
34650 * @api public
34651 */
34652
34653nanomatch.all = function(str, patterns, options) {
34654 if (typeof str !== 'string') {
34655 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34656 }
34657
34658 if (typeof patterns === 'string') {
34659 patterns = [patterns];
34660 }
34661
34662 for (var i = 0; i < patterns.length; i++) {
34663 if (!nanomatch.isMatch(str, patterns[i], options)) {
34664 return false;
34665 }
34666 }
34667 return true;
34668};
34669
34670/**
34671 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
34672 *
34673 * ```js
34674 * var nm = require('nanomatch');
34675 * nm.not(list, patterns[, options]);
34676 *
34677 * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a'));
34678 * //=> ['b.b', 'c.c']
34679 * ```
34680 * @param {Array} `list` Array of strings to match.
34681 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
34682 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34683 * @return {Array} Returns an array of strings that **do not match** the given patterns.
34684 * @api public
34685 */
34686
34687nanomatch.not = function(list, patterns, options) {
34688 var opts = extendShallow({}, options);
34689 var ignore = opts.ignore;
34690 delete opts.ignore;
34691
34692 list = utils_1$1.arrayify(list);
34693
34694 var matches = utils_1$1.diff(list, nanomatch(list, patterns, opts));
34695 if (ignore) {
34696 matches = utils_1$1.diff(matches, nanomatch(list, ignore));
34697 }
34698
34699 return opts.nodupes !== false ? utils_1$1.unique(matches) : matches;
34700};
34701
34702/**
34703 * Returns true if the given `string` contains the given pattern. Similar
34704 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
34705 *
34706 * ```js
34707 * var nm = require('nanomatch');
34708 * nm.contains(string, pattern[, options]);
34709 *
34710 * console.log(nm.contains('aa/bb/cc', '*b'));
34711 * //=> true
34712 * console.log(nm.contains('aa/bb/cc', '*d'));
34713 * //=> false
34714 * ```
34715 * @param {String} `str` The string to match.
34716 * @param {String|Array} `patterns` Glob pattern to use for matching.
34717 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34718 * @return {Boolean} Returns true if the patter matches any part of `str`.
34719 * @api public
34720 */
34721
34722nanomatch.contains = function(str, patterns, options) {
34723 if (typeof str !== 'string') {
34724 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34725 }
34726
34727 if (typeof patterns === 'string') {
34728 if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(patterns)) {
34729 return false;
34730 }
34731
34732 var equals = utils_1$1.equalsPattern(patterns, options);
34733 if (equals(str)) {
34734 return true;
34735 }
34736 var contains = utils_1$1.containsPattern(patterns, options);
34737 if (contains(str)) {
34738 return true;
34739 }
34740 }
34741
34742 var opts = extendShallow({}, options, {contains: true});
34743 return nanomatch.any(str, patterns, opts);
34744};
34745
34746/**
34747 * Returns true if the given pattern and options should enable
34748 * the `matchBase` option.
34749 * @return {Boolean}
34750 * @api private
34751 */
34752
34753nanomatch.matchBase = function(pattern, options) {
34754 if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
34755 return options.basename === true || options.matchBase === true;
34756};
34757
34758/**
34759 * Filter the keys of the given object with the given `glob` pattern
34760 * and `options`. Does not attempt to match nested keys. If you need this feature,
34761 * use [glob-object][] instead.
34762 *
34763 * ```js
34764 * var nm = require('nanomatch');
34765 * nm.matchKeys(object, patterns[, options]);
34766 *
34767 * var obj = { aa: 'a', ab: 'b', ac: 'c' };
34768 * console.log(nm.matchKeys(obj, '*b'));
34769 * //=> { ab: 'b' }
34770 * ```
34771 * @param {Object} `object` The object with keys to filter.
34772 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34773 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34774 * @return {Object} Returns an object with only keys that match the given patterns.
34775 * @api public
34776 */
34777
34778nanomatch.matchKeys = function(obj, patterns, options) {
34779 if (!utils_1$1.isObject(obj)) {
34780 throw new TypeError('expected the first argument to be an object');
34781 }
34782 var keys = nanomatch(Object.keys(obj), patterns, options);
34783 return utils_1$1.pick(obj, keys);
34784};
34785
34786/**
34787 * Returns a memoized matcher function from the given glob `pattern` and `options`.
34788 * The returned function takes a string to match as its only argument and returns
34789 * true if the string is a match.
34790 *
34791 * ```js
34792 * var nm = require('nanomatch');
34793 * nm.matcher(pattern[, options]);
34794 *
34795 * var isMatch = nm.matcher('*.!(*a)');
34796 * console.log(isMatch('a.a'));
34797 * //=> false
34798 * console.log(isMatch('a.b'));
34799 * //=> true
34800 * ```
34801 * @param {String} `pattern` Glob pattern
34802 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
34803 * @return {Function} Returns a matcher function.
34804 * @api public
34805 */
34806
34807nanomatch.matcher = function matcher(pattern, options) {
34808 if (utils_1$1.isEmptyString(pattern)) {
34809 return function() {
34810 return false;
34811 };
34812 }
34813
34814 if (Array.isArray(pattern)) {
34815 return compose(pattern, options, matcher);
34816 }
34817
34818 // if pattern is a regex
34819 if (pattern instanceof RegExp) {
34820 return test(pattern);
34821 }
34822
34823 // if pattern is invalid
34824 if (!utils_1$1.isString(pattern)) {
34825 throw new TypeError('expected pattern to be an array, string or regex');
34826 }
34827
34828 // if pattern is a non-glob string
34829 if (!utils_1$1.hasSpecialChars(pattern)) {
34830 if (options && options.nocase === true) {
34831 pattern = pattern.toLowerCase();
34832 }
34833 return utils_1$1.matchPath(pattern, options);
34834 }
34835
34836 // if pattern is a glob string
34837 var re = nanomatch.makeRe(pattern, options);
34838
34839 // if `options.matchBase` or `options.basename` is defined
34840 if (nanomatch.matchBase(pattern, options)) {
34841 return utils_1$1.matchBasename(re, options);
34842 }
34843
34844 function test(regex) {
34845 var equals = utils_1$1.equalsPattern(options);
34846 var unixify = utils_1$1.unixify(options);
34847
34848 return function(str) {
34849 if (equals(str)) {
34850 return true;
34851 }
34852
34853 if (regex.test(unixify(str))) {
34854 return true;
34855 }
34856 return false;
34857 };
34858 }
34859
34860 // create matcher function
34861 var matcherFn = test(re);
34862 // set result object from compiler on matcher function,
34863 // as a non-enumerable property. useful for debugging
34864 utils_1$1.define(matcherFn, 'result', re.result);
34865 return matcherFn;
34866};
34867
34868/**
34869 * Returns an array of matches captured by `pattern` in `string, or
34870 * `null` if the pattern did not match.
34871 *
34872 * ```js
34873 * var nm = require('nanomatch');
34874 * nm.capture(pattern, string[, options]);
34875 *
34876 * console.log(nm.capture('test/*.js', 'test/foo.js'));
34877 * //=> ['foo']
34878 * console.log(nm.capture('test/*.js', 'foo/bar.css'));
34879 * //=> null
34880 * ```
34881 * @param {String} `pattern` Glob pattern to use for matching.
34882 * @param {String} `string` String to match
34883 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34884 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
34885 * @api public
34886 */
34887
34888nanomatch.capture = function(pattern, str, options) {
34889 var re = nanomatch.makeRe(pattern, extendShallow({capture: true}, options));
34890 var unixify = utils_1$1.unixify(options);
34891
34892 function match() {
34893 return function(string) {
34894 var match = re.exec(unixify(string));
34895 if (!match) {
34896 return null;
34897 }
34898
34899 return match.slice(1);
34900 };
34901 }
34902
34903 var capture = memoize$2('capture', pattern, options, match);
34904 return capture(str);
34905};
34906
34907/**
34908 * Create a regular expression from the given glob `pattern`.
34909 *
34910 * ```js
34911 * var nm = require('nanomatch');
34912 * nm.makeRe(pattern[, options]);
34913 *
34914 * console.log(nm.makeRe('*.js'));
34915 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
34916 * ```
34917 * @param {String} `pattern` A glob pattern to convert to regex.
34918 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
34919 * @return {RegExp} Returns a regex created from the given pattern.
34920 * @api public
34921 */
34922
34923nanomatch.makeRe = function(pattern, options) {
34924 if (pattern instanceof RegExp) {
34925 return pattern;
34926 }
34927
34928 if (typeof pattern !== 'string') {
34929 throw new TypeError('expected pattern to be a string');
34930 }
34931
34932 if (pattern.length > MAX_LENGTH$2) {
34933 throw new Error('expected pattern to be less than ' + MAX_LENGTH$2 + ' characters');
34934 }
34935
34936 function makeRe() {
34937 var opts = utils_1$1.extend({wrap: false}, options);
34938 var result = nanomatch.create(pattern, opts);
34939 var regex = toRegex$1(result.output, opts);
34940 utils_1$1.define(regex, 'result', result);
34941 return regex;
34942 }
34943
34944 return memoize$2('makeRe', pattern, options, makeRe);
34945};
34946
34947/**
34948 * Parses the given glob `pattern` and returns an object with the compiled `output`
34949 * and optional source `map`.
34950 *
34951 * ```js
34952 * var nm = require('nanomatch');
34953 * nm.create(pattern[, options]);
34954 *
34955 * console.log(nm.create('abc/*.js'));
34956 * // { options: { source: 'string', sourcemap: true },
34957 * // state: {},
34958 * // compilers:
34959 * // { ... },
34960 * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
34961 * // ast:
34962 * // { type: 'root',
34963 * // errors: [],
34964 * // nodes:
34965 * // [ ... ],
34966 * // dot: false,
34967 * // input: 'abc/*.js' },
34968 * // parsingErrors: [],
34969 * // map:
34970 * // { version: 3,
34971 * // sources: [ 'string' ],
34972 * // names: [],
34973 * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
34974 * // sourcesContent: [ 'abc/*.js' ] },
34975 * // position: { line: 1, column: 28 },
34976 * // content: {},
34977 * // files: {},
34978 * // idx: 6 }
34979 * ```
34980 * @param {String} `pattern` Glob pattern to parse and compile.
34981 * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
34982 * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
34983 * @api public
34984 */
34985
34986nanomatch.create = function(pattern, options) {
34987 if (typeof pattern !== 'string') {
34988 throw new TypeError('expected a string');
34989 }
34990 function create() {
34991 return nanomatch.compile(nanomatch.parse(pattern, options), options);
34992 }
34993 return memoize$2('create', pattern, options, create);
34994};
34995
34996/**
34997 * Parse the given `str` with the given `options`.
34998 *
34999 * ```js
35000 * var nm = require('nanomatch');
35001 * nm.parse(pattern[, options]);
35002 *
35003 * var ast = nm.parse('a/{b,c}/d');
35004 * console.log(ast);
35005 * // { type: 'root',
35006 * // errors: [],
35007 * // input: 'a/{b,c}/d',
35008 * // nodes:
35009 * // [ { type: 'bos', val: '' },
35010 * // { type: 'text', val: 'a/' },
35011 * // { type: 'brace',
35012 * // nodes:
35013 * // [ { type: 'brace.open', val: '{' },
35014 * // { type: 'text', val: 'b,c' },
35015 * // { type: 'brace.close', val: '}' } ] },
35016 * // { type: 'text', val: '/d' },
35017 * // { type: 'eos', val: '' } ] }
35018 * ```
35019 * @param {String} `str`
35020 * @param {Object} `options`
35021 * @return {Object} Returns an AST
35022 * @api public
35023 */
35024
35025nanomatch.parse = function(pattern, options) {
35026 if (typeof pattern !== 'string') {
35027 throw new TypeError('expected a string');
35028 }
35029
35030 function parse() {
35031 var snapdragon = utils_1$1.instantiate(null, options);
35032 parsers$1(snapdragon, options);
35033
35034 var ast = snapdragon.parse(pattern, options);
35035 utils_1$1.define(ast, 'snapdragon', snapdragon);
35036 ast.input = pattern;
35037 return ast;
35038 }
35039
35040 return memoize$2('parse', pattern, options, parse);
35041};
35042
35043/**
35044 * Compile the given `ast` or string with the given `options`.
35045 *
35046 * ```js
35047 * var nm = require('nanomatch');
35048 * nm.compile(ast[, options]);
35049 *
35050 * var ast = nm.parse('a/{b,c}/d');
35051 * console.log(nm.compile(ast));
35052 * // { options: { source: 'string' },
35053 * // state: {},
35054 * // compilers:
35055 * // { eos: [Function],
35056 * // noop: [Function],
35057 * // bos: [Function],
35058 * // brace: [Function],
35059 * // 'brace.open': [Function],
35060 * // text: [Function],
35061 * // 'brace.close': [Function] },
35062 * // output: [ 'a/(b|c)/d' ],
35063 * // ast:
35064 * // { ... },
35065 * // parsingErrors: [] }
35066 * ```
35067 * @param {Object|String} `ast`
35068 * @param {Object} `options`
35069 * @return {Object} Returns an object that has an `output` property with the compiled string.
35070 * @api public
35071 */
35072
35073nanomatch.compile = function(ast, options) {
35074 if (typeof ast === 'string') {
35075 ast = nanomatch.parse(ast, options);
35076 }
35077
35078 function compile() {
35079 var snapdragon = utils_1$1.instantiate(ast, options);
35080 compilers$1(snapdragon, options);
35081 return snapdragon.compile(ast, options);
35082 }
35083
35084 return memoize$2('compile', ast.input, options, compile);
35085};
35086
35087/**
35088 * Clear the regex cache.
35089 *
35090 * ```js
35091 * nm.clearCache();
35092 * ```
35093 * @api public
35094 */
35095
35096nanomatch.clearCache = function() {
35097 nanomatch.cache.__data__ = {};
35098};
35099
35100/**
35101 * Compose a matcher function with the given patterns.
35102 * This allows matcher functions to be compiled once and
35103 * called multiple times.
35104 */
35105
35106function compose(patterns, options, matcher) {
35107 var matchers;
35108
35109 return memoize$2('compose', String(patterns), options, function() {
35110 return function(file) {
35111 // delay composition until it's invoked the first time,
35112 // after that it won't be called again
35113 if (!matchers) {
35114 matchers = [];
35115 for (var i = 0; i < patterns.length; i++) {
35116 matchers.push(matcher(patterns[i], options));
35117 }
35118 }
35119
35120 var len = matchers.length;
35121 while (len--) {
35122 if (matchers[len](file) === true) {
35123 return true;
35124 }
35125 }
35126 return false;
35127 };
35128 });
35129}
35130
35131/**
35132 * Memoize a generated regex or function. A unique key is generated
35133 * from the `type` (usually method name), the `pattern`, and
35134 * user-defined options.
35135 */
35136
35137function memoize$2(type, pattern, options, fn) {
35138 var key = utils_1$1.createKey(type + '=' + pattern, options);
35139
35140 if (options && options.cache === false) {
35141 return fn(pattern, options);
35142 }
35143
35144 if (cache$4.has(type, key)) {
35145 return cache$4.get(type, key);
35146 }
35147
35148 var val = fn(pattern, options);
35149 cache$4.set(type, key, val);
35150 return val;
35151}
35152
35153/**
35154 * Expose compiler, parser and cache on `nanomatch`
35155 */
35156
35157nanomatch.compilers = compilers$1;
35158nanomatch.parsers = parsers$1;
35159nanomatch.cache = cache$4;
35160
35161/**
35162 * Expose `nanomatch`
35163 * @type {Function}
35164 */
35165
35166var nanomatch_1 = nanomatch;
35167
35168var extendShallow$6 = function extend(o/*, objects*/) {
35169 if (!isExtendable$1(o)) { o = {}; }
35170
35171 var len = arguments.length;
35172 for (var i = 1; i < len; i++) {
35173 var obj = arguments[i];
35174
35175 if (isExtendable$1(obj)) {
35176 assign$6(o, obj);
35177 }
35178 }
35179 return o;
35180};
35181
35182function assign$6(a, b) {
35183 for (var key in b) {
35184 if (hasOwn$7(b, key)) {
35185 a[key] = b[key];
35186 }
35187 }
35188}
35189
35190/**
35191 * Returns true if the given `key` is an own property of `obj`.
35192 */
35193
35194function hasOwn$7(obj, key) {
35195 return Object.prototype.hasOwnProperty.call(obj, key);
35196}
35197
35198/**
35199 * POSIX character classes
35200 */
35201
35202var posixCharacterClasses = {
35203 alnum: 'a-zA-Z0-9',
35204 alpha: 'a-zA-Z',
35205 ascii: '\\x00-\\x7F',
35206 blank: ' \\t',
35207 cntrl: '\\x00-\\x1F\\x7F',
35208 digit: '0-9',
35209 graph: '\\x21-\\x7E',
35210 lower: 'a-z',
35211 print: '\\x20-\\x7E ',
35212 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
35213 space: ' \\t\\r\\n\\v\\f',
35214 upper: 'A-Z',
35215 word: 'A-Za-z0-9_',
35216 xdigit: 'A-Fa-f0-9'
35217};
35218
35219var compilers$2 = function(brackets) {
35220 brackets.compiler
35221
35222 /**
35223 * Escaped characters
35224 */
35225
35226 .set('escape', function(node) {
35227 return this.emit('\\' + node.val.replace(/^\\/, ''), node);
35228 })
35229
35230 /**
35231 * Text
35232 */
35233
35234 .set('text', function(node) {
35235 return this.emit(node.val.replace(/([{}])/g, '\\$1'), node);
35236 })
35237
35238 /**
35239 * POSIX character classes
35240 */
35241
35242 .set('posix', function(node) {
35243 if (node.val === '[::]') {
35244 return this.emit('\\[::\\]', node);
35245 }
35246
35247 var val = posixCharacterClasses[node.inner];
35248 if (typeof val === 'undefined') {
35249 val = '[' + node.inner + ']';
35250 }
35251 return this.emit(val, node);
35252 })
35253
35254 /**
35255 * Non-posix brackets
35256 */
35257
35258 .set('bracket', function(node) {
35259 return this.mapVisit(node.nodes);
35260 })
35261 .set('bracket.open', function(node) {
35262 return this.emit(node.val, node);
35263 })
35264 .set('bracket.inner', function(node) {
35265 var inner = node.val;
35266
35267 if (inner === '[' || inner === ']') {
35268 return this.emit('\\' + node.val, node);
35269 }
35270 if (inner === '^]') {
35271 return this.emit('^\\]', node);
35272 }
35273 if (inner === '^') {
35274 return this.emit('^', node);
35275 }
35276
35277 if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) {
35278 inner = inner.split('-').join('\\-');
35279 }
35280
35281 var isNegated = inner.charAt(0) === '^';
35282 // add slashes to negated brackets, per spec
35283 if (isNegated && inner.indexOf('/') === -1) {
35284 inner += '/';
35285 }
35286 if (isNegated && inner.indexOf('.') === -1) {
35287 inner += '.';
35288 }
35289
35290 // don't unescape `0` (octal literal)
35291 inner = inner.replace(/\\([1-9])/g, '$1');
35292 return this.emit(inner, node);
35293 })
35294 .set('bracket.close', function(node) {
35295 var val = node.val.replace(/^\\/, '');
35296 if (node.parent.escaped === true) {
35297 return this.emit('\\' + val, node);
35298 }
35299 return this.emit(val, node);
35300 });
35301};
35302
35303var cached$1;
35304
35305/**
35306 * Get the last element from `array`
35307 * @param {Array} `array`
35308 * @return {*}
35309 */
35310
35311var last$1 = function(arr) {
35312 return arr[arr.length - 1];
35313};
35314
35315/**
35316 * Create and cache regex to use for text nodes
35317 */
35318
35319var createRegex = function(pattern, include) {
35320 if (cached$1) return cached$1;
35321 var opts = {contains: true, strictClose: false};
35322 var not = regexNot.create(pattern, opts);
35323 var re;
35324
35325 if (typeof include === 'string') {
35326 re = toRegex$1('^(?:' + include + '|' + not + ')', opts);
35327 } else {
35328 re = toRegex$1(not, opts);
35329 }
35330
35331 return (cached$1 = re);
35332};
35333
35334var utils$2 = {
35335 last: last$1,
35336 createRegex: createRegex
35337};
35338
35339var defineProperty$7 = function defineProperty(obj, prop, val) {
35340 if (typeof obj !== 'object' && typeof obj !== 'function') {
35341 throw new TypeError('expected an object or function.');
35342 }
35343
35344 if (typeof prop !== 'string') {
35345 throw new TypeError('expected `prop` to be a string.');
35346 }
35347
35348 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
35349 return Object.defineProperty(obj, prop, val);
35350 }
35351
35352 return Object.defineProperty(obj, prop, {
35353 configurable: true,
35354 enumerable: false,
35355 writable: true,
35356 value: val
35357 });
35358};
35359
35360/**
35361 * Text regex
35362 */
35363
35364var TEXT_REGEX = '(\\[(?=.*\\])|\\])+';
35365var not$2 = utils$2.createRegex(TEXT_REGEX);
35366
35367/**
35368 * Brackets parsers
35369 */
35370
35371function parsers$2(brackets) {
35372 brackets.state = brackets.state || {};
35373 brackets.parser.sets.bracket = brackets.parser.sets.bracket || [];
35374 brackets.parser
35375
35376 .capture('escape', function() {
35377 if (this.isInside('bracket')) return;
35378 var pos = this.position();
35379 var m = this.match(/^\\(.)/);
35380 if (!m) return;
35381
35382 return pos({
35383 type: 'escape',
35384 val: m[0]
35385 });
35386 })
35387
35388 /**
35389 * Text parser
35390 */
35391
35392 .capture('text', function() {
35393 if (this.isInside('bracket')) return;
35394 var pos = this.position();
35395 var m = this.match(not$2);
35396 if (!m || !m[0]) return;
35397
35398 return pos({
35399 type: 'text',
35400 val: m[0]
35401 });
35402 })
35403
35404 /**
35405 * POSIX character classes: "[[:alpha:][:digits:]]"
35406 */
35407
35408 .capture('posix', function() {
35409 var pos = this.position();
35410 var m = this.match(/^\[:(.*?):\](?=.*\])/);
35411 if (!m) return;
35412
35413 var inside = this.isInside('bracket');
35414 if (inside) {
35415 brackets.posix++;
35416 }
35417
35418 return pos({
35419 type: 'posix',
35420 insideBracket: inside,
35421 inner: m[1],
35422 val: m[0]
35423 });
35424 })
35425
35426 /**
35427 * Bracket (noop)
35428 */
35429
35430 .capture('bracket', function() {})
35431
35432 /**
35433 * Open: '['
35434 */
35435
35436 .capture('bracket.open', function() {
35437 var parsed = this.parsed;
35438 var pos = this.position();
35439 var m = this.match(/^\[(?=.*\])/);
35440 if (!m) return;
35441
35442 var prev = this.prev();
35443 var last = utils$2.last(prev.nodes);
35444
35445 if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) {
35446 last.val = last.val.slice(0, last.val.length - 1);
35447 return pos({
35448 type: 'escape',
35449 val: m[0]
35450 });
35451 }
35452
35453 var open = pos({
35454 type: 'bracket.open',
35455 val: m[0]
35456 });
35457
35458 if (last.type === 'bracket.open' || this.isInside('bracket')) {
35459 open.val = '\\' + open.val;
35460 open.type = 'bracket.inner';
35461 open.escaped = true;
35462 return open;
35463 }
35464
35465 var node = pos({
35466 type: 'bracket',
35467 nodes: [open]
35468 });
35469
35470 defineProperty$7(node, 'parent', prev);
35471 defineProperty$7(open, 'parent', node);
35472 this.push('bracket', node);
35473 prev.nodes.push(node);
35474 })
35475
35476 /**
35477 * Bracket text
35478 */
35479
35480 .capture('bracket.inner', function() {
35481 if (!this.isInside('bracket')) return;
35482 var pos = this.position();
35483 var m = this.match(not$2);
35484 if (!m || !m[0]) return;
35485
35486 var next = this.input.charAt(0);
35487 var val = m[0];
35488
35489 var node = pos({
35490 type: 'bracket.inner',
35491 val: val
35492 });
35493
35494 if (val === '\\\\') {
35495 return node;
35496 }
35497
35498 var first = val.charAt(0);
35499 var last = val.slice(-1);
35500
35501 if (first === '!') {
35502 val = '^' + val.slice(1);
35503 }
35504
35505 if (last === '\\' || (val === '^' && next === ']')) {
35506 val += this.input[0];
35507 this.consume(1);
35508 }
35509
35510 node.val = val;
35511 return node;
35512 })
35513
35514 /**
35515 * Close: ']'
35516 */
35517
35518 .capture('bracket.close', function() {
35519 var parsed = this.parsed;
35520 var pos = this.position();
35521 var m = this.match(/^\]/);
35522 if (!m) return;
35523
35524 var prev = this.prev();
35525 var last = utils$2.last(prev.nodes);
35526
35527 if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) {
35528 last.val = last.val.slice(0, last.val.length - 1);
35529
35530 return pos({
35531 type: 'escape',
35532 val: m[0]
35533 });
35534 }
35535
35536 var node = pos({
35537 type: 'bracket.close',
35538 rest: this.input,
35539 val: m[0]
35540 });
35541
35542 if (last.type === 'bracket.open') {
35543 node.type = 'bracket.inner';
35544 node.escaped = true;
35545 return node;
35546 }
35547
35548 var bracket = this.pop('bracket');
35549 if (!this.isType(bracket, 'bracket')) {
35550 if (this.options.strict) {
35551 throw new Error('missing opening "["');
35552 }
35553 node.type = 'bracket.inner';
35554 node.escaped = true;
35555 return node;
35556 }
35557
35558 bracket.nodes.push(node);
35559 defineProperty$7(node, 'parent', bracket);
35560 });
35561}
35562
35563/**
35564 * Brackets parsers
35565 */
35566
35567var parsers_1 = parsers$2;
35568
35569/**
35570 * Expose text regex
35571 */
35572
35573var TEXT_REGEX_1 = TEXT_REGEX;
35574parsers_1.TEXT_REGEX = TEXT_REGEX_1;
35575
35576var extendShallow$7 = function extend(o/*, objects*/) {
35577 if (!isExtendable$1(o)) { o = {}; }
35578
35579 var len = arguments.length;
35580 for (var i = 1; i < len; i++) {
35581 var obj = arguments[i];
35582
35583 if (isExtendable$1(obj)) {
35584 assign$7(o, obj);
35585 }
35586 }
35587 return o;
35588};
35589
35590function assign$7(a, b) {
35591 for (var key in b) {
35592 if (hasOwn$8(b, key)) {
35593 a[key] = b[key];
35594 }
35595 }
35596}
35597
35598/**
35599 * Returns true if the given `key` is an own property of `obj`.
35600 */
35601
35602function hasOwn$8(obj, key) {
35603 return Object.prototype.hasOwnProperty.call(obj, key);
35604}
35605
35606/**
35607 * Local dependencies
35608 */
35609
35610
35611
35612
35613/**
35614 * Module dependencies
35615 */
35616
35617var debug$3 = src('expand-brackets');
35618
35619
35620
35621
35622/**
35623 * Parses the given POSIX character class `pattern` and returns a
35624 * string that can be used for creating regular expressions for matching.
35625 *
35626 * @param {String} `pattern`
35627 * @param {Object} `options`
35628 * @return {Object}
35629 * @api public
35630 */
35631
35632function brackets(pattern, options) {
35633 debug$3('initializing from <%s>', __filename);
35634 var res = brackets.create(pattern, options);
35635 return res.output;
35636}
35637
35638/**
35639 * Takes an array of strings and a POSIX character class pattern, and returns a new
35640 * array with only the strings that matched the pattern.
35641 *
35642 * ```js
35643 * var brackets = require('expand-brackets');
35644 * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]'));
35645 * //=> ['a']
35646 *
35647 * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+'));
35648 * //=> ['a', 'ab']
35649 * ```
35650 * @param {Array} `arr` Array of strings to match
35651 * @param {String} `pattern` POSIX character class pattern(s)
35652 * @param {Object} `options`
35653 * @return {Array}
35654 * @api public
35655 */
35656
35657brackets.match = function(arr, pattern, options) {
35658 arr = [].concat(arr);
35659 var opts = extendShallow$7({}, options);
35660 var isMatch = brackets.matcher(pattern, opts);
35661 var len = arr.length;
35662 var idx = -1;
35663 var res = [];
35664
35665 while (++idx < len) {
35666 var ele = arr[idx];
35667 if (isMatch(ele)) {
35668 res.push(ele);
35669 }
35670 }
35671
35672 if (res.length === 0) {
35673 if (opts.failglob === true) {
35674 throw new Error('no matches found for "' + pattern + '"');
35675 }
35676
35677 if (opts.nonull === true || opts.nullglob === true) {
35678 return [pattern.split('\\').join('')];
35679 }
35680 }
35681 return res;
35682};
35683
35684/**
35685 * Returns true if the specified `string` matches the given
35686 * brackets `pattern`.
35687 *
35688 * ```js
35689 * var brackets = require('expand-brackets');
35690 *
35691 * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]'));
35692 * //=> true
35693 * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]'));
35694 * //=> false
35695 * ```
35696 * @param {String} `string` String to match
35697 * @param {String} `pattern` Poxis pattern
35698 * @param {String} `options`
35699 * @return {Boolean}
35700 * @api public
35701 */
35702
35703brackets.isMatch = function(str, pattern, options) {
35704 return brackets.matcher(pattern, options)(str);
35705};
35706
35707/**
35708 * Takes a POSIX character class pattern and returns a matcher function. The returned
35709 * function takes the string to match as its only argument.
35710 *
35711 * ```js
35712 * var brackets = require('expand-brackets');
35713 * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]');
35714 *
35715 * console.log(isMatch('a.a'));
35716 * //=> false
35717 * console.log(isMatch('a.A'));
35718 * //=> true
35719 * ```
35720 * @param {String} `pattern` Poxis pattern
35721 * @param {String} `options`
35722 * @return {Boolean}
35723 * @api public
35724 */
35725
35726brackets.matcher = function(pattern, options) {
35727 var re = brackets.makeRe(pattern, options);
35728 return function(str) {
35729 return re.test(str);
35730 };
35731};
35732
35733/**
35734 * Create a regular expression from the given `pattern`.
35735 *
35736 * ```js
35737 * var brackets = require('expand-brackets');
35738 * var re = brackets.makeRe('[[:alpha:]]');
35739 * console.log(re);
35740 * //=> /^(?:[a-zA-Z])$/
35741 * ```
35742 * @param {String} `pattern` The pattern to convert to regex.
35743 * @param {Object} `options`
35744 * @return {RegExp}
35745 * @api public
35746 */
35747
35748brackets.makeRe = function(pattern, options) {
35749 var res = brackets.create(pattern, options);
35750 var opts = extendShallow$7({strictErrors: false}, options);
35751 return toRegex$1(res.output, opts);
35752};
35753
35754/**
35755 * Parses the given POSIX character class `pattern` and returns an object
35756 * with the compiled `output` and optional source `map`.
35757 *
35758 * ```js
35759 * var brackets = require('expand-brackets');
35760 * console.log(brackets('[[:alpha:]]'));
35761 * // { options: { source: 'string' },
35762 * // input: '[[:alpha:]]',
35763 * // state: {},
35764 * // compilers:
35765 * // { eos: [Function],
35766 * // noop: [Function],
35767 * // bos: [Function],
35768 * // not: [Function],
35769 * // escape: [Function],
35770 * // text: [Function],
35771 * // posix: [Function],
35772 * // bracket: [Function],
35773 * // 'bracket.open': [Function],
35774 * // 'bracket.inner': [Function],
35775 * // 'bracket.literal': [Function],
35776 * // 'bracket.close': [Function] },
35777 * // output: '[a-zA-Z]',
35778 * // ast:
35779 * // { type: 'root',
35780 * // errors: [],
35781 * // nodes: [ [Object], [Object], [Object] ] },
35782 * // parsingErrors: [] }
35783 * ```
35784 * @param {String} `pattern`
35785 * @param {Object} `options`
35786 * @return {Object}
35787 * @api public
35788 */
35789
35790brackets.create = function(pattern, options) {
35791 var snapdragon$1 = (options && options.snapdragon) || new snapdragon(options);
35792 compilers$2(snapdragon$1);
35793 parsers_1(snapdragon$1);
35794
35795 var ast = snapdragon$1.parse(pattern, options);
35796 ast.input = pattern;
35797 var res = snapdragon$1.compile(ast, options);
35798 res.input = pattern;
35799 return res;
35800};
35801
35802/**
35803 * Expose `brackets` constructor, parsers and compilers
35804 */
35805
35806brackets.compilers = compilers$2;
35807brackets.parsers = parsers_1;
35808
35809/**
35810 * Expose `brackets`
35811 * @type {Function}
35812 */
35813
35814var expandBrackets = brackets;
35815
35816/**
35817 * Extglob compilers
35818 */
35819
35820var compilers$3 = function(extglob) {
35821 function star() {
35822 if (typeof extglob.options.star === 'function') {
35823 return extglob.options.star.apply(this, arguments);
35824 }
35825 if (typeof extglob.options.star === 'string') {
35826 return extglob.options.star;
35827 }
35828 return '.*?';
35829 }
35830
35831 /**
35832 * Use `expand-brackets` compilers
35833 */
35834
35835 extglob.use(expandBrackets.compilers);
35836 extglob.compiler
35837
35838 /**
35839 * Escaped: "\\*"
35840 */
35841
35842 .set('escape', function(node) {
35843 return this.emit(node.val, node);
35844 })
35845
35846 /**
35847 * Dot: "."
35848 */
35849
35850 .set('dot', function(node) {
35851 return this.emit('\\' + node.val, node);
35852 })
35853
35854 /**
35855 * Question mark: "?"
35856 */
35857
35858 .set('qmark', function(node) {
35859 var val = '[^\\\\/.]';
35860 var prev = this.prev();
35861
35862 if (node.parsed.slice(-1) === '(') {
35863 var ch = node.rest.charAt(0);
35864 if (ch !== '!' && ch !== '=' && ch !== ':') {
35865 return this.emit(val, node);
35866 }
35867 return this.emit(node.val, node);
35868 }
35869
35870 if (prev.type === 'text' && prev.val) {
35871 return this.emit(val, node);
35872 }
35873
35874 if (node.val.length > 1) {
35875 val += '{' + node.val.length + '}';
35876 }
35877 return this.emit(val, node);
35878 })
35879
35880 /**
35881 * Plus: "+"
35882 */
35883
35884 .set('plus', function(node) {
35885 var prev = node.parsed.slice(-1);
35886 if (prev === ']' || prev === ')') {
35887 return this.emit(node.val, node);
35888 }
35889 var ch = this.output.slice(-1);
35890 if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {
35891 return this.emit('\\+', node);
35892 }
35893 if (/\w/.test(ch) && !node.inside) {
35894 return this.emit('+\\+?', node);
35895 }
35896 return this.emit('+', node);
35897 })
35898
35899 /**
35900 * Star: "*"
35901 */
35902
35903 .set('star', function(node) {
35904 var prev = this.prev();
35905 var prefix = prev.type !== 'text' && prev.type !== 'escape'
35906 ? '(?!\\.)'
35907 : '';
35908
35909 return this.emit(prefix + star.call(this, node), node);
35910 })
35911
35912 /**
35913 * Parens
35914 */
35915
35916 .set('paren', function(node) {
35917 return this.mapVisit(node.nodes);
35918 })
35919 .set('paren.open', function(node) {
35920 var capture = this.options.capture ? '(' : '';
35921
35922 switch (node.parent.prefix) {
35923 case '!':
35924 case '^':
35925 return this.emit(capture + '(?:(?!(?:', node);
35926 case '*':
35927 case '+':
35928 case '?':
35929 case '@':
35930 return this.emit(capture + '(?:', node);
35931 default: {
35932 var val = node.val;
35933 if (this.options.bash === true) {
35934 val = '\\' + val;
35935 } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') {
35936 val += '?:';
35937 }
35938
35939 return this.emit(val, node);
35940 }
35941 }
35942 })
35943 .set('paren.close', function(node) {
35944 var capture = this.options.capture ? ')' : '';
35945
35946 switch (node.prefix) {
35947 case '!':
35948 case '^':
35949 var prefix = /^(\)|$)/.test(node.rest) ? '$' : '';
35950 var str = star.call(this, node);
35951
35952 // if the extglob has a slash explicitly defined, we know the user wants
35953 // to match slashes, so we need to ensure the "star" regex allows for it
35954 if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) {
35955 str = '.*?';
35956 }
35957
35958 return this.emit(prefix + ('))' + str + ')') + capture, node);
35959 case '*':
35960 case '+':
35961 case '?':
35962 return this.emit(')' + node.prefix + capture, node);
35963 case '@':
35964 return this.emit(')' + capture, node);
35965 default: {
35966 var val = (this.options.bash === true ? '\\' : '') + ')';
35967 return this.emit(val, node);
35968 }
35969 }
35970 })
35971
35972 /**
35973 * Text
35974 */
35975
35976 .set('text', function(node) {
35977 var val = node.val.replace(/[\[\]]/g, '\\$&');
35978 return this.emit(val, node);
35979 });
35980};
35981
35982// accessor descriptor properties
35983var accessor$4 = {
35984 get: 'function',
35985 set: 'function',
35986 configurable: 'boolean',
35987 enumerable: 'boolean'
35988};
35989
35990function isAccessorDescriptor$4(obj, prop) {
35991 if (typeof prop === 'string') {
35992 var val = Object.getOwnPropertyDescriptor(obj, prop);
35993 return typeof val !== 'undefined';
35994 }
35995
35996 if (kindOf(obj) !== 'object') {
35997 return false;
35998 }
35999
36000 if (has$7(obj, 'value') || has$7(obj, 'writable')) {
36001 return false;
36002 }
36003
36004 if (!has$7(obj, 'get') || typeof obj.get !== 'function') {
36005 return false;
36006 }
36007
36008 // tldr: it's valid to have "set" be undefined
36009 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
36010 // was used to get the value, and only `get` was defined by the user
36011 if (has$7(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
36012 return false;
36013 }
36014
36015 for (var key in obj) {
36016 if (!accessor$4.hasOwnProperty(key)) {
36017 continue;
36018 }
36019
36020 if (kindOf(obj[key]) === accessor$4[key]) {
36021 continue;
36022 }
36023
36024 if (typeof obj[key] !== 'undefined') {
36025 return false;
36026 }
36027 }
36028 return true;
36029}
36030
36031function has$7(obj, key) {
36032 return {}.hasOwnProperty.call(obj, key);
36033}
36034
36035/**
36036 * Expose `isAccessorDescriptor`
36037 */
36038
36039var isAccessorDescriptor_1$4 = isAccessorDescriptor$4;
36040
36041var isDataDescriptor$4 = function isDataDescriptor(obj, prop) {
36042 // data descriptor properties
36043 var data = {
36044 configurable: 'boolean',
36045 enumerable: 'boolean',
36046 writable: 'boolean'
36047 };
36048
36049 if (kindOf(obj) !== 'object') {
36050 return false;
36051 }
36052
36053 if (typeof prop === 'string') {
36054 var val = Object.getOwnPropertyDescriptor(obj, prop);
36055 return typeof val !== 'undefined';
36056 }
36057
36058 if (!('value' in obj) && !('writable' in obj)) {
36059 return false;
36060 }
36061
36062 for (var key in obj) {
36063 if (key === 'value') continue;
36064
36065 if (!data.hasOwnProperty(key)) {
36066 continue;
36067 }
36068
36069 if (kindOf(obj[key]) === data[key]) {
36070 continue;
36071 }
36072
36073 if (typeof obj[key] !== 'undefined') {
36074 return false;
36075 }
36076 }
36077 return true;
36078};
36079
36080var isDescriptor$4 = function isDescriptor(obj, key) {
36081 if (kindOf(obj) !== 'object') {
36082 return false;
36083 }
36084 if ('get' in obj) {
36085 return isAccessorDescriptor_1$4(obj, key);
36086 }
36087 return isDataDescriptor$4(obj, key);
36088};
36089
36090var defineProperty$8 = function defineProperty(obj, prop, val) {
36091 if (typeof obj !== 'object' && typeof obj !== 'function') {
36092 throw new TypeError('expected an object or function.');
36093 }
36094
36095 if (typeof prop !== 'string') {
36096 throw new TypeError('expected `prop` to be a string.');
36097 }
36098
36099 if (isDescriptor$4(val) && ('set' in val || 'get' in val)) {
36100 return Object.defineProperty(obj, prop, val);
36101 }
36102
36103 return Object.defineProperty(obj, prop, {
36104 configurable: true,
36105 enumerable: false,
36106 writable: true,
36107 value: val
36108 });
36109};
36110
36111var utils_1$2 = createCommonjsModule(function (module) {
36112
36113
36114
36115
36116/**
36117 * Utils
36118 */
36119
36120var utils = module.exports;
36121var cache = utils.cache = new fragmentCache();
36122
36123/**
36124 * Cast `val` to an array
36125 * @return {Array}
36126 */
36127
36128utils.arrayify = function(val) {
36129 if (!Array.isArray(val)) {
36130 return [val];
36131 }
36132 return val;
36133};
36134
36135/**
36136 * Memoize a generated regex or function
36137 */
36138
36139utils.memoize = function(type, pattern, options, fn) {
36140 var key = utils.createKey(type + pattern, options);
36141
36142 if (cache.has(type, key)) {
36143 return cache.get(type, key);
36144 }
36145
36146 var val = fn(pattern, options);
36147 if (options && options.cache === false) {
36148 return val;
36149 }
36150
36151 cache.set(type, key, val);
36152 return val;
36153};
36154
36155/**
36156 * Create the key to use for memoization. The key is generated
36157 * by iterating over the options and concatenating key-value pairs
36158 * to the pattern string.
36159 */
36160
36161utils.createKey = function(pattern, options) {
36162 var key = pattern;
36163 if (typeof options === 'undefined') {
36164 return key;
36165 }
36166 for (var prop in options) {
36167 key += ';' + prop + '=' + String(options[prop]);
36168 }
36169 return key;
36170};
36171
36172/**
36173 * Create the regex to use for matching text
36174 */
36175
36176utils.createRegex = function(str) {
36177 var opts = {contains: true, strictClose: false};
36178 return regexNot(str, opts);
36179};
36180});
36181
36182/**
36183 * Characters to use in text regex (we want to "not" match
36184 * characters that are matched by other parsers)
36185 */
36186
36187var TEXT_REGEX$1 = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+';
36188var not$3 = utils_1$2.createRegex(TEXT_REGEX$1);
36189
36190/**
36191 * Extglob parsers
36192 */
36193
36194function parsers$3(extglob) {
36195 extglob.state = extglob.state || {};
36196
36197 /**
36198 * Use `expand-brackets` parsers
36199 */
36200
36201 extglob.use(expandBrackets.parsers);
36202 extglob.parser.sets.paren = extglob.parser.sets.paren || [];
36203 extglob.parser
36204
36205 /**
36206 * Extglob open: "*("
36207 */
36208
36209 .capture('paren.open', function() {
36210 var parsed = this.parsed;
36211 var pos = this.position();
36212 var m = this.match(/^([!@*?+])?\(/);
36213 if (!m) return;
36214
36215 var prev = this.prev();
36216 var prefix = m[1];
36217 var val = m[0];
36218
36219 var open = pos({
36220 type: 'paren.open',
36221 parsed: parsed,
36222 val: val
36223 });
36224
36225 var node = pos({
36226 type: 'paren',
36227 prefix: prefix,
36228 nodes: [open]
36229 });
36230
36231 // if nested negation extglobs, just cancel them out to simplify
36232 if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') {
36233 prev.prefix = '@';
36234 node.prefix = '@';
36235 }
36236
36237 defineProperty$8(node, 'rest', this.input);
36238 defineProperty$8(node, 'parsed', parsed);
36239 defineProperty$8(node, 'parent', prev);
36240 defineProperty$8(open, 'parent', node);
36241
36242 this.push('paren', node);
36243 prev.nodes.push(node);
36244 })
36245
36246 /**
36247 * Extglob close: ")"
36248 */
36249
36250 .capture('paren.close', function() {
36251 var parsed = this.parsed;
36252 var pos = this.position();
36253 var m = this.match(/^\)/);
36254 if (!m) return;
36255
36256 var parent = this.pop('paren');
36257 var node = pos({
36258 type: 'paren.close',
36259 rest: this.input,
36260 parsed: parsed,
36261 val: m[0]
36262 });
36263
36264 if (!this.isType(parent, 'paren')) {
36265 if (this.options.strict) {
36266 throw new Error('missing opening paren: "("');
36267 }
36268 node.escaped = true;
36269 return node;
36270 }
36271
36272 node.prefix = parent.prefix;
36273 parent.nodes.push(node);
36274 defineProperty$8(node, 'parent', parent);
36275 })
36276
36277 /**
36278 * Escape: "\\."
36279 */
36280
36281 .capture('escape', function() {
36282 var pos = this.position();
36283 var m = this.match(/^\\(.)/);
36284 if (!m) return;
36285
36286 return pos({
36287 type: 'escape',
36288 val: m[0],
36289 ch: m[1]
36290 });
36291 })
36292
36293 /**
36294 * Question marks: "?"
36295 */
36296
36297 .capture('qmark', function() {
36298 var parsed = this.parsed;
36299 var pos = this.position();
36300 var m = this.match(/^\?+(?!\()/);
36301 if (!m) return;
36302 extglob.state.metachar = true;
36303 return pos({
36304 type: 'qmark',
36305 rest: this.input,
36306 parsed: parsed,
36307 val: m[0]
36308 });
36309 })
36310
36311 /**
36312 * Character parsers
36313 */
36314
36315 .capture('star', /^\*(?!\()/)
36316 .capture('plus', /^\+(?!\()/)
36317 .capture('dot', /^\./)
36318 .capture('text', not$3);
36319}
36320/**
36321 * Expose text regex string
36322 */
36323
36324var TEXT_REGEX_1$1 = TEXT_REGEX$1;
36325
36326/**
36327 * Extglob parsers
36328 */
36329
36330var parsers_1$1 = parsers$3;
36331parsers_1$1.TEXT_REGEX = TEXT_REGEX_1$1;
36332
36333/**
36334 * Module dependencies
36335 */
36336
36337
36338
36339
36340
36341/**
36342 * Local dependencies
36343 */
36344
36345
36346
36347
36348/**
36349 * Customize Snapdragon parser and renderer
36350 */
36351
36352function Extglob(options) {
36353 this.options = extendShallow$6({source: 'extglob'}, options);
36354 this.snapdragon = this.options.snapdragon || new snapdragon(this.options);
36355 this.snapdragon.patterns = this.snapdragon.patterns || {};
36356 this.compiler = this.snapdragon.compiler;
36357 this.parser = this.snapdragon.parser;
36358
36359 compilers$3(this.snapdragon);
36360 parsers_1$1(this.snapdragon);
36361
36362 /**
36363 * Override Snapdragon `.parse` method
36364 */
36365
36366 defineProperty$8(this.snapdragon, 'parse', function(str, options) {
36367 var parsed = snapdragon.prototype.parse.apply(this, arguments);
36368 parsed.input = str;
36369
36370 // escape unmatched brace/bracket/parens
36371 var last = this.parser.stack.pop();
36372 if (last && this.options.strict !== true) {
36373 var node = last.nodes[0];
36374 node.val = '\\' + node.val;
36375 var sibling = node.parent.nodes[1];
36376 if (sibling.type === 'star') {
36377 sibling.loose = true;
36378 }
36379 }
36380
36381 // add non-enumerable parser reference
36382 defineProperty$8(parsed, 'parser', this.parser);
36383 return parsed;
36384 });
36385
36386 /**
36387 * Decorate `.parse` method
36388 */
36389
36390 defineProperty$8(this, 'parse', function(ast, options) {
36391 return this.snapdragon.parse.apply(this.snapdragon, arguments);
36392 });
36393
36394 /**
36395 * Decorate `.compile` method
36396 */
36397
36398 defineProperty$8(this, 'compile', function(ast, options) {
36399 return this.snapdragon.compile.apply(this.snapdragon, arguments);
36400 });
36401
36402}
36403
36404/**
36405 * Expose `Extglob`
36406 */
36407
36408var extglob = Extglob;
36409
36410/**
36411 * Module dependencies
36412 */
36413
36414
36415
36416
36417
36418/**
36419 * Local dependencies
36420 */
36421
36422
36423
36424
36425
36426var MAX_LENGTH$3 = 1024 * 64;
36427
36428/**
36429 * Convert the given `extglob` pattern into a regex-compatible string. Returns
36430 * an object with the compiled result and the parsed AST.
36431 *
36432 * ```js
36433 * var extglob = require('extglob');
36434 * console.log(extglob('*.!(*a)'));
36435 * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?'
36436 * ```
36437 * @param {String} `pattern`
36438 * @param {Object} `options`
36439 * @return {String}
36440 * @api public
36441 */
36442
36443function extglob$1(pattern, options) {
36444 return extglob$1.create(pattern, options).output;
36445}
36446
36447/**
36448 * Takes an array of strings and an extglob pattern and returns a new
36449 * array that contains only the strings that match the pattern.
36450 *
36451 * ```js
36452 * var extglob = require('extglob');
36453 * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)'));
36454 * //=> ['a.b', 'a.c']
36455 * ```
36456 * @param {Array} `list` Array of strings to match
36457 * @param {String} `pattern` Extglob pattern
36458 * @param {Object} `options`
36459 * @return {Array} Returns an array of matches
36460 * @api public
36461 */
36462
36463extglob$1.match = function(list, pattern, options) {
36464 if (typeof pattern !== 'string') {
36465 throw new TypeError('expected pattern to be a string');
36466 }
36467
36468 list = utils_1$2.arrayify(list);
36469 var isMatch = extglob$1.matcher(pattern, options);
36470 var len = list.length;
36471 var idx = -1;
36472 var matches = [];
36473
36474 while (++idx < len) {
36475 var ele = list[idx];
36476
36477 if (isMatch(ele)) {
36478 matches.push(ele);
36479 }
36480 }
36481
36482 // if no options were passed, uniquify results and return
36483 if (typeof options === 'undefined') {
36484 return arrayUnique(matches);
36485 }
36486
36487 if (matches.length === 0) {
36488 if (options.failglob === true) {
36489 throw new Error('no matches found for "' + pattern + '"');
36490 }
36491 if (options.nonull === true || options.nullglob === true) {
36492 return [pattern.split('\\').join('')];
36493 }
36494 }
36495
36496 return options.nodupes !== false ? arrayUnique(matches) : matches;
36497};
36498
36499/**
36500 * Returns true if the specified `string` matches the given
36501 * extglob `pattern`.
36502 *
36503 * ```js
36504 * var extglob = require('extglob');
36505 *
36506 * console.log(extglob.isMatch('a.a', '*.!(*a)'));
36507 * //=> false
36508 * console.log(extglob.isMatch('a.b', '*.!(*a)'));
36509 * //=> true
36510 * ```
36511 * @param {String} `string` String to match
36512 * @param {String} `pattern` Extglob pattern
36513 * @param {String} `options`
36514 * @return {Boolean}
36515 * @api public
36516 */
36517
36518extglob$1.isMatch = function(str, pattern, options) {
36519 if (typeof pattern !== 'string') {
36520 throw new TypeError('expected pattern to be a string');
36521 }
36522
36523 if (typeof str !== 'string') {
36524 throw new TypeError('expected a string');
36525 }
36526
36527 if (pattern === str) {
36528 return true;
36529 }
36530
36531 if (pattern === '' || pattern === ' ' || pattern === '.') {
36532 return pattern === str;
36533 }
36534
36535 var isMatch = utils_1$2.memoize('isMatch', pattern, options, extglob$1.matcher);
36536 return isMatch(str);
36537};
36538
36539/**
36540 * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but
36541 * the pattern can match any part of the string.
36542 *
36543 * ```js
36544 * var extglob = require('extglob');
36545 * console.log(extglob.contains('aa/bb/cc', '*b'));
36546 * //=> true
36547 * console.log(extglob.contains('aa/bb/cc', '*d'));
36548 * //=> false
36549 * ```
36550 * @param {String} `str` The string to match.
36551 * @param {String} `pattern` Glob pattern to use for matching.
36552 * @param {Object} `options`
36553 * @return {Boolean} Returns true if the patter matches any part of `str`.
36554 * @api public
36555 */
36556
36557extglob$1.contains = function(str, pattern, options) {
36558 if (typeof str !== 'string') {
36559 throw new TypeError('expected a string');
36560 }
36561
36562 if (pattern === '' || pattern === ' ' || pattern === '.') {
36563 return pattern === str;
36564 }
36565
36566 var opts = extendShallow$6({}, options, {contains: true});
36567 opts.strictClose = false;
36568 opts.strictOpen = false;
36569 return extglob$1.isMatch(str, pattern, opts);
36570};
36571
36572/**
36573 * Takes an extglob pattern and returns a matcher function. The returned
36574 * function takes the string to match as its only argument.
36575 *
36576 * ```js
36577 * var extglob = require('extglob');
36578 * var isMatch = extglob.matcher('*.!(*a)');
36579 *
36580 * console.log(isMatch('a.a'));
36581 * //=> false
36582 * console.log(isMatch('a.b'));
36583 * //=> true
36584 * ```
36585 * @param {String} `pattern` Extglob pattern
36586 * @param {String} `options`
36587 * @return {Boolean}
36588 * @api public
36589 */
36590
36591extglob$1.matcher = function(pattern, options) {
36592 if (typeof pattern !== 'string') {
36593 throw new TypeError('expected pattern to be a string');
36594 }
36595
36596 function matcher() {
36597 var re = extglob$1.makeRe(pattern, options);
36598 return function(str) {
36599 return re.test(str);
36600 };
36601 }
36602
36603 return utils_1$2.memoize('matcher', pattern, options, matcher);
36604};
36605
36606/**
36607 * Convert the given `extglob` pattern into a regex-compatible string. Returns
36608 * an object with the compiled result and the parsed AST.
36609 *
36610 * ```js
36611 * var extglob = require('extglob');
36612 * console.log(extglob.create('*.!(*a)').output);
36613 * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?'
36614 * ```
36615 * @param {String} `str`
36616 * @param {Object} `options`
36617 * @return {String}
36618 * @api public
36619 */
36620
36621extglob$1.create = function(pattern, options) {
36622 if (typeof pattern !== 'string') {
36623 throw new TypeError('expected pattern to be a string');
36624 }
36625
36626 function create() {
36627 var ext = new extglob(options);
36628 var ast = ext.parse(pattern, options);
36629 return ext.compile(ast, options);
36630 }
36631
36632 return utils_1$2.memoize('create', pattern, options, create);
36633};
36634
36635/**
36636 * Returns an array of matches captured by `pattern` in `string`, or `null`
36637 * if the pattern did not match.
36638 *
36639 * ```js
36640 * var extglob = require('extglob');
36641 * extglob.capture(pattern, string[, options]);
36642 *
36643 * console.log(extglob.capture('test/*.js', 'test/foo.js'));
36644 * //=> ['foo']
36645 * console.log(extglob.capture('test/*.js', 'foo/bar.css'));
36646 * //=> null
36647 * ```
36648 * @param {String} `pattern` Glob pattern to use for matching.
36649 * @param {String} `string` String to match
36650 * @param {Object} `options` See available [options](#options) for changing how matches are performed
36651 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
36652 * @api public
36653 */
36654
36655extglob$1.capture = function(pattern, str, options) {
36656 var re = extglob$1.makeRe(pattern, extendShallow$6({capture: true}, options));
36657
36658 function match() {
36659 return function(string) {
36660 var match = re.exec(string);
36661 if (!match) {
36662 return null;
36663 }
36664
36665 return match.slice(1);
36666 };
36667 }
36668
36669 var capture = utils_1$2.memoize('capture', pattern, options, match);
36670 return capture(str);
36671};
36672
36673/**
36674 * Create a regular expression from the given `pattern` and `options`.
36675 *
36676 * ```js
36677 * var extglob = require('extglob');
36678 * var re = extglob.makeRe('*.!(*a)');
36679 * console.log(re);
36680 * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/
36681 * ```
36682 * @param {String} `pattern` The pattern to convert to regex.
36683 * @param {Object} `options`
36684 * @return {RegExp}
36685 * @api public
36686 */
36687
36688extglob$1.makeRe = function(pattern, options) {
36689 if (pattern instanceof RegExp) {
36690 return pattern;
36691 }
36692
36693 if (typeof pattern !== 'string') {
36694 throw new TypeError('expected pattern to be a string');
36695 }
36696
36697 if (pattern.length > MAX_LENGTH$3) {
36698 throw new Error('expected pattern to be less than ' + MAX_LENGTH$3 + ' characters');
36699 }
36700
36701 function makeRe() {
36702 var opts = extendShallow$6({strictErrors: false}, options);
36703 if (opts.strictErrors === true) opts.strict = true;
36704 var res = extglob$1.create(pattern, opts);
36705 return toRegex$1(res.output, opts);
36706 }
36707
36708 var regex = utils_1$2.memoize('makeRe', pattern, options, makeRe);
36709 if (regex.source.length > MAX_LENGTH$3) {
36710 throw new SyntaxError('potentially malicious regex detected');
36711 }
36712
36713 return regex;
36714};
36715
36716/**
36717 * Cache
36718 */
36719
36720extglob$1.cache = utils_1$2.cache;
36721extglob$1.clearCache = function() {
36722 extglob$1.cache.__data__ = {};
36723};
36724
36725/**
36726 * Expose `Extglob` constructor, parsers and compilers
36727 */
36728
36729extglob$1.Extglob = extglob;
36730extglob$1.compilers = compilers$3;
36731extglob$1.parsers = parsers_1$1;
36732
36733/**
36734 * Expose `extglob`
36735 * @type {Function}
36736 */
36737
36738var extglob_1 = extglob$1;
36739
36740var compilers$4 = function(snapdragon) {
36741 var compilers = snapdragon.compiler.compilers;
36742 var opts = snapdragon.options;
36743
36744 // register nanomatch compilers
36745 snapdragon.use(nanomatch_1.compilers);
36746
36747 // get references to some specific nanomatch compilers before they
36748 // are overridden by the extglob and/or custom compilers
36749 var escape = compilers.escape;
36750 var qmark = compilers.qmark;
36751 var slash = compilers.slash;
36752 var star = compilers.star;
36753 var text = compilers.text;
36754 var plus = compilers.plus;
36755 var dot = compilers.dot;
36756
36757 // register extglob compilers or escape exglobs if disabled
36758 if (opts.extglob === false || opts.noext === true) {
36759 snapdragon.compiler.use(escapeExtglobs);
36760 } else {
36761 snapdragon.use(extglob_1.compilers);
36762 }
36763
36764 snapdragon.use(function() {
36765 this.options.star = this.options.star || function(/*node*/) {
36766 return '[^\\\\/]*?';
36767 };
36768 });
36769
36770 // custom micromatch compilers
36771 snapdragon.compiler
36772
36773 // reset referenced compiler
36774 .set('dot', dot)
36775 .set('escape', escape)
36776 .set('plus', plus)
36777 .set('slash', slash)
36778 .set('qmark', qmark)
36779 .set('star', star)
36780 .set('text', text);
36781};
36782
36783function escapeExtglobs(compiler) {
36784 compiler.set('paren', function(node) {
36785 var val = '';
36786 visit(node, function(tok) {
36787 if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val;
36788 });
36789 return this.emit(val, node);
36790 });
36791
36792 /**
36793 * Visit `node` with the given `fn`
36794 */
36795
36796 function visit(node, fn) {
36797 return node.nodes ? mapVisit(node.nodes, fn) : fn(node);
36798 }
36799
36800 /**
36801 * Map visit over array of `nodes`.
36802 */
36803
36804 function mapVisit(nodes, fn) {
36805 var len = nodes.length;
36806 var idx = -1;
36807 while (++idx < len) {
36808 visit(nodes[idx], fn);
36809 }
36810 }
36811}
36812
36813var not$4;
36814
36815/**
36816 * Characters to use in negation regex (we want to "not" match
36817 * characters that are matched by other parsers)
36818 */
36819
36820var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+';
36821var createNotRegex = function(opts) {
36822 return not$4 || (not$4 = textRegex(TEXT));
36823};
36824
36825/**
36826 * Parsers
36827 */
36828
36829var parsers$4 = function(snapdragon) {
36830 var parsers = snapdragon.parser.parsers;
36831
36832 // register nanomatch parsers
36833 snapdragon.use(nanomatch_1.parsers);
36834
36835 // get references to some specific nanomatch parsers before they
36836 // are overridden by the extglob and/or parsers
36837 var escape = parsers.escape;
36838 var slash = parsers.slash;
36839 var qmark = parsers.qmark;
36840 var plus = parsers.plus;
36841 var star = parsers.star;
36842 var dot = parsers.dot;
36843
36844 // register extglob parsers
36845 snapdragon.use(extglob_1.parsers);
36846
36847 // custom micromatch parsers
36848 snapdragon.parser
36849 .use(function() {
36850 // override "notRegex" created in nanomatch parser
36851 this.notRegex = /^\!+(?!\()/;
36852 })
36853 // reset the referenced parsers
36854 .capture('escape', escape)
36855 .capture('slash', slash)
36856 .capture('qmark', qmark)
36857 .capture('star', star)
36858 .capture('plus', plus)
36859 .capture('dot', dot)
36860
36861 /**
36862 * Override `text` parser
36863 */
36864
36865 .capture('text', function() {
36866 if (this.isInside('bracket')) return;
36867 var pos = this.position();
36868 var m = this.match(createNotRegex(this.options));
36869 if (!m || !m[0]) return;
36870
36871 // escape regex boundary characters and simple brackets
36872 var val = m[0].replace(/([[\]^$])/g, '\\$1');
36873
36874 return pos({
36875 type: 'text',
36876 val: val
36877 });
36878 });
36879};
36880
36881/**
36882 * Create text regex
36883 */
36884
36885function textRegex(pattern) {
36886 var notStr = regexNot.create(pattern, {contains: true, strictClose: false});
36887 var prefix = '(?:[\\^]|\\\\|';
36888 return toRegex$1(prefix + notStr + ')', {strictClose: false});
36889}
36890
36891var cache$5 = new (fragmentCache)();
36892
36893var utils_1$3 = createCommonjsModule(function (module) {
36894
36895var utils = module.exports;
36896
36897
36898/**
36899 * Module dependencies
36900 */
36901
36902
36903utils.define = defineProperty;
36904utils.diff = arrDiff;
36905utils.extend = extendShallow;
36906utils.pick = object_pick;
36907utils.typeOf = kindOf;
36908utils.unique = arrayUnique;
36909
36910/**
36911 * Returns true if the platform is windows, or `path.sep` is `\\`.
36912 * This is defined as a function to allow `path.sep` to be set in unit tests,
36913 * or by the user, if there is a reason to do so.
36914 * @return {Boolean}
36915 */
36916
36917utils.isWindows = function() {
36918 return path.sep === '\\' || process.platform === 'win32';
36919};
36920
36921/**
36922 * Get the `Snapdragon` instance to use
36923 */
36924
36925utils.instantiate = function(ast, options) {
36926 var snapdragon$1;
36927 // if an instance was created by `.parse`, use that instance
36928 if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
36929 snapdragon$1 = ast.snapdragon;
36930 // if the user supplies an instance on options, use that instance
36931 } else if (utils.typeOf(options) === 'object' && options.snapdragon) {
36932 snapdragon$1 = options.snapdragon;
36933 // create a new instance
36934 } else {
36935 snapdragon$1 = new snapdragon(options);
36936 }
36937
36938 utils.define(snapdragon$1, 'parse', function(str, options) {
36939 var parsed = snapdragon.prototype.parse.apply(this, arguments);
36940 parsed.input = str;
36941
36942 // escape unmatched brace/bracket/parens
36943 var last = this.parser.stack.pop();
36944 if (last && this.options.strictErrors !== true) {
36945 var open = last.nodes[0];
36946 var inner = last.nodes[1];
36947 if (last.type === 'bracket') {
36948 if (inner.val.charAt(0) === '[') {
36949 inner.val = '\\' + inner.val;
36950 }
36951
36952 } else {
36953 open.val = '\\' + open.val;
36954 var sibling = open.parent.nodes[1];
36955 if (sibling.type === 'star') {
36956 sibling.loose = true;
36957 }
36958 }
36959 }
36960
36961 // add non-enumerable parser reference
36962 utils.define(parsed, 'parser', this.parser);
36963 return parsed;
36964 });
36965
36966 return snapdragon$1;
36967};
36968
36969/**
36970 * Create the key to use for memoization. The key is generated
36971 * by iterating over the options and concatenating key-value pairs
36972 * to the pattern string.
36973 */
36974
36975utils.createKey = function(pattern, options) {
36976 if (utils.typeOf(options) !== 'object') {
36977 return pattern;
36978 }
36979 var val = pattern;
36980 var keys = Object.keys(options);
36981 for (var i = 0; i < keys.length; i++) {
36982 var key = keys[i];
36983 val += ';' + key + '=' + String(options[key]);
36984 }
36985 return val;
36986};
36987
36988/**
36989 * Cast `val` to an array
36990 * @return {Array}
36991 */
36992
36993utils.arrayify = function(val) {
36994 if (typeof val === 'string') return [val];
36995 return val ? (Array.isArray(val) ? val : [val]) : [];
36996};
36997
36998/**
36999 * Return true if `val` is a non-empty string
37000 */
37001
37002utils.isString = function(val) {
37003 return typeof val === 'string';
37004};
37005
37006/**
37007 * Return true if `val` is a non-empty string
37008 */
37009
37010utils.isObject = function(val) {
37011 return utils.typeOf(val) === 'object';
37012};
37013
37014/**
37015 * Returns true if the given `str` has special characters
37016 */
37017
37018utils.hasSpecialChars = function(str) {
37019 return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str);
37020};
37021
37022/**
37023 * Escape regex characters in the given string
37024 */
37025
37026utils.escapeRegex = function(str) {
37027 return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&');
37028};
37029
37030/**
37031 * Normalize slashes in the given filepath.
37032 *
37033 * @param {String} `filepath`
37034 * @return {String}
37035 */
37036
37037utils.toPosixPath = function(str) {
37038 return str.replace(/\\+/g, '/');
37039};
37040
37041/**
37042 * Strip backslashes before special characters in a string.
37043 *
37044 * @param {String} `str`
37045 * @return {String}
37046 */
37047
37048utils.unescape = function(str) {
37049 return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
37050};
37051
37052/**
37053 * Strip the prefix from a filepath
37054 * @param {String} `fp`
37055 * @return {String}
37056 */
37057
37058utils.stripPrefix = function(str) {
37059 if (str.charAt(0) !== '.') {
37060 return str;
37061 }
37062 var ch = str.charAt(1);
37063 if (utils.isSlash(ch)) {
37064 return str.slice(2);
37065 }
37066 return str;
37067};
37068
37069/**
37070 * Returns true if the given str is an escaped or
37071 * unescaped path character
37072 */
37073
37074utils.isSlash = function(str) {
37075 return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
37076};
37077
37078/**
37079 * Returns a function that returns true if the given
37080 * pattern matches or contains a `filepath`
37081 *
37082 * @param {String} `pattern`
37083 * @return {Function}
37084 */
37085
37086utils.matchPath = function(pattern, options) {
37087 return (options && options.contains)
37088 ? utils.containsPattern(pattern, options)
37089 : utils.equalsPattern(pattern, options);
37090};
37091
37092/**
37093 * Returns true if the given (original) filepath or unixified path are equal
37094 * to the given pattern.
37095 */
37096
37097utils._equals = function(filepath, unixPath, pattern) {
37098 return pattern === filepath || pattern === unixPath;
37099};
37100
37101/**
37102 * Returns true if the given (original) filepath or unixified path contain
37103 * the given pattern.
37104 */
37105
37106utils._contains = function(filepath, unixPath, pattern) {
37107 return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
37108};
37109
37110/**
37111 * Returns a function that returns true if the given
37112 * pattern is the same as a given `filepath`
37113 *
37114 * @param {String} `pattern`
37115 * @return {Function}
37116 */
37117
37118utils.equalsPattern = function(pattern, options) {
37119 var unixify = utils.unixify(options);
37120 options = options || {};
37121
37122 return function fn(filepath) {
37123 var equal = utils._equals(filepath, unixify(filepath), pattern);
37124 if (equal === true || options.nocase !== true) {
37125 return equal;
37126 }
37127 var lower = filepath.toLowerCase();
37128 return utils._equals(lower, unixify(lower), pattern);
37129 };
37130};
37131
37132/**
37133 * Returns a function that returns true if the given
37134 * pattern contains a `filepath`
37135 *
37136 * @param {String} `pattern`
37137 * @return {Function}
37138 */
37139
37140utils.containsPattern = function(pattern, options) {
37141 var unixify = utils.unixify(options);
37142 options = options || {};
37143
37144 return function(filepath) {
37145 var contains = utils._contains(filepath, unixify(filepath), pattern);
37146 if (contains === true || options.nocase !== true) {
37147 return contains;
37148 }
37149 var lower = filepath.toLowerCase();
37150 return utils._contains(lower, unixify(lower), pattern);
37151 };
37152};
37153
37154/**
37155 * Returns a function that returns true if the given
37156 * regex matches the `filename` of a file path.
37157 *
37158 * @param {RegExp} `re` Matching regex
37159 * @return {Function}
37160 */
37161
37162utils.matchBasename = function(re) {
37163 return function(filepath) {
37164 return re.test(path.basename(filepath));
37165 };
37166};
37167
37168/**
37169 * Determines the filepath to return based on the provided options.
37170 * @return {any}
37171 */
37172
37173utils.value = function(str, unixify, options) {
37174 if (options && options.unixify === false) {
37175 return str;
37176 }
37177 return unixify(str);
37178};
37179
37180/**
37181 * Returns a function that normalizes slashes in a string to forward
37182 * slashes, strips `./` from beginning of paths, and optionally unescapes
37183 * special characters.
37184 * @return {Function}
37185 */
37186
37187utils.unixify = function(options) {
37188 options = options || {};
37189 return function(filepath) {
37190 if (utils.isWindows() || options.unixify === true) {
37191 filepath = utils.toPosixPath(filepath);
37192 }
37193 if (options.stripPrefix !== false) {
37194 filepath = utils.stripPrefix(filepath);
37195 }
37196 if (options.unescape === true) {
37197 filepath = utils.unescape(filepath);
37198 }
37199 return filepath;
37200 };
37201};
37202});
37203
37204/**
37205 * Module dependencies
37206 */
37207
37208
37209
37210
37211
37212
37213/**
37214 * Local dependencies
37215 */
37216
37217
37218
37219
37220
37221var MAX_LENGTH$4 = 1024 * 64;
37222
37223/**
37224 * The main function takes a list of strings and one or more
37225 * glob patterns to use for matching.
37226 *
37227 * ```js
37228 * var mm = require('micromatch');
37229 * mm(list, patterns[, options]);
37230 *
37231 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
37232 * //=> [ 'a.js' ]
37233 * ```
37234 * @param {Array} `list` A list of strings to match
37235 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37236 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37237 * @return {Array} Returns an array of matches
37238 * @summary false
37239 * @api public
37240 */
37241
37242function micromatch(list, patterns, options) {
37243 patterns = utils_1$3.arrayify(patterns);
37244 list = utils_1$3.arrayify(list);
37245
37246 var len = patterns.length;
37247 if (list.length === 0 || len === 0) {
37248 return [];
37249 }
37250
37251 if (len === 1) {
37252 return micromatch.match(list, patterns[0], options);
37253 }
37254
37255 var omit = [];
37256 var keep = [];
37257 var idx = -1;
37258
37259 while (++idx < len) {
37260 var pattern = patterns[idx];
37261
37262 if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
37263 omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options));
37264 } else {
37265 keep.push.apply(keep, micromatch.match(list, pattern, options));
37266 }
37267 }
37268
37269 var matches = utils_1$3.diff(keep, omit);
37270 if (!options || options.nodupes !== false) {
37271 return utils_1$3.unique(matches);
37272 }
37273
37274 return matches;
37275}
37276
37277/**
37278 * Similar to the main function, but `pattern` must be a string.
37279 *
37280 * ```js
37281 * var mm = require('micromatch');
37282 * mm.match(list, pattern[, options]);
37283 *
37284 * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
37285 * //=> ['a.a', 'a.aa']
37286 * ```
37287 * @param {Array} `list` Array of strings to match
37288 * @param {String} `pattern` Glob pattern to use for matching.
37289 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37290 * @return {Array} Returns an array of matches
37291 * @api public
37292 */
37293
37294micromatch.match = function(list, pattern, options) {
37295 if (Array.isArray(pattern)) {
37296 throw new TypeError('expected pattern to be a string');
37297 }
37298
37299 var unixify = utils_1$3.unixify(options);
37300 var isMatch = memoize$3('match', pattern, options, micromatch.matcher);
37301 var matches = [];
37302
37303 list = utils_1$3.arrayify(list);
37304 var len = list.length;
37305 var idx = -1;
37306
37307 while (++idx < len) {
37308 var ele = list[idx];
37309 if (ele === pattern || isMatch(ele)) {
37310 matches.push(utils_1$3.value(ele, unixify, options));
37311 }
37312 }
37313
37314 // if no options were passed, uniquify results and return
37315 if (typeof options === 'undefined') {
37316 return utils_1$3.unique(matches);
37317 }
37318
37319 if (matches.length === 0) {
37320 if (options.failglob === true) {
37321 throw new Error('no matches found for "' + pattern + '"');
37322 }
37323 if (options.nonull === true || options.nullglob === true) {
37324 return [options.unescape ? utils_1$3.unescape(pattern) : pattern];
37325 }
37326 }
37327
37328 // if `opts.ignore` was defined, diff ignored list
37329 if (options.ignore) {
37330 matches = micromatch.not(matches, options.ignore, options);
37331 }
37332
37333 return options.nodupes !== false ? utils_1$3.unique(matches) : matches;
37334};
37335
37336/**
37337 * Returns true if the specified `string` matches the given glob `pattern`.
37338 *
37339 * ```js
37340 * var mm = require('micromatch');
37341 * mm.isMatch(string, pattern[, options]);
37342 *
37343 * console.log(mm.isMatch('a.a', '*.a'));
37344 * //=> true
37345 * console.log(mm.isMatch('a.b', '*.a'));
37346 * //=> false
37347 * ```
37348 * @param {String} `string` String to match
37349 * @param {String} `pattern` Glob pattern to use for matching.
37350 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37351 * @return {Boolean} Returns true if the string matches the glob pattern.
37352 * @api public
37353 */
37354
37355micromatch.isMatch = function(str, pattern, options) {
37356 if (typeof str !== 'string') {
37357 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37358 }
37359
37360 if (isEmptyString(str) || isEmptyString(pattern)) {
37361 return false;
37362 }
37363
37364 var equals = utils_1$3.equalsPattern(options);
37365 if (equals(str)) {
37366 return true;
37367 }
37368
37369 var isMatch = memoize$3('isMatch', pattern, options, micromatch.matcher);
37370 return isMatch(str);
37371};
37372
37373/**
37374 * Returns true if some of the strings in the given `list` match any of the
37375 * given glob `patterns`.
37376 *
37377 * ```js
37378 * var mm = require('micromatch');
37379 * mm.some(list, patterns[, options]);
37380 *
37381 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
37382 * // true
37383 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
37384 * // false
37385 * ```
37386 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
37387 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37388 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37389 * @return {Boolean} Returns true if any patterns match `str`
37390 * @api public
37391 */
37392
37393micromatch.some = function(list, patterns, options) {
37394 if (typeof list === 'string') {
37395 list = [list];
37396 }
37397 for (var i = 0; i < list.length; i++) {
37398 if (micromatch(list[i], patterns, options).length === 1) {
37399 return true;
37400 }
37401 }
37402 return false;
37403};
37404
37405/**
37406 * Returns true if every string in the given `list` matches
37407 * any of the given glob `patterns`.
37408 *
37409 * ```js
37410 * var mm = require('micromatch');
37411 * mm.every(list, patterns[, options]);
37412 *
37413 * console.log(mm.every('foo.js', ['foo.js']));
37414 * // true
37415 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
37416 * // true
37417 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
37418 * // false
37419 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
37420 * // false
37421 * ```
37422 * @param {String|Array} `list` The string or array of strings to test.
37423 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37424 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37425 * @return {Boolean} Returns true if any patterns match `str`
37426 * @api public
37427 */
37428
37429micromatch.every = function(list, patterns, options) {
37430 if (typeof list === 'string') {
37431 list = [list];
37432 }
37433 for (var i = 0; i < list.length; i++) {
37434 if (micromatch(list[i], patterns, options).length !== 1) {
37435 return false;
37436 }
37437 }
37438 return true;
37439};
37440
37441/**
37442 * Returns true if **any** of the given glob `patterns`
37443 * match the specified `string`.
37444 *
37445 * ```js
37446 * var mm = require('micromatch');
37447 * mm.any(string, patterns[, options]);
37448 *
37449 * console.log(mm.any('a.a', ['b.*', '*.a']));
37450 * //=> true
37451 * console.log(mm.any('a.a', 'b.*'));
37452 * //=> false
37453 * ```
37454 * @param {String|Array} `str` The string to test.
37455 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37456 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37457 * @return {Boolean} Returns true if any patterns match `str`
37458 * @api public
37459 */
37460
37461micromatch.any = function(str, patterns, options) {
37462 if (typeof str !== 'string') {
37463 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37464 }
37465
37466 if (isEmptyString(str) || isEmptyString(patterns)) {
37467 return false;
37468 }
37469
37470 if (typeof patterns === 'string') {
37471 patterns = [patterns];
37472 }
37473
37474 for (var i = 0; i < patterns.length; i++) {
37475 if (micromatch.isMatch(str, patterns[i], options)) {
37476 return true;
37477 }
37478 }
37479 return false;
37480};
37481
37482/**
37483 * Returns true if **all** of the given `patterns` match
37484 * the specified string.
37485 *
37486 * ```js
37487 * var mm = require('micromatch');
37488 * mm.all(string, patterns[, options]);
37489 *
37490 * console.log(mm.all('foo.js', ['foo.js']));
37491 * // true
37492 *
37493 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
37494 * // false
37495 *
37496 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
37497 * // true
37498 *
37499 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
37500 * // true
37501 * ```
37502 * @param {String|Array} `str` The string to test.
37503 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37504 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37505 * @return {Boolean} Returns true if any patterns match `str`
37506 * @api public
37507 */
37508
37509micromatch.all = function(str, patterns, options) {
37510 if (typeof str !== 'string') {
37511 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37512 }
37513 if (typeof patterns === 'string') {
37514 patterns = [patterns];
37515 }
37516 for (var i = 0; i < patterns.length; i++) {
37517 if (!micromatch.isMatch(str, patterns[i], options)) {
37518 return false;
37519 }
37520 }
37521 return true;
37522};
37523
37524/**
37525 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
37526 *
37527 * ```js
37528 * var mm = require('micromatch');
37529 * mm.not(list, patterns[, options]);
37530 *
37531 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
37532 * //=> ['b.b', 'c.c']
37533 * ```
37534 * @param {Array} `list` Array of strings to match.
37535 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
37536 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37537 * @return {Array} Returns an array of strings that **do not match** the given patterns.
37538 * @api public
37539 */
37540
37541micromatch.not = function(list, patterns, options) {
37542 var opts = extendShallow({}, options);
37543 var ignore = opts.ignore;
37544 delete opts.ignore;
37545
37546 var unixify = utils_1$3.unixify(opts);
37547 list = utils_1$3.arrayify(list).map(unixify);
37548
37549 var matches = utils_1$3.diff(list, micromatch(list, patterns, opts));
37550 if (ignore) {
37551 matches = utils_1$3.diff(matches, micromatch(list, ignore));
37552 }
37553
37554 return opts.nodupes !== false ? utils_1$3.unique(matches) : matches;
37555};
37556
37557/**
37558 * Returns true if the given `string` contains the given pattern. Similar
37559 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
37560 *
37561 * ```js
37562 * var mm = require('micromatch');
37563 * mm.contains(string, pattern[, options]);
37564 *
37565 * console.log(mm.contains('aa/bb/cc', '*b'));
37566 * //=> true
37567 * console.log(mm.contains('aa/bb/cc', '*d'));
37568 * //=> false
37569 * ```
37570 * @param {String} `str` The string to match.
37571 * @param {String|Array} `patterns` Glob pattern to use for matching.
37572 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37573 * @return {Boolean} Returns true if the patter matches any part of `str`.
37574 * @api public
37575 */
37576
37577micromatch.contains = function(str, patterns, options) {
37578 if (typeof str !== 'string') {
37579 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37580 }
37581
37582 if (typeof patterns === 'string') {
37583 if (isEmptyString(str) || isEmptyString(patterns)) {
37584 return false;
37585 }
37586
37587 var equals = utils_1$3.equalsPattern(patterns, options);
37588 if (equals(str)) {
37589 return true;
37590 }
37591 var contains = utils_1$3.containsPattern(patterns, options);
37592 if (contains(str)) {
37593 return true;
37594 }
37595 }
37596
37597 var opts = extendShallow({}, options, {contains: true});
37598 return micromatch.any(str, patterns, opts);
37599};
37600
37601/**
37602 * Returns true if the given pattern and options should enable
37603 * the `matchBase` option.
37604 * @return {Boolean}
37605 * @api private
37606 */
37607
37608micromatch.matchBase = function(pattern, options) {
37609 if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
37610 return options.basename === true || options.matchBase === true;
37611};
37612
37613/**
37614 * Filter the keys of the given object with the given `glob` pattern
37615 * and `options`. Does not attempt to match nested keys. If you need this feature,
37616 * use [glob-object][] instead.
37617 *
37618 * ```js
37619 * var mm = require('micromatch');
37620 * mm.matchKeys(object, patterns[, options]);
37621 *
37622 * var obj = { aa: 'a', ab: 'b', ac: 'c' };
37623 * console.log(mm.matchKeys(obj, '*b'));
37624 * //=> { ab: 'b' }
37625 * ```
37626 * @param {Object} `object` The object with keys to filter.
37627 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37628 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37629 * @return {Object} Returns an object with only keys that match the given patterns.
37630 * @api public
37631 */
37632
37633micromatch.matchKeys = function(obj, patterns, options) {
37634 if (!utils_1$3.isObject(obj)) {
37635 throw new TypeError('expected the first argument to be an object');
37636 }
37637 var keys = micromatch(Object.keys(obj), patterns, options);
37638 return utils_1$3.pick(obj, keys);
37639};
37640
37641/**
37642 * Returns a memoized matcher function from the given glob `pattern` and `options`.
37643 * The returned function takes a string to match as its only argument and returns
37644 * true if the string is a match.
37645 *
37646 * ```js
37647 * var mm = require('micromatch');
37648 * mm.matcher(pattern[, options]);
37649 *
37650 * var isMatch = mm.matcher('*.!(*a)');
37651 * console.log(isMatch('a.a'));
37652 * //=> false
37653 * console.log(isMatch('a.b'));
37654 * //=> true
37655 * ```
37656 * @param {String} `pattern` Glob pattern
37657 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
37658 * @return {Function} Returns a matcher function.
37659 * @api public
37660 */
37661
37662micromatch.matcher = function matcher(pattern, options) {
37663 if (Array.isArray(pattern)) {
37664 return compose$1(pattern, options, matcher);
37665 }
37666
37667 // if pattern is a regex
37668 if (pattern instanceof RegExp) {
37669 return test(pattern);
37670 }
37671
37672 // if pattern is invalid
37673 if (!utils_1$3.isString(pattern)) {
37674 throw new TypeError('expected pattern to be an array, string or regex');
37675 }
37676
37677 // if pattern is a non-glob string
37678 if (!utils_1$3.hasSpecialChars(pattern)) {
37679 if (options && options.nocase === true) {
37680 pattern = pattern.toLowerCase();
37681 }
37682 return utils_1$3.matchPath(pattern, options);
37683 }
37684
37685 // if pattern is a glob string
37686 var re = micromatch.makeRe(pattern, options);
37687
37688 // if `options.matchBase` or `options.basename` is defined
37689 if (micromatch.matchBase(pattern, options)) {
37690 return utils_1$3.matchBasename(re, options);
37691 }
37692
37693 function test(regex) {
37694 var equals = utils_1$3.equalsPattern(options);
37695 var unixify = utils_1$3.unixify(options);
37696
37697 return function(str) {
37698 if (equals(str)) {
37699 return true;
37700 }
37701
37702 if (regex.test(unixify(str))) {
37703 return true;
37704 }
37705 return false;
37706 };
37707 }
37708
37709 var fn = test(re);
37710 Object.defineProperty(fn, 'result', {
37711 configurable: true,
37712 enumerable: false,
37713 value: re.result
37714 });
37715 return fn;
37716};
37717
37718/**
37719 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
37720 *
37721 * ```js
37722 * var mm = require('micromatch');
37723 * mm.capture(pattern, string[, options]);
37724 *
37725 * console.log(mm.capture('test/*.js', 'test/foo.js'));
37726 * //=> ['foo']
37727 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
37728 * //=> null
37729 * ```
37730 * @param {String} `pattern` Glob pattern to use for matching.
37731 * @param {String} `string` String to match
37732 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37733 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
37734 * @api public
37735 */
37736
37737micromatch.capture = function(pattern, str, options) {
37738 var re = micromatch.makeRe(pattern, extendShallow({capture: true}, options));
37739 var unixify = utils_1$3.unixify(options);
37740
37741 function match() {
37742 return function(string) {
37743 var match = re.exec(unixify(string));
37744 if (!match) {
37745 return null;
37746 }
37747
37748 return match.slice(1);
37749 };
37750 }
37751
37752 var capture = memoize$3('capture', pattern, options, match);
37753 return capture(str);
37754};
37755
37756/**
37757 * Create a regular expression from the given glob `pattern`.
37758 *
37759 * ```js
37760 * var mm = require('micromatch');
37761 * mm.makeRe(pattern[, options]);
37762 *
37763 * console.log(mm.makeRe('*.js'));
37764 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
37765 * ```
37766 * @param {String} `pattern` A glob pattern to convert to regex.
37767 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
37768 * @return {RegExp} Returns a regex created from the given pattern.
37769 * @api public
37770 */
37771
37772micromatch.makeRe = function(pattern, options) {
37773 if (typeof pattern !== 'string') {
37774 throw new TypeError('expected pattern to be a string');
37775 }
37776
37777 if (pattern.length > MAX_LENGTH$4) {
37778 throw new Error('expected pattern to be less than ' + MAX_LENGTH$4 + ' characters');
37779 }
37780
37781 function makeRe() {
37782 var result = micromatch.create(pattern, options);
37783 var ast_array = [];
37784 var output = result.map(function(obj) {
37785 obj.ast.state = obj.state;
37786 ast_array.push(obj.ast);
37787 return obj.output;
37788 });
37789
37790 var regex = toRegex$1(output.join('|'), options);
37791 Object.defineProperty(regex, 'result', {
37792 configurable: true,
37793 enumerable: false,
37794 value: ast_array
37795 });
37796 return regex;
37797 }
37798
37799 return memoize$3('makeRe', pattern, options, makeRe);
37800};
37801
37802/**
37803 * Expand the given brace `pattern`.
37804 *
37805 * ```js
37806 * var mm = require('micromatch');
37807 * console.log(mm.braces('foo/{a,b}/bar'));
37808 * //=> ['foo/(a|b)/bar']
37809 *
37810 * console.log(mm.braces('foo/{a,b}/bar', {expand: true}));
37811 * //=> ['foo/(a|b)/bar']
37812 * ```
37813 * @param {String} `pattern` String with brace pattern to expand.
37814 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
37815 * @return {Array}
37816 * @api public
37817 */
37818
37819micromatch.braces = function(pattern, options) {
37820 if (typeof pattern !== 'string' && !Array.isArray(pattern)) {
37821 throw new TypeError('expected pattern to be an array or string');
37822 }
37823
37824 function expand() {
37825 if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
37826 return utils_1$3.arrayify(pattern);
37827 }
37828 return braces_1(pattern, options);
37829 }
37830
37831 return memoize$3('braces', pattern, options, expand);
37832};
37833
37834/**
37835 * Proxy to the [micromatch.braces](#method), for parity with
37836 * minimatch.
37837 */
37838
37839micromatch.braceExpand = function(pattern, options) {
37840 var opts = extendShallow({}, options, {expand: true});
37841 return micromatch.braces(pattern, opts);
37842};
37843
37844/**
37845 * Parses the given glob `pattern` and returns an array of abstract syntax
37846 * trees (ASTs), with the compiled `output` and optional source `map` on
37847 * each AST.
37848 *
37849 * ```js
37850 * var mm = require('micromatch');
37851 * mm.create(pattern[, options]);
37852 *
37853 * console.log(mm.create('abc/*.js'));
37854 * // [{ options: { source: 'string', sourcemap: true },
37855 * // state: {},
37856 * // compilers:
37857 * // { ... },
37858 * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
37859 * // ast:
37860 * // { type: 'root',
37861 * // errors: [],
37862 * // nodes:
37863 * // [ ... ],
37864 * // dot: false,
37865 * // input: 'abc/*.js' },
37866 * // parsingErrors: [],
37867 * // map:
37868 * // { version: 3,
37869 * // sources: [ 'string' ],
37870 * // names: [],
37871 * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
37872 * // sourcesContent: [ 'abc/*.js' ] },
37873 * // position: { line: 1, column: 28 },
37874 * // content: {},
37875 * // files: {},
37876 * // idx: 6 }]
37877 * ```
37878 * @param {String} `pattern` Glob pattern to parse and compile.
37879 * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
37880 * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
37881 * @api public
37882 */
37883
37884micromatch.create = function(pattern, options) {
37885 return memoize$3('create', pattern, options, function() {
37886 function create(str, opts) {
37887 return micromatch.compile(micromatch.parse(str, opts), opts);
37888 }
37889
37890 pattern = micromatch.braces(pattern, options);
37891 var len = pattern.length;
37892 var idx = -1;
37893 var res = [];
37894
37895 while (++idx < len) {
37896 res.push(create(pattern[idx], options));
37897 }
37898 return res;
37899 });
37900};
37901
37902/**
37903 * Parse the given `str` with the given `options`.
37904 *
37905 * ```js
37906 * var mm = require('micromatch');
37907 * mm.parse(pattern[, options]);
37908 *
37909 * var ast = mm.parse('a/{b,c}/d');
37910 * console.log(ast);
37911 * // { type: 'root',
37912 * // errors: [],
37913 * // input: 'a/{b,c}/d',
37914 * // nodes:
37915 * // [ { type: 'bos', val: '' },
37916 * // { type: 'text', val: 'a/' },
37917 * // { type: 'brace',
37918 * // nodes:
37919 * // [ { type: 'brace.open', val: '{' },
37920 * // { type: 'text', val: 'b,c' },
37921 * // { type: 'brace.close', val: '}' } ] },
37922 * // { type: 'text', val: '/d' },
37923 * // { type: 'eos', val: '' } ] }
37924 * ```
37925 * @param {String} `str`
37926 * @param {Object} `options`
37927 * @return {Object} Returns an AST
37928 * @api public
37929 */
37930
37931micromatch.parse = function(pattern, options) {
37932 if (typeof pattern !== 'string') {
37933 throw new TypeError('expected a string');
37934 }
37935
37936 function parse() {
37937 var snapdragon = utils_1$3.instantiate(null, options);
37938 parsers$4(snapdragon, options);
37939
37940 var ast = snapdragon.parse(pattern, options);
37941 utils_1$3.define(ast, 'snapdragon', snapdragon);
37942 ast.input = pattern;
37943 return ast;
37944 }
37945
37946 return memoize$3('parse', pattern, options, parse);
37947};
37948
37949/**
37950 * Compile the given `ast` or string with the given `options`.
37951 *
37952 * ```js
37953 * var mm = require('micromatch');
37954 * mm.compile(ast[, options]);
37955 *
37956 * var ast = mm.parse('a/{b,c}/d');
37957 * console.log(mm.compile(ast));
37958 * // { options: { source: 'string' },
37959 * // state: {},
37960 * // compilers:
37961 * // { eos: [Function],
37962 * // noop: [Function],
37963 * // bos: [Function],
37964 * // brace: [Function],
37965 * // 'brace.open': [Function],
37966 * // text: [Function],
37967 * // 'brace.close': [Function] },
37968 * // output: [ 'a/(b|c)/d' ],
37969 * // ast:
37970 * // { ... },
37971 * // parsingErrors: [] }
37972 * ```
37973 * @param {Object|String} `ast`
37974 * @param {Object} `options`
37975 * @return {Object} Returns an object that has an `output` property with the compiled string.
37976 * @api public
37977 */
37978
37979micromatch.compile = function(ast, options) {
37980 if (typeof ast === 'string') {
37981 ast = micromatch.parse(ast, options);
37982 }
37983
37984 return memoize$3('compile', ast.input, options, function() {
37985 var snapdragon = utils_1$3.instantiate(ast, options);
37986 compilers$4(snapdragon, options);
37987 return snapdragon.compile(ast, options);
37988 });
37989};
37990
37991/**
37992 * Clear the regex cache.
37993 *
37994 * ```js
37995 * mm.clearCache();
37996 * ```
37997 * @api public
37998 */
37999
38000micromatch.clearCache = function() {
38001 micromatch.cache.caches = {};
38002};
38003
38004/**
38005 * Returns true if the given value is effectively an empty string
38006 */
38007
38008function isEmptyString(val) {
38009 return String(val) === '' || String(val) === './';
38010}
38011
38012/**
38013 * Compose a matcher function with the given patterns.
38014 * This allows matcher functions to be compiled once and
38015 * called multiple times.
38016 */
38017
38018function compose$1(patterns, options, matcher) {
38019 var matchers;
38020
38021 return memoize$3('compose', String(patterns), options, function() {
38022 return function(file) {
38023 // delay composition until it's invoked the first time,
38024 // after that it won't be called again
38025 if (!matchers) {
38026 matchers = [];
38027 for (var i = 0; i < patterns.length; i++) {
38028 matchers.push(matcher(patterns[i], options));
38029 }
38030 }
38031
38032 var len = matchers.length;
38033 while (len--) {
38034 if (matchers[len](file) === true) {
38035 return true;
38036 }
38037 }
38038 return false;
38039 };
38040 });
38041}
38042
38043/**
38044 * Memoize a generated regex or function. A unique key is generated
38045 * from the `type` (usually method name), the `pattern`, and
38046 * user-defined options.
38047 */
38048
38049function memoize$3(type, pattern, options, fn) {
38050 var key = utils_1$3.createKey(type + '=' + pattern, options);
38051
38052 if (options && options.cache === false) {
38053 return fn(pattern, options);
38054 }
38055
38056 if (cache$5.has(type, key)) {
38057 return cache$5.get(type, key);
38058 }
38059
38060 var val = fn(pattern, options);
38061 cache$5.set(type, key, val);
38062 return val;
38063}
38064
38065/**
38066 * Expose compiler, parser and cache on `micromatch`
38067 */
38068
38069micromatch.compilers = compilers$4;
38070micromatch.parsers = parsers$4;
38071micromatch.caches = cache$5.caches;
38072
38073/**
38074 * Expose `micromatch`
38075 * @type {Function}
38076 */
38077
38078var micromatch_1 = micromatch;
38079var micromatch_2 = micromatch_1.matcher;
38080
38081function ensureArray(thing) {
38082 if (Array.isArray(thing))
38083 return thing;
38084 if (thing == undefined)
38085 return [];
38086 return [thing];
38087}
38088
38089var createFilter = function createFilter(include, exclude) {
38090 var getMatcher = function (id) {
38091 return id instanceof RegExp
38092 ? id
38093 : {
38094 test: micromatch_2(resolve$1(id)
38095 .split(sep)
38096 .join('/'))
38097 };
38098 };
38099 var includeMatchers = ensureArray(include).map(getMatcher);
38100 var excludeMatchers = ensureArray(exclude).map(getMatcher);
38101 return function (id) {
38102 if (typeof id !== 'string')
38103 return false;
38104 if (/\0/.test(id))
38105 return false;
38106 id = id.split(sep).join('/');
38107 for (var i = 0; i < excludeMatchers.length; ++i) {
38108 var matcher = excludeMatchers[i];
38109 if (matcher.test(id))
38110 return false;
38111 }
38112 for (var i = 0; i < includeMatchers.length; ++i) {
38113 var matcher = includeMatchers[i];
38114 if (matcher.test(id))
38115 return true;
38116 }
38117 return !includeMatchers.length;
38118 };
38119};
38120
38121var modules = {};
38122
38123var getModule = function(dir) {
38124 var rootPath = dir ? path.resolve(dir) : process.cwd();
38125 var rootName = path.join(rootPath, '@root');
38126 var root = modules[rootName];
38127 if (!root) {
38128 root = new module$1(rootName);
38129 root.filename = rootName;
38130 root.paths = module$1._nodeModulePaths(rootPath);
38131 modules[rootName] = root;
38132 }
38133 return root;
38134};
38135
38136var requireRelative = function(requested, relativeTo) {
38137 var root = getModule(relativeTo);
38138 return root.require(requested);
38139};
38140
38141requireRelative.resolve = function(requested, relativeTo) {
38142 var root = getModule(relativeTo);
38143 return module$1._resolveFilename(requested, root);
38144};
38145
38146var requireRelative_1 = requireRelative;
38147
38148var chokidar;
38149try {
38150 chokidar = requireRelative_1('chokidar', process.cwd());
38151}
38152catch (err) {
38153 chokidar = null;
38154}
38155var chokidar$1 = chokidar;
38156
38157var opts = { encoding: 'utf-8', persistent: true };
38158var watchers = new Map();
38159function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
38160 if (!watchers.has(chokidarOptionsHash))
38161 watchers.set(chokidarOptionsHash, new Map());
38162 var group = watchers.get(chokidarOptionsHash);
38163 var watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
38164 if (!watcher.fileExists) {
38165 if (isTransformDependency)
38166 throw new Error("Transform dependency " + id + " does not exist.");
38167 }
38168 else {
38169 watcher.addTask(task, isTransformDependency);
38170 }
38171}
38172function deleteTask(id, target, chokidarOptionsHash) {
38173 var group = watchers.get(chokidarOptionsHash);
38174 var watcher = group.get(id);
38175 if (watcher)
38176 watcher.deleteTask(target, group);
38177}
38178var FileWatcher = /** @class */ (function () {
38179 function FileWatcher(id, chokidarOptions, group) {
38180 var _this = this;
38181 this.id = id;
38182 this.tasks = new Set();
38183 this.transformDependencyTasks = new Set();
38184 var modifiedTime;
38185 try {
38186 var stats = statSync(id);
38187 modifiedTime = +stats.mtime;
38188 this.fileExists = true;
38189 }
38190 catch (err) {
38191 if (err.code === 'ENOENT') {
38192 // can't watch files that don't exist (e.g. injected
38193 // by plugins somehow)
38194 this.fileExists = false;
38195 return;
38196 }
38197 else {
38198 throw err;
38199 }
38200 }
38201 var handleWatchEvent = function (event) {
38202 if (event === 'rename' || event === 'unlink') {
38203 _this.close();
38204 group.delete(id);
38205 _this.trigger(id);
38206 }
38207 else {
38208 var stats = void 0;
38209 try {
38210 stats = statSync(id);
38211 }
38212 catch (err) {
38213 if (err.code === 'ENOENT') {
38214 modifiedTime = -1;
38215 _this.trigger(id);
38216 return;
38217 }
38218 throw err;
38219 }
38220 // debounce
38221 if (+stats.mtime - modifiedTime > 15)
38222 _this.trigger(id);
38223 }
38224 };
38225 if (chokidarOptions) {
38226 this.fsWatcher = chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent);
38227 }
38228 else {
38229 this.fsWatcher = watch$1(id, opts, handleWatchEvent);
38230 }
38231 group.set(id, this);
38232 }
38233 FileWatcher.prototype.addTask = function (task, isTransformDependency) {
38234 if (isTransformDependency === void 0) { isTransformDependency = false; }
38235 if (isTransformDependency)
38236 this.transformDependencyTasks.add(task);
38237 else
38238 this.tasks.add(task);
38239 };
38240 FileWatcher.prototype.close = function () {
38241 this.fsWatcher.close();
38242 };
38243 FileWatcher.prototype.deleteTask = function (task, group) {
38244 var deleted = this.tasks.delete(task);
38245 deleted = this.transformDependencyTasks.delete(task) || deleted;
38246 if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
38247 group.delete(this.id);
38248 this.close();
38249 }
38250 };
38251 FileWatcher.prototype.trigger = function (id) {
38252 this.tasks.forEach(function (task) {
38253 task.invalidate(id, false);
38254 });
38255 this.transformDependencyTasks.forEach(function (task) {
38256 task.invalidate(id, true);
38257 });
38258 };
38259 return FileWatcher;
38260}());
38261
38262var DELAY = 200;
38263var Watcher = /** @class */ (function () {
38264 function Watcher(configs) {
38265 var _this = this;
38266 this.invalidatedIds = new Set();
38267 this.rerun = false;
38268 this.succeeded = false;
38269 this.emitter = new /** @class */ (function (_super) {
38270 __extends(class_1, _super);
38271 function class_1(close) {
38272 var _this = _super.call(this) || this;
38273 _this.close = close;
38274 // Allows more than 10 bundles to be watched without
38275 // showing the `MaxListenersExceededWarning` to the user.
38276 _this.setMaxListeners(Infinity);
38277 return _this;
38278 }
38279 return class_1;
38280 }(EventEmitter))(this.close.bind(this));
38281 this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(function (config) { return new Task(_this, config); });
38282 this.running = true;
38283 process.nextTick(function () { return _this.run(); });
38284 }
38285 Watcher.prototype.close = function () {
38286 if (this.buildTimeout)
38287 clearTimeout(this.buildTimeout);
38288 this.tasks.forEach(function (task) {
38289 task.close();
38290 });
38291 this.emitter.removeAllListeners();
38292 };
38293 Watcher.prototype.emit = function (event, value) {
38294 this.emitter.emit(event, value);
38295 };
38296 Watcher.prototype.invalidate = function (id) {
38297 var _this = this;
38298 if (id) {
38299 this.invalidatedIds.add(id);
38300 }
38301 if (this.running) {
38302 this.rerun = true;
38303 return;
38304 }
38305 if (this.buildTimeout)
38306 clearTimeout(this.buildTimeout);
38307 this.buildTimeout = setTimeout(function () {
38308 _this.buildTimeout = undefined;
38309 _this.invalidatedIds.forEach(function (id) { return _this.emit('change', id); });
38310 _this.invalidatedIds.clear();
38311 _this.emit('restart');
38312 _this.run();
38313 }, DELAY);
38314 };
38315 Watcher.prototype.run = function () {
38316 var _this = this;
38317 this.running = true;
38318 this.emit('event', {
38319 code: 'START'
38320 });
38321 var taskPromise = Promise.resolve();
38322 var _loop_1 = function (task) {
38323 taskPromise = taskPromise.then(function () { return task.run(); });
38324 };
38325 for (var _i = 0, _a = this.tasks; _i < _a.length; _i++) {
38326 var task = _a[_i];
38327 _loop_1(task);
38328 }
38329 return taskPromise
38330 .then(function () {
38331 _this.succeeded = true;
38332 _this.running = false;
38333 _this.emit('event', {
38334 code: 'END'
38335 });
38336 })
38337 .catch(function (error) {
38338 _this.running = false;
38339 _this.emit('event', {
38340 code: _this.succeeded ? 'ERROR' : 'FATAL',
38341 error: error
38342 });
38343 })
38344 .then(function () {
38345 if (_this.rerun) {
38346 _this.rerun = false;
38347 _this.invalidate();
38348 }
38349 });
38350 };
38351 return Watcher;
38352}());
38353var Task = /** @class */ (function () {
38354 function Task(watcher, config) {
38355 this.invalidated = true;
38356 this.cache = null;
38357 this.watcher = watcher;
38358 this.closed = false;
38359 this.watched = new Set();
38360 var _a = mergeOptions({
38361 config: config
38362 }), inputOptions = _a.inputOptions, outputOptions = _a.outputOptions;
38363 this.inputOptions = inputOptions;
38364 this.outputs = outputOptions;
38365 this.outputFiles = this.outputs.map(function (output) {
38366 if (output.file || output.dir)
38367 return path.resolve(output.file || output.dir);
38368 });
38369 var watchOptions = inputOptions.watch || {};
38370 if ('useChokidar' in watchOptions)
38371 watchOptions.chokidar = watchOptions.useChokidar;
38372 var chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
38373 if (chokidarOptions) {
38374 chokidarOptions = __assign({}, (chokidarOptions === true ? {} : chokidarOptions), { disableGlobbing: true, ignoreInitial: true });
38375 }
38376 if (chokidarOptions && !chokidar$1) {
38377 throw new Error("watch.chokidar was provided, but chokidar could not be found. Have you installed it?");
38378 }
38379 this.chokidarOptions = chokidarOptions;
38380 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
38381 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
38382 }
38383 Task.prototype.close = function () {
38384 var _this = this;
38385 this.closed = true;
38386 this.watched.forEach(function (id) {
38387 deleteTask(id, _this, _this.chokidarOptionsHash);
38388 });
38389 };
38390 Task.prototype.invalidate = function (id, isTransformDependency) {
38391 this.invalidated = true;
38392 if (isTransformDependency) {
38393 this.cache.modules.forEach(function (module) {
38394 if (!module.transformDependencies || module.transformDependencies.indexOf(id) === -1)
38395 return;
38396 // effective invalidation
38397 module.originalCode = null;
38398 });
38399 }
38400 this.watcher.invalidate(id);
38401 };
38402 Task.prototype.run = function () {
38403 var _this = this;
38404 if (!this.invalidated)
38405 return;
38406 this.invalidated = false;
38407 var options = __assign({}, this.inputOptions, { cache: this.cache });
38408 var start = Date.now();
38409 this.watcher.emit('event', {
38410 code: 'BUNDLE_START',
38411 input: this.inputOptions.input,
38412 output: this.outputFiles
38413 });
38414 setWatcher(this.watcher.emitter);
38415 return rollup(options)
38416 .then(function (result) {
38417 if (_this.closed)
38418 return;
38419 var watched = (_this.watched = new Set());
38420 _this.cache = result.cache;
38421 _this.watchFiles = result.watchFiles;
38422 _this.cache.modules.forEach(function (module) {
38423 if (module.transformDependencies) {
38424 module.transformDependencies.forEach(function (depId) {
38425 watched.add(depId);
38426 _this.watchFile(depId, true);
38427 });
38428 }
38429 });
38430 _this.watchFiles.forEach(function (id) {
38431 watched.add(id);
38432 _this.watchFile(id);
38433 });
38434 _this.watched.forEach(function (id) {
38435 if (!watched.has(id))
38436 deleteTask(id, _this, _this.chokidarOptionsHash);
38437 });
38438 return Promise.all(_this.outputs.map(function (output) {
38439 return result.write(output);
38440 })).then(function () { return result; });
38441 })
38442 .then(function (result) {
38443 _this.watcher.emit('event', {
38444 code: 'BUNDLE_END',
38445 duration: Date.now() - start,
38446 input: _this.inputOptions.input,
38447 output: _this.outputFiles,
38448 result: result
38449 });
38450 })
38451 .catch(function (error) {
38452 if (_this.closed)
38453 return;
38454 if (_this.cache) {
38455 // this is necessary to ensure that any 'renamed' files
38456 // continue to be watched following an error
38457 if (_this.cache.modules) {
38458 _this.cache.modules.forEach(function (module) {
38459 if (module.transformDependencies) {
38460 module.transformDependencies.forEach(function (depId) {
38461 _this.watchFile(depId, true);
38462 });
38463 }
38464 });
38465 }
38466 _this.watchFiles.forEach(function (id) {
38467 _this.watchFile(id);
38468 });
38469 }
38470 throw error;
38471 });
38472 };
38473 Task.prototype.watchFile = function (id, isTransformDependency) {
38474 if (isTransformDependency === void 0) { isTransformDependency = false; }
38475 if (!this.filter(id))
38476 return;
38477 if (this.outputFiles.some(function (file) { return file === id; })) {
38478 throw new Error('Cannot import the generated bundle');
38479 }
38480 // this is necessary to ensure that any 'renamed' files
38481 // continue to be watched following an error
38482 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
38483 };
38484 return Task;
38485}());
38486function watch(configs) {
38487 return new Watcher(configs).emitter;
38488}
38489
38490export { version as VERSION, rollup, watch };