html-crush 4.2.0 → 5.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4021 +0,0 @@
1
- /**
2
- * @name html-crush
3
- * @fileoverview Minifies HTML/CSS: valid or broken, pure or mixed with other languages
4
- * @version 4.2.0
5
- * @author Roy Revelt, Codsen Ltd
6
- * @license MIT
7
- * {@link https://codsen.com/os/html-crush/}
8
- */
9
-
10
- (function (global, factory) {
11
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
12
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
13
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.htmlCrush = {}));
14
- }(this, (function (exports) { 'use strict';
15
-
16
- /**
17
- * @name ranges-sort
18
- * @fileoverview Sort string index ranges
19
- * @version 4.1.0
20
- * @author Roy Revelt, Codsen Ltd
21
- * @license MIT
22
- * {@link https://codsen.com/os/ranges-sort/}
23
- */
24
- const defaults$5 = {
25
- strictlyTwoElementsInRangeArrays: false,
26
- progressFn: null
27
- };
28
- function rSort(arrOfRanges, originalOptions) {
29
- if (!Array.isArray(arrOfRanges) || !arrOfRanges.length) {
30
- return arrOfRanges;
31
- }
32
- const opts = { ...defaults$5,
33
- ...originalOptions
34
- };
35
- let culpritsIndex;
36
- let culpritsLen;
37
- if (opts.strictlyTwoElementsInRangeArrays && !arrOfRanges.filter(range => range).every((rangeArr, indx) => {
38
- if (rangeArr.length !== 2) {
39
- culpritsIndex = indx;
40
- culpritsLen = rangeArr.length;
41
- return false;
42
- }
43
- return true;
44
- })) {
45
- throw new TypeError(`ranges-sort: [THROW_ID_03] The first argument should be an array and must consist of arrays which are natural number indexes representing TWO string index ranges. However, ${culpritsIndex}th range (${JSON.stringify(arrOfRanges[culpritsIndex], null, 4)}) has not two but ${culpritsLen} elements!`);
46
- }
47
- if (!arrOfRanges.filter(range => range).every((rangeArr, indx) => {
48
- if (!Number.isInteger(rangeArr[0]) || rangeArr[0] < 0 || !Number.isInteger(rangeArr[1]) || rangeArr[1] < 0) {
49
- culpritsIndex = indx;
50
- return false;
51
- }
52
- return true;
53
- })) {
54
- throw new TypeError(`ranges-sort: [THROW_ID_04] The first argument should be an array and must consist of arrays which are natural number indexes representing string index ranges. However, ${culpritsIndex}th range (${JSON.stringify(arrOfRanges[culpritsIndex], null, 4)}) does not consist of only natural numbers!`);
55
- }
56
- const maxPossibleIterations = arrOfRanges.filter(range => range).length ** 2;
57
- let counter = 0;
58
- return Array.from(arrOfRanges).filter(range => range).sort((range1, range2) => {
59
- if (opts.progressFn) {
60
- counter += 1;
61
- opts.progressFn(Math.floor(counter * 100 / maxPossibleIterations));
62
- }
63
- if (range1[0] === range2[0]) {
64
- if (range1[1] < range2[1]) {
65
- return -1;
66
- }
67
- if (range1[1] > range2[1]) {
68
- return 1;
69
- }
70
- return 0;
71
- }
72
- if (range1[0] < range2[0]) {
73
- return -1;
74
- }
75
- return 1;
76
- });
77
- }
78
-
79
- /**
80
- * @name ranges-merge
81
- * @fileoverview Merge and sort string index ranges
82
- * @version 7.1.0
83
- * @author Roy Revelt, Codsen Ltd
84
- * @license MIT
85
- * {@link https://codsen.com/os/ranges-merge/}
86
- */
87
- const defaults$4 = {
88
- mergeType: 1,
89
- progressFn: null,
90
- joinRangesThatTouchEdges: true
91
- };
92
- function rMerge(arrOfRanges, originalOpts) {
93
- function isObj(something) {
94
- return something && typeof something === "object" && !Array.isArray(something);
95
- }
96
- if (!Array.isArray(arrOfRanges) || !arrOfRanges.length) {
97
- return null;
98
- }
99
- let opts;
100
- if (originalOpts) {
101
- if (isObj(originalOpts)) {
102
- opts = { ...defaults$4,
103
- ...originalOpts
104
- };
105
- if (opts.progressFn && isObj(opts.progressFn) && !Object.keys(opts.progressFn).length) {
106
- opts.progressFn = null;
107
- } else if (opts.progressFn && typeof opts.progressFn !== "function") {
108
- throw new Error(`ranges-merge: [THROW_ID_01] opts.progressFn must be a function! It was given of a type: "${typeof opts.progressFn}", equal to ${JSON.stringify(opts.progressFn, null, 4)}`);
109
- }
110
- if (opts.mergeType && +opts.mergeType !== 1 && +opts.mergeType !== 2) {
111
- throw new Error(`ranges-merge: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof opts.mergeType}", equal to ${JSON.stringify(opts.mergeType, null, 4)}`);
112
- }
113
- if (typeof opts.joinRangesThatTouchEdges !== "boolean") {
114
- throw new Error(`ranges-merge: [THROW_ID_04] opts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof opts.joinRangesThatTouchEdges}", equal to ${JSON.stringify(opts.joinRangesThatTouchEdges, null, 4)}`);
115
- }
116
- } else {
117
- throw new Error(`emlint: [THROW_ID_03] the second input argument must be a plain object. It was given as:\n${JSON.stringify(originalOpts, null, 4)} (type ${typeof originalOpts})`);
118
- }
119
- } else {
120
- opts = { ...defaults$4
121
- };
122
- }
123
- const filtered = arrOfRanges
124
- .filter(range => range).map(subarr => [...subarr]).filter(
125
- rangeArr => rangeArr[2] !== undefined || rangeArr[0] !== rangeArr[1]);
126
- let sortedRanges;
127
- let lastPercentageDone;
128
- let percentageDone;
129
- if (opts.progressFn) {
130
- sortedRanges = rSort(filtered, {
131
- progressFn: percentage => {
132
- percentageDone = Math.floor(percentage / 5);
133
- if (percentageDone !== lastPercentageDone) {
134
- lastPercentageDone = percentageDone;
135
- opts.progressFn(percentageDone);
136
- }
137
- }
138
- });
139
- } else {
140
- sortedRanges = rSort(filtered);
141
- }
142
- if (!sortedRanges) {
143
- return null;
144
- }
145
- const len = sortedRanges.length - 1;
146
- for (let i = len; i > 0; i--) {
147
- if (opts.progressFn) {
148
- percentageDone = Math.floor((1 - i / len) * 78) + 21;
149
- if (percentageDone !== lastPercentageDone && percentageDone > lastPercentageDone) {
150
- lastPercentageDone = percentageDone;
151
- opts.progressFn(percentageDone);
152
- }
153
- }
154
- if (sortedRanges[i][0] <= sortedRanges[i - 1][0] || !opts.joinRangesThatTouchEdges && sortedRanges[i][0] < sortedRanges[i - 1][1] || opts.joinRangesThatTouchEdges && sortedRanges[i][0] <= sortedRanges[i - 1][1]) {
155
- sortedRanges[i - 1][0] = Math.min(sortedRanges[i][0], sortedRanges[i - 1][0]);
156
- sortedRanges[i - 1][1] = Math.max(sortedRanges[i][1], sortedRanges[i - 1][1]);
157
- if (sortedRanges[i][2] !== undefined && (sortedRanges[i - 1][0] >= sortedRanges[i][0] || sortedRanges[i - 1][1] <= sortedRanges[i][1])) {
158
- if (sortedRanges[i - 1][2] !== null) {
159
- if (sortedRanges[i][2] === null && sortedRanges[i - 1][2] !== null) {
160
- sortedRanges[i - 1][2] = null;
161
- } else if (sortedRanges[i - 1][2] != null) {
162
- if (+opts.mergeType === 2 && sortedRanges[i - 1][0] === sortedRanges[i][0]) {
163
- sortedRanges[i - 1][2] = sortedRanges[i][2];
164
- } else {
165
- sortedRanges[i - 1][2] += sortedRanges[i][2];
166
- }
167
- } else {
168
- sortedRanges[i - 1][2] = sortedRanges[i][2];
169
- }
170
- }
171
- }
172
- sortedRanges.splice(i, 1);
173
- i = sortedRanges.length;
174
- }
175
- }
176
- return sortedRanges.length ? sortedRanges : null;
177
- }
178
-
179
- /**
180
- * @name ranges-apply
181
- * @fileoverview Take an array of string index ranges, delete/replace the string according to them
182
- * @version 5.1.0
183
- * @author Roy Revelt, Codsen Ltd
184
- * @license MIT
185
- * {@link https://codsen.com/os/ranges-apply/}
186
- */
187
- function rApply(str, originalRangesArr, progressFn) {
188
- let percentageDone = 0;
189
- let lastPercentageDone = 0;
190
- if (arguments.length === 0) {
191
- throw new Error("ranges-apply: [THROW_ID_01] inputs missing!");
192
- }
193
- if (typeof str !== "string") {
194
- throw new TypeError(`ranges-apply: [THROW_ID_02] first input argument must be a string! Currently it's: ${typeof str}, equal to: ${JSON.stringify(str, null, 4)}`);
195
- }
196
- if (originalRangesArr && !Array.isArray(originalRangesArr)) {
197
- throw new TypeError(`ranges-apply: [THROW_ID_03] second input argument must be an array (or null)! Currently it's: ${typeof originalRangesArr}, equal to: ${JSON.stringify(originalRangesArr, null, 4)}`);
198
- }
199
- if (progressFn && typeof progressFn !== "function") {
200
- throw new TypeError(`ranges-apply: [THROW_ID_04] the third input argument must be a function (or falsey)! Currently it's: ${typeof progressFn}, equal to: ${JSON.stringify(progressFn, null, 4)}`);
201
- }
202
- if (!originalRangesArr || !originalRangesArr.filter(range => range).length) {
203
- return str;
204
- }
205
- let rangesArr;
206
- if (Array.isArray(originalRangesArr) && Number.isInteger(originalRangesArr[0]) && Number.isInteger(originalRangesArr[1])) {
207
- rangesArr = [Array.from(originalRangesArr)];
208
- } else {
209
- rangesArr = Array.from(originalRangesArr);
210
- }
211
- const len = rangesArr.length;
212
- let counter = 0;
213
- rangesArr.filter(range => range).forEach((el, i) => {
214
- if (progressFn) {
215
- percentageDone = Math.floor(counter / len * 10);
216
- /* istanbul ignore else */
217
- if (percentageDone !== lastPercentageDone) {
218
- lastPercentageDone = percentageDone;
219
- progressFn(percentageDone);
220
- }
221
- }
222
- if (!Array.isArray(el)) {
223
- throw new TypeError(`ranges-apply: [THROW_ID_05] ranges array, second input arg., has ${i}th element not an array: ${JSON.stringify(el, null, 4)}, which is ${typeof el}`);
224
- }
225
- if (!Number.isInteger(el[0])) {
226
- if (!Number.isInteger(+el[0]) || +el[0] < 0) {
227
- throw new TypeError(`ranges-apply: [THROW_ID_06] ranges array, second input arg. has ${i}th element, array ${JSON.stringify(el, null, 0)}. Its first element is not an integer, string index, but ${typeof el[0]}, equal to: ${JSON.stringify(el[0], null, 4)}.`);
228
- } else {
229
- rangesArr[i][0] = +rangesArr[i][0];
230
- }
231
- }
232
- if (!Number.isInteger(el[1])) {
233
- if (!Number.isInteger(+el[1]) || +el[1] < 0) {
234
- throw new TypeError(`ranges-apply: [THROW_ID_07] ranges array, second input arg. has ${i}th element, array ${JSON.stringify(el, null, 0)}. Its second element is not an integer, string index, but ${typeof el[1]}, equal to: ${JSON.stringify(el[1], null, 4)}.`);
235
- } else {
236
- rangesArr[i][1] = +rangesArr[i][1];
237
- }
238
- }
239
- counter += 1;
240
- });
241
- const workingRanges = rMerge(rangesArr, {
242
- progressFn: perc => {
243
- if (progressFn) {
244
- percentageDone = 10 + Math.floor(perc / 10);
245
- /* istanbul ignore else */
246
- if (percentageDone !== lastPercentageDone) {
247
- lastPercentageDone = percentageDone;
248
- progressFn(percentageDone);
249
- }
250
- }
251
- }
252
- });
253
- const len2 = Array.isArray(workingRanges) ? workingRanges.length : 0;
254
- /* istanbul ignore else */
255
- if (len2 > 0) {
256
- const tails = str.slice(workingRanges[len2 - 1][1]);
257
- str = workingRanges.reduce((acc, _val, i, arr) => {
258
- if (progressFn) {
259
- percentageDone = 20 + Math.floor(i / len2 * 80);
260
- /* istanbul ignore else */
261
- if (percentageDone !== lastPercentageDone) {
262
- lastPercentageDone = percentageDone;
263
- progressFn(percentageDone);
264
- }
265
- }
266
- const beginning = i === 0 ? 0 : arr[i - 1][1];
267
- const ending = arr[i][0];
268
- return acc + str.slice(beginning, ending) + (arr[i][2] || "");
269
- }, "");
270
- str += tails;
271
- }
272
- return str;
273
- }
274
-
275
- /**
276
- * @name string-collapse-leading-whitespace
277
- * @fileoverview Collapse the leading and trailing whitespace of a string
278
- * @version 5.1.0
279
- * @author Roy Revelt, Codsen Ltd
280
- * @license MIT
281
- * {@link https://codsen.com/os/string-collapse-leading-whitespace/}
282
- */
283
- function collWhitespace(str, originallineBreakLimit = 1) {
284
- const rawNbsp = "\u00A0";
285
- function reverse(s) {
286
- return Array.from(s).reverse().join("");
287
- }
288
- function prep(whitespaceChunk, limit, trailing) {
289
- const firstBreakChar = trailing ? "\n" : "\r";
290
- const secondBreakChar = trailing ? "\r" : "\n";
291
- if (!whitespaceChunk) {
292
- return whitespaceChunk;
293
- }
294
- let crlfCount = 0;
295
- let res = "";
296
- for (let i = 0, len = whitespaceChunk.length; i < len; i++) {
297
- if (whitespaceChunk[i] === firstBreakChar || whitespaceChunk[i] === secondBreakChar && whitespaceChunk[i - 1] !== firstBreakChar) {
298
- crlfCount++;
299
- }
300
- if (`\r\n`.includes(whitespaceChunk[i]) || whitespaceChunk[i] === rawNbsp) {
301
- if (whitespaceChunk[i] === rawNbsp) {
302
- res += whitespaceChunk[i];
303
- } else if (whitespaceChunk[i] === firstBreakChar) {
304
- if (crlfCount <= limit) {
305
- res += whitespaceChunk[i];
306
- if (whitespaceChunk[i + 1] === secondBreakChar) {
307
- res += whitespaceChunk[i + 1];
308
- i++;
309
- }
310
- }
311
- } else if (whitespaceChunk[i] === secondBreakChar && (!whitespaceChunk[i - 1] || whitespaceChunk[i - 1] !== firstBreakChar) && crlfCount <= limit) {
312
- res += whitespaceChunk[i];
313
- }
314
- } else {
315
- if (!whitespaceChunk[i + 1] && !crlfCount) {
316
- res += " ";
317
- }
318
- }
319
- }
320
- return res;
321
- }
322
- if (typeof str === "string" && str.length) {
323
- let lineBreakLimit = 1;
324
- if (typeof +originallineBreakLimit === "number" && Number.isInteger(+originallineBreakLimit) && +originallineBreakLimit >= 0) {
325
- lineBreakLimit = +originallineBreakLimit;
326
- }
327
- let frontPart = "";
328
- let endPart = "";
329
- if (!str.trim()) {
330
- frontPart = str;
331
- } else if (!str[0].trim()) {
332
- for (let i = 0, len = str.length; i < len; i++) {
333
- if (str[i].trim()) {
334
- frontPart = str.slice(0, i);
335
- break;
336
- }
337
- }
338
- }
339
- if (str.trim() && (str.slice(-1).trim() === "" || str.slice(-1) === rawNbsp)) {
340
- for (let i = str.length; i--;) {
341
- if (str[i].trim()) {
342
- endPart = str.slice(i + 1);
343
- break;
344
- }
345
- }
346
- }
347
- return `${prep(frontPart, lineBreakLimit, false)}${str.trim()}${reverse(prep(reverse(endPart), lineBreakLimit, true))}`;
348
- }
349
- return str;
350
- }
351
-
352
- /**
353
- * @name ranges-push
354
- * @fileoverview Gather string index ranges
355
- * @version 5.1.0
356
- * @author Roy Revelt, Codsen Ltd
357
- * @license MIT
358
- * {@link https://codsen.com/os/ranges-push/}
359
- */
360
- function existy(x) {
361
- return x != null;
362
- }
363
- function isNum(something) {
364
- return Number.isInteger(something) && something >= 0;
365
- }
366
- function isStr$2(something) {
367
- return typeof something === "string";
368
- }
369
- const defaults$3 = {
370
- limitToBeAddedWhitespace: false,
371
- limitLinebreaksCount: 1,
372
- mergeType: 1
373
- };
374
- class Ranges {
375
- constructor(originalOpts) {
376
- const opts = { ...defaults$3,
377
- ...originalOpts
378
- };
379
- if (opts.mergeType && opts.mergeType !== 1 && opts.mergeType !== 2) {
380
- if (isStr$2(opts.mergeType) && opts.mergeType.trim() === "1") {
381
- opts.mergeType = 1;
382
- } else if (isStr$2(opts.mergeType) && opts.mergeType.trim() === "2") {
383
- opts.mergeType = 2;
384
- } else {
385
- throw new Error(`ranges-push: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof opts.mergeType}", equal to ${JSON.stringify(opts.mergeType, null, 4)}`);
386
- }
387
- }
388
- this.opts = opts;
389
- this.ranges = [];
390
- }
391
- add(originalFrom, originalTo, addVal) {
392
- if (originalFrom == null && originalTo == null) {
393
- return;
394
- }
395
- if (existy(originalFrom) && !existy(originalTo)) {
396
- if (Array.isArray(originalFrom)) {
397
- if (originalFrom.length) {
398
- if (originalFrom.some(el => Array.isArray(el))) {
399
- originalFrom.forEach(thing => {
400
- if (Array.isArray(thing)) {
401
- this.add(...thing);
402
- }
403
- });
404
- return;
405
- }
406
- if (originalFrom.length && isNum(+originalFrom[0]) && isNum(+originalFrom[1])) {
407
- this.add(...originalFrom);
408
- }
409
- }
410
- return;
411
- }
412
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_12] the first input argument, "from" is set (${JSON.stringify(originalFrom, null, 0)}) but second-one, "to" is not (${JSON.stringify(originalTo, null, 0)})`);
413
- } else if (!existy(originalFrom) && existy(originalTo)) {
414
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_13] the second input argument, "to" is set (${JSON.stringify(originalTo, null, 0)}) but first-one, "from" is not (${JSON.stringify(originalFrom, null, 0)})`);
415
- }
416
- const from = +originalFrom;
417
- const to = +originalTo;
418
- if (isNum(addVal)) {
419
- addVal = String(addVal);
420
- }
421
- if (isNum(from) && isNum(to)) {
422
- if (existy(addVal) && !isStr$2(addVal) && !isNum(addVal)) {
423
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_08] The third argument, the value to add, was given not as string but ${typeof addVal}, equal to:\n${JSON.stringify(addVal, null, 4)}`);
424
- }
425
- if (existy(this.ranges) && Array.isArray(this.last()) && from === this.last()[1]) {
426
- this.last()[1] = to;
427
- if (this.last()[2] === null || addVal === null) ;
428
- if (this.last()[2] !== null && existy(addVal)) {
429
- let calculatedVal = this.last()[2] && this.last()[2].length > 0 && (!this.opts || !this.opts.mergeType || this.opts.mergeType === 1) ? this.last()[2] + addVal : addVal;
430
- if (this.opts.limitToBeAddedWhitespace) {
431
- calculatedVal = collWhitespace(calculatedVal, this.opts.limitLinebreaksCount);
432
- }
433
- if (!(isStr$2(calculatedVal) && !calculatedVal.length)) {
434
- this.last()[2] = calculatedVal;
435
- }
436
- }
437
- } else {
438
- if (!this.ranges) {
439
- this.ranges = [];
440
- }
441
- const whatToPush = addVal !== undefined && !(isStr$2(addVal) && !addVal.length) ? [from, to, addVal && this.opts.limitToBeAddedWhitespace ? collWhitespace(addVal, this.opts.limitLinebreaksCount) : addVal] : [from, to];
442
- this.ranges.push(whatToPush);
443
- }
444
- } else {
445
- if (!(isNum(from) && from >= 0)) {
446
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_09] "from" value, the first input argument, must be a natural number or zero! Currently it's of a type "${typeof from}" equal to: ${JSON.stringify(from, null, 4)}`);
447
- } else {
448
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_10] "to" value, the second input argument, must be a natural number or zero! Currently it's of a type "${typeof to}" equal to: ${JSON.stringify(to, null, 4)}`);
449
- }
450
- }
451
- }
452
- push(originalFrom, originalTo, addVal) {
453
- this.add(originalFrom, originalTo, addVal);
454
- }
455
- current() {
456
- if (Array.isArray(this.ranges) && this.ranges.length) {
457
- this.ranges = rMerge(this.ranges, {
458
- mergeType: this.opts.mergeType
459
- });
460
- if (this.ranges && this.opts.limitToBeAddedWhitespace) {
461
- return this.ranges.map(val => {
462
- if (existy(val[2])) {
463
- return [val[0], val[1], collWhitespace(val[2], this.opts.limitLinebreaksCount)];
464
- }
465
- return val;
466
- });
467
- }
468
- return this.ranges;
469
- }
470
- return null;
471
- }
472
- wipe() {
473
- this.ranges = [];
474
- }
475
- replace(givenRanges) {
476
- if (Array.isArray(givenRanges) && givenRanges.length) {
477
- if (!(Array.isArray(givenRanges[0]) && isNum(givenRanges[0][0]))) {
478
- throw new Error(`ranges-push/Ranges/replace(): [THROW_ID_11] Single range was given but we expected array of arrays! The first element, ${JSON.stringify(givenRanges[0], null, 4)} should be an array and its first element should be an integer, a string index.`);
479
- } else {
480
- this.ranges = Array.from(givenRanges);
481
- }
482
- } else {
483
- this.ranges = [];
484
- }
485
- }
486
- last() {
487
- if (Array.isArray(this.ranges) && this.ranges.length) {
488
- return this.ranges[this.ranges.length - 1];
489
- }
490
- return null;
491
- }
492
- }
493
-
494
- /**
495
- * @name arrayiffy-if-string
496
- * @fileoverview Put non-empty strings into arrays, turn empty-ones into empty arrays. Bypass everything else.
497
- * @version 3.14.0
498
- * @author Roy Revelt, Codsen Ltd
499
- * @license MIT
500
- * {@link https://codsen.com/os/arrayiffy-if-string/}
501
- */
502
-
503
- function arrayiffy(something) {
504
- if (typeof something === "string") {
505
- if (something.length) {
506
- return [something];
507
- }
508
- return [];
509
- }
510
- return something;
511
- }
512
-
513
- /**
514
- * @name string-match-left-right
515
- * @fileoverview Match substrings on the left or right of a given index, ignoring whitespace
516
- * @version 7.1.0
517
- * @author Roy Revelt, Codsen Ltd
518
- * @license MIT
519
- * {@link https://codsen.com/os/string-match-left-right/}
520
- */
521
-
522
- function isObj(something) {
523
- return something && typeof something === "object" && !Array.isArray(something);
524
- }
525
- function isStr$1(something) {
526
- return typeof something === "string";
527
- }
528
- const defaults$2 = {
529
- cb: undefined,
530
- i: false,
531
- trimBeforeMatching: false,
532
- trimCharsBeforeMatching: [],
533
- maxMismatches: 0,
534
- firstMustMatch: false,
535
- lastMustMatch: false,
536
- hungry: false
537
- };
538
- const defaultGetNextIdx = index => index + 1;
539
- function march(str, position, whatToMatchVal, originalOpts, special = false, getNextIdx = defaultGetNextIdx) {
540
- const whatToMatchValVal = typeof whatToMatchVal === "function" ? whatToMatchVal() : whatToMatchVal;
541
- if (+position < 0 && special && whatToMatchValVal === "EOL") {
542
- return whatToMatchValVal;
543
- }
544
- const opts = { ...defaults$2,
545
- ...originalOpts
546
- };
547
- if (position >= str.length && !special) {
548
- return false;
549
- }
550
- let charsToCheckCount = special ? 1 : whatToMatchVal.length;
551
- let charsMatchedTotal = 0;
552
- let patienceReducedBeforeFirstMatch = false;
553
- let lastWasMismatched = false;
554
- let atLeastSomethingWasMatched = false;
555
- let patience = opts.maxMismatches;
556
- let i = position;
557
- let somethingFound = false;
558
- let firstCharacterMatched = false;
559
- let lastCharacterMatched = false;
560
- function whitespaceInFrontOfFirstChar() {
561
- return (
562
- charsMatchedTotal === 1 &&
563
- patience < opts.maxMismatches - 1
564
- );
565
- }
566
- while (str[i]) {
567
- const nextIdx = getNextIdx(i);
568
- if (opts.trimBeforeMatching && str[i].trim() === "") {
569
- if (!str[nextIdx] && special && whatToMatchVal === "EOL") {
570
- return true;
571
- }
572
- i = getNextIdx(i);
573
- continue;
574
- }
575
- if (opts && !opts.i && opts.trimCharsBeforeMatching && opts.trimCharsBeforeMatching.includes(str[i]) || opts && opts.i && opts.trimCharsBeforeMatching && opts.trimCharsBeforeMatching.map(val => val.toLowerCase()).includes(str[i].toLowerCase())) {
576
- if (special && whatToMatchVal === "EOL" && !str[nextIdx]) {
577
- return true;
578
- }
579
- i = getNextIdx(i);
580
- continue;
581
- }
582
- const charToCompareAgainst = nextIdx > i ? whatToMatchVal[whatToMatchVal.length - charsToCheckCount] : whatToMatchVal[charsToCheckCount - 1];
583
- if (!opts.i && str[i] === charToCompareAgainst || opts.i && str[i].toLowerCase() === charToCompareAgainst.toLowerCase()) {
584
- if (!somethingFound) {
585
- somethingFound = true;
586
- }
587
- if (!atLeastSomethingWasMatched) {
588
- atLeastSomethingWasMatched = true;
589
- }
590
- if (charsToCheckCount === whatToMatchVal.length) {
591
- firstCharacterMatched = true;
592
- if (patience !== opts.maxMismatches) {
593
- return false;
594
- }
595
- } else if (charsToCheckCount === 1) {
596
- lastCharacterMatched = true;
597
- }
598
- charsToCheckCount -= 1;
599
- charsMatchedTotal++;
600
- if (whitespaceInFrontOfFirstChar()) {
601
- return false;
602
- }
603
- if (!charsToCheckCount) {
604
- return (
605
- charsMatchedTotal !== whatToMatchVal.length ||
606
- patience === opts.maxMismatches ||
607
- !patienceReducedBeforeFirstMatch ? i : false
608
- );
609
- }
610
- } else {
611
- if (!patienceReducedBeforeFirstMatch && !charsMatchedTotal) {
612
- patienceReducedBeforeFirstMatch = true;
613
- }
614
- if (opts.maxMismatches && patience && i) {
615
- patience -= 1;
616
- for (let y = 0; y <= patience; y++) {
617
- const nextCharToCompareAgainst = nextIdx > i ? whatToMatchVal[whatToMatchVal.length - charsToCheckCount + 1 + y] : whatToMatchVal[charsToCheckCount - 2 - y];
618
- const nextCharInSource = str[getNextIdx(i)];
619
- if (nextCharToCompareAgainst && (!opts.i && str[i] === nextCharToCompareAgainst || opts.i && str[i].toLowerCase() === nextCharToCompareAgainst.toLowerCase()) && (
620
- !opts.firstMustMatch || charsToCheckCount !== whatToMatchVal.length)) {
621
- charsMatchedTotal++;
622
- if (whitespaceInFrontOfFirstChar()) {
623
- return false;
624
- }
625
- charsToCheckCount -= 2;
626
- somethingFound = true;
627
- break;
628
- } else if (nextCharInSource && nextCharToCompareAgainst && (!opts.i && nextCharInSource === nextCharToCompareAgainst || opts.i && nextCharInSource.toLowerCase() === nextCharToCompareAgainst.toLowerCase()) && (
629
- !opts.firstMustMatch || charsToCheckCount !== whatToMatchVal.length)) {
630
- if (!charsMatchedTotal && !opts.hungry) {
631
- return false;
632
- }
633
- charsToCheckCount -= 1;
634
- somethingFound = true;
635
- break;
636
- } else if (nextCharToCompareAgainst === undefined && patience >= 0 && somethingFound && (!opts.firstMustMatch || firstCharacterMatched) && (!opts.lastMustMatch || lastCharacterMatched)) {
637
- return i;
638
- }
639
- }
640
- if (!somethingFound) {
641
- lastWasMismatched = i;
642
- }
643
- } else if (i === 0 && charsToCheckCount === 1 && !opts.lastMustMatch && atLeastSomethingWasMatched) {
644
- return 0;
645
- } else {
646
- return false;
647
- }
648
- }
649
- if (lastWasMismatched !== false && lastWasMismatched !== i) {
650
- lastWasMismatched = false;
651
- }
652
- if (charsToCheckCount < 1) {
653
- return i;
654
- }
655
- i = getNextIdx(i);
656
- }
657
- if (charsToCheckCount > 0) {
658
- if (special && whatToMatchValVal === "EOL") {
659
- return true;
660
- }
661
- if (opts && opts.maxMismatches >= charsToCheckCount && atLeastSomethingWasMatched) {
662
- return lastWasMismatched || 0;
663
- }
664
- return false;
665
- }
666
- }
667
- function main(mode, str, position, originalWhatToMatch, originalOpts) {
668
- if (isObj(originalOpts) && Object.prototype.hasOwnProperty.call(originalOpts, "trimBeforeMatching") && typeof originalOpts.trimBeforeMatching !== "boolean") {
669
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_09] opts.trimBeforeMatching should be boolean!${Array.isArray(originalOpts.trimBeforeMatching) ? ` Did you mean to use opts.trimCharsBeforeMatching?` : ""}`);
670
- }
671
- const opts = { ...defaults$2,
672
- ...originalOpts
673
- };
674
- if (typeof opts.trimCharsBeforeMatching === "string") {
675
- opts.trimCharsBeforeMatching = arrayiffy(opts.trimCharsBeforeMatching);
676
- }
677
- opts.trimCharsBeforeMatching = opts.trimCharsBeforeMatching.map(el => isStr$1(el) ? el : String(el));
678
- if (!isStr$1(str)) {
679
- return false;
680
- }
681
- if (!str.length) {
682
- return false;
683
- }
684
- if (!Number.isInteger(position) || position < 0) {
685
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_03] the second argument should be a natural number. Currently it's of a type: ${typeof position}, equal to:\n${JSON.stringify(position, null, 4)}`);
686
- }
687
- let whatToMatch;
688
- let special;
689
- if (isStr$1(originalWhatToMatch)) {
690
- whatToMatch = [originalWhatToMatch];
691
- } else if (Array.isArray(originalWhatToMatch)) {
692
- whatToMatch = originalWhatToMatch;
693
- } else if (!originalWhatToMatch) {
694
- whatToMatch = originalWhatToMatch;
695
- } else if (typeof originalWhatToMatch === "function") {
696
- whatToMatch = [];
697
- whatToMatch.push(originalWhatToMatch);
698
- } else {
699
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_05] the third argument, whatToMatch, is neither string nor array of strings! It's ${typeof originalWhatToMatch}, equal to:\n${JSON.stringify(originalWhatToMatch, null, 4)}`);
700
- }
701
- if (originalOpts && !isObj(originalOpts)) {
702
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_06] the fourth argument, options object, should be a plain object. Currently it's of a type "${typeof originalOpts}", and equal to:\n${JSON.stringify(originalOpts, null, 4)}`);
703
- }
704
- let culpritsIndex = 0;
705
- let culpritsVal = "";
706
- if (opts && opts.trimCharsBeforeMatching && opts.trimCharsBeforeMatching.some((el, i) => {
707
- if (el.length > 1) {
708
- culpritsIndex = i;
709
- culpritsVal = el;
710
- return true;
711
- }
712
- return false;
713
- })) {
714
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_07] the fourth argument, options object contains trimCharsBeforeMatching. It was meant to list the single characters but one of the entries at index ${culpritsIndex} is longer than 1 character, ${culpritsVal.length} (equals to ${culpritsVal}). Please split it into separate characters and put into array as separate elements.`);
715
- }
716
- if (!whatToMatch || !Array.isArray(whatToMatch) ||
717
- Array.isArray(whatToMatch) && !whatToMatch.length ||
718
- Array.isArray(whatToMatch) && whatToMatch.length === 1 && isStr$1(whatToMatch[0]) && !whatToMatch[0].trim()
719
- ) {
720
- if (typeof opts.cb === "function") {
721
- let firstCharOutsideIndex;
722
- let startingPosition = position;
723
- if (mode === "matchLeftIncl" || mode === "matchRight") {
724
- startingPosition += 1;
725
- }
726
- if (mode[5] === "L") {
727
- for (let y = startingPosition; y--;) {
728
- const currentChar = str[y];
729
- if ((!opts.trimBeforeMatching || opts.trimBeforeMatching && currentChar !== undefined && currentChar.trim()) && (!opts.trimCharsBeforeMatching || !opts.trimCharsBeforeMatching.length || currentChar !== undefined && !opts.trimCharsBeforeMatching.includes(currentChar))) {
730
- firstCharOutsideIndex = y;
731
- break;
732
- }
733
- }
734
- } else if (mode.startsWith("matchRight")) {
735
- for (let y = startingPosition; y < str.length; y++) {
736
- const currentChar = str[y];
737
- if ((!opts.trimBeforeMatching || opts.trimBeforeMatching && currentChar.trim()) && (!opts.trimCharsBeforeMatching || !opts.trimCharsBeforeMatching.length || !opts.trimCharsBeforeMatching.includes(currentChar))) {
738
- firstCharOutsideIndex = y;
739
- break;
740
- }
741
- }
742
- }
743
- if (firstCharOutsideIndex === undefined) {
744
- return false;
745
- }
746
- const wholeCharacterOutside = str[firstCharOutsideIndex];
747
- const indexOfTheCharacterAfter = firstCharOutsideIndex + 1;
748
- let theRemainderOfTheString = "";
749
- if (indexOfTheCharacterAfter && indexOfTheCharacterAfter > 0) {
750
- theRemainderOfTheString = str.slice(0, indexOfTheCharacterAfter);
751
- }
752
- if (mode[5] === "L") {
753
- return opts.cb(wholeCharacterOutside, theRemainderOfTheString, firstCharOutsideIndex);
754
- }
755
- if (firstCharOutsideIndex && firstCharOutsideIndex > 0) {
756
- theRemainderOfTheString = str.slice(firstCharOutsideIndex);
757
- }
758
- return opts.cb(wholeCharacterOutside, theRemainderOfTheString, firstCharOutsideIndex);
759
- }
760
- let extraNote = "";
761
- if (!originalOpts) {
762
- extraNote = " More so, the whole options object, the fourth input argument, is missing!";
763
- }
764
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_08] the third argument, "whatToMatch", was given as an empty string. This means, you intend to match purely by a callback. The callback was not set though, the opts key "cb" is not set!${extraNote}`);
765
- }
766
- for (let i = 0, len = whatToMatch.length; i < len; i++) {
767
- special = typeof whatToMatch[i] === "function";
768
- const whatToMatchVal = whatToMatch[i];
769
- let fullCharacterInFront;
770
- let indexOfTheCharacterInFront;
771
- let restOfStringInFront = "";
772
- let startingPosition = position;
773
- if (mode === "matchRight") {
774
- startingPosition += 1;
775
- } else if (mode === "matchLeft") {
776
- startingPosition -= 1;
777
- }
778
- const found = march(str, startingPosition, whatToMatchVal, opts, special, i2 => mode[5] === "L" ? i2 - 1 : i2 + 1);
779
- if (found && special && typeof whatToMatchVal === "function" && whatToMatchVal() === "EOL") {
780
- return whatToMatchVal() && (opts.cb ? opts.cb(fullCharacterInFront, restOfStringInFront, indexOfTheCharacterInFront) : true) ? whatToMatchVal() : false;
781
- }
782
- if (Number.isInteger(found)) {
783
- indexOfTheCharacterInFront = mode.startsWith("matchLeft") ? found - 1 : found + 1;
784
- if (mode[5] === "L") {
785
- restOfStringInFront = str.slice(0, found);
786
- } else {
787
- restOfStringInFront = str.slice(indexOfTheCharacterInFront);
788
- }
789
- }
790
- if (indexOfTheCharacterInFront < 0) {
791
- indexOfTheCharacterInFront = undefined;
792
- }
793
- if (str[indexOfTheCharacterInFront]) {
794
- fullCharacterInFront = str[indexOfTheCharacterInFront];
795
- }
796
- if (Number.isInteger(found) && (opts.cb ? opts.cb(fullCharacterInFront, restOfStringInFront, indexOfTheCharacterInFront) : true)) {
797
- return whatToMatchVal;
798
- }
799
- }
800
- return false;
801
- }
802
- function matchLeft(str, position, whatToMatch, opts) {
803
- return main("matchLeft", str, position, whatToMatch, opts);
804
- }
805
- function matchRightIncl(str, position, whatToMatch, opts) {
806
- return main("matchRightIncl", str, position, whatToMatch, opts);
807
- }
808
- function matchRight(str, position, whatToMatch, opts) {
809
- return main("matchRight", str, position, whatToMatch, opts);
810
- }
811
-
812
- /**
813
- * @name string-range-expander
814
- * @fileoverview Expands string index ranges within whitespace boundaries until letters are met
815
- * @version 2.1.0
816
- * @author Roy Revelt, Codsen Ltd
817
- * @license MIT
818
- * {@link https://codsen.com/os/string-range-expander/}
819
- */
820
- const defaults$1 = {
821
- str: "",
822
- from: 0,
823
- to: 0,
824
- ifLeftSideIncludesThisThenCropTightly: "",
825
- ifLeftSideIncludesThisCropItToo: "",
826
- ifRightSideIncludesThisThenCropTightly: "",
827
- ifRightSideIncludesThisCropItToo: "",
828
- extendToOneSide: false,
829
- wipeAllWhitespaceOnLeft: false,
830
- wipeAllWhitespaceOnRight: false,
831
- addSingleSpaceToPreventAccidentalConcatenation: false
832
- };
833
- function expander(originalOpts) {
834
- const letterOrDigit = /^[0-9a-zA-Z]+$/;
835
- function isWhitespace(char) {
836
- if (!char || typeof char !== "string") {
837
- return false;
838
- }
839
- return !char.trim();
840
- }
841
- function isStr(something) {
842
- return typeof something === "string";
843
- }
844
- if (!originalOpts || typeof originalOpts !== "object" || Array.isArray(originalOpts)) {
845
- let supplementalString;
846
- if (originalOpts === undefined) {
847
- supplementalString = "but it is missing completely.";
848
- } else if (originalOpts === null) {
849
- supplementalString = "but it was given as null.";
850
- } else {
851
- supplementalString = `but it was given as ${typeof originalOpts}, equal to:\n${JSON.stringify(originalOpts, null, 4)}.`;
852
- }
853
- throw new Error(`string-range-expander: [THROW_ID_01] Input must be a plain object ${supplementalString}`);
854
- } else if (typeof originalOpts === "object" && originalOpts !== null && !Array.isArray(originalOpts) && !Object.keys(originalOpts).length) {
855
- throw new Error(`string-range-expander: [THROW_ID_02] Input must be a plain object but it was given as a plain object without any keys.`);
856
- }
857
- if (typeof originalOpts.from !== "number") {
858
- throw new Error(`string-range-expander: [THROW_ID_03] The input's "from" value opts.from, is not a number! Currently it's given as ${typeof originalOpts.from}, equal to ${JSON.stringify(originalOpts.from, null, 0)}`);
859
- }
860
- if (typeof originalOpts.to !== "number") {
861
- throw new Error(`string-range-expander: [THROW_ID_04] The input's "to" value opts.to, is not a number! Currently it's given as ${typeof originalOpts.to}, equal to ${JSON.stringify(originalOpts.to, null, 0)}`);
862
- }
863
- if (originalOpts && originalOpts.str && !originalOpts.str[originalOpts.from] && originalOpts.from !== originalOpts.to) {
864
- throw new Error(`string-range-expander: [THROW_ID_05] The given input string opts.str ("${originalOpts.str}") must contain the character at index "from" ("${originalOpts.from}")`);
865
- }
866
- if (originalOpts && originalOpts.str && !originalOpts.str[originalOpts.to - 1]) {
867
- throw new Error(`string-range-expander: [THROW_ID_06] The given input string, opts.str ("${originalOpts.str}") must contain the character at index before "to" ("${originalOpts.to - 1}")`);
868
- }
869
- if (originalOpts.from > originalOpts.to) {
870
- throw new Error(`string-range-expander: [THROW_ID_07] The given "from" index, "${originalOpts.from}" is greater than "to" index, "${originalOpts.to}". That's wrong!`);
871
- }
872
- if (isStr(originalOpts.extendToOneSide) && originalOpts.extendToOneSide !== "left" && originalOpts.extendToOneSide !== "right" || !isStr(originalOpts.extendToOneSide) && originalOpts.extendToOneSide !== undefined && originalOpts.extendToOneSide !== false) {
873
- throw new Error(`string-range-expander: [THROW_ID_08] The opts.extendToOneSide value is not recogniseable! It's set to: "${originalOpts.extendToOneSide}" (${typeof originalOpts.extendToOneSide}). It has to be either Boolean "false" or strings "left" or "right"`);
874
- }
875
- const opts = { ...defaults$1,
876
- ...originalOpts
877
- };
878
- if (Array.isArray(opts.ifLeftSideIncludesThisThenCropTightly)) {
879
- let culpritsIndex;
880
- let culpritsValue;
881
- if (opts.ifLeftSideIncludesThisThenCropTightly.every((val, i) => {
882
- if (!isStr(val)) {
883
- culpritsIndex = i;
884
- culpritsValue = val;
885
- return false;
886
- }
887
- return true;
888
- })) {
889
- opts.ifLeftSideIncludesThisThenCropTightly = opts.ifLeftSideIncludesThisThenCropTightly.join("");
890
- } else {
891
- throw new Error(`string-range-expander: [THROW_ID_09] The opts.ifLeftSideIncludesThisThenCropTightly was set to an array:\n${JSON.stringify(opts.ifLeftSideIncludesThisThenCropTightly, null, 4)}. Now, that array contains not only string elements. For example, an element at index ${culpritsIndex} is of a type ${typeof culpritsValue} (equal to ${JSON.stringify(culpritsValue, null, 0)}).`);
892
- }
893
- }
894
- const str = opts.str;
895
- let from = opts.from;
896
- let to = opts.to;
897
- if (opts.extendToOneSide !== "right" && (isWhitespace(str[from - 1]) && (isWhitespace(str[from - 2]) || opts.ifLeftSideIncludesThisCropItToo.includes(str[from - 2])) || str[from - 1] && opts.ifLeftSideIncludesThisCropItToo.includes(str[from - 1]) || opts.wipeAllWhitespaceOnLeft && isWhitespace(str[from - 1]))) {
898
- for (let i = from; i--;) {
899
- if (!opts.ifLeftSideIncludesThisCropItToo.includes(str[i])) {
900
- if (str[i].trim()) {
901
- if (opts.wipeAllWhitespaceOnLeft || opts.ifLeftSideIncludesThisCropItToo.includes(str[i + 1])) {
902
- from = i + 1;
903
- } else {
904
- from = i + 2;
905
- }
906
- break;
907
- } else if (i === 0) {
908
- if (opts.wipeAllWhitespaceOnLeft) {
909
- from = 0;
910
- } else {
911
- from = 1;
912
- }
913
- break;
914
- }
915
- }
916
- }
917
- }
918
- if (opts.extendToOneSide !== "left" && (isWhitespace(str[to]) && (opts.wipeAllWhitespaceOnRight || isWhitespace(str[to + 1])) || opts.ifRightSideIncludesThisCropItToo.includes(str[to]))) {
919
- for (let i = to, len = str.length; i < len; i++) {
920
- if (!opts.ifRightSideIncludesThisCropItToo.includes(str[i]) && (str[i] && str[i].trim() || str[i] === undefined)) {
921
- if (opts.wipeAllWhitespaceOnRight || opts.ifRightSideIncludesThisCropItToo.includes(str[i - 1])) {
922
- to = i;
923
- } else {
924
- to = i - 1;
925
- }
926
- break;
927
- }
928
- }
929
- }
930
- if (opts.extendToOneSide !== "right" && isStr(opts.ifLeftSideIncludesThisThenCropTightly) && opts.ifLeftSideIncludesThisThenCropTightly && (str[from - 2] && opts.ifLeftSideIncludesThisThenCropTightly.includes(str[from - 2]) || str[from - 1] && opts.ifLeftSideIncludesThisThenCropTightly.includes(str[from - 1])) || opts.extendToOneSide !== "left" && isStr(opts.ifRightSideIncludesThisThenCropTightly) && opts.ifRightSideIncludesThisThenCropTightly && (str[to + 1] && opts.ifRightSideIncludesThisThenCropTightly.includes(str[to + 1]) || str[to] && opts.ifRightSideIncludesThisThenCropTightly.includes(str[to]))) {
931
- if (opts.extendToOneSide !== "right" && isWhitespace(str[from - 1]) && !opts.wipeAllWhitespaceOnLeft) {
932
- from -= 1;
933
- }
934
- if (opts.extendToOneSide !== "left" && isWhitespace(str[to]) && !opts.wipeAllWhitespaceOnRight) {
935
- to += 1;
936
- }
937
- }
938
- if (opts.addSingleSpaceToPreventAccidentalConcatenation && str[from - 1] && str[from - 1].trim() && str[to] && str[to].trim() && (!opts.ifLeftSideIncludesThisThenCropTightly && !opts.ifRightSideIncludesThisThenCropTightly || !((!opts.ifLeftSideIncludesThisThenCropTightly || opts.ifLeftSideIncludesThisThenCropTightly.includes(str[from - 1])) && (!opts.ifRightSideIncludesThisThenCropTightly || str[to] && opts.ifRightSideIncludesThisThenCropTightly.includes(str[to])))) && (letterOrDigit.test(str[from - 1]) || letterOrDigit.test(str[to]))) {
939
- return [from, to, " "];
940
- }
941
- return [from, to];
942
- }
943
-
944
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
945
-
946
- /**
947
- * lodash (Custom Build) <https://lodash.com/>
948
- * Build: `lodash modularize exports="npm" -o ./`
949
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
950
- * Released under MIT license <https://lodash.com/license>
951
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
952
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
953
- */
954
-
955
- /** Used for built-in method references. */
956
- var funcProto = Function.prototype;
957
-
958
- /** Used to resolve the decompiled source of functions. */
959
- var funcToString = funcProto.toString;
960
-
961
- /** Used to infer the `Object` constructor. */
962
- funcToString.call(Object);
963
-
964
- var lodash_clonedeep = {exports: {}};
965
-
966
- /**
967
- * lodash (Custom Build) <https://lodash.com/>
968
- * Build: `lodash modularize exports="npm" -o ./`
969
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
970
- * Released under MIT license <https://lodash.com/license>
971
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
972
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
973
- */
974
-
975
- (function (module, exports) {
976
- /** Used as the size to enable large array optimizations. */
977
- var LARGE_ARRAY_SIZE = 200;
978
-
979
- /** Used to stand-in for `undefined` hash values. */
980
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
981
-
982
- /** Used as references for various `Number` constants. */
983
- var MAX_SAFE_INTEGER = 9007199254740991;
984
-
985
- /** `Object#toString` result references. */
986
- var argsTag = '[object Arguments]',
987
- arrayTag = '[object Array]',
988
- boolTag = '[object Boolean]',
989
- dateTag = '[object Date]',
990
- errorTag = '[object Error]',
991
- funcTag = '[object Function]',
992
- genTag = '[object GeneratorFunction]',
993
- mapTag = '[object Map]',
994
- numberTag = '[object Number]',
995
- objectTag = '[object Object]',
996
- promiseTag = '[object Promise]',
997
- regexpTag = '[object RegExp]',
998
- setTag = '[object Set]',
999
- stringTag = '[object String]',
1000
- symbolTag = '[object Symbol]',
1001
- weakMapTag = '[object WeakMap]';
1002
-
1003
- var arrayBufferTag = '[object ArrayBuffer]',
1004
- dataViewTag = '[object DataView]',
1005
- float32Tag = '[object Float32Array]',
1006
- float64Tag = '[object Float64Array]',
1007
- int8Tag = '[object Int8Array]',
1008
- int16Tag = '[object Int16Array]',
1009
- int32Tag = '[object Int32Array]',
1010
- uint8Tag = '[object Uint8Array]',
1011
- uint8ClampedTag = '[object Uint8ClampedArray]',
1012
- uint16Tag = '[object Uint16Array]',
1013
- uint32Tag = '[object Uint32Array]';
1014
-
1015
- /**
1016
- * Used to match `RegExp`
1017
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
1018
- */
1019
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
1020
-
1021
- /** Used to match `RegExp` flags from their coerced string values. */
1022
- var reFlags = /\w*$/;
1023
-
1024
- /** Used to detect host constructors (Safari). */
1025
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
1026
-
1027
- /** Used to detect unsigned integer values. */
1028
- var reIsUint = /^(?:0|[1-9]\d*)$/;
1029
-
1030
- /** Used to identify `toStringTag` values supported by `_.clone`. */
1031
- var cloneableTags = {};
1032
- cloneableTags[argsTag] = cloneableTags[arrayTag] =
1033
- cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
1034
- cloneableTags[boolTag] = cloneableTags[dateTag] =
1035
- cloneableTags[float32Tag] = cloneableTags[float64Tag] =
1036
- cloneableTags[int8Tag] = cloneableTags[int16Tag] =
1037
- cloneableTags[int32Tag] = cloneableTags[mapTag] =
1038
- cloneableTags[numberTag] = cloneableTags[objectTag] =
1039
- cloneableTags[regexpTag] = cloneableTags[setTag] =
1040
- cloneableTags[stringTag] = cloneableTags[symbolTag] =
1041
- cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
1042
- cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
1043
- cloneableTags[errorTag] = cloneableTags[funcTag] =
1044
- cloneableTags[weakMapTag] = false;
1045
-
1046
- /** Detect free variable `global` from Node.js. */
1047
- var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
1048
-
1049
- /** Detect free variable `self`. */
1050
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
1051
-
1052
- /** Used as a reference to the global object. */
1053
- var root = freeGlobal || freeSelf || Function('return this')();
1054
-
1055
- /** Detect free variable `exports`. */
1056
- var freeExports = exports && !exports.nodeType && exports;
1057
-
1058
- /** Detect free variable `module`. */
1059
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
1060
-
1061
- /** Detect the popular CommonJS extension `module.exports`. */
1062
- var moduleExports = freeModule && freeModule.exports === freeExports;
1063
-
1064
- /**
1065
- * Adds the key-value `pair` to `map`.
1066
- *
1067
- * @private
1068
- * @param {Object} map The map to modify.
1069
- * @param {Array} pair The key-value pair to add.
1070
- * @returns {Object} Returns `map`.
1071
- */
1072
- function addMapEntry(map, pair) {
1073
- // Don't return `map.set` because it's not chainable in IE 11.
1074
- map.set(pair[0], pair[1]);
1075
- return map;
1076
- }
1077
-
1078
- /**
1079
- * Adds `value` to `set`.
1080
- *
1081
- * @private
1082
- * @param {Object} set The set to modify.
1083
- * @param {*} value The value to add.
1084
- * @returns {Object} Returns `set`.
1085
- */
1086
- function addSetEntry(set, value) {
1087
- // Don't return `set.add` because it's not chainable in IE 11.
1088
- set.add(value);
1089
- return set;
1090
- }
1091
-
1092
- /**
1093
- * A specialized version of `_.forEach` for arrays without support for
1094
- * iteratee shorthands.
1095
- *
1096
- * @private
1097
- * @param {Array} [array] The array to iterate over.
1098
- * @param {Function} iteratee The function invoked per iteration.
1099
- * @returns {Array} Returns `array`.
1100
- */
1101
- function arrayEach(array, iteratee) {
1102
- var index = -1,
1103
- length = array ? array.length : 0;
1104
-
1105
- while (++index < length) {
1106
- if (iteratee(array[index], index, array) === false) {
1107
- break;
1108
- }
1109
- }
1110
- return array;
1111
- }
1112
-
1113
- /**
1114
- * Appends the elements of `values` to `array`.
1115
- *
1116
- * @private
1117
- * @param {Array} array The array to modify.
1118
- * @param {Array} values The values to append.
1119
- * @returns {Array} Returns `array`.
1120
- */
1121
- function arrayPush(array, values) {
1122
- var index = -1,
1123
- length = values.length,
1124
- offset = array.length;
1125
-
1126
- while (++index < length) {
1127
- array[offset + index] = values[index];
1128
- }
1129
- return array;
1130
- }
1131
-
1132
- /**
1133
- * A specialized version of `_.reduce` for arrays without support for
1134
- * iteratee shorthands.
1135
- *
1136
- * @private
1137
- * @param {Array} [array] The array to iterate over.
1138
- * @param {Function} iteratee The function invoked per iteration.
1139
- * @param {*} [accumulator] The initial value.
1140
- * @param {boolean} [initAccum] Specify using the first element of `array` as
1141
- * the initial value.
1142
- * @returns {*} Returns the accumulated value.
1143
- */
1144
- function arrayReduce(array, iteratee, accumulator, initAccum) {
1145
- var index = -1,
1146
- length = array ? array.length : 0;
1147
-
1148
- if (initAccum && length) {
1149
- accumulator = array[++index];
1150
- }
1151
- while (++index < length) {
1152
- accumulator = iteratee(accumulator, array[index], index, array);
1153
- }
1154
- return accumulator;
1155
- }
1156
-
1157
- /**
1158
- * The base implementation of `_.times` without support for iteratee shorthands
1159
- * or max array length checks.
1160
- *
1161
- * @private
1162
- * @param {number} n The number of times to invoke `iteratee`.
1163
- * @param {Function} iteratee The function invoked per iteration.
1164
- * @returns {Array} Returns the array of results.
1165
- */
1166
- function baseTimes(n, iteratee) {
1167
- var index = -1,
1168
- result = Array(n);
1169
-
1170
- while (++index < n) {
1171
- result[index] = iteratee(index);
1172
- }
1173
- return result;
1174
- }
1175
-
1176
- /**
1177
- * Gets the value at `key` of `object`.
1178
- *
1179
- * @private
1180
- * @param {Object} [object] The object to query.
1181
- * @param {string} key The key of the property to get.
1182
- * @returns {*} Returns the property value.
1183
- */
1184
- function getValue(object, key) {
1185
- return object == null ? undefined : object[key];
1186
- }
1187
-
1188
- /**
1189
- * Checks if `value` is a host object in IE < 9.
1190
- *
1191
- * @private
1192
- * @param {*} value The value to check.
1193
- * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
1194
- */
1195
- function isHostObject(value) {
1196
- // Many host objects are `Object` objects that can coerce to strings
1197
- // despite having improperly defined `toString` methods.
1198
- var result = false;
1199
- if (value != null && typeof value.toString != 'function') {
1200
- try {
1201
- result = !!(value + '');
1202
- } catch (e) {}
1203
- }
1204
- return result;
1205
- }
1206
-
1207
- /**
1208
- * Converts `map` to its key-value pairs.
1209
- *
1210
- * @private
1211
- * @param {Object} map The map to convert.
1212
- * @returns {Array} Returns the key-value pairs.
1213
- */
1214
- function mapToArray(map) {
1215
- var index = -1,
1216
- result = Array(map.size);
1217
-
1218
- map.forEach(function(value, key) {
1219
- result[++index] = [key, value];
1220
- });
1221
- return result;
1222
- }
1223
-
1224
- /**
1225
- * Creates a unary function that invokes `func` with its argument transformed.
1226
- *
1227
- * @private
1228
- * @param {Function} func The function to wrap.
1229
- * @param {Function} transform The argument transform.
1230
- * @returns {Function} Returns the new function.
1231
- */
1232
- function overArg(func, transform) {
1233
- return function(arg) {
1234
- return func(transform(arg));
1235
- };
1236
- }
1237
-
1238
- /**
1239
- * Converts `set` to an array of its values.
1240
- *
1241
- * @private
1242
- * @param {Object} set The set to convert.
1243
- * @returns {Array} Returns the values.
1244
- */
1245
- function setToArray(set) {
1246
- var index = -1,
1247
- result = Array(set.size);
1248
-
1249
- set.forEach(function(value) {
1250
- result[++index] = value;
1251
- });
1252
- return result;
1253
- }
1254
-
1255
- /** Used for built-in method references. */
1256
- var arrayProto = Array.prototype,
1257
- funcProto = Function.prototype,
1258
- objectProto = Object.prototype;
1259
-
1260
- /** Used to detect overreaching core-js shims. */
1261
- var coreJsData = root['__core-js_shared__'];
1262
-
1263
- /** Used to detect methods masquerading as native. */
1264
- var maskSrcKey = (function() {
1265
- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
1266
- return uid ? ('Symbol(src)_1.' + uid) : '';
1267
- }());
1268
-
1269
- /** Used to resolve the decompiled source of functions. */
1270
- var funcToString = funcProto.toString;
1271
-
1272
- /** Used to check objects for own properties. */
1273
- var hasOwnProperty = objectProto.hasOwnProperty;
1274
-
1275
- /**
1276
- * Used to resolve the
1277
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
1278
- * of values.
1279
- */
1280
- var objectToString = objectProto.toString;
1281
-
1282
- /** Used to detect if a method is native. */
1283
- var reIsNative = RegExp('^' +
1284
- funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
1285
- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
1286
- );
1287
-
1288
- /** Built-in value references. */
1289
- var Buffer = moduleExports ? root.Buffer : undefined,
1290
- Symbol = root.Symbol,
1291
- Uint8Array = root.Uint8Array,
1292
- getPrototype = overArg(Object.getPrototypeOf, Object),
1293
- objectCreate = Object.create,
1294
- propertyIsEnumerable = objectProto.propertyIsEnumerable,
1295
- splice = arrayProto.splice;
1296
-
1297
- /* Built-in method references for those with the same name as other `lodash` methods. */
1298
- var nativeGetSymbols = Object.getOwnPropertySymbols,
1299
- nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
1300
- nativeKeys = overArg(Object.keys, Object);
1301
-
1302
- /* Built-in method references that are verified to be native. */
1303
- var DataView = getNative(root, 'DataView'),
1304
- Map = getNative(root, 'Map'),
1305
- Promise = getNative(root, 'Promise'),
1306
- Set = getNative(root, 'Set'),
1307
- WeakMap = getNative(root, 'WeakMap'),
1308
- nativeCreate = getNative(Object, 'create');
1309
-
1310
- /** Used to detect maps, sets, and weakmaps. */
1311
- var dataViewCtorString = toSource(DataView),
1312
- mapCtorString = toSource(Map),
1313
- promiseCtorString = toSource(Promise),
1314
- setCtorString = toSource(Set),
1315
- weakMapCtorString = toSource(WeakMap);
1316
-
1317
- /** Used to convert symbols to primitives and strings. */
1318
- var symbolProto = Symbol ? Symbol.prototype : undefined,
1319
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
1320
-
1321
- /**
1322
- * Creates a hash object.
1323
- *
1324
- * @private
1325
- * @constructor
1326
- * @param {Array} [entries] The key-value pairs to cache.
1327
- */
1328
- function Hash(entries) {
1329
- var index = -1,
1330
- length = entries ? entries.length : 0;
1331
-
1332
- this.clear();
1333
- while (++index < length) {
1334
- var entry = entries[index];
1335
- this.set(entry[0], entry[1]);
1336
- }
1337
- }
1338
-
1339
- /**
1340
- * Removes all key-value entries from the hash.
1341
- *
1342
- * @private
1343
- * @name clear
1344
- * @memberOf Hash
1345
- */
1346
- function hashClear() {
1347
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
1348
- }
1349
-
1350
- /**
1351
- * Removes `key` and its value from the hash.
1352
- *
1353
- * @private
1354
- * @name delete
1355
- * @memberOf Hash
1356
- * @param {Object} hash The hash to modify.
1357
- * @param {string} key The key of the value to remove.
1358
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1359
- */
1360
- function hashDelete(key) {
1361
- return this.has(key) && delete this.__data__[key];
1362
- }
1363
-
1364
- /**
1365
- * Gets the hash value for `key`.
1366
- *
1367
- * @private
1368
- * @name get
1369
- * @memberOf Hash
1370
- * @param {string} key The key of the value to get.
1371
- * @returns {*} Returns the entry value.
1372
- */
1373
- function hashGet(key) {
1374
- var data = this.__data__;
1375
- if (nativeCreate) {
1376
- var result = data[key];
1377
- return result === HASH_UNDEFINED ? undefined : result;
1378
- }
1379
- return hasOwnProperty.call(data, key) ? data[key] : undefined;
1380
- }
1381
-
1382
- /**
1383
- * Checks if a hash value for `key` exists.
1384
- *
1385
- * @private
1386
- * @name has
1387
- * @memberOf Hash
1388
- * @param {string} key The key of the entry to check.
1389
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1390
- */
1391
- function hashHas(key) {
1392
- var data = this.__data__;
1393
- return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
1394
- }
1395
-
1396
- /**
1397
- * Sets the hash `key` to `value`.
1398
- *
1399
- * @private
1400
- * @name set
1401
- * @memberOf Hash
1402
- * @param {string} key The key of the value to set.
1403
- * @param {*} value The value to set.
1404
- * @returns {Object} Returns the hash instance.
1405
- */
1406
- function hashSet(key, value) {
1407
- var data = this.__data__;
1408
- data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
1409
- return this;
1410
- }
1411
-
1412
- // Add methods to `Hash`.
1413
- Hash.prototype.clear = hashClear;
1414
- Hash.prototype['delete'] = hashDelete;
1415
- Hash.prototype.get = hashGet;
1416
- Hash.prototype.has = hashHas;
1417
- Hash.prototype.set = hashSet;
1418
-
1419
- /**
1420
- * Creates an list cache object.
1421
- *
1422
- * @private
1423
- * @constructor
1424
- * @param {Array} [entries] The key-value pairs to cache.
1425
- */
1426
- function ListCache(entries) {
1427
- var index = -1,
1428
- length = entries ? entries.length : 0;
1429
-
1430
- this.clear();
1431
- while (++index < length) {
1432
- var entry = entries[index];
1433
- this.set(entry[0], entry[1]);
1434
- }
1435
- }
1436
-
1437
- /**
1438
- * Removes all key-value entries from the list cache.
1439
- *
1440
- * @private
1441
- * @name clear
1442
- * @memberOf ListCache
1443
- */
1444
- function listCacheClear() {
1445
- this.__data__ = [];
1446
- }
1447
-
1448
- /**
1449
- * Removes `key` and its value from the list cache.
1450
- *
1451
- * @private
1452
- * @name delete
1453
- * @memberOf ListCache
1454
- * @param {string} key The key of the value to remove.
1455
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1456
- */
1457
- function listCacheDelete(key) {
1458
- var data = this.__data__,
1459
- index = assocIndexOf(data, key);
1460
-
1461
- if (index < 0) {
1462
- return false;
1463
- }
1464
- var lastIndex = data.length - 1;
1465
- if (index == lastIndex) {
1466
- data.pop();
1467
- } else {
1468
- splice.call(data, index, 1);
1469
- }
1470
- return true;
1471
- }
1472
-
1473
- /**
1474
- * Gets the list cache value for `key`.
1475
- *
1476
- * @private
1477
- * @name get
1478
- * @memberOf ListCache
1479
- * @param {string} key The key of the value to get.
1480
- * @returns {*} Returns the entry value.
1481
- */
1482
- function listCacheGet(key) {
1483
- var data = this.__data__,
1484
- index = assocIndexOf(data, key);
1485
-
1486
- return index < 0 ? undefined : data[index][1];
1487
- }
1488
-
1489
- /**
1490
- * Checks if a list cache value for `key` exists.
1491
- *
1492
- * @private
1493
- * @name has
1494
- * @memberOf ListCache
1495
- * @param {string} key The key of the entry to check.
1496
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1497
- */
1498
- function listCacheHas(key) {
1499
- return assocIndexOf(this.__data__, key) > -1;
1500
- }
1501
-
1502
- /**
1503
- * Sets the list cache `key` to `value`.
1504
- *
1505
- * @private
1506
- * @name set
1507
- * @memberOf ListCache
1508
- * @param {string} key The key of the value to set.
1509
- * @param {*} value The value to set.
1510
- * @returns {Object} Returns the list cache instance.
1511
- */
1512
- function listCacheSet(key, value) {
1513
- var data = this.__data__,
1514
- index = assocIndexOf(data, key);
1515
-
1516
- if (index < 0) {
1517
- data.push([key, value]);
1518
- } else {
1519
- data[index][1] = value;
1520
- }
1521
- return this;
1522
- }
1523
-
1524
- // Add methods to `ListCache`.
1525
- ListCache.prototype.clear = listCacheClear;
1526
- ListCache.prototype['delete'] = listCacheDelete;
1527
- ListCache.prototype.get = listCacheGet;
1528
- ListCache.prototype.has = listCacheHas;
1529
- ListCache.prototype.set = listCacheSet;
1530
-
1531
- /**
1532
- * Creates a map cache object to store key-value pairs.
1533
- *
1534
- * @private
1535
- * @constructor
1536
- * @param {Array} [entries] The key-value pairs to cache.
1537
- */
1538
- function MapCache(entries) {
1539
- var index = -1,
1540
- length = entries ? entries.length : 0;
1541
-
1542
- this.clear();
1543
- while (++index < length) {
1544
- var entry = entries[index];
1545
- this.set(entry[0], entry[1]);
1546
- }
1547
- }
1548
-
1549
- /**
1550
- * Removes all key-value entries from the map.
1551
- *
1552
- * @private
1553
- * @name clear
1554
- * @memberOf MapCache
1555
- */
1556
- function mapCacheClear() {
1557
- this.__data__ = {
1558
- 'hash': new Hash,
1559
- 'map': new (Map || ListCache),
1560
- 'string': new Hash
1561
- };
1562
- }
1563
-
1564
- /**
1565
- * Removes `key` and its value from the map.
1566
- *
1567
- * @private
1568
- * @name delete
1569
- * @memberOf MapCache
1570
- * @param {string} key The key of the value to remove.
1571
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1572
- */
1573
- function mapCacheDelete(key) {
1574
- return getMapData(this, key)['delete'](key);
1575
- }
1576
-
1577
- /**
1578
- * Gets the map value for `key`.
1579
- *
1580
- * @private
1581
- * @name get
1582
- * @memberOf MapCache
1583
- * @param {string} key The key of the value to get.
1584
- * @returns {*} Returns the entry value.
1585
- */
1586
- function mapCacheGet(key) {
1587
- return getMapData(this, key).get(key);
1588
- }
1589
-
1590
- /**
1591
- * Checks if a map value for `key` exists.
1592
- *
1593
- * @private
1594
- * @name has
1595
- * @memberOf MapCache
1596
- * @param {string} key The key of the entry to check.
1597
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1598
- */
1599
- function mapCacheHas(key) {
1600
- return getMapData(this, key).has(key);
1601
- }
1602
-
1603
- /**
1604
- * Sets the map `key` to `value`.
1605
- *
1606
- * @private
1607
- * @name set
1608
- * @memberOf MapCache
1609
- * @param {string} key The key of the value to set.
1610
- * @param {*} value The value to set.
1611
- * @returns {Object} Returns the map cache instance.
1612
- */
1613
- function mapCacheSet(key, value) {
1614
- getMapData(this, key).set(key, value);
1615
- return this;
1616
- }
1617
-
1618
- // Add methods to `MapCache`.
1619
- MapCache.prototype.clear = mapCacheClear;
1620
- MapCache.prototype['delete'] = mapCacheDelete;
1621
- MapCache.prototype.get = mapCacheGet;
1622
- MapCache.prototype.has = mapCacheHas;
1623
- MapCache.prototype.set = mapCacheSet;
1624
-
1625
- /**
1626
- * Creates a stack cache object to store key-value pairs.
1627
- *
1628
- * @private
1629
- * @constructor
1630
- * @param {Array} [entries] The key-value pairs to cache.
1631
- */
1632
- function Stack(entries) {
1633
- this.__data__ = new ListCache(entries);
1634
- }
1635
-
1636
- /**
1637
- * Removes all key-value entries from the stack.
1638
- *
1639
- * @private
1640
- * @name clear
1641
- * @memberOf Stack
1642
- */
1643
- function stackClear() {
1644
- this.__data__ = new ListCache;
1645
- }
1646
-
1647
- /**
1648
- * Removes `key` and its value from the stack.
1649
- *
1650
- * @private
1651
- * @name delete
1652
- * @memberOf Stack
1653
- * @param {string} key The key of the value to remove.
1654
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1655
- */
1656
- function stackDelete(key) {
1657
- return this.__data__['delete'](key);
1658
- }
1659
-
1660
- /**
1661
- * Gets the stack value for `key`.
1662
- *
1663
- * @private
1664
- * @name get
1665
- * @memberOf Stack
1666
- * @param {string} key The key of the value to get.
1667
- * @returns {*} Returns the entry value.
1668
- */
1669
- function stackGet(key) {
1670
- return this.__data__.get(key);
1671
- }
1672
-
1673
- /**
1674
- * Checks if a stack value for `key` exists.
1675
- *
1676
- * @private
1677
- * @name has
1678
- * @memberOf Stack
1679
- * @param {string} key The key of the entry to check.
1680
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1681
- */
1682
- function stackHas(key) {
1683
- return this.__data__.has(key);
1684
- }
1685
-
1686
- /**
1687
- * Sets the stack `key` to `value`.
1688
- *
1689
- * @private
1690
- * @name set
1691
- * @memberOf Stack
1692
- * @param {string} key The key of the value to set.
1693
- * @param {*} value The value to set.
1694
- * @returns {Object} Returns the stack cache instance.
1695
- */
1696
- function stackSet(key, value) {
1697
- var cache = this.__data__;
1698
- if (cache instanceof ListCache) {
1699
- var pairs = cache.__data__;
1700
- if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
1701
- pairs.push([key, value]);
1702
- return this;
1703
- }
1704
- cache = this.__data__ = new MapCache(pairs);
1705
- }
1706
- cache.set(key, value);
1707
- return this;
1708
- }
1709
-
1710
- // Add methods to `Stack`.
1711
- Stack.prototype.clear = stackClear;
1712
- Stack.prototype['delete'] = stackDelete;
1713
- Stack.prototype.get = stackGet;
1714
- Stack.prototype.has = stackHas;
1715
- Stack.prototype.set = stackSet;
1716
-
1717
- /**
1718
- * Creates an array of the enumerable property names of the array-like `value`.
1719
- *
1720
- * @private
1721
- * @param {*} value The value to query.
1722
- * @param {boolean} inherited Specify returning inherited property names.
1723
- * @returns {Array} Returns the array of property names.
1724
- */
1725
- function arrayLikeKeys(value, inherited) {
1726
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
1727
- // Safari 9 makes `arguments.length` enumerable in strict mode.
1728
- var result = (isArray(value) || isArguments(value))
1729
- ? baseTimes(value.length, String)
1730
- : [];
1731
-
1732
- var length = result.length,
1733
- skipIndexes = !!length;
1734
-
1735
- for (var key in value) {
1736
- if ((inherited || hasOwnProperty.call(value, key)) &&
1737
- !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
1738
- result.push(key);
1739
- }
1740
- }
1741
- return result;
1742
- }
1743
-
1744
- /**
1745
- * Assigns `value` to `key` of `object` if the existing value is not equivalent
1746
- * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
1747
- * for equality comparisons.
1748
- *
1749
- * @private
1750
- * @param {Object} object The object to modify.
1751
- * @param {string} key The key of the property to assign.
1752
- * @param {*} value The value to assign.
1753
- */
1754
- function assignValue(object, key, value) {
1755
- var objValue = object[key];
1756
- if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
1757
- (value === undefined && !(key in object))) {
1758
- object[key] = value;
1759
- }
1760
- }
1761
-
1762
- /**
1763
- * Gets the index at which the `key` is found in `array` of key-value pairs.
1764
- *
1765
- * @private
1766
- * @param {Array} array The array to inspect.
1767
- * @param {*} key The key to search for.
1768
- * @returns {number} Returns the index of the matched value, else `-1`.
1769
- */
1770
- function assocIndexOf(array, key) {
1771
- var length = array.length;
1772
- while (length--) {
1773
- if (eq(array[length][0], key)) {
1774
- return length;
1775
- }
1776
- }
1777
- return -1;
1778
- }
1779
-
1780
- /**
1781
- * The base implementation of `_.assign` without support for multiple sources
1782
- * or `customizer` functions.
1783
- *
1784
- * @private
1785
- * @param {Object} object The destination object.
1786
- * @param {Object} source The source object.
1787
- * @returns {Object} Returns `object`.
1788
- */
1789
- function baseAssign(object, source) {
1790
- return object && copyObject(source, keys(source), object);
1791
- }
1792
-
1793
- /**
1794
- * The base implementation of `_.clone` and `_.cloneDeep` which tracks
1795
- * traversed objects.
1796
- *
1797
- * @private
1798
- * @param {*} value The value to clone.
1799
- * @param {boolean} [isDeep] Specify a deep clone.
1800
- * @param {boolean} [isFull] Specify a clone including symbols.
1801
- * @param {Function} [customizer] The function to customize cloning.
1802
- * @param {string} [key] The key of `value`.
1803
- * @param {Object} [object] The parent object of `value`.
1804
- * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
1805
- * @returns {*} Returns the cloned value.
1806
- */
1807
- function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
1808
- var result;
1809
- if (customizer) {
1810
- result = object ? customizer(value, key, object, stack) : customizer(value);
1811
- }
1812
- if (result !== undefined) {
1813
- return result;
1814
- }
1815
- if (!isObject(value)) {
1816
- return value;
1817
- }
1818
- var isArr = isArray(value);
1819
- if (isArr) {
1820
- result = initCloneArray(value);
1821
- if (!isDeep) {
1822
- return copyArray(value, result);
1823
- }
1824
- } else {
1825
- var tag = getTag(value),
1826
- isFunc = tag == funcTag || tag == genTag;
1827
-
1828
- if (isBuffer(value)) {
1829
- return cloneBuffer(value, isDeep);
1830
- }
1831
- if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
1832
- if (isHostObject(value)) {
1833
- return object ? value : {};
1834
- }
1835
- result = initCloneObject(isFunc ? {} : value);
1836
- if (!isDeep) {
1837
- return copySymbols(value, baseAssign(result, value));
1838
- }
1839
- } else {
1840
- if (!cloneableTags[tag]) {
1841
- return object ? value : {};
1842
- }
1843
- result = initCloneByTag(value, tag, baseClone, isDeep);
1844
- }
1845
- }
1846
- // Check for circular references and return its corresponding clone.
1847
- stack || (stack = new Stack);
1848
- var stacked = stack.get(value);
1849
- if (stacked) {
1850
- return stacked;
1851
- }
1852
- stack.set(value, result);
1853
-
1854
- if (!isArr) {
1855
- var props = isFull ? getAllKeys(value) : keys(value);
1856
- }
1857
- arrayEach(props || value, function(subValue, key) {
1858
- if (props) {
1859
- key = subValue;
1860
- subValue = value[key];
1861
- }
1862
- // Recursively populate clone (susceptible to call stack limits).
1863
- assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
1864
- });
1865
- return result;
1866
- }
1867
-
1868
- /**
1869
- * The base implementation of `_.create` without support for assigning
1870
- * properties to the created object.
1871
- *
1872
- * @private
1873
- * @param {Object} prototype The object to inherit from.
1874
- * @returns {Object} Returns the new object.
1875
- */
1876
- function baseCreate(proto) {
1877
- return isObject(proto) ? objectCreate(proto) : {};
1878
- }
1879
-
1880
- /**
1881
- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
1882
- * `keysFunc` and `symbolsFunc` to get the enumerable property names and
1883
- * symbols of `object`.
1884
- *
1885
- * @private
1886
- * @param {Object} object The object to query.
1887
- * @param {Function} keysFunc The function to get the keys of `object`.
1888
- * @param {Function} symbolsFunc The function to get the symbols of `object`.
1889
- * @returns {Array} Returns the array of property names and symbols.
1890
- */
1891
- function baseGetAllKeys(object, keysFunc, symbolsFunc) {
1892
- var result = keysFunc(object);
1893
- return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
1894
- }
1895
-
1896
- /**
1897
- * The base implementation of `getTag`.
1898
- *
1899
- * @private
1900
- * @param {*} value The value to query.
1901
- * @returns {string} Returns the `toStringTag`.
1902
- */
1903
- function baseGetTag(value) {
1904
- return objectToString.call(value);
1905
- }
1906
-
1907
- /**
1908
- * The base implementation of `_.isNative` without bad shim checks.
1909
- *
1910
- * @private
1911
- * @param {*} value The value to check.
1912
- * @returns {boolean} Returns `true` if `value` is a native function,
1913
- * else `false`.
1914
- */
1915
- function baseIsNative(value) {
1916
- if (!isObject(value) || isMasked(value)) {
1917
- return false;
1918
- }
1919
- var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
1920
- return pattern.test(toSource(value));
1921
- }
1922
-
1923
- /**
1924
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
1925
- *
1926
- * @private
1927
- * @param {Object} object The object to query.
1928
- * @returns {Array} Returns the array of property names.
1929
- */
1930
- function baseKeys(object) {
1931
- if (!isPrototype(object)) {
1932
- return nativeKeys(object);
1933
- }
1934
- var result = [];
1935
- for (var key in Object(object)) {
1936
- if (hasOwnProperty.call(object, key) && key != 'constructor') {
1937
- result.push(key);
1938
- }
1939
- }
1940
- return result;
1941
- }
1942
-
1943
- /**
1944
- * Creates a clone of `buffer`.
1945
- *
1946
- * @private
1947
- * @param {Buffer} buffer The buffer to clone.
1948
- * @param {boolean} [isDeep] Specify a deep clone.
1949
- * @returns {Buffer} Returns the cloned buffer.
1950
- */
1951
- function cloneBuffer(buffer, isDeep) {
1952
- if (isDeep) {
1953
- return buffer.slice();
1954
- }
1955
- var result = new buffer.constructor(buffer.length);
1956
- buffer.copy(result);
1957
- return result;
1958
- }
1959
-
1960
- /**
1961
- * Creates a clone of `arrayBuffer`.
1962
- *
1963
- * @private
1964
- * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
1965
- * @returns {ArrayBuffer} Returns the cloned array buffer.
1966
- */
1967
- function cloneArrayBuffer(arrayBuffer) {
1968
- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
1969
- new Uint8Array(result).set(new Uint8Array(arrayBuffer));
1970
- return result;
1971
- }
1972
-
1973
- /**
1974
- * Creates a clone of `dataView`.
1975
- *
1976
- * @private
1977
- * @param {Object} dataView The data view to clone.
1978
- * @param {boolean} [isDeep] Specify a deep clone.
1979
- * @returns {Object} Returns the cloned data view.
1980
- */
1981
- function cloneDataView(dataView, isDeep) {
1982
- var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
1983
- return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
1984
- }
1985
-
1986
- /**
1987
- * Creates a clone of `map`.
1988
- *
1989
- * @private
1990
- * @param {Object} map The map to clone.
1991
- * @param {Function} cloneFunc The function to clone values.
1992
- * @param {boolean} [isDeep] Specify a deep clone.
1993
- * @returns {Object} Returns the cloned map.
1994
- */
1995
- function cloneMap(map, isDeep, cloneFunc) {
1996
- var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
1997
- return arrayReduce(array, addMapEntry, new map.constructor);
1998
- }
1999
-
2000
- /**
2001
- * Creates a clone of `regexp`.
2002
- *
2003
- * @private
2004
- * @param {Object} regexp The regexp to clone.
2005
- * @returns {Object} Returns the cloned regexp.
2006
- */
2007
- function cloneRegExp(regexp) {
2008
- var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
2009
- result.lastIndex = regexp.lastIndex;
2010
- return result;
2011
- }
2012
-
2013
- /**
2014
- * Creates a clone of `set`.
2015
- *
2016
- * @private
2017
- * @param {Object} set The set to clone.
2018
- * @param {Function} cloneFunc The function to clone values.
2019
- * @param {boolean} [isDeep] Specify a deep clone.
2020
- * @returns {Object} Returns the cloned set.
2021
- */
2022
- function cloneSet(set, isDeep, cloneFunc) {
2023
- var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
2024
- return arrayReduce(array, addSetEntry, new set.constructor);
2025
- }
2026
-
2027
- /**
2028
- * Creates a clone of the `symbol` object.
2029
- *
2030
- * @private
2031
- * @param {Object} symbol The symbol object to clone.
2032
- * @returns {Object} Returns the cloned symbol object.
2033
- */
2034
- function cloneSymbol(symbol) {
2035
- return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
2036
- }
2037
-
2038
- /**
2039
- * Creates a clone of `typedArray`.
2040
- *
2041
- * @private
2042
- * @param {Object} typedArray The typed array to clone.
2043
- * @param {boolean} [isDeep] Specify a deep clone.
2044
- * @returns {Object} Returns the cloned typed array.
2045
- */
2046
- function cloneTypedArray(typedArray, isDeep) {
2047
- var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
2048
- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
2049
- }
2050
-
2051
- /**
2052
- * Copies the values of `source` to `array`.
2053
- *
2054
- * @private
2055
- * @param {Array} source The array to copy values from.
2056
- * @param {Array} [array=[]] The array to copy values to.
2057
- * @returns {Array} Returns `array`.
2058
- */
2059
- function copyArray(source, array) {
2060
- var index = -1,
2061
- length = source.length;
2062
-
2063
- array || (array = Array(length));
2064
- while (++index < length) {
2065
- array[index] = source[index];
2066
- }
2067
- return array;
2068
- }
2069
-
2070
- /**
2071
- * Copies properties of `source` to `object`.
2072
- *
2073
- * @private
2074
- * @param {Object} source The object to copy properties from.
2075
- * @param {Array} props The property identifiers to copy.
2076
- * @param {Object} [object={}] The object to copy properties to.
2077
- * @param {Function} [customizer] The function to customize copied values.
2078
- * @returns {Object} Returns `object`.
2079
- */
2080
- function copyObject(source, props, object, customizer) {
2081
- object || (object = {});
2082
-
2083
- var index = -1,
2084
- length = props.length;
2085
-
2086
- while (++index < length) {
2087
- var key = props[index];
2088
-
2089
- var newValue = customizer
2090
- ? customizer(object[key], source[key], key, object, source)
2091
- : undefined;
2092
-
2093
- assignValue(object, key, newValue === undefined ? source[key] : newValue);
2094
- }
2095
- return object;
2096
- }
2097
-
2098
- /**
2099
- * Copies own symbol properties of `source` to `object`.
2100
- *
2101
- * @private
2102
- * @param {Object} source The object to copy symbols from.
2103
- * @param {Object} [object={}] The object to copy symbols to.
2104
- * @returns {Object} Returns `object`.
2105
- */
2106
- function copySymbols(source, object) {
2107
- return copyObject(source, getSymbols(source), object);
2108
- }
2109
-
2110
- /**
2111
- * Creates an array of own enumerable property names and symbols of `object`.
2112
- *
2113
- * @private
2114
- * @param {Object} object The object to query.
2115
- * @returns {Array} Returns the array of property names and symbols.
2116
- */
2117
- function getAllKeys(object) {
2118
- return baseGetAllKeys(object, keys, getSymbols);
2119
- }
2120
-
2121
- /**
2122
- * Gets the data for `map`.
2123
- *
2124
- * @private
2125
- * @param {Object} map The map to query.
2126
- * @param {string} key The reference key.
2127
- * @returns {*} Returns the map data.
2128
- */
2129
- function getMapData(map, key) {
2130
- var data = map.__data__;
2131
- return isKeyable(key)
2132
- ? data[typeof key == 'string' ? 'string' : 'hash']
2133
- : data.map;
2134
- }
2135
-
2136
- /**
2137
- * Gets the native function at `key` of `object`.
2138
- *
2139
- * @private
2140
- * @param {Object} object The object to query.
2141
- * @param {string} key The key of the method to get.
2142
- * @returns {*} Returns the function if it's native, else `undefined`.
2143
- */
2144
- function getNative(object, key) {
2145
- var value = getValue(object, key);
2146
- return baseIsNative(value) ? value : undefined;
2147
- }
2148
-
2149
- /**
2150
- * Creates an array of the own enumerable symbol properties of `object`.
2151
- *
2152
- * @private
2153
- * @param {Object} object The object to query.
2154
- * @returns {Array} Returns the array of symbols.
2155
- */
2156
- var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
2157
-
2158
- /**
2159
- * Gets the `toStringTag` of `value`.
2160
- *
2161
- * @private
2162
- * @param {*} value The value to query.
2163
- * @returns {string} Returns the `toStringTag`.
2164
- */
2165
- var getTag = baseGetTag;
2166
-
2167
- // Fallback for data views, maps, sets, and weak maps in IE 11,
2168
- // for data views in Edge < 14, and promises in Node.js.
2169
- if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
2170
- (Map && getTag(new Map) != mapTag) ||
2171
- (Promise && getTag(Promise.resolve()) != promiseTag) ||
2172
- (Set && getTag(new Set) != setTag) ||
2173
- (WeakMap && getTag(new WeakMap) != weakMapTag)) {
2174
- getTag = function(value) {
2175
- var result = objectToString.call(value),
2176
- Ctor = result == objectTag ? value.constructor : undefined,
2177
- ctorString = Ctor ? toSource(Ctor) : undefined;
2178
-
2179
- if (ctorString) {
2180
- switch (ctorString) {
2181
- case dataViewCtorString: return dataViewTag;
2182
- case mapCtorString: return mapTag;
2183
- case promiseCtorString: return promiseTag;
2184
- case setCtorString: return setTag;
2185
- case weakMapCtorString: return weakMapTag;
2186
- }
2187
- }
2188
- return result;
2189
- };
2190
- }
2191
-
2192
- /**
2193
- * Initializes an array clone.
2194
- *
2195
- * @private
2196
- * @param {Array} array The array to clone.
2197
- * @returns {Array} Returns the initialized clone.
2198
- */
2199
- function initCloneArray(array) {
2200
- var length = array.length,
2201
- result = array.constructor(length);
2202
-
2203
- // Add properties assigned by `RegExp#exec`.
2204
- if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
2205
- result.index = array.index;
2206
- result.input = array.input;
2207
- }
2208
- return result;
2209
- }
2210
-
2211
- /**
2212
- * Initializes an object clone.
2213
- *
2214
- * @private
2215
- * @param {Object} object The object to clone.
2216
- * @returns {Object} Returns the initialized clone.
2217
- */
2218
- function initCloneObject(object) {
2219
- return (typeof object.constructor == 'function' && !isPrototype(object))
2220
- ? baseCreate(getPrototype(object))
2221
- : {};
2222
- }
2223
-
2224
- /**
2225
- * Initializes an object clone based on its `toStringTag`.
2226
- *
2227
- * **Note:** This function only supports cloning values with tags of
2228
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
2229
- *
2230
- * @private
2231
- * @param {Object} object The object to clone.
2232
- * @param {string} tag The `toStringTag` of the object to clone.
2233
- * @param {Function} cloneFunc The function to clone values.
2234
- * @param {boolean} [isDeep] Specify a deep clone.
2235
- * @returns {Object} Returns the initialized clone.
2236
- */
2237
- function initCloneByTag(object, tag, cloneFunc, isDeep) {
2238
- var Ctor = object.constructor;
2239
- switch (tag) {
2240
- case arrayBufferTag:
2241
- return cloneArrayBuffer(object);
2242
-
2243
- case boolTag:
2244
- case dateTag:
2245
- return new Ctor(+object);
2246
-
2247
- case dataViewTag:
2248
- return cloneDataView(object, isDeep);
2249
-
2250
- case float32Tag: case float64Tag:
2251
- case int8Tag: case int16Tag: case int32Tag:
2252
- case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
2253
- return cloneTypedArray(object, isDeep);
2254
-
2255
- case mapTag:
2256
- return cloneMap(object, isDeep, cloneFunc);
2257
-
2258
- case numberTag:
2259
- case stringTag:
2260
- return new Ctor(object);
2261
-
2262
- case regexpTag:
2263
- return cloneRegExp(object);
2264
-
2265
- case setTag:
2266
- return cloneSet(object, isDeep, cloneFunc);
2267
-
2268
- case symbolTag:
2269
- return cloneSymbol(object);
2270
- }
2271
- }
2272
-
2273
- /**
2274
- * Checks if `value` is a valid array-like index.
2275
- *
2276
- * @private
2277
- * @param {*} value The value to check.
2278
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
2279
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
2280
- */
2281
- function isIndex(value, length) {
2282
- length = length == null ? MAX_SAFE_INTEGER : length;
2283
- return !!length &&
2284
- (typeof value == 'number' || reIsUint.test(value)) &&
2285
- (value > -1 && value % 1 == 0 && value < length);
2286
- }
2287
-
2288
- /**
2289
- * Checks if `value` is suitable for use as unique object key.
2290
- *
2291
- * @private
2292
- * @param {*} value The value to check.
2293
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
2294
- */
2295
- function isKeyable(value) {
2296
- var type = typeof value;
2297
- return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
2298
- ? (value !== '__proto__')
2299
- : (value === null);
2300
- }
2301
-
2302
- /**
2303
- * Checks if `func` has its source masked.
2304
- *
2305
- * @private
2306
- * @param {Function} func The function to check.
2307
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
2308
- */
2309
- function isMasked(func) {
2310
- return !!maskSrcKey && (maskSrcKey in func);
2311
- }
2312
-
2313
- /**
2314
- * Checks if `value` is likely a prototype object.
2315
- *
2316
- * @private
2317
- * @param {*} value The value to check.
2318
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
2319
- */
2320
- function isPrototype(value) {
2321
- var Ctor = value && value.constructor,
2322
- proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
2323
-
2324
- return value === proto;
2325
- }
2326
-
2327
- /**
2328
- * Converts `func` to its source code.
2329
- *
2330
- * @private
2331
- * @param {Function} func The function to process.
2332
- * @returns {string} Returns the source code.
2333
- */
2334
- function toSource(func) {
2335
- if (func != null) {
2336
- try {
2337
- return funcToString.call(func);
2338
- } catch (e) {}
2339
- try {
2340
- return (func + '');
2341
- } catch (e) {}
2342
- }
2343
- return '';
2344
- }
2345
-
2346
- /**
2347
- * This method is like `_.clone` except that it recursively clones `value`.
2348
- *
2349
- * @static
2350
- * @memberOf _
2351
- * @since 1.0.0
2352
- * @category Lang
2353
- * @param {*} value The value to recursively clone.
2354
- * @returns {*} Returns the deep cloned value.
2355
- * @see _.clone
2356
- * @example
2357
- *
2358
- * var objects = [{ 'a': 1 }, { 'b': 2 }];
2359
- *
2360
- * var deep = _.cloneDeep(objects);
2361
- * console.log(deep[0] === objects[0]);
2362
- * // => false
2363
- */
2364
- function cloneDeep(value) {
2365
- return baseClone(value, true, true);
2366
- }
2367
-
2368
- /**
2369
- * Performs a
2370
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
2371
- * comparison between two values to determine if they are equivalent.
2372
- *
2373
- * @static
2374
- * @memberOf _
2375
- * @since 4.0.0
2376
- * @category Lang
2377
- * @param {*} value The value to compare.
2378
- * @param {*} other The other value to compare.
2379
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2380
- * @example
2381
- *
2382
- * var object = { 'a': 1 };
2383
- * var other = { 'a': 1 };
2384
- *
2385
- * _.eq(object, object);
2386
- * // => true
2387
- *
2388
- * _.eq(object, other);
2389
- * // => false
2390
- *
2391
- * _.eq('a', 'a');
2392
- * // => true
2393
- *
2394
- * _.eq('a', Object('a'));
2395
- * // => false
2396
- *
2397
- * _.eq(NaN, NaN);
2398
- * // => true
2399
- */
2400
- function eq(value, other) {
2401
- return value === other || (value !== value && other !== other);
2402
- }
2403
-
2404
- /**
2405
- * Checks if `value` is likely an `arguments` object.
2406
- *
2407
- * @static
2408
- * @memberOf _
2409
- * @since 0.1.0
2410
- * @category Lang
2411
- * @param {*} value The value to check.
2412
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
2413
- * else `false`.
2414
- * @example
2415
- *
2416
- * _.isArguments(function() { return arguments; }());
2417
- * // => true
2418
- *
2419
- * _.isArguments([1, 2, 3]);
2420
- * // => false
2421
- */
2422
- function isArguments(value) {
2423
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
2424
- return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
2425
- (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
2426
- }
2427
-
2428
- /**
2429
- * Checks if `value` is classified as an `Array` object.
2430
- *
2431
- * @static
2432
- * @memberOf _
2433
- * @since 0.1.0
2434
- * @category Lang
2435
- * @param {*} value The value to check.
2436
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
2437
- * @example
2438
- *
2439
- * _.isArray([1, 2, 3]);
2440
- * // => true
2441
- *
2442
- * _.isArray(document.body.children);
2443
- * // => false
2444
- *
2445
- * _.isArray('abc');
2446
- * // => false
2447
- *
2448
- * _.isArray(_.noop);
2449
- * // => false
2450
- */
2451
- var isArray = Array.isArray;
2452
-
2453
- /**
2454
- * Checks if `value` is array-like. A value is considered array-like if it's
2455
- * not a function and has a `value.length` that's an integer greater than or
2456
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
2457
- *
2458
- * @static
2459
- * @memberOf _
2460
- * @since 4.0.0
2461
- * @category Lang
2462
- * @param {*} value The value to check.
2463
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
2464
- * @example
2465
- *
2466
- * _.isArrayLike([1, 2, 3]);
2467
- * // => true
2468
- *
2469
- * _.isArrayLike(document.body.children);
2470
- * // => true
2471
- *
2472
- * _.isArrayLike('abc');
2473
- * // => true
2474
- *
2475
- * _.isArrayLike(_.noop);
2476
- * // => false
2477
- */
2478
- function isArrayLike(value) {
2479
- return value != null && isLength(value.length) && !isFunction(value);
2480
- }
2481
-
2482
- /**
2483
- * This method is like `_.isArrayLike` except that it also checks if `value`
2484
- * is an object.
2485
- *
2486
- * @static
2487
- * @memberOf _
2488
- * @since 4.0.0
2489
- * @category Lang
2490
- * @param {*} value The value to check.
2491
- * @returns {boolean} Returns `true` if `value` is an array-like object,
2492
- * else `false`.
2493
- * @example
2494
- *
2495
- * _.isArrayLikeObject([1, 2, 3]);
2496
- * // => true
2497
- *
2498
- * _.isArrayLikeObject(document.body.children);
2499
- * // => true
2500
- *
2501
- * _.isArrayLikeObject('abc');
2502
- * // => false
2503
- *
2504
- * _.isArrayLikeObject(_.noop);
2505
- * // => false
2506
- */
2507
- function isArrayLikeObject(value) {
2508
- return isObjectLike(value) && isArrayLike(value);
2509
- }
2510
-
2511
- /**
2512
- * Checks if `value` is a buffer.
2513
- *
2514
- * @static
2515
- * @memberOf _
2516
- * @since 4.3.0
2517
- * @category Lang
2518
- * @param {*} value The value to check.
2519
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
2520
- * @example
2521
- *
2522
- * _.isBuffer(new Buffer(2));
2523
- * // => true
2524
- *
2525
- * _.isBuffer(new Uint8Array(2));
2526
- * // => false
2527
- */
2528
- var isBuffer = nativeIsBuffer || stubFalse;
2529
-
2530
- /**
2531
- * Checks if `value` is classified as a `Function` object.
2532
- *
2533
- * @static
2534
- * @memberOf _
2535
- * @since 0.1.0
2536
- * @category Lang
2537
- * @param {*} value The value to check.
2538
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
2539
- * @example
2540
- *
2541
- * _.isFunction(_);
2542
- * // => true
2543
- *
2544
- * _.isFunction(/abc/);
2545
- * // => false
2546
- */
2547
- function isFunction(value) {
2548
- // The use of `Object#toString` avoids issues with the `typeof` operator
2549
- // in Safari 8-9 which returns 'object' for typed array and other constructors.
2550
- var tag = isObject(value) ? objectToString.call(value) : '';
2551
- return tag == funcTag || tag == genTag;
2552
- }
2553
-
2554
- /**
2555
- * Checks if `value` is a valid array-like length.
2556
- *
2557
- * **Note:** This method is loosely based on
2558
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
2559
- *
2560
- * @static
2561
- * @memberOf _
2562
- * @since 4.0.0
2563
- * @category Lang
2564
- * @param {*} value The value to check.
2565
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
2566
- * @example
2567
- *
2568
- * _.isLength(3);
2569
- * // => true
2570
- *
2571
- * _.isLength(Number.MIN_VALUE);
2572
- * // => false
2573
- *
2574
- * _.isLength(Infinity);
2575
- * // => false
2576
- *
2577
- * _.isLength('3');
2578
- * // => false
2579
- */
2580
- function isLength(value) {
2581
- return typeof value == 'number' &&
2582
- value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
2583
- }
2584
-
2585
- /**
2586
- * Checks if `value` is the
2587
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
2588
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
2589
- *
2590
- * @static
2591
- * @memberOf _
2592
- * @since 0.1.0
2593
- * @category Lang
2594
- * @param {*} value The value to check.
2595
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
2596
- * @example
2597
- *
2598
- * _.isObject({});
2599
- * // => true
2600
- *
2601
- * _.isObject([1, 2, 3]);
2602
- * // => true
2603
- *
2604
- * _.isObject(_.noop);
2605
- * // => true
2606
- *
2607
- * _.isObject(null);
2608
- * // => false
2609
- */
2610
- function isObject(value) {
2611
- var type = typeof value;
2612
- return !!value && (type == 'object' || type == 'function');
2613
- }
2614
-
2615
- /**
2616
- * Checks if `value` is object-like. A value is object-like if it's not `null`
2617
- * and has a `typeof` result of "object".
2618
- *
2619
- * @static
2620
- * @memberOf _
2621
- * @since 4.0.0
2622
- * @category Lang
2623
- * @param {*} value The value to check.
2624
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
2625
- * @example
2626
- *
2627
- * _.isObjectLike({});
2628
- * // => true
2629
- *
2630
- * _.isObjectLike([1, 2, 3]);
2631
- * // => true
2632
- *
2633
- * _.isObjectLike(_.noop);
2634
- * // => false
2635
- *
2636
- * _.isObjectLike(null);
2637
- * // => false
2638
- */
2639
- function isObjectLike(value) {
2640
- return !!value && typeof value == 'object';
2641
- }
2642
-
2643
- /**
2644
- * Creates an array of the own enumerable property names of `object`.
2645
- *
2646
- * **Note:** Non-object values are coerced to objects. See the
2647
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
2648
- * for more details.
2649
- *
2650
- * @static
2651
- * @since 0.1.0
2652
- * @memberOf _
2653
- * @category Object
2654
- * @param {Object} object The object to query.
2655
- * @returns {Array} Returns the array of property names.
2656
- * @example
2657
- *
2658
- * function Foo() {
2659
- * this.a = 1;
2660
- * this.b = 2;
2661
- * }
2662
- *
2663
- * Foo.prototype.c = 3;
2664
- *
2665
- * _.keys(new Foo);
2666
- * // => ['a', 'b'] (iteration order is not guaranteed)
2667
- *
2668
- * _.keys('hi');
2669
- * // => ['0', '1']
2670
- */
2671
- function keys(object) {
2672
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
2673
- }
2674
-
2675
- /**
2676
- * This method returns a new empty array.
2677
- *
2678
- * @static
2679
- * @memberOf _
2680
- * @since 4.13.0
2681
- * @category Util
2682
- * @returns {Array} Returns the new empty array.
2683
- * @example
2684
- *
2685
- * var arrays = _.times(2, _.stubArray);
2686
- *
2687
- * console.log(arrays);
2688
- * // => [[], []]
2689
- *
2690
- * console.log(arrays[0] === arrays[1]);
2691
- * // => false
2692
- */
2693
- function stubArray() {
2694
- return [];
2695
- }
2696
-
2697
- /**
2698
- * This method returns `false`.
2699
- *
2700
- * @static
2701
- * @memberOf _
2702
- * @since 4.13.0
2703
- * @category Util
2704
- * @returns {boolean} Returns `false`.
2705
- * @example
2706
- *
2707
- * _.times(2, _.stubFalse);
2708
- * // => [false, false]
2709
- */
2710
- function stubFalse() {
2711
- return false;
2712
- }
2713
-
2714
- module.exports = cloneDeep;
2715
- }(lodash_clonedeep, lodash_clonedeep.exports));
2716
-
2717
- /**
2718
- * @name string-left-right
2719
- * @fileoverview Looks up the first non-whitespace character to the left/right of a given index
2720
- * @version 4.1.0
2721
- * @author Roy Revelt, Codsen Ltd
2722
- * @license MIT
2723
- * {@link https://codsen.com/os/string-left-right/}
2724
- */
2725
- const RAWNBSP = "\u00A0";
2726
- function rightMain({
2727
- str,
2728
- idx = 0,
2729
- stopAtNewlines = false,
2730
- stopAtRawNbsp = false
2731
- }) {
2732
- if (typeof str !== "string" || !str.length) {
2733
- return null;
2734
- }
2735
- if (!idx || typeof idx !== "number") {
2736
- idx = 0;
2737
- }
2738
- if (!str[idx + 1]) {
2739
- return null;
2740
- }
2741
- if (
2742
- str[idx + 1] && (
2743
- str[idx + 1].trim() ||
2744
- stopAtNewlines &&
2745
- "\n\r".includes(str[idx + 1]) ||
2746
- stopAtRawNbsp &&
2747
- str[idx + 1] === RAWNBSP)) {
2748
- return idx + 1;
2749
- }
2750
- if (
2751
- str[idx + 2] && (
2752
- str[idx + 2].trim() ||
2753
- stopAtNewlines &&
2754
- "\n\r".includes(str[idx + 2]) ||
2755
- stopAtRawNbsp &&
2756
- str[idx + 2] === RAWNBSP)) {
2757
- return idx + 2;
2758
- }
2759
- for (let i = idx + 1, len = str.length; i < len; i++) {
2760
- if (
2761
- str[i].trim() ||
2762
- stopAtNewlines &&
2763
- "\n\r".includes(str[i]) ||
2764
- stopAtRawNbsp &&
2765
- str[i] === RAWNBSP) {
2766
- return i;
2767
- }
2768
- }
2769
- return null;
2770
- }
2771
- function right(str, idx = 0) {
2772
- return rightMain({
2773
- str,
2774
- idx,
2775
- stopAtNewlines: false,
2776
- stopAtRawNbsp: false
2777
- });
2778
- }
2779
- function leftMain({
2780
- str,
2781
- idx,
2782
- stopAtNewlines,
2783
- stopAtRawNbsp
2784
- }) {
2785
- if (typeof str !== "string" || !str.length) {
2786
- return null;
2787
- }
2788
- if (!idx || typeof idx !== "number") {
2789
- idx = 0;
2790
- }
2791
- if (idx < 1) {
2792
- return null;
2793
- }
2794
- if (
2795
- str[~-idx] && (
2796
- str[~-idx].trim() ||
2797
- stopAtNewlines &&
2798
- "\n\r".includes(str[~-idx]) ||
2799
- stopAtRawNbsp &&
2800
- str[~-idx] === RAWNBSP)) {
2801
- return ~-idx;
2802
- }
2803
- if (
2804
- str[idx - 2] && (
2805
- str[idx - 2].trim() ||
2806
- stopAtNewlines &&
2807
- "\n\r".includes(str[idx - 2]) ||
2808
- stopAtRawNbsp &&
2809
- str[idx - 2] === RAWNBSP)) {
2810
- return idx - 2;
2811
- }
2812
- for (let i = idx; i--;) {
2813
- if (str[i] && (
2814
- str[i].trim() ||
2815
- stopAtNewlines &&
2816
- "\n\r".includes(str[i]) ||
2817
- stopAtRawNbsp &&
2818
- str[i] === RAWNBSP)) {
2819
- return i;
2820
- }
2821
- }
2822
- return null;
2823
- }
2824
- function left(str, idx = 0) {
2825
- return leftMain({
2826
- str,
2827
- idx,
2828
- stopAtNewlines: false,
2829
- stopAtRawNbsp: false
2830
- });
2831
- }
2832
-
2833
- var version$1 = "4.2.0";
2834
-
2835
- const version = version$1;
2836
- const finalIndexesToDelete = new Ranges({ limitToBeAddedWhitespace: true });
2837
- const defaults = {
2838
- lineLengthLimit: 500,
2839
- removeIndentations: true,
2840
- removeLineBreaks: false,
2841
- removeHTMLComments: false,
2842
- removeCSSComments: true,
2843
- reportProgressFunc: null,
2844
- reportProgressFuncFrom: 0,
2845
- reportProgressFuncTo: 100,
2846
- breakToTheLeftOf: [
2847
- "</td",
2848
- "<html",
2849
- "</html",
2850
- "<head",
2851
- "</head",
2852
- "<meta",
2853
- "<link",
2854
- "<table",
2855
- "<script",
2856
- "</script",
2857
- "<!DOCTYPE",
2858
- "<style",
2859
- "</style",
2860
- "<title",
2861
- "<body",
2862
- "@media",
2863
- "</body",
2864
- "<!--[if",
2865
- "<!--<![endif",
2866
- "<![endif]",
2867
- ],
2868
- mindTheInlineTags: [
2869
- "a",
2870
- "abbr",
2871
- "acronym",
2872
- "audio",
2873
- "b",
2874
- "bdi",
2875
- "bdo",
2876
- "big",
2877
- "br",
2878
- "button",
2879
- "canvas",
2880
- "cite",
2881
- "code",
2882
- "data",
2883
- "datalist",
2884
- "del",
2885
- "dfn",
2886
- "em",
2887
- "embed",
2888
- "i",
2889
- "iframe",
2890
- "img",
2891
- "input",
2892
- "ins",
2893
- "kbd",
2894
- "label",
2895
- "map",
2896
- "mark",
2897
- "meter",
2898
- "noscript",
2899
- "object",
2900
- "output",
2901
- "picture",
2902
- "progress",
2903
- "q",
2904
- "ruby",
2905
- "s",
2906
- "samp",
2907
- "script",
2908
- "select",
2909
- "slot",
2910
- "small",
2911
- "span",
2912
- "strong",
2913
- "sub",
2914
- "sup",
2915
- "svg",
2916
- "template",
2917
- "textarea",
2918
- "time",
2919
- "u",
2920
- "tt",
2921
- "var",
2922
- "video",
2923
- "wbr",
2924
- ],
2925
- };
2926
- const applicableOpts = {
2927
- removeHTMLComments: false,
2928
- removeCSSComments: false,
2929
- };
2930
- function isStr(something) {
2931
- return typeof something === "string";
2932
- }
2933
- function isLetter(something) {
2934
- return (typeof something === "string" &&
2935
- something.toUpperCase() !== something.toLowerCase());
2936
- }
2937
- /**
2938
- * Minifies HTML/CSS: valid or broken, pure or mixed with other languages
2939
- */
2940
- function crush(str, originalOpts) {
2941
- const start = Date.now();
2942
- // insurance:
2943
- if (!isStr(str)) {
2944
- if (str === undefined) {
2945
- throw new Error("html-crush: [THROW_ID_01] the first input argument is completely missing! It should be given as string.");
2946
- }
2947
- else {
2948
- throw new Error(`html-crush: [THROW_ID_02] the first input argument must be string! It was given as "${typeof str}", equal to:\n${JSON.stringify(str, null, 4)}`);
2949
- }
2950
- }
2951
- if (originalOpts && typeof originalOpts !== "object") {
2952
- throw new Error(`html-crush: [THROW_ID_03] the second input argument, options object, should be a plain object but it was given as type ${typeof originalOpts}, equal to ${JSON.stringify(originalOpts, null, 4)}`);
2953
- }
2954
- if (originalOpts &&
2955
- Array.isArray(originalOpts.breakToTheLeftOf) &&
2956
- originalOpts.breakToTheLeftOf.length) {
2957
- for (let z = 0, len = originalOpts.breakToTheLeftOf.length; z < len; z++) {
2958
- if (!isStr(originalOpts.breakToTheLeftOf[z])) {
2959
- throw new TypeError(`html-crush: [THROW_ID_05] the opts.breakToTheLeftOf array contains non-string elements! For example, element at index ${z} is of a type "${typeof originalOpts
2960
- .breakToTheLeftOf[z]}" and is equal to:\n${JSON.stringify(originalOpts.breakToTheLeftOf[z], null, 4)}`);
2961
- }
2962
- }
2963
- }
2964
- const opts = { ...defaults, ...originalOpts };
2965
- // normalize the opts.removeHTMLComments
2966
- if (typeof opts.removeHTMLComments === "boolean") {
2967
- opts.removeHTMLComments = opts.removeHTMLComments ? 1 : 0;
2968
- }
2969
- let breakToTheLeftOfFirstLetters = "";
2970
- if (Array.isArray(opts.breakToTheLeftOf) && opts.breakToTheLeftOf.length) {
2971
- breakToTheLeftOfFirstLetters = [
2972
- ...new Set(opts.breakToTheLeftOf.map((val) => val[0])),
2973
- ].join("");
2974
- }
2975
- // console.log(
2976
- // `0187 ${`\u001b[${33}m${`breakToTheLeftOfFirstLetters`}\u001b[${39}m`} = ${JSON.stringify(
2977
- // breakToTheLeftOfFirstLetters,
2978
- // null,
2979
- // 4
2980
- // )}`
2981
- // );
2982
- //
2983
- // console.log("\n");
2984
- // console.log(
2985
- // `0196 ${`\u001b[${33}m${`██ ██ ██`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
2986
- // opts,
2987
- // null,
2988
- // 4
2989
- // )}`
2990
- // );
2991
- let lastLinebreak = null;
2992
- let whitespaceStartedAt = null;
2993
- let nonWhitespaceCharMet = false;
2994
- let countCharactersPerLine = 0;
2995
- // new characters-per-line counter
2996
- let cpl = 0;
2997
- let withinStyleTag = false;
2998
- let withinHTMLConditional = false; // <!--[if lte mso 11]> etc
2999
- let withinInlineStyle = null;
3000
- let styleCommentStartedAt = null;
3001
- let htmlCommentStartedAt = null;
3002
- let scriptStartedAt = null;
3003
- // main do nothing switch, used to skip chunks of code and perform no action
3004
- let doNothing;
3005
- // we use staging "from" and "to" to preemptively mark the chunks
3006
- // of whitespace that will be either: a) replaced with a space; or
3007
- // b) replaced with linebreak. If opts.removeLineBreaks is on,
3008
- // if we need to break where the particular whitespace chunk is
3009
- // located, we replace it with line break. Otherwise, if
3010
- // the next chunk of characters that follows it fits on one line,
3011
- // we replace it with a single space.
3012
- let stageFrom = null;
3013
- let stageTo = null;
3014
- let stageAdd = null;
3015
- let tagName = null;
3016
- let tagNameStartsAt = null;
3017
- let leftTagName = null;
3018
- const CHARS_BREAK_ON_THE_RIGHT_OF_THEM = `>};`;
3019
- const CHARS_BREAK_ON_THE_LEFT_OF_THEM = `<`;
3020
- const CHARS_DONT_BREAK_ON_THE_LEFT_OF_THEM = `!`;
3021
- const DELETE_TIGHTLY_IF_ON_LEFT_IS = `>`;
3022
- const DELETE_TIGHTLY_IF_ON_RIGHT_IS = `<`;
3023
- const set = `{},:;<>~+`;
3024
- const DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS = set;
3025
- const DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS = set;
3026
- // the first non-whitespace character turns this flag off:
3027
- let beginningOfAFile = true;
3028
- // it will be used to trim start of the file.
3029
- const len = str.length;
3030
- const midLen = Math.floor(len / 2);
3031
- const leavePercForLastStage = 0.01; // in range of [0, 1]
3032
- // ceil - total range which is allocated to the main processing
3033
- let ceil;
3034
- if (opts.reportProgressFunc) {
3035
- ceil = Math.floor(opts.reportProgressFuncTo -
3036
- (opts.reportProgressFuncTo - opts.reportProgressFuncFrom) *
3037
- leavePercForLastStage -
3038
- opts.reportProgressFuncFrom);
3039
- }
3040
- // one more round to collapse the whitespace to:
3041
- // 1. Tackle indentations
3042
- // 2. Remove excessive whitespace between strings on each line (not touching indentations)
3043
- // progress-wise, 98% will be allocated to loop, rest 2% - to range applies and
3044
- // final return clauses
3045
- let currentPercentageDone;
3046
- let lastPercentage = 0;
3047
- let lineEnding = `\n`;
3048
- if (str.includes(`\r\n`)) {
3049
- lineEnding = `\r\n`;
3050
- }
3051
- else if (str.includes(`\r`)) {
3052
- lineEnding = `\r`;
3053
- }
3054
- if (len) {
3055
- for (let i = 0; i < len; i++) {
3056
- //
3057
- //
3058
- //
3059
- //
3060
- // TOP
3061
- //
3062
- //
3063
- //
3064
- //
3065
- // Logging:
3066
- // ███████████████████████████████████████
3067
- // Report the progress. We'll allocate 98% of the progress bar to this stage
3068
- if (opts.reportProgressFunc) {
3069
- if (len > 1000 && len < 2000) {
3070
- if (i === midLen) {
3071
- opts.reportProgressFunc(Math.floor((opts.reportProgressFuncTo - opts.reportProgressFuncFrom) / 2));
3072
- }
3073
- }
3074
- else if (len >= 2000) {
3075
- // defaults:
3076
- // opts.reportProgressFuncFrom = 0
3077
- // opts.reportProgressFuncTo = 100
3078
- currentPercentageDone =
3079
- opts.reportProgressFuncFrom + Math.floor((i / len) * (ceil || 1));
3080
- if (currentPercentageDone !== lastPercentage) {
3081
- lastPercentage = currentPercentageDone;
3082
- opts.reportProgressFunc(currentPercentageDone);
3083
- }
3084
- }
3085
- }
3086
- // count characters-per-line
3087
- cpl++;
3088
- // turn off doNothing if marker passed
3089
- // ███████████████████████████████████████
3090
- if (doNothing && typeof doNothing === "number" && i >= doNothing) {
3091
- doNothing = undefined;
3092
- }
3093
- // catch ending of </script...
3094
- // ███████████████████████████████████████
3095
- if (scriptStartedAt !== null &&
3096
- str.startsWith("</script", i) &&
3097
- !isLetter(str[i + 8])) {
3098
- // 1. if there is a line break, chunk of whitespace and </script>,
3099
- // delete that chunk of whitespace, leave line break.
3100
- // If there's non-whitespace character, chunk of whitespace and </script>,
3101
- // delete that chunk of whitespace.
3102
- // Basically, traverse backwards from "<" of "</script>", stop either
3103
- // at first line break or non-whitespace character.
3104
- if ((opts.removeIndentations || opts.removeLineBreaks) &&
3105
- i > 0 &&
3106
- str[~-i] &&
3107
- !str[~-i].trim()) {
3108
- // march backwards
3109
- for (let y = i; y--;) {
3110
- if (str[y] === "\n" || str[y] === "\r" || str[y].trim()) {
3111
- if (y + 1 < i) {
3112
- finalIndexesToDelete.push(y + 1, i);
3113
- }
3114
- break;
3115
- }
3116
- }
3117
- }
3118
- // 2.
3119
- scriptStartedAt = null;
3120
- doNothing = false;
3121
- i += 8;
3122
- continue;
3123
- }
3124
- // catch start of <script...
3125
- // ███████████████████████████████████████
3126
- if (!doNothing &&
3127
- !withinStyleTag &&
3128
- str.startsWith("<script", i) &&
3129
- !isLetter(str[i + 7])) {
3130
- scriptStartedAt = i;
3131
- doNothing = true;
3132
- let whatToInsert = "";
3133
- if ((opts.removeLineBreaks || opts.removeIndentations) &&
3134
- whitespaceStartedAt !== null) {
3135
- if (whitespaceStartedAt > 0) {
3136
- whatToInsert = lineEnding;
3137
- }
3138
- finalIndexesToDelete.push(whitespaceStartedAt, i, whatToInsert);
3139
- }
3140
- whitespaceStartedAt = null;
3141
- lastLinebreak = null;
3142
- }
3143
- //
3144
- //
3145
- //
3146
- //
3147
- //
3148
- //
3149
- //
3150
- //
3151
- // MIDDLE
3152
- //
3153
- //
3154
- //
3155
- //
3156
- //
3157
- //
3158
- //
3159
- //
3160
- // catch ending of the tag's name
3161
- // ███████████████████████████████████████
3162
- if (tagNameStartsAt !== null &&
3163
- tagName === null &&
3164
- !/\w/.test(str[i]) // not a letter
3165
- ) {
3166
- tagName = str.slice(tagNameStartsAt, i);
3167
- // check for inner tag whitespace
3168
- const idxOnTheRight = right(str, ~-i);
3169
- if (typeof idxOnTheRight === "number" &&
3170
- str[idxOnTheRight] === ">" &&
3171
- !str[i].trim() &&
3172
- right(str, i)) {
3173
- finalIndexesToDelete.push(i, right(str, i));
3174
- }
3175
- else if (idxOnTheRight &&
3176
- str[idxOnTheRight] === "/" &&
3177
- str[right(str, idxOnTheRight)] === ">") {
3178
- // if there's a space in front of "/>"
3179
- if (!str[i].trim() && right(str, i)) {
3180
- finalIndexesToDelete.push(i, right(str, i));
3181
- }
3182
- // if there's space between slash and bracket
3183
- if (str[idxOnTheRight + 1] !== ">" && right(str, idxOnTheRight + 1)) {
3184
- finalIndexesToDelete.push(idxOnTheRight + 1, right(str, idxOnTheRight + 1));
3185
- }
3186
- }
3187
- }
3188
- // catch a tag's opening bracket
3189
- // ███████████████████████████████████████
3190
- if (!doNothing &&
3191
- !withinStyleTag &&
3192
- !withinInlineStyle &&
3193
- str[~-i] === "<" &&
3194
- tagNameStartsAt === null) {
3195
- if (/\w/.test(str[i])) {
3196
- tagNameStartsAt = i;
3197
- }
3198
- else if (str[right(str, ~-i)] === "/" &&
3199
- /\w/.test(str[right(str, right(str, ~-i))] || "")) {
3200
- tagNameStartsAt = right(str, right(str, ~-i));
3201
- }
3202
- }
3203
- // catch an end of CSS comments
3204
- // ███████████████████████████████████████
3205
- if (!doNothing &&
3206
- (withinStyleTag || withinInlineStyle) &&
3207
- styleCommentStartedAt !== null &&
3208
- str[i] === "*" &&
3209
- str[i + 1] === "/") {
3210
- // stage:
3211
- [stageFrom, stageTo] = expander({
3212
- str,
3213
- from: styleCommentStartedAt,
3214
- to: i + 2,
3215
- ifLeftSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS ,
3216
- ifRightSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS ,
3217
- });
3218
- // reset marker:
3219
- styleCommentStartedAt = null;
3220
- if (stageFrom != null) {
3221
- finalIndexesToDelete.push(stageFrom, stageTo);
3222
- }
3223
- else {
3224
- countCharactersPerLine += 1;
3225
- i += 1;
3226
- }
3227
- // console.log(`0796 CONTINUE`);
3228
- // continue;
3229
- doNothing = i + 2;
3230
- }
3231
- // catch a start of CSS comments
3232
- // ███████████████████████████████████████
3233
- if (!doNothing &&
3234
- (withinStyleTag || withinInlineStyle) &&
3235
- styleCommentStartedAt === null &&
3236
- str[i] === "/" &&
3237
- str[i + 1] === "*") {
3238
- // independently of options settings, mark the options setting
3239
- // "removeCSSComments" as applicable:
3240
- if (!applicableOpts.removeCSSComments) {
3241
- applicableOpts.removeCSSComments = true;
3242
- }
3243
- if (opts.removeCSSComments) {
3244
- styleCommentStartedAt = i;
3245
- }
3246
- }
3247
- // catch an ending of mso conditional tags
3248
- // ███████████████████████████████████████
3249
- if (withinHTMLConditional && str.startsWith("![endif", i + 1)) {
3250
- withinHTMLConditional = false;
3251
- }
3252
- // catch an end of HTML comment
3253
- // ███████████████████████████████████████
3254
- if (!doNothing &&
3255
- !withinStyleTag &&
3256
- !withinInlineStyle &&
3257
- htmlCommentStartedAt !== null) {
3258
- let distanceFromHereToCommentEnding;
3259
- if (str.startsWith("-->", i)) {
3260
- distanceFromHereToCommentEnding = 3;
3261
- }
3262
- else if (str[i] === ">" && str[i - 1] === "]") {
3263
- distanceFromHereToCommentEnding = 1;
3264
- }
3265
- if (distanceFromHereToCommentEnding) {
3266
- // stage:
3267
- [stageFrom, stageTo] = expander({
3268
- str,
3269
- from: htmlCommentStartedAt,
3270
- to: i + distanceFromHereToCommentEnding,
3271
- });
3272
- // reset marker:
3273
- htmlCommentStartedAt = null;
3274
- if (stageFrom != null) {
3275
- // it depends is there any character allowance left from the
3276
- // line length limit or not
3277
- if (opts.lineLengthLimit &&
3278
- cpl - (stageTo - stageFrom) >= opts.lineLengthLimit) {
3279
- finalIndexesToDelete.push(stageFrom, stageTo, lineEnding);
3280
- // Currently we're not on the bracket ">" of the comment
3281
- // closing "-->", we're at the start of it, that first
3282
- // dash. This means, we'll still traverse to the end
3283
- // of this comment tag, before the actual "reset" should
3284
- // happen.
3285
- // Luckily we know how many characters are there left
3286
- // to traverse until the comment's ending is reached -
3287
- // "distanceFromHereToCommentEnding".
3288
- cpl = -distanceFromHereToCommentEnding;
3289
- // here we've reset cpl to some negative value, like -3
3290
- }
3291
- else {
3292
- // we have some character length allowance left so
3293
- // let's just delete the comment and reduce the cpl
3294
- // by that length
3295
- finalIndexesToDelete.push(stageFrom, stageTo);
3296
- cpl -= stageTo - stageFrom;
3297
- }
3298
- // finalIndexesToDelete.push(i + 1, i + 1, "\n");
3299
- // console.log(`1485 PUSH [${i + 1}, ${i + 1}, "\\n"]`);
3300
- // countCharactersPerLine = 0;
3301
- }
3302
- else {
3303
- countCharactersPerLine += distanceFromHereToCommentEnding - 1;
3304
- i += distanceFromHereToCommentEnding - 1;
3305
- }
3306
- // console.log(`0796 CONTINUE`);
3307
- // continue;
3308
- doNothing = i + distanceFromHereToCommentEnding;
3309
- }
3310
- }
3311
- // catch a start of HTML comment
3312
- // ███████████████████████████████████████
3313
- if (!doNothing &&
3314
- !withinStyleTag &&
3315
- !withinInlineStyle &&
3316
- str.startsWith("<!--", i) &&
3317
- htmlCommentStartedAt === null) {
3318
- // detect outlook conditionals
3319
- if (str.startsWith("[if", i + 4)) {
3320
- if (!withinHTMLConditional) {
3321
- withinHTMLConditional = true;
3322
- }
3323
- // skip the second counterpart, "<!-->" of "<!--[if !mso]><!-->"
3324
- // the plan is to not set the "htmlCommentStartedAt" at all if deletion
3325
- // is not needed
3326
- if (opts.removeHTMLComments === 2) {
3327
- htmlCommentStartedAt = i;
3328
- }
3329
- }
3330
- else if (
3331
- // setting is either 1 or 2 (delete text comments only or any comments):
3332
- opts.removeHTMLComments &&
3333
- // prevent the "not" type tails' "<!--" of "<!--<![endif]-->" from
3334
- // accidentally triggering the clauses
3335
- (!withinHTMLConditional || opts.removeHTMLComments === 2)) {
3336
- htmlCommentStartedAt = i;
3337
- }
3338
- // independently of options settings, mark the options setting
3339
- // "removeHTMLComments" as applicable:
3340
- if (!applicableOpts.removeHTMLComments) {
3341
- applicableOpts.removeHTMLComments = true;
3342
- }
3343
- // opts.removeHTMLComments: 0|1|2
3344
- }
3345
- // catch style tag
3346
- // ███████████████████████████████████████
3347
- if (!doNothing &&
3348
- withinStyleTag &&
3349
- styleCommentStartedAt === null &&
3350
- str.startsWith("</style", i) &&
3351
- !isLetter(str[i + 7])) {
3352
- withinStyleTag = false;
3353
- }
3354
- else if (!doNothing &&
3355
- !withinStyleTag &&
3356
- styleCommentStartedAt === null &&
3357
- str.startsWith("<style", i) &&
3358
- !isLetter(str[i + 6])) {
3359
- withinStyleTag = true;
3360
- // if opts.breakToTheLeftOf have "<style" among them, break to the
3361
- // right of this tag as well
3362
- if ((opts.removeLineBreaks || opts.removeIndentations) &&
3363
- opts.breakToTheLeftOf.includes("<style") &&
3364
- str.startsWith(` type="text/css">`, i + 6) &&
3365
- str[i + 24]) {
3366
- finalIndexesToDelete.push(i + 23, i + 23, lineEnding);
3367
- }
3368
- }
3369
- // catch start of inline styles
3370
- // ███████████████████████████████████████
3371
- if (!doNothing &&
3372
- !withinInlineStyle &&
3373
- `"'`.includes(str[i]) &&
3374
- str.endsWith("style=", i)) {
3375
- withinInlineStyle = i;
3376
- }
3377
- // catch whitespace
3378
- // ███████████████████████████████████████
3379
- if (!doNothing && !str[i].trim()) {
3380
- // if whitespace
3381
- if (whitespaceStartedAt === null) {
3382
- whitespaceStartedAt = i;
3383
- }
3384
- }
3385
- else if (!doNothing &&
3386
- !((withinStyleTag || withinInlineStyle) &&
3387
- styleCommentStartedAt !== null)) {
3388
- // catch the ending of a whitespace chunk
3389
- // console.log(`0912`);
3390
- if (whitespaceStartedAt !== null) {
3391
- if (opts.removeLineBreaks) {
3392
- countCharactersPerLine += 1;
3393
- }
3394
- if (beginningOfAFile) {
3395
- beginningOfAFile = false;
3396
- if (opts.removeIndentations || opts.removeLineBreaks) {
3397
- finalIndexesToDelete.push(0, i);
3398
- }
3399
- }
3400
- else {
3401
- // so it's not beginning of a file
3402
- // this is the most important area of the program - catching normal
3403
- // whitespace chunks
3404
- // ===================================================================
3405
- // ██ CASE 1. Remove indentations only.
3406
- if (opts.removeIndentations && !opts.removeLineBreaks) {
3407
- if (!nonWhitespaceCharMet &&
3408
- lastLinebreak !== null &&
3409
- i > lastLinebreak) {
3410
- finalIndexesToDelete.push(lastLinebreak + 1, i);
3411
- }
3412
- else if (whitespaceStartedAt + 1 < i) {
3413
- // we'll try to recycle some spaces, either at the
3414
- // beginning (preferable) or ending (at least) of the
3415
- // whitespace chunk, instead of wiping whole whitespace
3416
- // chunk and adding single space again.
3417
- // first, crop tight around the conditional comments
3418
- if (
3419
- // imagine <!--[if mso]>
3420
- str.endsWith("]>", whitespaceStartedAt) ||
3421
- // imagine <!--[if !mso]><!-->...<
3422
- // ^
3423
- // |
3424
- // our "whitespaceStartedAt"
3425
- str.endsWith("-->", whitespaceStartedAt) ||
3426
- // imagine closing counterparts, .../>...<![endif]-->
3427
- str.startsWith("<![", i) ||
3428
- // imagine other type of closing counterpart, .../>...<!--<![
3429
- str.startsWith("<!--<![", i)) {
3430
- // push the whole whitespace chunk
3431
- finalIndexesToDelete.push(whitespaceStartedAt, i);
3432
- }
3433
- else if (str[whitespaceStartedAt] === " ") {
3434
- finalIndexesToDelete.push(whitespaceStartedAt + 1, i);
3435
- }
3436
- else if (str[~-i] === " ") {
3437
- finalIndexesToDelete.push(whitespaceStartedAt, ~-i);
3438
- }
3439
- else {
3440
- finalIndexesToDelete.push(whitespaceStartedAt, i, " ");
3441
- }
3442
- }
3443
- }
3444
- // ===================================================================
3445
- // ██ CASE 2. Remove linebreaks (includes indentation removal by definition).
3446
- if (opts.removeLineBreaks || withinInlineStyle) {
3447
- //
3448
- // ██ CASE 2-1 - special break points from opts.breakToTheLeftOf
3449
- if (breakToTheLeftOfFirstLetters.includes(str[i]) &&
3450
- matchRightIncl(str, i, opts.breakToTheLeftOf)) {
3451
- // maybe there was just single line break?
3452
- if (
3453
- // CR or LF endings
3454
- !(`\r\n`.includes(str[~-i]) && whitespaceStartedAt === ~-i) &&
3455
- // CRLF endings
3456
- !(str[~-i] === "\n" &&
3457
- str[i - 2] === "\r" &&
3458
- whitespaceStartedAt === i - 2)) {
3459
- finalIndexesToDelete.push(whitespaceStartedAt, i, lineEnding);
3460
- }
3461
- stageFrom = null;
3462
- stageTo = null;
3463
- stageAdd = null;
3464
- whitespaceStartedAt = null;
3465
- countCharactersPerLine = 1;
3466
- continue;
3467
- }
3468
- // ██ CASE 2-2 - rest of whitespace chunk removal clauses
3469
- let whatToAdd = " ";
3470
- // skip for inline tags and also inline comparisons vs. numbers
3471
- // for example "something < 2" or "zzz > 1"
3472
- if (
3473
- // (
3474
- str[i] === "<" &&
3475
- matchRight(str, i, opts.mindTheInlineTags, {
3476
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3477
- })
3478
- // ) ||
3479
- // ("<>".includes(str[i]) &&
3480
- // ("0123456789".includes(str[right(str, i)]) ||
3481
- // "0123456789".includes(str[left(str, i)])))
3482
- ) ;
3483
- else if ((str[~-whitespaceStartedAt] &&
3484
- DELETE_TIGHTLY_IF_ON_LEFT_IS.includes(str[~-whitespaceStartedAt]) &&
3485
- DELETE_TIGHTLY_IF_ON_RIGHT_IS.includes(str[i])) ||
3486
- ((withinStyleTag || withinInlineStyle) &&
3487
- styleCommentStartedAt === null &&
3488
- (DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS.includes(str[~-whitespaceStartedAt]) ||
3489
- DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS.includes(str[i]))) ||
3490
- (str.startsWith("!important", i) && !withinHTMLConditional) ||
3491
- (withinInlineStyle &&
3492
- (str[~-whitespaceStartedAt] === "'" ||
3493
- str[~-whitespaceStartedAt] === '"')) ||
3494
- (str[~-whitespaceStartedAt] === "}" &&
3495
- str.startsWith("</style", i)) ||
3496
- (str[i] === ">" &&
3497
- (`'"`.includes(str[left(str, i)]) ||
3498
- str[right(str, i)] === "<")) ||
3499
- (str[i] === "/" && str[right(str, i)] === ">")) {
3500
- whatToAdd = "";
3501
- if (str[i] === "/" &&
3502
- str[i + 1] === ">" &&
3503
- right(str, i) &&
3504
- right(str, i) > i + 1) {
3505
- // delete whitespace between / and >
3506
- finalIndexesToDelete.push(i + 1, right(str, i));
3507
- countCharactersPerLine -= right(str, i) - i + 1;
3508
- }
3509
- }
3510
- if (whatToAdd && whatToAdd.length) {
3511
- countCharactersPerLine += 1;
3512
- }
3513
- // TWO CASES:
3514
- if (!opts.lineLengthLimit) {
3515
- // 2-1: Line-length limiting is off (easy)
3516
- // We skip the stage part, the whitespace chunks to straight to
3517
- // finalIndexesToDelete ranges array.
3518
- // but ensure that we're not replacing a single space with a single space
3519
- if (!(i === whitespaceStartedAt + 1 &&
3520
- // str[whitespaceStartedAt] === " " &&
3521
- whatToAdd === " ")) {
3522
- finalIndexesToDelete.push(whitespaceStartedAt, i, whatToAdd);
3523
- }
3524
- }
3525
- else {
3526
- // 2-2: Line-length limiting is on (not that easy)
3527
- // maybe we are already beyond the limit?
3528
- if (countCharactersPerLine >= opts.lineLengthLimit ||
3529
- !str[i + 1] ||
3530
- str[i] === ">" ||
3531
- (str[i] === "/" && str[i + 1] === ">")) {
3532
- if (countCharactersPerLine > opts.lineLengthLimit ||
3533
- (countCharactersPerLine === opts.lineLengthLimit &&
3534
- str[i + 1] &&
3535
- str[i + 1].trim() &&
3536
- !CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) &&
3537
- !CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i + 1]))) {
3538
- whatToAdd = lineEnding;
3539
- countCharactersPerLine = 1;
3540
- }
3541
- // replace the whitespace only in two cases:
3542
- // 1) if line length limit would otherwise be exceeded
3543
- // 2) if this replacement reduces the file length. For example,
3544
- // don't replace the linebreak with a space. But do delete
3545
- // linebreak like it happens between tags.
3546
- if (countCharactersPerLine > opts.lineLengthLimit ||
3547
- !(whatToAdd === " " && i === whitespaceStartedAt + 1)) {
3548
- finalIndexesToDelete.push(whitespaceStartedAt, i, whatToAdd);
3549
- lastLinebreak = null;
3550
- }
3551
- stageFrom = null;
3552
- stageTo = null;
3553
- stageAdd = null;
3554
- }
3555
- else if (stageFrom === null ||
3556
- whitespaceStartedAt < stageFrom) {
3557
- // only submit the range if it's bigger
3558
- stageFrom = whitespaceStartedAt;
3559
- stageTo = i;
3560
- stageAdd = whatToAdd;
3561
- }
3562
- }
3563
- }
3564
- // ===================================================================
3565
- }
3566
- // finally, toggle the marker:
3567
- whitespaceStartedAt = null;
3568
- // toggle nonWhitespaceCharMet
3569
- if (!nonWhitespaceCharMet) {
3570
- nonWhitespaceCharMet = true;
3571
- }
3572
- // continue;
3573
- }
3574
- else {
3575
- // 1. case when first character in string is not whitespace:
3576
- if (beginningOfAFile) {
3577
- beginningOfAFile = false;
3578
- }
3579
- // 2. tend count if linebreak removal is on:
3580
- if (opts.removeLineBreaks) {
3581
- // there was no whitespace gap and linebreak removal is on, so just
3582
- // increment the count
3583
- countCharactersPerLine += 1;
3584
- }
3585
- }
3586
- // ===================================================================
3587
- // ██ EXTRAS:
3588
- // toggle nonWhitespaceCharMet
3589
- if (!nonWhitespaceCharMet) {
3590
- nonWhitespaceCharMet = true;
3591
- }
3592
- }
3593
- // catch the characters, suitable for a break
3594
- if (!doNothing &&
3595
- !beginningOfAFile &&
3596
- i !== 0 &&
3597
- opts.removeLineBreaks &&
3598
- (opts.lineLengthLimit || breakToTheLeftOfFirstLetters) &&
3599
- !str.startsWith("</a", i)) {
3600
- if (breakToTheLeftOfFirstLetters &&
3601
- matchRightIncl(str, i, opts.breakToTheLeftOf) &&
3602
- str.slice(0, i).trim() &&
3603
- (!str.startsWith("<![endif]", i) || !matchLeft(str, i, "<!--"))) {
3604
- finalIndexesToDelete.push(i, i, lineEnding);
3605
- stageFrom = null;
3606
- stageTo = null;
3607
- stageAdd = null;
3608
- countCharactersPerLine = 1;
3609
- continue;
3610
- }
3611
- else if (opts.lineLengthLimit &&
3612
- countCharactersPerLine <= opts.lineLengthLimit) {
3613
- if (!str[i + 1] ||
3614
- (CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) &&
3615
- !CHARS_DONT_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i])) ||
3616
- CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) ||
3617
- !str[i].trim()) {
3618
- // 1. release stage contents - now they'll be definitely deleted
3619
- // =============================================================
3620
- if (stageFrom !== null &&
3621
- stageTo !== null &&
3622
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) {
3623
- let whatToAdd = stageAdd;
3624
- // if we are not on breaking point, last "stageAdd" needs to be
3625
- // amended into linebreak because otherwise we'll exceed the
3626
- // character limit
3627
- if (str[i].trim() &&
3628
- str[i + 1] &&
3629
- str[i + 1].trim() &&
3630
- countCharactersPerLine + (stageAdd ? stageAdd.length : 0) >
3631
- opts.lineLengthLimit) {
3632
- whatToAdd = lineEnding;
3633
- }
3634
- // if line is beyond the line length limit or whitespace is not
3635
- // a single space, staged to be replaced with single space,
3636
- // tackle this whitespace
3637
- if (countCharactersPerLine + (whatToAdd ? whatToAdd.length : 0) >
3638
- opts.lineLengthLimit ||
3639
- !(whatToAdd === " " &&
3640
- stageTo === stageFrom + 1 &&
3641
- str[stageFrom] === " ")) {
3642
- // push this range only if it's not between curlies, } and {
3643
- if (!(str[~-stageFrom] === "}" && str[stageTo] === "{")) {
3644
- finalIndexesToDelete.push(stageFrom, stageTo, whatToAdd);
3645
- lastLinebreak = null;
3646
- } // else {
3647
- // console.log(
3648
- // `1419 didn't push because whitespace is between curlies`
3649
- // );
3650
- // }
3651
- }
3652
- else {
3653
- countCharactersPerLine -= lastLinebreak || 0;
3654
- }
3655
- }
3656
- // 2. put this current place into stage
3657
- // =============================================================
3658
- if (str[i].trim() &&
3659
- (CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) ||
3660
- (str[~-i] &&
3661
- CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[~-i]))) &&
3662
- isStr(leftTagName) &&
3663
- (!tagName || !opts.mindTheInlineTags.includes(tagName)) &&
3664
- !(str[i] === "<" &&
3665
- matchRight(str, i, opts.mindTheInlineTags, {
3666
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3667
- })) &&
3668
- !(str[i] === "<" &&
3669
- matchRight(str, i, opts.mindTheInlineTags, {
3670
- trimCharsBeforeMatching: "/",
3671
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3672
- }))) {
3673
- stageFrom = i;
3674
- stageTo = i;
3675
- stageAdd = null;
3676
- }
3677
- else if (styleCommentStartedAt === null &&
3678
- stageFrom !== null &&
3679
- (withinInlineStyle ||
3680
- !opts.mindTheInlineTags ||
3681
- !Array.isArray(opts.mindTheInlineTags) ||
3682
- (Array.isArray(opts.mindTheInlineTags.length) &&
3683
- !opts.mindTheInlineTags.length) ||
3684
- !isStr(tagName) ||
3685
- (Array.isArray(opts.mindTheInlineTags) &&
3686
- opts.mindTheInlineTags.length &&
3687
- isStr(tagName) &&
3688
- !opts.mindTheInlineTags.includes(tagName))) &&
3689
- !(str[i] === "<" &&
3690
- matchRight(str, i, opts.mindTheInlineTags, {
3691
- trimCharsBeforeMatching: "/",
3692
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3693
- }))) {
3694
- stageFrom = null;
3695
- stageTo = null;
3696
- stageAdd = null;
3697
- // if (str[i] === "\n" || str[i] === "\r") {
3698
- // countCharactersPerLine -= lastLinebreak;
3699
- // console.log(
3700
- // `1449 SET countCharactersPerLine = ${countCharactersPerLine}`
3701
- // );
3702
- // }
3703
- }
3704
- }
3705
- }
3706
- else if (opts.lineLengthLimit) {
3707
- // countCharactersPerLine > opts.lineLengthLimit
3708
- // LIMIT HAS BEEN EXCEEDED!
3709
- // WE NEED TO BREAK RIGHT HERE
3710
- if (CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) &&
3711
- !(str[i] === "<" &&
3712
- matchRight(str, i, opts.mindTheInlineTags, {
3713
- trimCharsBeforeMatching: "/",
3714
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3715
- }))) {
3716
- // ██ 1.
3717
- //
3718
- // if really exceeded, not on limit, commit stage which will shorten
3719
- // the string and maybe we'll be within the limit range again
3720
- if (stageFrom !== null &&
3721
- stageTo !== null &&
3722
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) {
3723
- // case in test 02.11.09
3724
- // We might have passed some tabs for example, which should be
3725
- // deleted what might put line length back within limit. Or not.
3726
- //
3727
- const whatToAddLength = stageAdd && stageAdd.length ? stageAdd.length : 0;
3728
- // Currently, countCharactersPerLine > opts.lineLengthLimit
3729
- // But, will it still be true if we compensate for what's in stage?
3730
- if (countCharactersPerLine -
3731
- (stageTo - stageFrom - whatToAddLength) -
3732
- 1 >
3733
- opts.lineLengthLimit) ;
3734
- else {
3735
- // So,
3736
- // countCharactersPerLine -
3737
- // (stageTo - stageFrom - whatToAddLength) - 1 <=
3738
- // opts.lineLengthLimit
3739
- // don't break at stage, just apply its contents and we're good
3740
- finalIndexesToDelete.push(stageFrom, stageTo, stageAdd);
3741
- // We're not done yet. We are currently located on a potential
3742
- // break point,
3743
- // countCharactersPerLine -
3744
- // (stageTo - stageFrom - whatToAddLength) - 1 ===
3745
- // opts.lineLengthLimit ?
3746
- if (countCharactersPerLine -
3747
- (stageTo - stageFrom - whatToAddLength) -
3748
- 1 ===
3749
- opts.lineLengthLimit) {
3750
- finalIndexesToDelete.push(i, i, lineEnding);
3751
- countCharactersPerLine = 0;
3752
- }
3753
- // reset
3754
- stageFrom = null;
3755
- stageTo = null;
3756
- stageAdd = null;
3757
- }
3758
- }
3759
- else {
3760
- //
3761
- finalIndexesToDelete.push(i, i, lineEnding);
3762
- countCharactersPerLine = 0;
3763
- }
3764
- }
3765
- else if (str[i + 1] &&
3766
- CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) &&
3767
- isStr(tagName) &&
3768
- Array.isArray(opts.mindTheInlineTags) &&
3769
- opts.mindTheInlineTags.length &&
3770
- !opts.mindTheInlineTags.includes(tagName)) {
3771
- // ██ 2.
3772
- //
3773
- if (stageFrom !== null &&
3774
- stageTo !== null &&
3775
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) ;
3776
- else {
3777
- //
3778
- finalIndexesToDelete.push(i + 1, i + 1, lineEnding);
3779
- countCharactersPerLine = 0;
3780
- }
3781
- }
3782
- else if (!str[i].trim()) ;
3783
- else if (!str[i + 1]) {
3784
- // ██ 4.
3785
- //
3786
- // if we reached the end of string, check what's in stage
3787
- if (stageFrom !== null &&
3788
- stageTo !== null &&
3789
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) {
3790
- finalIndexesToDelete.push(stageFrom, stageTo, lineEnding);
3791
- }
3792
- }
3793
- }
3794
- }
3795
- // catch any character beyond the line length limit:
3796
- if (!doNothing &&
3797
- !beginningOfAFile &&
3798
- opts.removeLineBreaks &&
3799
- opts.lineLengthLimit &&
3800
- countCharactersPerLine >= opts.lineLengthLimit &&
3801
- stageFrom !== null &&
3802
- stageTo !== null &&
3803
- !CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) &&
3804
- !CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) &&
3805
- !"/".includes(str[i])) {
3806
- // two possible cases:
3807
- // 1. we hit the line length limit and we can break afterwards
3808
- // 2. we can't break afterwards, and there might be stage present
3809
- if (!(countCharactersPerLine === opts.lineLengthLimit &&
3810
- str[i + 1] &&
3811
- !str[i + 1].trim())) {
3812
- //
3813
- let whatToAdd = lineEnding;
3814
- if (str[i + 1] &&
3815
- !str[i + 1].trim() &&
3816
- countCharactersPerLine === opts.lineLengthLimit) {
3817
- whatToAdd = stageAdd;
3818
- }
3819
- // final correction - we might need to extend stageFrom to include
3820
- // all whitespace on the left if whatToAdd is a line break
3821
- if (whatToAdd === lineEnding &&
3822
- !str[~-stageFrom].trim() &&
3823
- left(str, stageFrom)) {
3824
- stageFrom = left(str, stageFrom) + 1;
3825
- }
3826
- finalIndexesToDelete.push(stageFrom, stageTo, whatToAdd);
3827
- countCharactersPerLine = i - stageTo;
3828
- if (str[i].length) {
3829
- countCharactersPerLine += 1;
3830
- }
3831
- stageFrom = null;
3832
- stageTo = null;
3833
- stageAdd = null;
3834
- }
3835
- }
3836
- // catch line breaks
3837
- // ███████████████████████████████████████
3838
- if ((!doNothing && str[i] === "\n") ||
3839
- (str[i] === "\r" &&
3840
- (!str[i + 1] || (str[i + 1] && str[i + 1] !== "\n")))) {
3841
- // =======================================================================
3842
- // mark this
3843
- lastLinebreak = i;
3844
- // =======================================================================
3845
- // reset nonWhitespaceCharMet
3846
- if (nonWhitespaceCharMet) {
3847
- nonWhitespaceCharMet = false;
3848
- }
3849
- // =======================================================================
3850
- // delete trailing whitespace on each line OR empty lines
3851
- if (!opts.removeLineBreaks &&
3852
- whitespaceStartedAt !== null &&
3853
- whitespaceStartedAt < i &&
3854
- str[i + 1] &&
3855
- str[i + 1] !== "\r" &&
3856
- str[i + 1] !== "\n") {
3857
- finalIndexesToDelete.push(whitespaceStartedAt, i);
3858
- }
3859
- }
3860
- // catch the EOF
3861
- // ███████████████████████████████████████
3862
- if (!str[i + 1]) {
3863
- if (withinStyleTag && styleCommentStartedAt !== null) {
3864
- finalIndexesToDelete.push(...expander({
3865
- str,
3866
- from: styleCommentStartedAt,
3867
- to: i,
3868
- ifLeftSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS ,
3869
- ifRightSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS ,
3870
- }));
3871
- }
3872
- else if (whitespaceStartedAt && str[i] !== "\n" && str[i] !== "\r") {
3873
- // catch trailing whitespace at the end of the string which is not legit
3874
- // trailing linebreak
3875
- finalIndexesToDelete.push(whitespaceStartedAt, i + 1);
3876
- }
3877
- else if (whitespaceStartedAt &&
3878
- ((str[i] === "\r" && str[i + 1] === "\n") ||
3879
- (str[i] === "\n" && str[i - 1] !== "\r"))) {
3880
- finalIndexesToDelete.push(whitespaceStartedAt, i);
3881
- }
3882
- }
3883
- //
3884
- //
3885
- //
3886
- //
3887
- //
3888
- //
3889
- //
3890
- //
3891
- //
3892
- // BOTTOM
3893
- //
3894
- //
3895
- //
3896
- //
3897
- //
3898
- //
3899
- //
3900
- //
3901
- // catch end of inline styles
3902
- // ███████████████████████████████████████
3903
- if (!doNothing &&
3904
- withinInlineStyle &&
3905
- withinInlineStyle < i &&
3906
- str[withinInlineStyle] === str[i]) {
3907
- withinInlineStyle = null;
3908
- }
3909
- // catch <pre...>
3910
- // ███████████████████████████████████████
3911
- if (!doNothing &&
3912
- !withinStyleTag &&
3913
- str.startsWith("<pre", i) &&
3914
- !isLetter(str[i + 4])) {
3915
- const locationOfClosingPre = str.indexOf("</pre", i + 5);
3916
- if (locationOfClosingPre > 0) {
3917
- doNothing = locationOfClosingPre;
3918
- }
3919
- }
3920
- // catch <code...>
3921
- // ███████████████████████████████████████
3922
- if (!doNothing &&
3923
- !withinStyleTag &&
3924
- str.startsWith("<code", i) &&
3925
- !isLetter(str[i + 5])) {
3926
- const locationOfClosingCode = str.indexOf("</code", i + 5);
3927
- if (locationOfClosingCode > 0) {
3928
- doNothing = locationOfClosingCode;
3929
- }
3930
- }
3931
- // catch start of <![CDATA[
3932
- // ███████████████████████████████████████
3933
- if (!doNothing && str.startsWith("<![CDATA[", i)) {
3934
- const locationOfClosingCData = str.indexOf("]]>", i + 9);
3935
- if (locationOfClosingCData > 0) {
3936
- doNothing = locationOfClosingCData;
3937
- }
3938
- }
3939
- // catch tag's closing bracket
3940
- // ███████████████████████████████████████
3941
- if (!doNothing &&
3942
- !withinStyleTag &&
3943
- !withinInlineStyle &&
3944
- tagNameStartsAt !== null &&
3945
- str[i] === ">") {
3946
- // if another tag starts on the right, hand over the name:
3947
- if (str[right(str, i)] === "<") {
3948
- leftTagName = tagName;
3949
- }
3950
- tagNameStartsAt = null;
3951
- tagName = null;
3952
- }
3953
- // catch tag's opening bracket
3954
- // ███████████████████████████████████████
3955
- if (str[i] === "<" && leftTagName !== null) {
3956
- // reset it after use
3957
- leftTagName = null;
3958
- }
3959
- //
3960
- //
3961
- //
3962
- // end of the loop
3963
- }
3964
- if (finalIndexesToDelete.current()) {
3965
- const ranges = finalIndexesToDelete.current();
3966
- finalIndexesToDelete.wipe();
3967
- const startingPercentageDone = opts.reportProgressFuncTo -
3968
- (opts.reportProgressFuncTo - opts.reportProgressFuncFrom) *
3969
- leavePercForLastStage;
3970
- const res = rApply(str, ranges, (applyPercDone) => {
3971
- // allocate remaining "leavePercForLastStage" percentage of the total
3972
- // progress reporting to this stage:
3973
- if (opts.reportProgressFunc && len >= 2000) {
3974
- currentPercentageDone = Math.floor(startingPercentageDone +
3975
- (opts.reportProgressFuncTo - startingPercentageDone) *
3976
- (applyPercDone / 100));
3977
- if (currentPercentageDone !== lastPercentage) {
3978
- lastPercentage = currentPercentageDone;
3979
- opts.reportProgressFunc(currentPercentageDone);
3980
- }
3981
- }
3982
- });
3983
- const resLen = res.length;
3984
- return {
3985
- log: {
3986
- timeTakenInMilliseconds: Date.now() - start,
3987
- originalLength: len,
3988
- cleanedLength: resLen,
3989
- bytesSaved: Math.max(len - resLen, 0),
3990
- percentageReducedOfOriginal: len
3991
- ? Math.round((Math.max(len - resLen, 0) * 100) / len)
3992
- : 0,
3993
- },
3994
- ranges,
3995
- applicableOpts,
3996
- result: res,
3997
- };
3998
- }
3999
- }
4000
- // ELSE - return the original input string
4001
- return {
4002
- log: {
4003
- timeTakenInMilliseconds: Date.now() - start,
4004
- originalLength: len,
4005
- cleanedLength: len,
4006
- bytesSaved: 0,
4007
- percentageReducedOfOriginal: 0,
4008
- },
4009
- applicableOpts,
4010
- ranges: null,
4011
- result: str,
4012
- };
4013
- }
4014
-
4015
- exports.crush = crush;
4016
- exports.defaults = defaults;
4017
- exports.version = version;
4018
-
4019
- Object.defineProperty(exports, '__esModule', { value: true });
4020
-
4021
- })));